@sentry/opentelemetry 8.0.0-alpha.1 → 8.0.0-alpha.3

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 (178) hide show
  1. package/README.md +2 -1
  2. package/cjs/index.js +2120 -55
  3. package/cjs/index.js.map +1 -1
  4. package/esm/index.js +2091 -22
  5. package/esm/index.js.map +1 -1
  6. package/esm/package.json +1 -0
  7. package/package.json +18 -5
  8. package/types/asyncContextStrategy.d.ts.map +1 -1
  9. package/types/constants.d.ts +3 -5
  10. package/types/constants.d.ts.map +1 -1
  11. package/types/contextManager.d.ts.map +1 -1
  12. package/types/custom/getCurrentHub.d.ts.map +1 -1
  13. package/types/index.d.ts +6 -7
  14. package/types/index.d.ts.map +1 -1
  15. package/types/propagator.d.ts +26 -2
  16. package/types/propagator.d.ts.map +1 -1
  17. package/types/sampler.d.ts.map +1 -1
  18. package/types/semanticAttributes.d.ts +2 -7
  19. package/types/semanticAttributes.d.ts.map +1 -1
  20. package/types/setupEventContextTrace.d.ts.map +1 -1
  21. package/types/spanExporter.d.ts.map +1 -1
  22. package/types/spanProcessor.d.ts.map +1 -1
  23. package/types/trace.d.ts +14 -1
  24. package/types/trace.d.ts.map +1 -1
  25. package/types/types.d.ts +3 -4
  26. package/types/types.d.ts.map +1 -1
  27. package/types/utils/captureExceptionForTimedEvent.d.ts +1 -2
  28. package/types/utils/captureExceptionForTimedEvent.d.ts.map +1 -1
  29. package/types/utils/contextData.d.ts +1 -21
  30. package/types/utils/contextData.d.ts.map +1 -1
  31. package/types/utils/dynamicSamplingContext.d.ts.map +1 -1
  32. package/types/utils/getActiveSpan.d.ts +0 -5
  33. package/types/utils/getActiveSpan.d.ts.map +1 -1
  34. package/types/utils/groupSpansWithParents.d.ts.map +1 -1
  35. package/types/utils/mapStatus.d.ts +2 -2
  36. package/types/utils/mapStatus.d.ts.map +1 -1
  37. package/types/utils/setupCheck.d.ts +9 -0
  38. package/types/utils/setupCheck.d.ts.map +1 -0
  39. package/types/utils/spanData.d.ts +1 -14
  40. package/types/utils/spanData.d.ts.map +1 -1
  41. package/types-ts3.8/constants.d.ts +3 -5
  42. package/types-ts3.8/index.d.ts +6 -7
  43. package/types-ts3.8/propagator.d.ts +26 -2
  44. package/types-ts3.8/semanticAttributes.d.ts +2 -7
  45. package/types-ts3.8/trace.d.ts +14 -1
  46. package/types-ts3.8/types.d.ts +3 -4
  47. package/types-ts3.8/utils/captureExceptionForTimedEvent.d.ts +1 -2
  48. package/types-ts3.8/utils/contextData.d.ts +1 -21
  49. package/types-ts3.8/utils/getActiveSpan.d.ts +0 -5
  50. package/types-ts3.8/utils/mapStatus.d.ts +2 -2
  51. package/types-ts3.8/utils/setupCheck.d.ts +9 -0
  52. package/types-ts3.8/utils/spanData.d.ts +1 -14
  53. package/cjs/asyncContextStrategy.js +0 -114
  54. package/cjs/asyncContextStrategy.js.map +0 -1
  55. package/cjs/constants.js +0 -32
  56. package/cjs/constants.js.map +0 -1
  57. package/cjs/contextManager.js +0 -82
  58. package/cjs/contextManager.js.map +0 -1
  59. package/cjs/custom/client.js +0 -64
  60. package/cjs/custom/client.js.map +0 -1
  61. package/cjs/custom/getCurrentHub.js +0 -106
  62. package/cjs/custom/getCurrentHub.js.map +0 -1
  63. package/cjs/custom/hub.js +0 -13
  64. package/cjs/custom/hub.js.map +0 -1
  65. package/cjs/custom/hubextensions.js +0 -37
  66. package/cjs/custom/hubextensions.js.map +0 -1
  67. package/cjs/custom/transaction.js +0 -26
  68. package/cjs/custom/transaction.js.map +0 -1
  69. package/cjs/debug-build.js +0 -11
  70. package/cjs/debug-build.js.map +0 -1
  71. package/cjs/propagator.js +0 -159
  72. package/cjs/propagator.js.map +0 -1
  73. package/cjs/sampler.js +0 -186
  74. package/cjs/sampler.js.map +0 -1
  75. package/cjs/semanticAttributes.js +0 -12
  76. package/cjs/semanticAttributes.js.map +0 -1
  77. package/cjs/setupEventContextTrace.js +0 -40
  78. package/cjs/setupEventContextTrace.js.map +0 -1
  79. package/cjs/spanExporter.js +0 -314
  80. package/cjs/spanExporter.js.map +0 -1
  81. package/cjs/spanProcessor.js +0 -95
  82. package/cjs/spanProcessor.js.map +0 -1
  83. package/cjs/trace.js +0 -222
  84. package/cjs/trace.js.map +0 -1
  85. package/cjs/utils/addOriginToSpan.js +0 -11
  86. package/cjs/utils/addOriginToSpan.js.map +0 -1
  87. package/cjs/utils/captureExceptionForTimedEvent.js +0 -59
  88. package/cjs/utils/captureExceptionForTimedEvent.js.map +0 -1
  89. package/cjs/utils/contextData.js +0 -79
  90. package/cjs/utils/contextData.js.map +0 -1
  91. package/cjs/utils/convertOtelTimeToSeconds.js +0 -9
  92. package/cjs/utils/convertOtelTimeToSeconds.js.map +0 -1
  93. package/cjs/utils/dynamicSamplingContext.js +0 -64
  94. package/cjs/utils/dynamicSamplingContext.js.map +0 -1
  95. package/cjs/utils/getActiveSpan.js +0 -29
  96. package/cjs/utils/getActiveSpan.js.map +0 -1
  97. package/cjs/utils/getRequestSpanData.js +0 -48
  98. package/cjs/utils/getRequestSpanData.js.map +0 -1
  99. package/cjs/utils/getSpanKind.js +0 -21
  100. package/cjs/utils/getSpanKind.js.map +0 -1
  101. package/cjs/utils/groupSpansWithParents.js +0 -74
  102. package/cjs/utils/groupSpansWithParents.js.map +0 -1
  103. package/cjs/utils/isSentryRequest.js +0 -29
  104. package/cjs/utils/isSentryRequest.js.map +0 -1
  105. package/cjs/utils/mapStatus.js +0 -76
  106. package/cjs/utils/mapStatus.js.map +0 -1
  107. package/cjs/utils/parseSpanDescription.js +0 -158
  108. package/cjs/utils/parseSpanDescription.js.map +0 -1
  109. package/cjs/utils/spanData.js +0 -72
  110. package/cjs/utils/spanData.js.map +0 -1
  111. package/cjs/utils/spanTypes.js +0 -77
  112. package/cjs/utils/spanTypes.js.map +0 -1
  113. package/esm/asyncContextStrategy.js +0 -112
  114. package/esm/asyncContextStrategy.js.map +0 -1
  115. package/esm/constants.js +0 -22
  116. package/esm/constants.js.map +0 -1
  117. package/esm/contextManager.js +0 -77
  118. package/esm/contextManager.js.map +0 -1
  119. package/esm/custom/client.js +0 -59
  120. package/esm/custom/client.js.map +0 -1
  121. package/esm/custom/getCurrentHub.js +0 -101
  122. package/esm/custom/getCurrentHub.js.map +0 -1
  123. package/esm/custom/hub.js +0 -11
  124. package/esm/custom/hub.js.map +0 -1
  125. package/esm/custom/hubextensions.js +0 -35
  126. package/esm/custom/hubextensions.js.map +0 -1
  127. package/esm/custom/transaction.js +0 -24
  128. package/esm/custom/transaction.js.map +0 -1
  129. package/esm/debug-build.js +0 -9
  130. package/esm/debug-build.js.map +0 -1
  131. package/esm/propagator.js +0 -154
  132. package/esm/propagator.js.map +0 -1
  133. package/esm/sampler.js +0 -184
  134. package/esm/sampler.js.map +0 -1
  135. package/esm/semanticAttributes.js +0 -10
  136. package/esm/semanticAttributes.js.map +0 -1
  137. package/esm/setupEventContextTrace.js +0 -38
  138. package/esm/setupEventContextTrace.js.map +0 -1
  139. package/esm/spanExporter.js +0 -312
  140. package/esm/spanExporter.js.map +0 -1
  141. package/esm/spanProcessor.js +0 -93
  142. package/esm/spanProcessor.js.map +0 -1
  143. package/esm/trace.js +0 -217
  144. package/esm/trace.js.map +0 -1
  145. package/esm/utils/addOriginToSpan.js +0 -9
  146. package/esm/utils/addOriginToSpan.js.map +0 -1
  147. package/esm/utils/captureExceptionForTimedEvent.js +0 -57
  148. package/esm/utils/captureExceptionForTimedEvent.js.map +0 -1
  149. package/esm/utils/contextData.js +0 -70
  150. package/esm/utils/contextData.js.map +0 -1
  151. package/esm/utils/convertOtelTimeToSeconds.js +0 -7
  152. package/esm/utils/convertOtelTimeToSeconds.js.map +0 -1
  153. package/esm/utils/dynamicSamplingContext.js +0 -59
  154. package/esm/utils/dynamicSamplingContext.js.map +0 -1
  155. package/esm/utils/getActiveSpan.js +0 -26
  156. package/esm/utils/getActiveSpan.js.map +0 -1
  157. package/esm/utils/getRequestSpanData.js +0 -46
  158. package/esm/utils/getRequestSpanData.js.map +0 -1
  159. package/esm/utils/getSpanKind.js +0 -19
  160. package/esm/utils/getSpanKind.js.map +0 -1
  161. package/esm/utils/groupSpansWithParents.js +0 -72
  162. package/esm/utils/groupSpansWithParents.js.map +0 -1
  163. package/esm/utils/isSentryRequest.js +0 -27
  164. package/esm/utils/isSentryRequest.js.map +0 -1
  165. package/esm/utils/mapStatus.js +0 -74
  166. package/esm/utils/mapStatus.js.map +0 -1
  167. package/esm/utils/parseSpanDescription.js +0 -154
  168. package/esm/utils/parseSpanDescription.js.map +0 -1
  169. package/esm/utils/spanData.js +0 -63
  170. package/esm/utils/spanData.js.map +0 -1
  171. package/esm/utils/spanTypes.js +0 -70
  172. package/esm/utils/spanTypes.js.map +0 -1
  173. package/types/custom/hubextensions.d.ts +0 -5
  174. package/types/custom/hubextensions.d.ts.map +0 -1
  175. package/types/custom/transaction.d.ts +0 -8
  176. package/types/custom/transaction.d.ts.map +0 -1
  177. package/types-ts3.8/custom/hubextensions.d.ts +0 -5
  178. package/types-ts3.8/custom/transaction.d.ts +0 -8
package/esm/index.js CHANGED
@@ -1,34 +1,2103 @@
1
- import { addOriginToSpan } from './utils/addOriginToSpan.js';
2
- import { maybeCaptureExceptionForTimedEvent } from './utils/captureExceptionForTimedEvent.js';
3
- import { getRequestSpanData } from './utils/getRequestSpanData.js';
4
- export { wrapClientClass } from './custom/client.js';
5
- export { getSpanKind } from './utils/getSpanKind.js';
6
- export { getSpanHub, getSpanMetadata, getSpanParent, getSpanScopes, setSpanMetadata } from './utils/spanData.js';
7
- export { getPropagationContextFromContext, getScopesFromContext, setPropagationContextOnContext } from './utils/contextData.js';
8
- export { spanHasAttributes, spanHasEvents, spanHasKind, spanHasName, spanHasParentId, spanHasStatus } from './utils/spanTypes.js';
9
- export { isSentryRequestSpan } from './utils/isSentryRequest.js';
10
- export { getActiveSpan, getRootSpan } from './utils/getActiveSpan.js';
11
- export { startInactiveSpan, startSpan, startSpanManual, withActiveSpan } from './trace.js';
12
- export { setupGlobalHub } from './custom/hub.js';
13
- export { getCurrentHub } from './custom/getCurrentHub.js';
14
- export { addTracingExtensions } from './custom/hubextensions.js';
15
- export { setupEventContextTrace } from './setupEventContextTrace.js';
16
- export { setOpenTelemetryContextAsyncContextStrategy } from './asyncContextStrategy.js';
17
- export { wrapContextManagerClass } from './contextManager.js';
18
- export { SentryPropagator } from './propagator.js';
19
- export { SentrySpanProcessor } from './spanProcessor.js';
20
- export { SentrySampler } from './sampler.js';
1
+ import { _optionalChain } from '@sentry/utils';
2
+ import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
3
+ import { captureException, SDK_VERSION, getCurrentScope, getIsolationScope, getClient, getDynamicSamplingContextFromClient, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, isSentryRequestUrl, handleCallbackErrors, SEMANTIC_ATTRIBUTE_SENTRY_OP, getRootSpan, continueTrace as continueTrace$1, withScope, captureEvent, addBreadcrumb, setUser, setTags, setTag, setExtra, setExtras, setContext, startSession, endSession, setAsyncContextStrategy, getDefaultCurrentScope, getDefaultIsolationScope, SPAN_STATUS_ERROR, SPAN_STATUS_OK, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, getStatusMessage, getMetricSummaryJsonForSpan, addChildSpanToSpan, hasTracingEnabled } from '@sentry/core';
21
4
  export { getClient } from '@sentry/core';
5
+ import { isString, parseUrl, getSanitizedUrlString, SENTRY_BAGGAGE_KEY_PREFIX, generateSentryTraceHeader, propagationContextFromHeaders, baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader, dropUndefinedKeys, stripUrlQueryAndFragment, logger, isNaN } from '@sentry/utils';
6
+ import * as api from '@opentelemetry/api';
7
+ import { trace, SpanKind, createContextKey, propagation, TraceFlags, context, SpanStatusCode, ROOT_CONTEXT, isSpanContextValid } from '@opentelemetry/api';
8
+ import { W3CBaggagePropagator, isTracingSuppressed, TraceState, suppressTracing, ExportResultCode } from '@opentelemetry/core';
9
+ import { BatchSpanProcessor, SamplingDecision } from '@opentelemetry/sdk-trace-base';
10
+
11
+ /**
12
+ * Maybe capture a Sentry exception for an OTEL timed event.
13
+ * This will check if the event is exception-like and in that case capture it as an exception.
14
+ */
15
+ function maybeCaptureExceptionForTimedEvent(event, otelSpan) {
16
+ if (event.name !== 'exception') {
17
+ return;
18
+ }
19
+
20
+ const attributes = event.attributes;
21
+ if (!attributes) {
22
+ return;
23
+ }
24
+
25
+ const message = attributes[SemanticAttributes.EXCEPTION_MESSAGE];
26
+
27
+ if (typeof message !== 'string') {
28
+ return;
29
+ }
30
+
31
+ const syntheticError = new Error(message);
32
+
33
+ const stack = attributes[SemanticAttributes.EXCEPTION_STACKTRACE];
34
+ if (isString(stack)) {
35
+ syntheticError.stack = stack;
36
+ }
37
+
38
+ const type = attributes[SemanticAttributes.EXCEPTION_TYPE];
39
+ if (isString(type)) {
40
+ syntheticError.name = type;
41
+ }
42
+
43
+ captureException(syntheticError, {
44
+ captureContext: otelSpan
45
+ ? {
46
+ contexts: {
47
+ otel: {
48
+ attributes: otelSpan.attributes,
49
+ resource: otelSpan.resource.attributes,
50
+ },
51
+ trace: {
52
+ trace_id: otelSpan.spanContext().traceId,
53
+ span_id: otelSpan.spanContext().spanId,
54
+ parent_span_id: otelSpan.parentSpanId,
55
+ },
56
+ },
57
+ }
58
+ : undefined,
59
+ });
60
+ }
61
+
62
+ /**
63
+ * Check if a given span has attributes.
64
+ * This is necessary because the base `Span` type does not have attributes,
65
+ * so in places where we are passed a generic span, we need to check if we want to access them.
66
+ */
67
+ function spanHasAttributes(
68
+ span,
69
+ ) {
70
+ const castSpan = span ;
71
+ return !!castSpan.attributes && typeof castSpan.attributes === 'object';
72
+ }
73
+
74
+ /**
75
+ * Check if a given span has a kind.
76
+ * This is necessary because the base `Span` type does not have a kind,
77
+ * so in places where we are passed a generic span, we need to check if we want to access it.
78
+ */
79
+ function spanHasKind(span) {
80
+ const castSpan = span ;
81
+ return !!castSpan.kind;
82
+ }
83
+
84
+ /**
85
+ * Check if a given span has a status.
86
+ * This is necessary because the base `Span` type does not have a status,
87
+ * so in places where we are passed a generic span, we need to check if we want to access it.
88
+ */
89
+ function spanHasStatus(
90
+ span,
91
+ ) {
92
+ const castSpan = span ;
93
+ return !!castSpan.status;
94
+ }
95
+
96
+ /**
97
+ * Check if a given span has a name.
98
+ * This is necessary because the base `Span` type does not have a name,
99
+ * so in places where we are passed a generic span, we need to check if we want to access it.
100
+ */
101
+ function spanHasName(span) {
102
+ const castSpan = span ;
103
+ return !!castSpan.name;
104
+ }
105
+
106
+ /**
107
+ * Check if a given span has a kind.
108
+ * This is necessary because the base `Span` type does not have a kind,
109
+ * so in places where we are passed a generic span, we need to check if we want to access it.
110
+ */
111
+ function spanHasParentId(
112
+ span,
113
+ ) {
114
+ const castSpan = span ;
115
+ return !!castSpan.parentSpanId;
116
+ }
117
+
118
+ /**
119
+ * Check if a given span has events.
120
+ * This is necessary because the base `Span` type does not have events,
121
+ * so in places where we are passed a generic span, we need to check if we want to access it.
122
+ */
123
+ function spanHasEvents(
124
+ span,
125
+ ) {
126
+ const castSpan = span ;
127
+ return Array.isArray(castSpan.events);
128
+ }
129
+
130
+ /**
131
+ * Get sanitizied request data from an OTEL span.
132
+ */
133
+ function getRequestSpanData(span) {
134
+ // The base `Span` type has no `attributes`, so we need to guard here against that
135
+ if (!spanHasAttributes(span)) {
136
+ return {};
137
+ }
138
+
139
+ const data = {
140
+ url: span.attributes[SemanticAttributes.HTTP_URL] ,
141
+ 'http.method': span.attributes[SemanticAttributes.HTTP_METHOD] ,
142
+ };
143
+
144
+ // Default to GET if URL is set but method is not
145
+ if (!data['http.method'] && data.url) {
146
+ data['http.method'] = 'GET';
147
+ }
148
+
149
+ try {
150
+ const urlStr = span.attributes[SemanticAttributes.HTTP_URL];
151
+ if (typeof urlStr === 'string') {
152
+ const url = parseUrl(urlStr);
153
+
154
+ data.url = getSanitizedUrlString(url);
155
+
156
+ if (url.search) {
157
+ data['http.query'] = url.search;
158
+ }
159
+ if (url.hash) {
160
+ data['http.fragment'] = url.hash;
161
+ }
162
+ }
163
+ } catch (e) {
164
+ // ignore
165
+ }
166
+
167
+ return data;
168
+ }
169
+
170
+ function _optionalChain$8(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
171
+
172
+ // Typescript complains if we do not use `...args: any[]` for the mixin, with:
173
+ // A mixin class must have a constructor with a single rest parameter of type 'any[]'.ts(2545)
174
+ /* eslint-disable @typescript-eslint/no-explicit-any */
175
+
176
+ /**
177
+ * Wrap an Client with things we need for OpenTelemetry support.
178
+ *
179
+ * Usage:
180
+ * const OpenTelemetryClient = getWrappedClientClass(NodeClient);
181
+ * const client = new OpenTelemetryClient(options);
182
+ */
183
+ function wrapClientClass
184
+
185
+ (ClientClass) {
186
+ class OpenTelemetryClient extends ClientClass {
187
+
188
+ constructor(...args) {
189
+ super(...args);
190
+ }
191
+
192
+ /** Get the OTEL tracer. */
193
+ get tracer() {
194
+ if (this._tracer) {
195
+ return this._tracer;
196
+ }
197
+
198
+ const name = '@sentry/opentelemetry';
199
+ const version = SDK_VERSION;
200
+ const tracer = trace.getTracer(name, version);
201
+ this._tracer = tracer;
202
+
203
+ return tracer;
204
+ }
205
+
206
+ /**
207
+ * @inheritDoc
208
+ */
209
+ async flush(timeout) {
210
+ const provider = this.traceProvider;
211
+ const spanProcessor = _optionalChain$8([provider, 'optionalAccess', _ => _.activeSpanProcessor]);
212
+
213
+ if (spanProcessor) {
214
+ await spanProcessor.forceFlush();
215
+ }
216
+
217
+ return super.flush(timeout);
218
+ }
219
+ }
220
+
221
+ return OpenTelemetryClient ;
222
+ }
223
+ /* eslint-enable @typescript-eslint/no-explicit-any */
224
+
225
+ /**
226
+ * Get the span kind from a span.
227
+ * For whatever reason, this is not public API on the generic "Span" type,
228
+ * so we need to check if we actually have a `SDKTraceBaseSpan` where we can fetch this from.
229
+ * Otherwise, we fall back to `SpanKind.INTERNAL`.
230
+ */
231
+ function getSpanKind(span) {
232
+ if (spanHasKind(span)) {
233
+ return span.kind;
234
+ }
235
+
236
+ return SpanKind.INTERNAL;
237
+ }
238
+
239
+ // We store the parent span, scopes & metadata in separate weakmaps, so we can access them for a given span
240
+ // This way we can enhance the data that an OTEL Span natively gives us
241
+ // and since we are using weakmaps, we do not need to clean up after ourselves
242
+ const SpanScopes = new WeakMap
243
+
244
+ ();
245
+
246
+ /**
247
+ * Set the Sentry scope to be used for finishing a given OTEL span.
248
+ * This is different from `setCapturedScopesOnSpan`, as that works on _sentry_ spans,
249
+ * while here we are basically "caching" this on the otel spans.
250
+ */
251
+ function setSpanScopes(
252
+ span,
253
+ scopes
254
+
255
+ ,
256
+ ) {
257
+ SpanScopes.set(span, scopes);
258
+ }
259
+
260
+ /** Get the Sentry scopes to use for finishing an OTEL span. */
261
+ function getSpanScopes(span)
262
+
263
+ {
264
+ return SpanScopes.get(span);
265
+ }
266
+
267
+ const SENTRY_TRACE_HEADER = 'sentry-trace';
268
+ const SENTRY_BAGGAGE_HEADER = 'baggage';
269
+
270
+ const SENTRY_TRACE_STATE_DSC = 'sentry.dsc';
271
+ const SENTRY_TRACE_STATE_PARENT_SPAN_ID = 'sentry.parent_span_id';
272
+ const SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING = 'sentry.sampled_not_recording';
273
+
274
+ const SENTRY_SCOPES_CONTEXT_KEY = createContextKey('sentry_scopes');
275
+
276
+ const SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY = createContextKey('sentry_fork_isolation_scope');
277
+
278
+ const SENTRY_FORK_SET_SCOPE_CONTEXT_KEY = createContextKey('sentry_fork_set_scope');
279
+
280
+ const SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY = createContextKey('sentry_fork_set_isolation_scope');
281
+
282
+ const SCOPE_CONTEXT_MAP = new WeakMap();
283
+
284
+ /**
285
+ * Try to get the current scopes from the given OTEL context.
286
+ * This requires a Context Manager that was wrapped with getWrappedContextManager.
287
+ */
288
+ function getScopesFromContext(context) {
289
+ return context.getValue(SENTRY_SCOPES_CONTEXT_KEY) ;
290
+ }
291
+
292
+ /**
293
+ * Set the current scopes on an OTEL context.
294
+ * This will return a forked context with the Propagation Context set.
295
+ */
296
+ function setScopesOnContext(context, scopes) {
297
+ return context.setValue(SENTRY_SCOPES_CONTEXT_KEY, scopes);
298
+ }
299
+
300
+ /**
301
+ * Set the context on the scope so we can later look it up.
302
+ * We need this to get the context from the scope in the `trace` functions.
303
+ */
304
+ function setContextOnScope(scope, context) {
305
+ SCOPE_CONTEXT_MAP.set(scope, context);
306
+ }
307
+
308
+ /**
309
+ * Get the context related to a scope.
310
+ * TODO v8: Use this for the `trace` functions.
311
+ * */
312
+ function getContextFromScope(scope) {
313
+ return SCOPE_CONTEXT_MAP.get(scope);
314
+ }
315
+
316
+ const setupElements = new Set();
317
+
318
+ /** Get all the OpenTelemetry elements that have been set up. */
319
+ function openTelemetrySetupCheck() {
320
+ return Array.from(setupElements);
321
+ }
322
+
323
+ /** Mark an OpenTelemetry element as setup. */
324
+ function setIsSetup(element) {
325
+ setupElements.add(element);
326
+ }
327
+
328
+ function _optionalChain$7(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
329
+
330
+ /** Get the Sentry propagation context from a span context. */
331
+ function getPropagationContextFromSpanContext(spanContext) {
332
+ const { traceId, spanId, traceState } = spanContext;
333
+
334
+ const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;
335
+ const dsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : undefined;
336
+ const parentSpanId = traceState ? traceState.get(SENTRY_TRACE_STATE_PARENT_SPAN_ID) : undefined;
337
+
338
+ const sampled = getSamplingDecision(spanContext);
339
+
340
+ return {
341
+ traceId,
342
+ spanId,
343
+ sampled,
344
+ parentSpanId,
345
+ dsc,
346
+ };
347
+ }
348
+
349
+ /**
350
+ * Injects and extracts `sentry-trace` and `baggage` headers from carriers.
351
+ */
352
+ class SentryPropagator extends W3CBaggagePropagator {
353
+ constructor() {
354
+ super();
355
+ setIsSetup('SentryPropagator');
356
+ }
357
+
358
+ /**
359
+ * @inheritDoc
360
+ */
361
+ inject(context, carrier, setter) {
362
+ if (isTracingSuppressed(context)) {
363
+ return;
364
+ }
365
+
366
+ let baggage = propagation.getBaggage(context) || propagation.createBaggage({});
367
+
368
+ const { dynamicSamplingContext, traceId, spanId, sampled } = getInjectionData(context);
369
+
370
+ if (dynamicSamplingContext) {
371
+ baggage = Object.entries(dynamicSamplingContext).reduce((b, [dscKey, dscValue]) => {
372
+ if (dscValue) {
373
+ return b.setEntry(`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`, { value: dscValue });
374
+ }
375
+ return b;
376
+ }, baggage);
377
+ }
378
+
379
+ setter.set(carrier, SENTRY_TRACE_HEADER, generateSentryTraceHeader(traceId, spanId, sampled));
380
+
381
+ super.inject(propagation.setBaggage(context, baggage), carrier, setter);
382
+ }
383
+
384
+ /**
385
+ * @inheritDoc
386
+ */
387
+ extract(context, carrier, getter) {
388
+ const maybeSentryTraceHeader = getter.get(carrier, SENTRY_TRACE_HEADER);
389
+ const baggage = getter.get(carrier, SENTRY_BAGGAGE_HEADER);
390
+
391
+ const sentryTrace = maybeSentryTraceHeader
392
+ ? Array.isArray(maybeSentryTraceHeader)
393
+ ? maybeSentryTraceHeader[0]
394
+ : maybeSentryTraceHeader
395
+ : undefined;
396
+
397
+ const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);
398
+
399
+ // Add remote parent span context,
400
+ const ctxWithSpanContext = getContextWithRemoteActiveSpan(context, { sentryTrace, baggage });
401
+
402
+ // Also update the scope on the context (to be sure this is picked up everywhere)
403
+ const scopes = getScopesFromContext(ctxWithSpanContext);
404
+ const newScopes = {
405
+ scope: scopes ? scopes.scope.clone() : getCurrentScope().clone(),
406
+ isolationScope: scopes ? scopes.isolationScope : getIsolationScope(),
407
+ };
408
+ newScopes.scope.setPropagationContext(propagationContext);
409
+
410
+ return setScopesOnContext(ctxWithSpanContext, newScopes);
411
+ }
412
+
413
+ /**
414
+ * @inheritDoc
415
+ */
416
+ fields() {
417
+ return [SENTRY_TRACE_HEADER, SENTRY_BAGGAGE_HEADER];
418
+ }
419
+ }
420
+
421
+ /** Exported for tests. */
422
+ function makeTraceState({
423
+ parentSpanId,
424
+ dsc,
425
+ sampled,
426
+ }
427
+
428
+ ) {
429
+ if (!parentSpanId && !dsc && sampled !== false) {
430
+ return undefined;
431
+ }
432
+
433
+ // We store the DSC as OTEL trace state on the span context
434
+ const dscString = dsc ? dynamicSamplingContextToSentryBaggageHeader(dsc) : undefined;
435
+
436
+ const traceStateBase = parentSpanId
437
+ ? new TraceState().set(SENTRY_TRACE_STATE_PARENT_SPAN_ID, parentSpanId)
438
+ : new TraceState();
439
+
440
+ const traceStateWithDsc = dscString ? traceStateBase.set(SENTRY_TRACE_STATE_DSC, dscString) : traceStateBase;
441
+
442
+ // We also specifically want to store if this is sampled to be not recording,
443
+ // or unsampled (=could be either sampled or not)
444
+ return sampled === false ? traceStateWithDsc.set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, '1') : traceStateWithDsc;
445
+ }
446
+
447
+ function getInjectionData(context)
448
+
449
+ {
450
+ const span = trace.getSpan(context);
451
+ const spanIsRemote = _optionalChain$7([span, 'optionalAccess', _ => _.spanContext, 'call', _2 => _2(), 'access', _3 => _3.isRemote]);
452
+
453
+ // If we have a local span, we can just pick everything from it
454
+ if (span && !spanIsRemote) {
455
+ const spanContext = span.spanContext();
456
+ const propagationContext = getPropagationContextFromSpanContext(spanContext);
457
+ const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, spanContext.traceId);
458
+ return {
459
+ dynamicSamplingContext,
460
+ traceId: spanContext.traceId,
461
+ spanId: spanContext.spanId,
462
+ sampled: getSamplingDecision(spanContext),
463
+ };
464
+ }
465
+
466
+ // Else we try to use the propagation context from the scope
467
+ const scope = _optionalChain$7([getScopesFromContext, 'call', _4 => _4(context), 'optionalAccess', _5 => _5.scope]);
468
+ if (scope) {
469
+ const propagationContext = scope.getPropagationContext();
470
+ const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, propagationContext.traceId);
471
+ return {
472
+ dynamicSamplingContext,
473
+ traceId: propagationContext.traceId,
474
+ spanId: propagationContext.spanId,
475
+ sampled: propagationContext.sampled,
476
+ };
477
+ }
478
+
479
+ // Else, we look at the remote span context
480
+ const spanContext = trace.getSpanContext(context);
481
+ if (spanContext) {
482
+ const propagationContext = getPropagationContextFromSpanContext(spanContext);
483
+ const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, spanContext.traceId);
484
+
485
+ return {
486
+ dynamicSamplingContext,
487
+ traceId: spanContext.traceId,
488
+ spanId: spanContext.spanId,
489
+ sampled: getSamplingDecision(spanContext),
490
+ };
491
+ }
492
+
493
+ // If we have neither, there is nothing much we can do, but that should not happen usually
494
+ // Unless there is a detached OTEL context being passed around
495
+ return {
496
+ dynamicSamplingContext: undefined,
497
+ traceId: undefined,
498
+ spanId: undefined,
499
+ sampled: undefined,
500
+ };
501
+ }
502
+
503
+ /** Get the DSC from a context, or fall back to use the one from the client. */
504
+ function getDynamicSamplingContext(
505
+ propagationContext,
506
+ traceId,
507
+ ) {
508
+ // If we have a DSC on the propagation context, we just use it
509
+ if (_optionalChain$7([propagationContext, 'optionalAccess', _6 => _6.dsc])) {
510
+ return propagationContext.dsc;
511
+ }
512
+
513
+ // Else, we try to generate a new one
514
+ const client = getClient();
515
+
516
+ if (client) {
517
+ return getDynamicSamplingContextFromClient(traceId || propagationContext.traceId, client);
518
+ }
519
+
520
+ return undefined;
521
+ }
522
+
523
+ function getContextWithRemoteActiveSpan(
524
+ ctx,
525
+ { sentryTrace, baggage },
526
+ ) {
527
+ const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);
528
+
529
+ // We store the DSC as OTEL trace state on the span context
530
+ const traceState = makeTraceState({
531
+ parentSpanId: propagationContext.parentSpanId,
532
+ dsc: propagationContext.dsc,
533
+ sampled: propagationContext.sampled,
534
+ });
535
+
536
+ const spanContext = {
537
+ traceId: propagationContext.traceId,
538
+ spanId: propagationContext.parentSpanId || '',
539
+ isRemote: true,
540
+ traceFlags: propagationContext.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
541
+ traceState,
542
+ };
543
+
544
+ return trace.setSpanContext(ctx, spanContext);
545
+ }
546
+
547
+ /**
548
+ * Takes trace strings and propagates them as a remote active span.
549
+ * This should be used in addition to `continueTrace` in OTEL-powered environments.
550
+ */
551
+ function continueTraceAsRemoteSpan(
552
+ ctx,
553
+ options,
554
+ callback,
555
+ ) {
556
+ const ctxWithSpanContext = getContextWithRemoteActiveSpan(ctx, options);
557
+
558
+ return context.with(ctxWithSpanContext, callback);
559
+ }
560
+
561
+ /**
562
+ * OpenTelemetry only knows about SAMPLED or NONE decision,
563
+ * but for us it is important to differentiate between unset and unsampled.
564
+ *
565
+ * Both of these are identified as `traceFlags === TracegFlags.NONE`,
566
+ * but we additionally look at a special trace state to differentiate between them.
567
+ */
568
+ function getSamplingDecision(spanContext) {
569
+ const { traceFlags, traceState } = spanContext;
570
+
571
+ const sampledNotRecording = traceState ? traceState.get(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING) === '1' : false;
572
+
573
+ // If trace flag is `SAMPLED`, we interpret this as sampled
574
+ // If it is `NONE`, it could mean either it was sampled to be not recorder, or that it was not sampled at all
575
+ // For us this is an important difference, sow e look at the SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING
576
+ // to identify which it is
577
+ if (traceFlags === TraceFlags.SAMPLED) {
578
+ return true;
579
+ }
580
+
581
+ if (sampledNotRecording) {
582
+ return false;
583
+ }
584
+
585
+ // Fall back to DSC as a last resort, that may also contain `sampled`...
586
+ const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;
587
+ const dsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : undefined;
588
+
589
+ if (_optionalChain$7([dsc, 'optionalAccess', _7 => _7.sampled]) === 'true') {
590
+ return true;
591
+ }
592
+ if (_optionalChain$7([dsc, 'optionalAccess', _8 => _8.sampled]) === 'false') {
593
+ return false;
594
+ }
595
+
596
+ return undefined;
597
+ }
598
+
599
+ function _optionalChain$6(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
600
+ /**
601
+ * Creates a dynamic sampling context from a span (and client and scope)
602
+ *
603
+ * @param span the span from which a few values like the root span name and sample rate are extracted.
604
+ *
605
+ * @returns a dynamic sampling context
606
+ */
607
+ function getDynamicSamplingContextFromSpan(span) {
608
+ const client = getClient();
609
+ if (!client) {
610
+ return {};
611
+ }
612
+
613
+ const traceState = span.spanContext().traceState;
614
+ const traceStateDsc = _optionalChain$6([traceState, 'optionalAccess', _ => _.get, 'call', _2 => _2(SENTRY_TRACE_STATE_DSC)]);
615
+
616
+ // If the span has a DSC, we want it to take precedence
617
+ const dscOnSpan = traceStateDsc ? baggageHeaderToDynamicSamplingContext(traceStateDsc) : undefined;
618
+
619
+ if (dscOnSpan) {
620
+ return dscOnSpan;
621
+ }
622
+
623
+ const dsc = getDynamicSamplingContextFromClient(span.spanContext().traceId, client);
624
+
625
+ const attributes = spanHasAttributes(span) ? span.attributes : {};
626
+
627
+ const sampleRate = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];
628
+ if (sampleRate != null) {
629
+ dsc.sample_rate = `${sampleRate}`;
630
+ }
631
+
632
+ // We don't want to have a transaction name in the DSC if the source is "url" because URLs might contain PII
633
+ const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
634
+ const name = spanHasName(span) ? span.name : '';
635
+
636
+ if (source !== 'url' && name) {
637
+ dsc.transaction = name;
638
+ }
639
+
640
+ const sampled = getSamplingDecision(span.spanContext());
641
+ if (sampled != null) {
642
+ dsc.sampled = String(sampled);
643
+ }
644
+
645
+ client.emit('createDsc', dsc);
646
+
647
+ return dsc;
648
+ }
649
+
650
+ /**
651
+ *
652
+ * @param otelSpan Checks wheter a given OTEL Span is an http request to sentry.
653
+ * @returns boolean
654
+ */
655
+ function isSentryRequestSpan(span) {
656
+ if (!spanHasAttributes(span)) {
657
+ return false;
658
+ }
659
+
660
+ const { attributes } = span;
661
+
662
+ const httpUrl = attributes[SemanticAttributes.HTTP_URL];
663
+
664
+ if (!httpUrl) {
665
+ return false;
666
+ }
667
+
668
+ return isSentryRequestUrl(httpUrl.toString(), getClient());
669
+ }
670
+
671
+ /**
672
+ * Returns the currently active span.
673
+ */
674
+ function getActiveSpan() {
675
+ return trace.getActiveSpan();
676
+ }
677
+
678
+ function _optionalChain$5(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
679
+
680
+ /**
681
+ * Wraps a function with a transaction/span and finishes the span after the function is done.
682
+ * The created span is the active span and will be used as parent by other spans created inside the function
683
+ * and can be accessed via `Sentry.getSpan()`, as long as the function is executed while the scope is active.
684
+ *
685
+ * If you want to create a span that is not set as active, use {@link startInactiveSpan}.
686
+ *
687
+ * Note that you'll always get a span passed to the callback, it may just be a NonRecordingSpan if the span is not sampled.
688
+ */
689
+ function startSpan(options, callback) {
690
+ const tracer = getTracer();
691
+
692
+ const { name } = options;
693
+
694
+ const activeCtx = getContext(options.scope, options.forceTransaction);
695
+ const shouldSkipSpan = options.onlyIfParent && !trace.getSpan(activeCtx);
696
+ const ctx = shouldSkipSpan ? suppressTracing(activeCtx) : activeCtx;
697
+
698
+ const spanContext = getSpanContext(options);
699
+
700
+ return tracer.startActiveSpan(name, spanContext, ctx, span => {
701
+ _applySentryAttributesToSpan(span, options);
702
+
703
+ return handleCallbackErrors(
704
+ () => callback(span),
705
+ () => {
706
+ span.setStatus({ code: SpanStatusCode.ERROR });
707
+ },
708
+ () => span.end(),
709
+ );
710
+ });
711
+ }
712
+
713
+ /**
714
+ * Similar to `Sentry.startSpan`. Wraps a function with a span, but does not finish the span
715
+ * after the function is done automatically. You'll have to call `span.end()` manually.
716
+ *
717
+ * The created span is the active span and will be used as parent by other spans created inside the function
718
+ * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.
719
+ *
720
+ * Note that you'll always get a span passed to the callback, it may just be a NonRecordingSpan if the span is not sampled.
721
+ */
722
+ function startSpanManual(
723
+ options,
724
+ callback,
725
+ ) {
726
+ const tracer = getTracer();
727
+
728
+ const { name } = options;
729
+
730
+ const activeCtx = getContext(options.scope, options.forceTransaction);
731
+ const shouldSkipSpan = options.onlyIfParent && !trace.getSpan(activeCtx);
732
+ const ctx = shouldSkipSpan ? suppressTracing(activeCtx) : activeCtx;
733
+
734
+ const spanContext = getSpanContext(options);
735
+
736
+ return tracer.startActiveSpan(name, spanContext, ctx, span => {
737
+ _applySentryAttributesToSpan(span, options);
738
+
739
+ return handleCallbackErrors(
740
+ () => callback(span, () => span.end()),
741
+ () => {
742
+ span.setStatus({ code: SpanStatusCode.ERROR });
743
+ },
744
+ );
745
+ });
746
+ }
747
+
748
+ /**
749
+ * Creates a span. This span is not set as active, so will not get automatic instrumentation spans
750
+ * as children or be able to be accessed via `Sentry.getSpan()`.
751
+ *
752
+ * If you want to create a span that is set as active, use {@link startSpan}.
753
+ *
754
+ * Note that if you have not enabled tracing extensions via `addTracingExtensions`
755
+ * or you didn't set `tracesSampleRate` or `tracesSampler`, this function will not generate spans
756
+ * and the `span` returned from the callback will be undefined.
757
+ */
758
+ function startInactiveSpan(options) {
759
+ const tracer = getTracer();
760
+
761
+ const { name } = options;
762
+
763
+ const activeCtx = getContext(options.scope, options.forceTransaction);
764
+ const shouldSkipSpan = options.onlyIfParent && !trace.getSpan(activeCtx);
765
+ const ctx = shouldSkipSpan ? suppressTracing(activeCtx) : activeCtx;
766
+
767
+ const spanContext = getSpanContext(options);
768
+
769
+ const span = tracer.startSpan(name, spanContext, ctx);
770
+
771
+ _applySentryAttributesToSpan(span, options);
772
+
773
+ return span;
774
+ }
775
+
776
+ /**
777
+ * Forks the current scope and sets the provided span as active span in the context of the provided callback. Can be
778
+ * passed `null` to start an entirely new span tree.
779
+ *
780
+ * @param span Spans started in the context of the provided callback will be children of this span. If `null` is passed,
781
+ * spans started within the callback will not be attached to a parent span.
782
+ * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.
783
+ * @returns the value returned from the provided callback function.
784
+ */
785
+ function withActiveSpan(span, callback) {
786
+ const newContextWithActiveSpan = span ? trace.setSpan(context.active(), span) : trace.deleteSpan(context.active());
787
+ return context.with(newContextWithActiveSpan, () => callback(getCurrentScope()));
788
+ }
789
+
790
+ function getTracer() {
791
+ const client = getClient();
792
+ return (client && client.tracer) || trace.getTracer('@sentry/opentelemetry', SDK_VERSION);
793
+ }
794
+
795
+ function _applySentryAttributesToSpan(span, options) {
796
+ const { op } = options;
797
+
798
+ if (op) {
799
+ span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, op);
800
+ }
801
+ }
802
+
803
+ function getSpanContext(options) {
804
+ const { startTime, attributes, kind } = options;
805
+
806
+ // OTEL expects timestamps in ms, not seconds
807
+ const fixedStartTime = typeof startTime === 'number' ? ensureTimestampInMilliseconds(startTime) : startTime;
808
+
809
+ return {
810
+ attributes,
811
+ kind,
812
+ startTime: fixedStartTime,
813
+ };
814
+ }
815
+
816
+ function ensureTimestampInMilliseconds(timestamp) {
817
+ const isMs = timestamp < 9999999999;
818
+ return isMs ? timestamp * 1000 : timestamp;
819
+ }
820
+
821
+ function getContext(scope, forceTransaction) {
822
+ const ctx = getContextForScope(scope);
823
+ const actualScope = _optionalChain$5([getScopesFromContext, 'call', _ => _(ctx), 'optionalAccess', _2 => _2.scope]);
824
+
825
+ const parentSpan = trace.getSpan(ctx);
826
+
827
+ // In the case that we have no parent span, we need to "simulate" one to ensure the propagation context is correct
828
+ if (!parentSpan) {
829
+ const client = getClient();
830
+
831
+ if (actualScope && client) {
832
+ const propagationContext = actualScope.getPropagationContext();
833
+ const dynamicSamplingContext =
834
+ propagationContext.dsc || getDynamicSamplingContextFromClient(propagationContext.traceId, client);
835
+
836
+ // We store the DSC as OTEL trace state on the span context
837
+ const traceState = makeTraceState({
838
+ parentSpanId: propagationContext.parentSpanId,
839
+ dsc: dynamicSamplingContext,
840
+ sampled: propagationContext.sampled,
841
+ });
842
+
843
+ const spanContext = {
844
+ traceId: propagationContext.traceId,
845
+ spanId: propagationContext.parentSpanId || propagationContext.spanId,
846
+ isRemote: true,
847
+ traceFlags: propagationContext.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
848
+ traceState,
849
+ };
850
+
851
+ // Add remote parent span context,
852
+ return trace.setSpanContext(ctx, spanContext);
853
+ }
854
+
855
+ // if we have no scope or client, we just return the context as-is
856
+ return ctx;
857
+ }
858
+
859
+ // If we don't want to force a transaction, and we have a parent span, all good, we just return as-is!
860
+ if (!forceTransaction) {
861
+ return ctx;
862
+ }
863
+
864
+ // Else, if we do have a parent span but want to force a transaction, we have to simulate a "root" context
865
+
866
+ // Else, we need to do two things:
867
+ // 1. Unset the parent span from the context, so we'll create a new root span
868
+ // 2. Ensure the propagation context is correct, so we'll continue from the parent span
869
+ const ctxWithoutSpan = trace.deleteSpan(ctx);
870
+
871
+ const { spanId, traceId } = parentSpan.spanContext();
872
+ const sampled = getSamplingDecision(parentSpan.spanContext());
873
+
874
+ const rootSpan = getRootSpan(parentSpan);
875
+ const dsc = getDynamicSamplingContextFromSpan(rootSpan);
876
+
877
+ const traceState = makeTraceState({
878
+ dsc,
879
+ parentSpanId: spanId,
880
+ sampled,
881
+ });
882
+
883
+ const spanContext = {
884
+ traceId,
885
+ spanId,
886
+ isRemote: true,
887
+ traceFlags: sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
888
+ traceState,
889
+ };
890
+
891
+ const ctxWithSpanContext = trace.setSpanContext(ctxWithoutSpan, spanContext);
892
+
893
+ return ctxWithSpanContext;
894
+ }
895
+
896
+ function getContextForScope(scope) {
897
+ if (scope) {
898
+ const ctx = getContextFromScope(scope);
899
+ if (ctx) {
900
+ return ctx;
901
+ }
902
+ }
903
+
904
+ return context.active();
905
+ }
906
+
907
+ /**
908
+ * Continue a trace from `sentry-trace` and `baggage` values.
909
+ * These values can be obtained from incoming request headers, or in the browser from `<meta name="sentry-trace">`
910
+ * and `<meta name="baggage">` HTML tags.
911
+ *
912
+ * Spans started with `startSpan`, `startSpanManual` and `startInactiveSpan`, within the callback will automatically
913
+ * be attached to the incoming trace.
914
+ *
915
+ * This is a custom version of `continueTrace` that is used in OTEL-powered environments.
916
+ * It propagates the trace as a remote span, in addition to setting it on the propagation context.
917
+ */
918
+ function continueTrace(options, callback) {
919
+ return continueTrace$1(options, () => {
920
+ return continueTraceAsRemoteSpan(context.active(), options, callback);
921
+ });
922
+ }
923
+
924
+ /**
925
+ * Ensure the global hub is setup.
926
+ *
927
+ * @deprecated This will be removed in the next major version.
928
+ */
929
+ function setupGlobalHub() {
930
+ // noop
931
+ }
932
+
933
+ function _optionalChain$4(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
934
+
935
+ /**
936
+ * This is for legacy reasons, and returns a proxy object instead of a hub to be used.
937
+ * @deprecated Use the methods directly.
938
+ */
939
+ function getCurrentHub() {
940
+ return {
941
+ isOlderThan(_version) {
942
+ return false;
943
+ },
944
+
945
+ bindClient(client) {
946
+ const scope = getCurrentScope();
947
+ scope.setClient(client);
948
+ },
949
+
950
+ pushScope() {
951
+ // TODO: This does not work and is actually deprecated
952
+ return getCurrentScope();
953
+ },
954
+
955
+ popScope() {
956
+ // TODO: This does not work and is actually deprecated
957
+ return false;
958
+ },
959
+
960
+ withScope,
961
+ getClient: () => getClient() ,
962
+ getScope: getCurrentScope,
963
+ getIsolationScope,
964
+ captureException: (exception, hint) => {
965
+ return getCurrentScope().captureException(exception, hint);
966
+ },
967
+ captureMessage: (message, level, hint) => {
968
+ return getCurrentScope().captureMessage(message, level, hint);
969
+ },
970
+ captureEvent,
971
+ addBreadcrumb,
972
+ setUser,
973
+ setTags,
974
+ setTag,
975
+ setExtra,
976
+ setExtras,
977
+ setContext,
978
+
979
+ getIntegration(integration) {
980
+ // eslint-disable-next-line deprecation/deprecation
981
+ return _optionalChain$4([getClient, 'call', _ => _(), 'optionalAccess', _2 => _2.getIntegration, 'call', _3 => _3(integration)]) || null;
982
+ },
983
+
984
+ startSession,
985
+
986
+ endSession,
987
+
988
+ captureSession(endSession) {
989
+ // both send the update and pull the session from the scope
990
+ if (endSession) {
991
+ // eslint-disable-next-line deprecation/deprecation
992
+ return this.endSession();
993
+ }
994
+
995
+ // only send the update
996
+ _sendSessionUpdate();
997
+ },
998
+
999
+ shouldSendDefaultPii() {
1000
+ const client = getClient();
1001
+ return Boolean(client ? client.getOptions().sendDefaultPii : false);
1002
+ },
1003
+ };
1004
+ }
1005
+
1006
+ /**
1007
+ * Sends the current Session on the scope
1008
+ */
1009
+ function _sendSessionUpdate() {
1010
+ const scope = getCurrentScope();
1011
+ const client = getClient();
1012
+
1013
+ const session = scope.getSession();
1014
+ if (client && session) {
1015
+ client.captureSession(session);
1016
+ }
1017
+ }
1018
+
1019
+ /** Ensure the `trace` context is set on all events. */
1020
+ function setupEventContextTrace(client) {
1021
+ client.addEventProcessor(event => {
1022
+ const span = getActiveSpan();
1023
+ // For transaction events, this is handled separately
1024
+ // Because the active span may not be the span that is actually the transaction event
1025
+ if (!span || event.type === 'transaction') {
1026
+ return event;
1027
+ }
1028
+
1029
+ const spanContext = span.spanContext();
1030
+
1031
+ // If event has already set `trace` context, use that one.
1032
+ event.contexts = {
1033
+ trace: dropUndefinedKeys({
1034
+ trace_id: spanContext.traceId,
1035
+ span_id: spanContext.spanId,
1036
+ parent_span_id: spanHasParentId(span) ? span.parentSpanId : undefined,
1037
+ }),
1038
+ ...event.contexts,
1039
+ };
1040
+
1041
+ const rootSpan = getRootSpan(span);
1042
+ const transactionName = spanHasName(rootSpan) ? rootSpan.name : undefined;
1043
+ if (transactionName && !event.transaction) {
1044
+ event.transaction = transactionName;
1045
+ }
1046
+
1047
+ return event;
1048
+ });
1049
+ }
1050
+
1051
+ /**
1052
+ * Sets the async context strategy to use follow the OTEL context under the hood.
1053
+ * We handle forking a hub inside of our custom OTEL Context Manager (./otelContextManager.ts)
1054
+ */
1055
+ function setOpenTelemetryContextAsyncContextStrategy() {
1056
+ function getScopes() {
1057
+ const ctx = api.context.active();
1058
+ const scopes = getScopesFromContext(ctx);
1059
+
1060
+ if (scopes) {
1061
+ return scopes;
1062
+ }
1063
+
1064
+ // fallback behavior:
1065
+ // if, for whatever reason, we can't find scopes on the context here, we have to fix this somehow
1066
+ return {
1067
+ scope: getDefaultCurrentScope(),
1068
+ isolationScope: getDefaultIsolationScope(),
1069
+ };
1070
+ }
1071
+
1072
+ function getCurrentHub$1() {
1073
+ // eslint-disable-next-line deprecation/deprecation
1074
+ const hub = getCurrentHub();
1075
+ return {
1076
+ ...hub,
1077
+ getScope: () => {
1078
+ const scopes = getScopes();
1079
+ return scopes.scope;
1080
+ },
1081
+ getIsolationScope: () => {
1082
+ const scopes = getScopes();
1083
+ return scopes.isolationScope;
1084
+ },
1085
+ };
1086
+ }
1087
+
1088
+ function withScope(callback) {
1089
+ const ctx = api.context.active();
1090
+
1091
+ // We depend on the otelContextManager to handle the context/hub
1092
+ // We set the `SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY` context value, which is picked up by
1093
+ // the OTEL context manager, which uses the presence of this key to determine if it should
1094
+ // fork the isolation scope, or not
1095
+ // as by default, we don't want to fork this, unless triggered explicitly by `withScope`
1096
+ return api.context.with(ctx, () => {
1097
+ return callback(getCurrentScope());
1098
+ });
1099
+ }
1100
+
1101
+ function withSetScope(scope, callback) {
1102
+ const ctx = api.context.active();
1103
+
1104
+ // We depend on the otelContextManager to handle the context/hub
1105
+ // We set the `SENTRY_FORK_SET_SCOPE_CONTEXT_KEY` context value, which is picked up by
1106
+ // the OTEL context manager, which picks up this scope as the current scope
1107
+ return api.context.with(ctx.setValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY, scope), () => {
1108
+ return callback(scope);
1109
+ });
1110
+ }
1111
+
1112
+ function withIsolationScope(callback) {
1113
+ const ctx = api.context.active();
1114
+
1115
+ // We depend on the otelContextManager to handle the context/hub
1116
+ // We set the `SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY` context value, which is picked up by
1117
+ // the OTEL context manager, which uses the presence of this key to determine if it should
1118
+ // fork the isolation scope, or not
1119
+ return api.context.with(ctx.setValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY, true), () => {
1120
+ return callback(getIsolationScope());
1121
+ });
1122
+ }
1123
+
1124
+ function withSetIsolationScope(isolationScope, callback) {
1125
+ const ctx = api.context.active();
1126
+
1127
+ // We depend on the otelContextManager to handle the context/hub
1128
+ // We set the `SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY` context value, which is picked up by
1129
+ // the OTEL context manager, which uses the presence of this key to determine if it should
1130
+ // fork the isolation scope, or not
1131
+ return api.context.with(ctx.setValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY, isolationScope), () => {
1132
+ return callback(getIsolationScope());
1133
+ });
1134
+ }
1135
+
1136
+ function getCurrentScope() {
1137
+ return getScopes().scope;
1138
+ }
1139
+
1140
+ function getIsolationScope() {
1141
+ return getScopes().isolationScope;
1142
+ }
1143
+
1144
+ setAsyncContextStrategy({
1145
+ getCurrentHub: getCurrentHub$1,
1146
+ withScope,
1147
+ withSetScope,
1148
+ withSetIsolationScope,
1149
+ withIsolationScope,
1150
+ getCurrentScope,
1151
+ getIsolationScope,
1152
+ startSpan,
1153
+ startSpanManual,
1154
+ startInactiveSpan,
1155
+ getActiveSpan,
1156
+ // The types here don't fully align, because our own `Span` type is narrower
1157
+ // than the OTEL one - but this is OK for here, as we now we'll only have OTEL spans passed around
1158
+ withActiveSpan: withActiveSpan ,
1159
+ });
1160
+ }
1161
+
1162
+ function _optionalChain$3(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
1163
+
1164
+ /**
1165
+ * Wrap an OpenTelemetry ContextManager in a way that ensures the context is kept in sync with the Sentry Hub.
1166
+ *
1167
+ * Usage:
1168
+ * import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';
1169
+ * const SentryContextManager = wrapContextManagerClass(AsyncLocalStorageContextManager);
1170
+ * const contextManager = new SentryContextManager();
1171
+ */
1172
+ function wrapContextManagerClass(
1173
+ ContextManagerClass,
1174
+ ) {
1175
+ /**
1176
+ * This is a custom ContextManager for OpenTelemetry, which extends the default AsyncLocalStorageContextManager.
1177
+ * It ensures that we create a new hub per context, so that the OTEL Context & the Sentry Hub are always in sync.
1178
+ *
1179
+ * Note that we currently only support AsyncHooks with this,
1180
+ * but since this should work for Node 14+ anyhow that should be good enough.
1181
+ */
1182
+
1183
+ // @ts-expect-error TS does not like this, but we know this is fine
1184
+ class SentryContextManager extends ContextManagerClass {
1185
+ constructor() {
1186
+ super();
1187
+ setIsSetup('SentryContextManager');
1188
+ }
1189
+ /**
1190
+ * Overwrite with() of the original AsyncLocalStorageContextManager
1191
+ * to ensure we also create a new hub per context.
1192
+ */
1193
+ with(
1194
+ context,
1195
+ fn,
1196
+ thisArg,
1197
+ ...args
1198
+ ) {
1199
+ const currentScopes = getScopesFromContext(context);
1200
+ const currentScope = _optionalChain$3([currentScopes, 'optionalAccess', _ => _.scope]) || getCurrentScope();
1201
+ const currentIsolationScope = _optionalChain$3([currentScopes, 'optionalAccess', _2 => _2.isolationScope]) || getIsolationScope();
1202
+
1203
+ const shouldForkIsolationScope = context.getValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY) === true;
1204
+ const scope = context.getValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY) ;
1205
+ const isolationScope = context.getValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY) ;
1206
+
1207
+ const newCurrentScope = scope || currentScope.clone();
1208
+ const newIsolationScope =
1209
+ isolationScope || (shouldForkIsolationScope ? currentIsolationScope.clone() : currentIsolationScope);
1210
+ const scopes = { scope: newCurrentScope, isolationScope: newIsolationScope };
1211
+
1212
+ const ctx1 = setScopesOnContext(context, scopes);
1213
+
1214
+ // Remove the unneeded values again
1215
+ const ctx2 = ctx1
1216
+ .deleteValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY)
1217
+ .deleteValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY)
1218
+ .deleteValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY);
1219
+
1220
+ setContextOnScope(newCurrentScope, ctx2);
1221
+
1222
+ return super.with(ctx2, fn, thisArg, ...args);
1223
+ }
1224
+ }
1225
+
1226
+ return SentryContextManager ;
1227
+ }
1228
+
1229
+ /**
1230
+ * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.
1231
+ *
1232
+ * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
1233
+ */
1234
+ const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);
1235
+
1236
+ /** If this attribute is true, it means that the parent is a remote span. */
1237
+ const SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE = 'sentry.parentIsRemote';
1238
+
1239
+ /** Convert an OTEL time to seconds */
1240
+ function convertOtelTimeToSeconds([seconds, nano]) {
1241
+ return seconds + nano / 1000000000;
1242
+ }
1243
+
1244
+ /**
1245
+ * This function runs through a list of OTEL Spans, and wraps them in an `SpanNode`
1246
+ * where each node holds a reference to their parent node.
1247
+ */
1248
+ function groupSpansWithParents(spans) {
1249
+ const nodeMap = new Map();
1250
+
1251
+ for (const span of spans) {
1252
+ createOrUpdateSpanNodeAndRefs(nodeMap, span);
1253
+ }
1254
+
1255
+ return Array.from(nodeMap, function ([_id, spanNode]) {
1256
+ return spanNode;
1257
+ });
1258
+ }
1259
+
1260
+ function createOrUpdateSpanNodeAndRefs(nodeMap, span) {
1261
+ const parentIsRemote = span.attributes[SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE] === true;
1262
+
1263
+ const id = span.spanContext().spanId;
1264
+
1265
+ // If the parentId is the trace parent ID, we pretend it's undefined
1266
+ // As this means the parent exists somewhere else
1267
+ const parentId = !parentIsRemote ? span.parentSpanId : undefined;
1268
+
1269
+ if (!parentId) {
1270
+ createOrUpdateNode(nodeMap, { id, span, children: [] });
1271
+ return;
1272
+ }
1273
+
1274
+ // Else make sure to create parent node as well
1275
+ // Note that the parent may not know it's parent _yet_, this may be updated in a later pass
1276
+ const parentNode = createOrGetParentNode(nodeMap, parentId);
1277
+ const node = createOrUpdateNode(nodeMap, { id, span, parentNode, children: [] });
1278
+ parentNode.children.push(node);
1279
+ }
1280
+
1281
+ function createOrGetParentNode(nodeMap, id) {
1282
+ const existing = nodeMap.get(id);
1283
+
1284
+ if (existing) {
1285
+ return existing;
1286
+ }
1287
+
1288
+ return createOrUpdateNode(nodeMap, { id, children: [] });
1289
+ }
1290
+
1291
+ function createOrUpdateNode(nodeMap, spanNode) {
1292
+ const existing = nodeMap.get(spanNode.id);
1293
+
1294
+ // If span is already set, nothing to do here
1295
+ if (existing && existing.span) {
1296
+ return existing;
1297
+ }
1298
+
1299
+ // If it exists but span is not set yet, we update it
1300
+ if (existing && !existing.span) {
1301
+ existing.span = spanNode.span;
1302
+ existing.parentNode = spanNode.parentNode;
1303
+ return existing;
1304
+ }
1305
+
1306
+ // Else, we create a new one...
1307
+ nodeMap.set(spanNode.id, spanNode);
1308
+ return spanNode;
1309
+ }
1310
+
1311
+ // canonicalCodesHTTPMap maps some HTTP codes to Sentry's span statuses. See possible mapping in https://develop.sentry.dev/sdk/event-payloads/span/
1312
+ const canonicalCodesHTTPMap = {
1313
+ '400': 'failed_precondition',
1314
+ '401': 'unauthenticated',
1315
+ '403': 'permission_denied',
1316
+ '404': 'not_found',
1317
+ '409': 'aborted',
1318
+ '429': 'resource_exhausted',
1319
+ '499': 'cancelled',
1320
+ '500': 'internal_error',
1321
+ '501': 'unimplemented',
1322
+ '503': 'unavailable',
1323
+ '504': 'deadline_exceeded',
1324
+ } ;
1325
+
1326
+ // canonicalCodesGrpcMap maps some GRPC codes to Sentry's span statuses. See description in grpc documentation.
1327
+ const canonicalCodesGrpcMap = {
1328
+ '1': 'cancelled',
1329
+ '2': 'unknown_error',
1330
+ '3': 'invalid_argument',
1331
+ '4': 'deadline_exceeded',
1332
+ '5': 'not_found',
1333
+ '6': 'already_exists',
1334
+ '7': 'permission_denied',
1335
+ '8': 'resource_exhausted',
1336
+ '9': 'failed_precondition',
1337
+ '10': 'aborted',
1338
+ '11': 'out_of_range',
1339
+ '12': 'unimplemented',
1340
+ '13': 'internal_error',
1341
+ '14': 'unavailable',
1342
+ '15': 'data_loss',
1343
+ '16': 'unauthenticated',
1344
+ } ;
1345
+
1346
+ /**
1347
+ * Get a Sentry span status from an otel span.
1348
+ */
1349
+ function mapStatus(span) {
1350
+ const attributes = spanHasAttributes(span) ? span.attributes : {};
1351
+ const status = spanHasStatus(span) ? span.status : undefined;
1352
+
1353
+ const httpCode = attributes[SemanticAttributes.HTTP_STATUS_CODE];
1354
+ const grpcCode = attributes[SemanticAttributes.RPC_GRPC_STATUS_CODE];
1355
+
1356
+ const code = typeof httpCode === 'string' ? httpCode : typeof httpCode === 'number' ? httpCode.toString() : undefined;
1357
+ if (code) {
1358
+ const sentryStatus = canonicalCodesHTTPMap[code];
1359
+ if (sentryStatus) {
1360
+ return { code: SPAN_STATUS_ERROR, message: sentryStatus };
1361
+ }
1362
+ }
1363
+
1364
+ if (typeof grpcCode === 'string') {
1365
+ const sentryStatus = canonicalCodesGrpcMap[grpcCode];
1366
+ if (sentryStatus) {
1367
+ return { code: SPAN_STATUS_ERROR, message: sentryStatus };
1368
+ }
1369
+ }
1370
+
1371
+ const statusCode = status && status.code;
1372
+ if (statusCode === SpanStatusCode.OK || statusCode === SpanStatusCode.UNSET) {
1373
+ return { code: SPAN_STATUS_OK };
1374
+ }
1375
+
1376
+ return { code: SPAN_STATUS_ERROR, message: 'unknown_error' };
1377
+ }
1378
+
1379
+ /**
1380
+ * Extract better op/description from an otel span.
1381
+ *
1382
+ * Based on https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/7422ce2a06337f68a59b552b8c5a2ac125d6bae5/exporter/sentryexporter/sentry_exporter.go#L306
1383
+ */
1384
+ function parseSpanDescription(span) {
1385
+ const attributes = spanHasAttributes(span) ? span.attributes : {};
1386
+ const name = spanHasName(span) ? span.name : '<unknown>';
1387
+
1388
+ // if http.method exists, this is an http request span
1389
+ const httpMethod = attributes[SemanticAttributes.HTTP_METHOD];
1390
+ if (httpMethod) {
1391
+ return descriptionForHttpMethod({ attributes, name, kind: getSpanKind(span) }, httpMethod);
1392
+ }
1393
+
1394
+ // If db.type exists then this is a database call span.
1395
+ const dbSystem = attributes[SemanticAttributes.DB_SYSTEM];
1396
+ if (dbSystem) {
1397
+ return descriptionForDbSystem({ attributes, name });
1398
+ }
1399
+
1400
+ // If rpc.service exists then this is a rpc call span.
1401
+ const rpcService = attributes[SemanticAttributes.RPC_SERVICE];
1402
+ if (rpcService) {
1403
+ return {
1404
+ op: 'rpc',
1405
+ description: name,
1406
+ source: 'route',
1407
+ };
1408
+ }
1409
+
1410
+ // If messaging.system exists then this is a messaging system span.
1411
+ const messagingSystem = attributes[SemanticAttributes.MESSAGING_SYSTEM];
1412
+ if (messagingSystem) {
1413
+ return {
1414
+ op: 'message',
1415
+ description: name,
1416
+ source: 'route',
1417
+ };
1418
+ }
1419
+
1420
+ // If faas.trigger exists then this is a function as a service span.
1421
+ const faasTrigger = attributes[SemanticAttributes.FAAS_TRIGGER];
1422
+ if (faasTrigger) {
1423
+ return { op: faasTrigger.toString(), description: name, source: 'route' };
1424
+ }
1425
+
1426
+ return { op: undefined, description: name, source: 'custom' };
1427
+ }
1428
+
1429
+ function descriptionForDbSystem({ attributes, name }) {
1430
+ // Use DB statement (Ex "SELECT * FROM table") if possible as description.
1431
+ const statement = attributes[SemanticAttributes.DB_STATEMENT];
1432
+
1433
+ const description = statement ? statement.toString() : name;
1434
+
1435
+ return { op: 'db', description, source: 'task' };
1436
+ }
1437
+
1438
+ /** Only exported for tests. */
1439
+ function descriptionForHttpMethod(
1440
+ { name, kind, attributes },
1441
+ httpMethod,
1442
+ ) {
1443
+ const opParts = ['http'];
1444
+
1445
+ switch (kind) {
1446
+ case SpanKind.CLIENT:
1447
+ opParts.push('client');
1448
+ break;
1449
+ case SpanKind.SERVER:
1450
+ opParts.push('server');
1451
+ break;
1452
+ }
1453
+
1454
+ const { urlPath, url, query, fragment, hasRoute } = getSanitizedUrl(attributes, kind);
1455
+
1456
+ if (!urlPath) {
1457
+ return { op: opParts.join('.'), description: name, source: 'custom' };
1458
+ }
1459
+
1460
+ // Ex. description="GET /api/users".
1461
+ const description = `${httpMethod} ${urlPath}`;
1462
+
1463
+ // If `httpPath` is a root path, then we can categorize the transaction source as route.
1464
+ const source = hasRoute || urlPath === '/' ? 'route' : 'url';
1465
+
1466
+ const data = {};
1467
+
1468
+ if (url) {
1469
+ data.url = url;
1470
+ }
1471
+ if (query) {
1472
+ data['http.query'] = query;
1473
+ }
1474
+ if (fragment) {
1475
+ data['http.fragment'] = fragment;
1476
+ }
1477
+
1478
+ return {
1479
+ op: opParts.join('.'),
1480
+ description,
1481
+ source,
1482
+ data,
1483
+ };
1484
+ }
1485
+
1486
+ /** Exported for tests only */
1487
+ function getSanitizedUrl(
1488
+ attributes,
1489
+ kind,
1490
+ )
1491
+
1492
+ {
1493
+ // This is the relative path of the URL, e.g. /sub
1494
+ const httpTarget = attributes[SemanticAttributes.HTTP_TARGET];
1495
+ // This is the full URL, including host & query params etc., e.g. https://example.com/sub?foo=bar
1496
+ const httpUrl = attributes[SemanticAttributes.HTTP_URL];
1497
+ // This is the normalized route name - may not always be available!
1498
+ const httpRoute = attributes[SemanticAttributes.HTTP_ROUTE];
1499
+
1500
+ const parsedUrl = typeof httpUrl === 'string' ? parseUrl(httpUrl) : undefined;
1501
+ const url = parsedUrl ? getSanitizedUrlString(parsedUrl) : undefined;
1502
+ const query = parsedUrl && parsedUrl.search ? parsedUrl.search : undefined;
1503
+ const fragment = parsedUrl && parsedUrl.hash ? parsedUrl.hash : undefined;
1504
+
1505
+ if (typeof httpRoute === 'string') {
1506
+ return { urlPath: httpRoute, url, query, fragment, hasRoute: true };
1507
+ }
1508
+
1509
+ if (kind === SpanKind.SERVER && typeof httpTarget === 'string') {
1510
+ return { urlPath: stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };
1511
+ }
1512
+
1513
+ if (parsedUrl) {
1514
+ return { urlPath: url, url, query, fragment, hasRoute: false };
1515
+ }
1516
+
1517
+ // fall back to target even for client spans, if no URL is present
1518
+ if (typeof httpTarget === 'string') {
1519
+ return { urlPath: stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };
1520
+ }
1521
+
1522
+ return { urlPath: undefined, url, query, fragment, hasRoute: false };
1523
+ }
1524
+
1525
+ function _optionalChain$2(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
1526
+
1527
+ /**
1528
+ * A Sentry-specific exporter that converts OpenTelemetry Spans to Sentry Spans & Transactions.
1529
+ */
1530
+ class SentrySpanExporter {
1531
+
1532
+ constructor() {
1533
+ this._stopped = false;
1534
+ this._finishedSpans = [];
1535
+ }
1536
+
1537
+ /** @inheritDoc */
1538
+ export(spans, resultCallback) {
1539
+ if (this._stopped) {
1540
+ return resultCallback({
1541
+ code: ExportResultCode.FAILED,
1542
+ error: new Error('Exporter has been stopped'),
1543
+ });
1544
+ }
1545
+
1546
+ const openSpanCount = this._finishedSpans.length;
1547
+ const newSpanCount = spans.length;
1548
+
1549
+ this._finishedSpans.push(...spans);
1550
+
1551
+ const remainingSpans = maybeSend(this._finishedSpans);
1552
+
1553
+ const remainingOpenSpanCount = remainingSpans.length;
1554
+ const sentSpanCount = openSpanCount + newSpanCount - remainingOpenSpanCount;
1555
+
1556
+ DEBUG_BUILD &&
1557
+ logger.log(`SpanExporter exported ${sentSpanCount} spans, ${remainingOpenSpanCount} unsent spans remaining`);
1558
+
1559
+ this._finishedSpans = remainingSpans.filter(span => {
1560
+ const shouldDrop = shouldCleanupSpan(span, 5 * 60);
1561
+ DEBUG_BUILD &&
1562
+ shouldDrop &&
1563
+ logger.log(
1564
+ `SpanExporter dropping span ${span.name} (${
1565
+ span.spanContext().spanId
1566
+ }) because it is pending for more than 5 minutes.`,
1567
+ );
1568
+ return !shouldDrop;
1569
+ });
1570
+
1571
+ resultCallback({ code: ExportResultCode.SUCCESS });
1572
+ }
1573
+
1574
+ /** @inheritDoc */
1575
+ shutdown() {
1576
+ const forceFlush = this.forceFlush();
1577
+ this._stopped = true;
1578
+ this._finishedSpans = [];
1579
+ return forceFlush;
1580
+ }
1581
+
1582
+ /** @inheritDoc */
1583
+ forceFlush() {
1584
+ return new Promise(resolve => {
1585
+ this.export(this._finishedSpans, () => resolve());
1586
+ });
1587
+ }
1588
+ }
1589
+
1590
+ /**
1591
+ * Send the given spans, but only if they are part of a finished transaction.
1592
+ *
1593
+ * Returns the unsent spans.
1594
+ * Spans remain unsent when their parent span is not yet finished.
1595
+ * This will happen regularly, as child spans are generally finished before their parents.
1596
+ * But it _could_ also happen because, for whatever reason, a parent span was lost.
1597
+ * In this case, we'll eventually need to clean this up.
1598
+ */
1599
+ function maybeSend(spans) {
1600
+ const grouped = groupSpansWithParents(spans);
1601
+ const remaining = new Set(grouped);
1602
+
1603
+ const rootNodes = getCompletedRootNodes(grouped);
1604
+
1605
+ rootNodes.forEach(root => {
1606
+ remaining.delete(root);
1607
+ const span = root.span;
1608
+ const transactionEvent = createTransactionForOtelSpan(span);
1609
+
1610
+ // We'll recursively add all the child spans to this array
1611
+ const spans = transactionEvent.spans || [];
1612
+
1613
+ root.children.forEach(child => {
1614
+ createAndFinishSpanForOtelSpan(child, spans, remaining);
1615
+ });
1616
+
1617
+ transactionEvent.spans = spans;
1618
+
1619
+ // TODO Measurements are not yet implemented in OTEL
1620
+
1621
+ captureEvent(transactionEvent);
1622
+ });
1623
+
1624
+ return Array.from(remaining)
1625
+ .map(node => node.span)
1626
+ .filter((span) => !!span);
1627
+ }
1628
+
1629
+ function getCompletedRootNodes(nodes) {
1630
+ return nodes.filter((node) => !!node.span && !node.parentNode);
1631
+ }
1632
+
1633
+ function shouldCleanupSpan(span, maxStartTimeOffsetSeconds) {
1634
+ const cutoff = Date.now() / 1000 - maxStartTimeOffsetSeconds;
1635
+ return convertOtelTimeToSeconds(span.startTime) < cutoff;
1636
+ }
1637
+
1638
+ function parseSpan(span) {
1639
+ const attributes = span.attributes;
1640
+
1641
+ const origin = attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] ;
1642
+ const op = attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] ;
1643
+ const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] ;
1644
+
1645
+ return { origin, op, source };
1646
+ }
1647
+
1648
+ function createTransactionForOtelSpan(span) {
1649
+ const { op, description, data, origin = 'manual', source } = getSpanData(span);
1650
+ const capturedSpanScopes = getSpanScopes(span);
1651
+
1652
+ const sampleRate = span.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] ;
1653
+
1654
+ const attributes = dropUndefinedKeys({
1655
+ [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: source,
1656
+ [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: sampleRate,
1657
+ [SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,
1658
+ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: origin,
1659
+ ...data,
1660
+ ...removeSentryAttributes(span.attributes),
1661
+ });
1662
+
1663
+ const { traceId: trace_id, spanId: span_id } = span.spanContext();
1664
+ const parent_span_id = span.parentSpanId;
1665
+
1666
+ const status = mapStatus(span);
1667
+
1668
+ const traceContext = dropUndefinedKeys({
1669
+ parent_span_id,
1670
+ span_id,
1671
+ trace_id,
1672
+ data: attributes,
1673
+ origin,
1674
+ op,
1675
+ status: getStatusMessage(status),
1676
+ });
1677
+
1678
+ const transactionEvent = {
1679
+ contexts: {
1680
+ trace: traceContext,
1681
+ otel: {
1682
+ // TODO: remove the attributes here?
1683
+ attributes: removeSentryAttributes(span.attributes),
1684
+ resource: span.resource.attributes,
1685
+ },
1686
+ },
1687
+ spans: [],
1688
+ start_timestamp: convertOtelTimeToSeconds(span.startTime),
1689
+ timestamp: convertOtelTimeToSeconds(span.endTime),
1690
+ transaction: description,
1691
+ type: 'transaction',
1692
+ sdkProcessingMetadata: {
1693
+ ...dropUndefinedKeys({
1694
+ capturedSpanScope: _optionalChain$2([capturedSpanScopes, 'optionalAccess', _ => _.scope]),
1695
+ capturedSpanIsolationScope: _optionalChain$2([capturedSpanScopes, 'optionalAccess', _2 => _2.isolationScope]),
1696
+ sampleRate,
1697
+ dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),
1698
+ }),
1699
+ },
1700
+ ...(source && {
1701
+ transaction_info: {
1702
+ source,
1703
+ },
1704
+ }),
1705
+ _metrics_summary: getMetricSummaryJsonForSpan(span ),
1706
+ };
1707
+
1708
+ return transactionEvent;
1709
+ }
1710
+
1711
+ function createAndFinishSpanForOtelSpan(node, spans, remaining) {
1712
+ remaining.delete(node);
1713
+ const span = node.span;
1714
+
1715
+ const shouldDrop = !span;
1716
+
1717
+ // If this span should be dropped, we still want to create spans for the children of this
1718
+ if (shouldDrop) {
1719
+ node.children.forEach(child => {
1720
+ createAndFinishSpanForOtelSpan(child, spans, remaining);
1721
+ });
1722
+ return;
1723
+ }
1724
+
1725
+ const span_id = span.spanContext().spanId;
1726
+ const trace_id = span.spanContext().traceId;
1727
+
1728
+ const { attributes, startTime, endTime, parentSpanId } = span;
1729
+
1730
+ const { op, description, data, origin = 'manual' } = getSpanData(span);
1731
+ const allData = dropUndefinedKeys({
1732
+ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: origin,
1733
+ [SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,
1734
+ ...removeSentryAttributes(attributes),
1735
+ ...data,
1736
+ });
1737
+
1738
+ const status = mapStatus(span);
1739
+
1740
+ const spanJSON = dropUndefinedKeys({
1741
+ span_id,
1742
+ trace_id,
1743
+ data: allData,
1744
+ description,
1745
+ parent_span_id: parentSpanId,
1746
+ start_timestamp: convertOtelTimeToSeconds(startTime),
1747
+ // This is [0,0] by default in OTEL, in which case we want to interpret this as no end time
1748
+ timestamp: convertOtelTimeToSeconds(endTime) || undefined,
1749
+ status: getStatusMessage(status),
1750
+ op,
1751
+ origin,
1752
+ _metrics_summary: getMetricSummaryJsonForSpan(span ),
1753
+ });
1754
+
1755
+ spans.push(spanJSON);
1756
+
1757
+ node.children.forEach(child => {
1758
+ createAndFinishSpanForOtelSpan(child, spans, remaining);
1759
+ });
1760
+ }
1761
+
1762
+ function getSpanData(span)
1763
+
1764
+ {
1765
+ const { op: definedOp, source: definedSource, origin } = parseSpan(span);
1766
+ const { op: inferredOp, description, source: inferredSource, data: inferredData } = parseSpanDescription(span);
1767
+
1768
+ const op = definedOp || inferredOp;
1769
+ const source = definedSource || inferredSource;
1770
+
1771
+ const data = { ...inferredData, ...getData(span) };
1772
+
1773
+ return {
1774
+ op,
1775
+ description,
1776
+ source,
1777
+ origin,
1778
+ data,
1779
+ };
1780
+ }
1781
+
1782
+ /**
1783
+ * Remove custom `sentry.` attribtues we do not need to send.
1784
+ * These are more carrier attributes we use inside of the SDK, we do not need to send them to the API.
1785
+ */
1786
+ function removeSentryAttributes(data) {
1787
+ const cleanedData = { ...data };
1788
+
1789
+ /* eslint-disable @typescript-eslint/no-dynamic-delete */
1790
+ delete cleanedData[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];
1791
+ delete cleanedData[SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE];
1792
+ /* eslint-enable @typescript-eslint/no-dynamic-delete */
1793
+
1794
+ return cleanedData;
1795
+ }
1796
+
1797
+ function getData(span) {
1798
+ const attributes = span.attributes;
1799
+ const data = {
1800
+ 'otel.kind': SpanKind[span.kind],
1801
+ };
1802
+
1803
+ if (attributes[SemanticAttributes.HTTP_STATUS_CODE]) {
1804
+ const statusCode = attributes[SemanticAttributes.HTTP_STATUS_CODE] ;
1805
+ data['http.response.status_code'] = statusCode;
1806
+ }
1807
+
1808
+ const requestData = getRequestSpanData(span);
1809
+
1810
+ if (requestData.url) {
1811
+ data.url = requestData.url;
1812
+ }
1813
+
1814
+ if (requestData['http.query']) {
1815
+ data['http.query'] = requestData['http.query'].slice(1);
1816
+ }
1817
+ if (requestData['http.fragment']) {
1818
+ data['http.fragment'] = requestData['http.fragment'].slice(1);
1819
+ }
1820
+
1821
+ return data;
1822
+ }
1823
+
1824
+ function _optionalChain$1(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
1825
+
1826
+ function onSpanStart(span, parentContext) {
1827
+ // This is a reliable way to get the parent span - because this is exactly how the parent is identified in the OTEL SDK
1828
+ const parentSpan = trace.getSpan(parentContext);
1829
+
1830
+ let scopes = getScopesFromContext(parentContext);
1831
+
1832
+ // We need access to the parent span in order to be able to move up the span tree for breadcrumbs
1833
+ if (parentSpan && !parentSpan.spanContext().isRemote) {
1834
+ addChildSpanToSpan(parentSpan, span);
1835
+ }
1836
+
1837
+ // We need this in the span exporter
1838
+ if (parentSpan && parentSpan.spanContext().isRemote) {
1839
+ span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE, true);
1840
+ }
1841
+
1842
+ // The root context does not have scopes stored, so we check for this specifically
1843
+ // As fallback we attach the global scopes
1844
+ if (parentContext === ROOT_CONTEXT) {
1845
+ scopes = {
1846
+ scope: getDefaultCurrentScope(),
1847
+ isolationScope: getDefaultIsolationScope(),
1848
+ };
1849
+ }
1850
+
1851
+ // We need the scope at time of span creation in order to apply it to the event when the span is finished
1852
+ if (scopes) {
1853
+ setSpanScopes(span, scopes);
1854
+ }
1855
+
1856
+ const client = getClient();
1857
+ _optionalChain$1([client, 'optionalAccess', _ => _.emit, 'call', _2 => _2('spanStart', span)]);
1858
+ }
1859
+
1860
+ function onSpanEnd(span) {
1861
+ // Capture exceptions as events
1862
+ span.events.forEach(event => {
1863
+ maybeCaptureExceptionForTimedEvent(event, span);
1864
+ });
1865
+
1866
+ const client = getClient();
1867
+ _optionalChain$1([client, 'optionalAccess', _3 => _3.emit, 'call', _4 => _4('spanEnd', span)]);
1868
+ }
1869
+
1870
+ /**
1871
+ * Converts OpenTelemetry Spans to Sentry Spans and sends them to Sentry via
1872
+ * the Sentry SDK.
1873
+ */
1874
+ class SentrySpanProcessor extends BatchSpanProcessor {
1875
+ constructor() {
1876
+ super(new SentrySpanExporter());
1877
+
1878
+ setIsSetup('SentrySpanProcessor');
1879
+ }
1880
+
1881
+ /**
1882
+ * @inheritDoc
1883
+ */
1884
+ onStart(span, parentContext) {
1885
+ onSpanStart(span, parentContext);
1886
+
1887
+ // TODO (v8): Trigger client `spanStart` & `spanEnd` in here,
1888
+ // once we decoupled opentelemetry from SentrySpan
1889
+
1890
+ DEBUG_BUILD && logger.log(`[Tracing] Starting span "${span.name}" (${span.spanContext().spanId})`);
1891
+
1892
+ return super.onStart(span, parentContext);
1893
+ }
1894
+
1895
+ /** @inheritDoc */
1896
+ onEnd(span) {
1897
+ DEBUG_BUILD && logger.log(`[Tracing] Finishing span "${span.name}" (${span.spanContext().spanId})`);
1898
+
1899
+ if (!this._shouldSendSpanToSentry(span)) {
1900
+ // Prevent this being called to super.onEnd(), which would pass this to the span exporter
1901
+ return;
1902
+ }
1903
+
1904
+ onSpanEnd(span);
1905
+
1906
+ return super.onEnd(span);
1907
+ }
1908
+
1909
+ /**
1910
+ * You can overwrite this in a sub class to implement custom behavior for dropping spans.
1911
+ * If you return `false` here, the span will not be passed to the exporter and thus not be sent.
1912
+ */
1913
+ _shouldSendSpanToSentry(_span) {
1914
+ return true;
1915
+ }
1916
+ }
1917
+
1918
+ /**
1919
+ * A custom OTEL sampler that uses Sentry sampling rates to make it's decision
1920
+ */
1921
+ class SentrySampler {
1922
+
1923
+ constructor(client) {
1924
+ this._client = client;
1925
+ setIsSetup('SentrySampler');
1926
+ }
1927
+
1928
+ /** @inheritDoc */
1929
+ shouldSample(
1930
+ context,
1931
+ traceId,
1932
+ spanName,
1933
+ _spanKind,
1934
+ spanAttributes,
1935
+ _links,
1936
+ ) {
1937
+ const options = this._client.getOptions();
1938
+
1939
+ if (!hasTracingEnabled(options)) {
1940
+ return { decision: SamplingDecision.NOT_RECORD };
1941
+ }
1942
+
1943
+ const parentContext = trace.getSpanContext(context);
1944
+ const traceState = _optionalChain([parentContext, 'optionalAccess', _ => _.traceState]) || new TraceState();
1945
+
1946
+ let parentSampled = undefined;
1947
+
1948
+ // Only inherit sample rate if `traceId` is the same
1949
+ // Note for testing: `isSpanContextValid()` checks the format of the traceId/spanId, so we need to pass valid ones
1950
+ if (parentContext && isSpanContextValid(parentContext) && parentContext.traceId === traceId) {
1951
+ if (parentContext.isRemote) {
1952
+ parentSampled = getParentRemoteSampled(parentContext);
1953
+ DEBUG_BUILD &&
1954
+ logger.log(`[Tracing] Inheriting remote parent's sampled decision for ${spanName}: ${parentSampled}`);
1955
+ } else {
1956
+ parentSampled = getSamplingDecision(parentContext);
1957
+ DEBUG_BUILD && logger.log(`[Tracing] Inheriting parent's sampled decision for ${spanName}: ${parentSampled}`);
1958
+ }
1959
+ }
1960
+
1961
+ const sampleRate = getSampleRate(options, {
1962
+ name: spanName,
1963
+ attributes: spanAttributes,
1964
+ transactionContext: {
1965
+ name: spanName,
1966
+ parentSampled,
1967
+ },
1968
+ parentSampled,
1969
+ });
1970
+
1971
+ const attributes = {
1972
+ [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: Number(sampleRate),
1973
+ };
1974
+
1975
+ // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The
1976
+ // only valid values are booleans or numbers between 0 and 1.)
1977
+ if (!isValidSampleRate(sampleRate)) {
1978
+ DEBUG_BUILD && logger.warn('[Tracing] Discarding span because of invalid sample rate.');
1979
+
1980
+ return {
1981
+ decision: SamplingDecision.NOT_RECORD,
1982
+ attributes,
1983
+ traceState: traceState.set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, '1'),
1984
+ };
1985
+ }
1986
+
1987
+ // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped
1988
+ if (!sampleRate) {
1989
+ DEBUG_BUILD &&
1990
+ logger.log(
1991
+ `[Tracing] Discarding span because ${
1992
+ typeof options.tracesSampler === 'function'
1993
+ ? 'tracesSampler returned 0 or false'
1994
+ : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'
1995
+ }`,
1996
+ );
1997
+
1998
+ return {
1999
+ decision: SamplingDecision.NOT_RECORD,
2000
+ attributes,
2001
+ traceState: traceState.set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, '1'),
2002
+ };
2003
+ }
2004
+
2005
+ // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is
2006
+ // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.
2007
+ const isSampled = Math.random() < (sampleRate );
2008
+
2009
+ // if we're not going to keep it, we're done
2010
+ if (!isSampled) {
2011
+ DEBUG_BUILD &&
2012
+ logger.log(
2013
+ `[Tracing] Discarding span because it's not included in the random sample (sampling rate = ${Number(
2014
+ sampleRate,
2015
+ )})`,
2016
+ );
2017
+
2018
+ return {
2019
+ decision: SamplingDecision.NOT_RECORD,
2020
+ attributes,
2021
+ traceState: traceState.set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, '1'),
2022
+ };
2023
+ }
2024
+
2025
+ return {
2026
+ decision: SamplingDecision.RECORD_AND_SAMPLED,
2027
+ attributes,
2028
+ };
2029
+ }
2030
+
2031
+ /** Returns the sampler name or short description with the configuration. */
2032
+ toString() {
2033
+ return 'SentrySampler';
2034
+ }
2035
+ }
2036
+
2037
+ function getSampleRate(
2038
+ options,
2039
+ samplingContext,
2040
+ ) {
2041
+ if (typeof options.tracesSampler === 'function') {
2042
+ return options.tracesSampler(samplingContext);
2043
+ }
2044
+
2045
+ if (samplingContext.parentSampled !== undefined) {
2046
+ return samplingContext.parentSampled;
2047
+ }
2048
+
2049
+ if (typeof options.tracesSampleRate !== 'undefined') {
2050
+ return options.tracesSampleRate;
2051
+ }
2052
+
2053
+ // When `enableTracing === true`, we use a sample rate of 100%
2054
+ if (options.enableTracing) {
2055
+ return 1;
2056
+ }
2057
+
2058
+ return 0;
2059
+ }
2060
+
2061
+ /**
2062
+ * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).
2063
+ */
2064
+ function isValidSampleRate(rate) {
2065
+ // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck
2066
+ if (isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) {
2067
+ DEBUG_BUILD &&
2068
+ logger.warn(
2069
+ `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(
2070
+ rate,
2071
+ )} of type ${JSON.stringify(typeof rate)}.`,
2072
+ );
2073
+ return false;
2074
+ }
2075
+
2076
+ // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false
2077
+ if (rate < 0 || rate > 1) {
2078
+ DEBUG_BUILD &&
2079
+ logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`);
2080
+ return false;
2081
+ }
2082
+ return true;
2083
+ }
2084
+
2085
+ function getParentRemoteSampled(spanContext) {
2086
+ const traceId = spanContext.traceId;
2087
+ const traceparentData = getPropagationContextFromSpanContext(spanContext);
2088
+
2089
+ // Only inherit sampled if `traceId` is the same
2090
+ return traceparentData && traceId === traceparentData.traceId ? traceparentData.sampled : undefined;
2091
+ }
22
2092
 
23
2093
  /**
24
2094
  * The following internal utils are not considered public API and are subject to change.
25
2095
  * @hidden
26
2096
  */
27
2097
  const _INTERNAL = {
28
- addOriginToSpan,
29
2098
  maybeCaptureExceptionForTimedEvent,
30
2099
  getRequestSpanData,
31
2100
  } ;
32
2101
 
33
- export { _INTERNAL };
2102
+ export { SentryPropagator, SentrySampler, SentrySpanProcessor, _INTERNAL, continueTrace, getActiveSpan, getCurrentHub, getDynamicSamplingContextFromSpan, getScopesFromContext, getSpanKind, getSpanScopes, isSentryRequestSpan, openTelemetrySetupCheck, setOpenTelemetryContextAsyncContextStrategy, setupEventContextTrace, setupGlobalHub, spanHasAttributes, spanHasEvents, spanHasKind, spanHasName, spanHasParentId, spanHasStatus, startInactiveSpan, startSpan, startSpanManual, withActiveSpan, wrapClientClass, wrapContextManagerClass };
34
2103
  //# sourceMappingURL=index.js.map