@sentry/opentelemetry 8.54.0 → 9.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 (32) hide show
  1. package/LICENSE +1 -1
  2. package/build/cjs/index.js +135 -178
  3. package/build/cjs/index.js.map +1 -1
  4. package/build/esm/index.js +137 -173
  5. package/build/esm/index.js.map +1 -1
  6. package/build/esm/package.json +1 -1
  7. package/build/types/constants.d.ts +2 -0
  8. package/build/types/constants.d.ts.map +1 -1
  9. package/build/types/custom/client.d.ts +4 -3
  10. package/build/types/custom/client.d.ts.map +1 -1
  11. package/build/types/index.d.ts +1 -4
  12. package/build/types/index.d.ts.map +1 -1
  13. package/build/types/propagator.d.ts +2 -4
  14. package/build/types/propagator.d.ts.map +1 -1
  15. package/build/types/sampler.d.ts +3 -1
  16. package/build/types/sampler.d.ts.map +1 -1
  17. package/build/types/spanExporter.d.ts.map +1 -1
  18. package/build/types/utils/contextData.d.ts +1 -2
  19. package/build/types/utils/contextData.d.ts.map +1 -1
  20. package/build/types-ts3.8/constants.d.ts +2 -0
  21. package/build/types-ts3.8/custom/client.d.ts +4 -3
  22. package/build/types-ts3.8/index.d.ts +1 -4
  23. package/build/types-ts3.8/propagator.d.ts +2 -4
  24. package/build/types-ts3.8/sampler.d.ts +3 -1
  25. package/build/types-ts3.8/utils/contextData.d.ts +1 -2
  26. package/package.json +4 -4
  27. package/build/types/instrumentation.d.ts +0 -10
  28. package/build/types/instrumentation.d.ts.map +0 -1
  29. package/build/types/utils/generateSpanContextForPropagationContext.d.ts +0 -10
  30. package/build/types/utils/generateSpanContextForPropagationContext.d.ts.map +0 -1
  31. package/build/types-ts3.8/instrumentation.d.ts +0 -10
  32. package/build/types-ts3.8/utils/generateSpanContextForPropagationContext.d.ts +0 -10
@@ -1,12 +1,10 @@
1
- import { _optionalChain } from '@sentry/core';
2
1
  import { ATTR_URL_FULL, SEMATTRS_HTTP_URL, ATTR_HTTP_REQUEST_METHOD, SEMATTRS_HTTP_METHOD, SEMATTRS_DB_SYSTEM, SEMATTRS_RPC_SERVICE, SEMATTRS_MESSAGING_SYSTEM, SEMATTRS_FAAS_TRIGGER, SEMATTRS_DB_STATEMENT, SEMATTRS_HTTP_TARGET, ATTR_HTTP_ROUTE, ATTR_HTTP_RESPONSE_STATUS_CODE, SEMATTRS_HTTP_STATUS_CODE, SEMATTRS_RPC_GRPC_STATUS_CODE } from '@opentelemetry/semantic-conventions';
3
- import { parseUrl, getSanitizedUrlString, SDK_VERSION, addNonEnumerableProperty, isSentryRequestUrl, getClient, baggageHeaderToDynamicSamplingContext, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, stripUrlQueryAndFragment, spanToJSON, hasTracingEnabled, dynamicSamplingContextToSentryBaggageHeader, getDynamicSamplingContextFromSpan, getRootSpan, LRUMap, logger, parseBaggageHeader, SENTRY_BAGGAGE_KEY_PREFIX, generateSentryTraceHeader, stringMatchesSomePattern, generateSpanId, getCurrentScope, getDynamicSamplingContextFromScope, propagationContextFromHeaders, getIsolationScope, handleCallbackErrors, spanToTraceContext, getTraceContextFromScope, getCapturedScopesOnSpan, setAsyncContextStrategy, getDefaultCurrentScope, getDefaultIsolationScope, SPAN_STATUS_OK, SPAN_STATUS_ERROR, getSpanStatusFromHttpCode, timedEventsToMeasurements, captureEvent, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, dropUndefinedKeys, getStatusMessage, spanTimeInputToSeconds, getMetricSummaryJsonForSpan, addChildSpanToSpan, setCapturedScopesOnSpan, logSpanStart, logSpanEnd, sampleSpan } from '@sentry/core';
4
- export { getClient, getCurrentHubShim, getDynamicSamplingContextFromSpan } from '@sentry/core';
2
+ import { parseUrl, getSanitizedUrlString, SDK_VERSION, addNonEnumerableProperty, isSentryRequestUrl, getClient, baggageHeaderToDynamicSamplingContext, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, stripUrlQueryAndFragment, spanToJSON, hasTracingEnabled, dynamicSamplingContextToSentryBaggageHeader, LRUMap, logger, parseBaggageHeader, SENTRY_BAGGAGE_KEY_PREFIX, generateSentryTraceHeader, stringMatchesSomePattern, getDynamicSamplingContextFromSpan, getCurrentScope, getDynamicSamplingContextFromScope, propagationContextFromHeaders, getIsolationScope, handleCallbackErrors, getRootSpan, spanToTraceContext, getTraceContextFromScope, getCapturedScopesOnSpan, setAsyncContextStrategy, getDefaultCurrentScope, getDefaultIsolationScope, SPAN_STATUS_OK, SPAN_STATUS_ERROR, getSpanStatusFromHttpCode, timedEventsToMeasurements, captureEvent, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, dropUndefinedKeys, getStatusMessage, spanTimeInputToSeconds, addChildSpanToSpan, setCapturedScopesOnSpan, logSpanStart, logSpanEnd, parseSampleRate, sampleSpan } from '@sentry/core';
3
+ export { getClient, getDynamicSamplingContextFromSpan } from '@sentry/core';
5
4
  import * as api from '@opentelemetry/api';
6
5
  import { trace, SpanKind, createContextKey, TraceFlags, propagation, INVALID_TRACEID, context, SpanStatusCode, ROOT_CONTEXT, isSpanContextValid } from '@opentelemetry/api';
7
6
  import { TraceState, W3CBaggagePropagator, isTracingSuppressed, suppressTracing as suppressTracing$1 } from '@opentelemetry/core';
8
7
  import { SamplingDecision } from '@opentelemetry/sdk-trace-base';
9
- import { registerInstrumentations } from '@opentelemetry/instrumentation';
10
8
 
11
9
  /** If this attribute is true, it means that the parent is a remote span. */
12
10
  const SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE = 'sentry.parentIsRemote';
@@ -122,21 +120,20 @@ function getRequestSpanData(span) {
122
120
  data['http.fragment'] = url.hash;
123
121
  }
124
122
  }
125
- } catch (e) {
123
+ } catch {
126
124
  // ignore
127
125
  }
128
126
 
129
127
  return data;
130
128
  }
131
129
 
132
- 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; }
133
-
134
130
  // Typescript complains if we do not use `...args: any[]` for the mixin, with:
135
131
  // A mixin class must have a constructor with a single rest parameter of type 'any[]'.ts(2545)
136
132
  /* eslint-disable @typescript-eslint/no-explicit-any */
137
133
 
138
134
  /**
139
- * Wrap an Client with things we need for OpenTelemetry support.
135
+ * Wrap an Client class with things we need for OpenTelemetry support.
136
+ * Make sure that the Client class passed in is non-abstract!
140
137
  *
141
138
  * Usage:
142
139
  * const OpenTelemetryClient = getWrappedClientClass(NodeClient);
@@ -145,6 +142,7 @@ function _optionalChain$6(ops) { let lastAccessLHS = undefined; let value = ops[
145
142
  function wrapClientClass
146
143
 
147
144
  (ClientClass) {
145
+ // @ts-expect-error We just assume that this is non-abstract, if you pass in an abstract class this would make it non-abstract
148
146
  class OpenTelemetryClient extends ClientClass {
149
147
 
150
148
  constructor(...args) {
@@ -170,7 +168,7 @@ function wrapClientClass
170
168
  */
171
169
  async flush(timeout) {
172
170
  const provider = this.traceProvider;
173
- const spanProcessor = _optionalChain$6([provider, 'optionalAccess', _ => _.activeSpanProcessor]);
171
+ const spanProcessor = provider?.activeSpanProcessor;
174
172
 
175
173
  if (spanProcessor) {
176
174
  await spanProcessor.forceFlush();
@@ -204,6 +202,8 @@ const SENTRY_BAGGAGE_HEADER = 'baggage';
204
202
  const SENTRY_TRACE_STATE_DSC = 'sentry.dsc';
205
203
  const SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING = 'sentry.sampled_not_recording';
206
204
  const SENTRY_TRACE_STATE_URL = 'sentry.url';
205
+ const SENTRY_TRACE_STATE_SAMPLE_RAND = 'sentry.sample_rand';
206
+ const SENTRY_TRACE_STATE_SAMPLE_RATE = 'sentry.sample_rate';
207
207
 
208
208
  const SENTRY_SCOPES_CONTEXT_KEY = createContextKey('sentry_scopes');
209
209
 
@@ -241,8 +241,7 @@ function setContextOnScope(scope, context) {
241
241
 
242
242
  /**
243
243
  * Get the context related to a scope.
244
- * TODO v8: Use this for the `trace` functions.
245
- * */
244
+ */
246
245
  function getContextFromScope(scope) {
247
246
  return (scope )[SCOPE_CONTEXT_FIELD];
248
247
  }
@@ -270,8 +269,6 @@ function isSentryRequestSpan(span) {
270
269
  return isSentryRequestUrl(httpUrl.toString(), getClient());
271
270
  }
272
271
 
273
- 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; }
274
-
275
272
  /**
276
273
  * OpenTelemetry only knows about SAMPLED or NONE decision,
277
274
  * but for us it is important to differentiate between unset and unsampled.
@@ -300,10 +297,10 @@ function getSamplingDecision(spanContext) {
300
297
  const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;
301
298
  const dsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : undefined;
302
299
 
303
- if (_optionalChain$5([dsc, 'optionalAccess', _ => _.sampled]) === 'true') {
300
+ if (dsc?.sampled === 'true') {
304
301
  return true;
305
302
  }
306
- if (_optionalChain$5([dsc, 'optionalAccess', _2 => _2.sampled]) === 'false') {
303
+ if (dsc?.sampled === 'false') {
307
304
  return false;
308
305
  }
309
306
 
@@ -526,8 +523,8 @@ function getSanitizedUrl(
526
523
 
527
524
  const parsedUrl = typeof httpUrl === 'string' ? parseUrl(httpUrl) : undefined;
528
525
  const url = parsedUrl ? getSanitizedUrlString(parsedUrl) : undefined;
529
- const query = parsedUrl && parsedUrl.search ? parsedUrl.search : undefined;
530
- const fragment = parsedUrl && parsedUrl.hash ? parsedUrl.hash : undefined;
526
+ const query = parsedUrl?.search || undefined;
527
+ const fragment = parsedUrl?.hash || undefined;
531
528
 
532
529
  if (typeof httpRoute === 'string') {
533
530
  return { urlPath: httpRoute, url, query, fragment, hasRoute: true };
@@ -598,7 +595,7 @@ function enhanceDscWithOpenTelemetryRootSpanName(client) {
598
595
  // This mutates the passed-in DSC
599
596
 
600
597
  const jsonSpan = spanToJSON(rootSpan);
601
- const attributes = jsonSpan.data || {};
598
+ const attributes = jsonSpan.data;
602
599
  const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
603
600
 
604
601
  const { description } = spanHasName(rootSpan) ? parseSpanDescription(rootSpan) : { description: undefined };
@@ -616,6 +613,20 @@ function enhanceDscWithOpenTelemetryRootSpanName(client) {
616
613
  });
617
614
  }
618
615
 
616
+ /**
617
+ * Returns the currently active span.
618
+ */
619
+ function getActiveSpan() {
620
+ return trace.getActiveSpan();
621
+ }
622
+
623
+ /**
624
+ * 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.
625
+ *
626
+ * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
627
+ */
628
+ const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);
629
+
619
630
  /**
620
631
  * Generate a TraceState for the given data.
621
632
  */
@@ -637,45 +648,6 @@ function makeTraceState({
637
648
  return sampled === false ? traceStateWithDsc.set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, '1') : traceStateWithDsc;
638
649
  }
639
650
 
640
- /**
641
- * Generates a SpanContext that represents a PropagationContext.
642
- * This can be set on a `context` to make this a (virtual) active span.
643
- *
644
- * @deprecated This function is deprecated and will be removed in the next major version.
645
- */
646
- function generateSpanContextForPropagationContext(propagationContext) {
647
- // We store the DSC as OTEL trace state on the span context
648
- const traceState = makeTraceState({
649
- dsc: propagationContext.dsc,
650
- sampled: propagationContext.sampled,
651
- });
652
-
653
- const spanContext = {
654
- traceId: propagationContext.traceId,
655
- // TODO: Do not create an invalid span context here
656
- spanId: propagationContext.parentSpanId || '',
657
- isRemote: true,
658
- traceFlags: propagationContext.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
659
- traceState,
660
- };
661
-
662
- return spanContext;
663
- }
664
-
665
- /**
666
- * Returns the currently active span.
667
- */
668
- function getActiveSpan() {
669
- return trace.getActiveSpan();
670
- }
671
-
672
- /**
673
- * 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.
674
- *
675
- * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
676
- */
677
- const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);
678
-
679
651
  const setupElements = new Set();
680
652
 
681
653
  /** Get all the OpenTelemetry elements that have been set up. */
@@ -688,33 +660,6 @@ function setIsSetup(element) {
688
660
  setupElements.add(element);
689
661
  }
690
662
 
691
- 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; }
692
-
693
- /** Get the Sentry propagation context from a span context. */
694
- function getPropagationContextFromSpan(span) {
695
- const spanContext = span.spanContext();
696
- const { traceId, spanId, traceState } = spanContext;
697
-
698
- // When we have a dsc trace state, it means this came from the incoming trace
699
- // Then this takes presedence over the root span
700
- const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;
701
- const traceStateDsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : undefined;
702
-
703
- const parentSpanId = spanHasParentId(span) ? span.parentSpanId : undefined;
704
- const sampled = getSamplingDecision(spanContext);
705
-
706
- // No trace state? --> Take DSC from root span
707
- const dsc = traceStateDsc || getDynamicSamplingContextFromSpan(getRootSpan(span));
708
-
709
- return {
710
- traceId,
711
- spanId,
712
- sampled,
713
- parentSpanId,
714
- dsc,
715
- };
716
- }
717
-
718
663
  /**
719
664
  * Injects and extracts `sentry-trace` and `baggage` headers from carriers.
720
665
  */
@@ -741,7 +686,7 @@ class SentryPropagator extends W3CBaggagePropagator {
741
686
  const activeSpan = trace.getSpan(context);
742
687
  const url = activeSpan && getCurrentURL(activeSpan);
743
688
 
744
- const tracePropagationTargets = _optionalChain$4([getClient, 'call', _ => _(), 'optionalAccess', _2 => _2.getOptions, 'call', _3 => _3(), 'optionalAccess', _4 => _4.tracePropagationTargets]);
689
+ const tracePropagationTargets = getClient()?.getOptions()?.tracePropagationTargets;
745
690
  if (!shouldPropagateTraceForUrl(url, tracePropagationTargets, this._urlMatchesTargetsMap)) {
746
691
  DEBUG_BUILD &&
747
692
  logger.log(
@@ -826,14 +771,14 @@ function shouldPropagateTraceForUrl(
826
771
  return true;
827
772
  }
828
773
 
829
- const cachedDecision = _optionalChain$4([decisionMap, 'optionalAccess', _5 => _5.get, 'call', _6 => _6(url)]);
774
+ const cachedDecision = decisionMap?.get(url);
830
775
  if (cachedDecision !== undefined) {
831
776
  DEBUG_BUILD && !cachedDecision && logger.log(NOT_PROPAGATED_MESSAGE, url);
832
777
  return cachedDecision;
833
778
  }
834
779
 
835
780
  const decision = stringMatchesSomePattern(url, tracePropagationTargets);
836
- _optionalChain$4([decisionMap, 'optionalAccess', _7 => _7.set, 'call', _8 => _8(url, decision)]);
781
+ decisionMap?.set(url, decision);
837
782
 
838
783
  DEBUG_BUILD && !decision && logger.log(NOT_PROPAGATED_MESSAGE, url);
839
784
  return decision;
@@ -849,17 +794,15 @@ function getInjectionData(context)
849
794
 
850
795
  // If we have a remote span, the spanId should be considered as the parentSpanId, not spanId itself
851
796
  // Instead, we use a virtual (generated) spanId for propagation
852
- if (span && span.spanContext().isRemote) {
797
+ if (span?.spanContext().isRemote) {
853
798
  const spanContext = span.spanContext();
854
799
  const dynamicSamplingContext = getDynamicSamplingContextFromSpan(span);
855
800
 
856
801
  return {
857
802
  dynamicSamplingContext,
858
803
  traceId: spanContext.traceId,
859
- // Because this is a remote span, we do not want to propagate this directly
860
- // As otherwise things may be attached "directly" to an unrelated span
861
- spanId: generateSpanId(),
862
- sampled: getSamplingDecision(spanContext),
804
+ spanId: undefined,
805
+ sampled: getSamplingDecision(spanContext), // TODO: Do we need to change something here?
863
806
  };
864
807
  }
865
808
 
@@ -872,13 +815,13 @@ function getInjectionData(context)
872
815
  dynamicSamplingContext,
873
816
  traceId: spanContext.traceId,
874
817
  spanId: spanContext.spanId,
875
- sampled: getSamplingDecision(spanContext),
818
+ sampled: getSamplingDecision(spanContext), // TODO: Do we need to change something here?
876
819
  };
877
820
  }
878
821
 
879
822
  // Else we try to use the propagation context from the scope
880
823
  // The only scenario where this should happen is when we neither have a span, nor an incoming trace
881
- const scope = _optionalChain$4([getScopesFromContext, 'call', _9 => _9(context), 'optionalAccess', _10 => _10.scope]) || getCurrentScope();
824
+ const scope = getScopesFromContext(context)?.scope || getCurrentScope();
882
825
  const client = getClient();
883
826
 
884
827
  const propagationContext = scope.getPropagationContext();
@@ -886,9 +829,7 @@ function getInjectionData(context)
886
829
  return {
887
830
  dynamicSamplingContext,
888
831
  traceId: propagationContext.traceId,
889
- // TODO(v9): Use generateSpanId() instead
890
- // eslint-disable-next-line deprecation/deprecation
891
- spanId: propagationContext.spanId,
832
+ spanId: propagationContext.propagationSpanId,
892
833
  sampled: propagationContext.sampled,
893
834
  };
894
835
  }
@@ -949,7 +890,7 @@ function getExistingBaggage(carrier) {
949
890
  try {
950
891
  const baggage = (carrier )[SENTRY_BAGGAGE_HEADER];
951
892
  return Array.isArray(baggage) ? baggage.join(',') : baggage;
952
- } catch (e) {
893
+ } catch {
953
894
  return undefined;
954
895
  }
955
896
  }
@@ -967,13 +908,13 @@ function getCurrentURL(span) {
967
908
  const spanData = spanToJSON(span).data;
968
909
  // `ATTR_URL_FULL` is the new attribute, but we still support the old one, `SEMATTRS_HTTP_URL`, for now.
969
910
  // eslint-disable-next-line deprecation/deprecation
970
- const urlAttribute = _optionalChain$4([spanData, 'optionalAccess', _11 => _11[SEMATTRS_HTTP_URL]]) || _optionalChain$4([spanData, 'optionalAccess', _12 => _12[ATTR_URL_FULL]]);
971
- if (urlAttribute) {
911
+ const urlAttribute = spanData[SEMATTRS_HTTP_URL] || spanData[ATTR_URL_FULL];
912
+ if (typeof urlAttribute === 'string') {
972
913
  return urlAttribute;
973
914
  }
974
915
 
975
916
  // Also look at the traceState, which we may set in the sampler even for unsampled spans
976
- const urlTraceState = _optionalChain$4([span, 'access', _13 => _13.spanContext, 'call', _14 => _14(), 'access', _15 => _15.traceState, 'optionalAccess', _16 => _16.get, 'call', _17 => _17(SENTRY_TRACE_STATE_URL)]);
917
+ const urlTraceState = span.spanContext().traceState?.get(SENTRY_TRACE_STATE_URL);
977
918
  if (urlTraceState) {
978
919
  return urlTraceState;
979
920
  }
@@ -1134,7 +1075,7 @@ function withActiveSpan(span, callback) {
1134
1075
 
1135
1076
  function getTracer() {
1136
1077
  const client = getClient();
1137
- return (client && client.tracer) || trace.getTracer('@sentry/opentelemetry', SDK_VERSION);
1078
+ return client?.tracer || trace.getTracer('@sentry/opentelemetry', SDK_VERSION);
1138
1079
  }
1139
1080
 
1140
1081
  function getSpanOptions(options) {
@@ -1412,8 +1353,6 @@ function setOpenTelemetryContextAsyncContextStrategy() {
1412
1353
  });
1413
1354
  }
1414
1355
 
1415
- 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; }
1416
-
1417
1356
  /**
1418
1357
  * Wrap an OpenTelemetry ContextManager in a way that ensures the context is kept in sync with the Sentry Scope.
1419
1358
  *
@@ -1450,8 +1389,8 @@ function wrapContextManagerClass(
1450
1389
  ...args
1451
1390
  ) {
1452
1391
  const currentScopes = getScopesFromContext(context);
1453
- const currentScope = _optionalChain$3([currentScopes, 'optionalAccess', _ => _.scope]) || getCurrentScope();
1454
- const currentIsolationScope = _optionalChain$3([currentScopes, 'optionalAccess', _2 => _2.isolationScope]) || getIsolationScope();
1392
+ const currentScope = currentScopes?.scope || getCurrentScope();
1393
+ const currentIsolationScope = currentScopes?.isolationScope || getIsolationScope();
1455
1394
 
1456
1395
  const shouldForkIsolationScope = context.getValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY) === true;
1457
1396
  const scope = context.getValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY) ;
@@ -1535,7 +1474,7 @@ function createOrUpdateNode(nodeMap, spanNode) {
1535
1474
  const existing = nodeMap.get(spanNode.id);
1536
1475
 
1537
1476
  // If span is already set, nothing to do here
1538
- if (existing && existing.span) {
1477
+ if (existing?.span) {
1539
1478
  return existing;
1540
1479
  }
1541
1480
 
@@ -1611,7 +1550,7 @@ function mapStatus(span) {
1611
1550
  }
1612
1551
 
1613
1552
  // We default to setting the spans status to ok.
1614
- if (status && status.code === SpanStatusCode.UNSET) {
1553
+ if (status?.code === SpanStatusCode.UNSET) {
1615
1554
  return { code: SPAN_STATUS_OK };
1616
1555
  } else {
1617
1556
  return { code: SPAN_STATUS_ERROR, message: 'unknown_error' };
@@ -1644,8 +1583,6 @@ function inferStatusFromAttributes(attributes) {
1644
1583
  return undefined;
1645
1584
  }
1646
1585
 
1647
- 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; }
1648
-
1649
1586
  const MAX_SPAN_COUNT = 1000;
1650
1587
  const DEFAULT_TIMEOUT = 300; // 5 min
1651
1588
 
@@ -1674,7 +1611,7 @@ class SentrySpanExporter {
1674
1611
  constructor(options
1675
1612
 
1676
1613
  ) {
1677
- this._finishedSpanBucketSize = _optionalChain$2([options, 'optionalAccess', _ => _.timeout]) || DEFAULT_TIMEOUT;
1614
+ this._finishedSpanBucketSize = options?.timeout || DEFAULT_TIMEOUT;
1678
1615
  this._finishedSpanBuckets = new Array(this._finishedSpanBucketSize).fill(undefined);
1679
1616
  this._lastCleanupTimestampInS = Math.floor(Date.now() / 1000);
1680
1617
  this._spansToBucketEntry = new WeakMap();
@@ -1896,7 +1833,6 @@ function createTransactionForOtelSpan(span) {
1896
1833
  source,
1897
1834
  },
1898
1835
  }),
1899
- _metrics_summary: getMetricSummaryJsonForSpan(span ),
1900
1836
  });
1901
1837
 
1902
1838
  return transactionEvent;
@@ -1946,7 +1882,6 @@ function createAndFinishSpanForOtelSpan(node, spans, sentSpans) {
1946
1882
  status: getStatusMessage(status), // As per protocol, span status is allowed to be undefined
1947
1883
  op,
1948
1884
  origin,
1949
- _metrics_summary: getMetricSummaryJsonForSpan(span ),
1950
1885
  measurements: timedEventsToMeasurements(span.events),
1951
1886
  });
1952
1887
 
@@ -2023,8 +1958,6 @@ function getData(span) {
2023
1958
  return data;
2024
1959
  }
2025
1960
 
2026
- 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; }
2027
-
2028
1961
  function onSpanStart(span, parentContext) {
2029
1962
  // This is a reliable way to get the parent span - because this is exactly how the parent is identified in the OTEL SDK
2030
1963
  const parentSpan = trace.getSpan(parentContext);
@@ -2037,7 +1970,7 @@ function onSpanStart(span, parentContext) {
2037
1970
  }
2038
1971
 
2039
1972
  // We need this in the span exporter
2040
- if (parentSpan && parentSpan.spanContext().isRemote) {
1973
+ if (parentSpan?.spanContext().isRemote) {
2041
1974
  span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE, true);
2042
1975
  }
2043
1976
 
@@ -2058,14 +1991,14 @@ function onSpanStart(span, parentContext) {
2058
1991
  logSpanStart(span);
2059
1992
 
2060
1993
  const client = getClient();
2061
- _optionalChain$1([client, 'optionalAccess', _ => _.emit, 'call', _2 => _2('spanStart', span)]);
1994
+ client?.emit('spanStart', span);
2062
1995
  }
2063
1996
 
2064
1997
  function onSpanEnd(span) {
2065
1998
  logSpanEnd(span);
2066
1999
 
2067
2000
  const client = getClient();
2068
- _optionalChain$1([client, 'optionalAccess', _3 => _3.emit, 'call', _4 => _4('spanEnd', span)]);
2001
+ client?.emit('spanEnd', span);
2069
2002
  }
2070
2003
 
2071
2004
  /**
@@ -2130,7 +2063,7 @@ class SentrySampler {
2130
2063
  const options = this._client.getOptions();
2131
2064
 
2132
2065
  const parentSpan = getValidSpan(context);
2133
- const parentContext = _optionalChain([parentSpan, 'optionalAccess', _ => _.spanContext, 'call', _2 => _2()]);
2066
+ const parentContext = parentSpan?.spanContext();
2134
2067
 
2135
2068
  if (!hasTracingEnabled(options)) {
2136
2069
  return wrapSamplingDecision({ decision: undefined, context, spanAttributes });
@@ -2142,7 +2075,7 @@ class SentrySampler {
2142
2075
 
2143
2076
  // If we have a http.client span that has no local parent, we never want to sample it
2144
2077
  // but we want to leave downstream sampling decisions up to the server
2145
- if (spanKind === SpanKind.CLIENT && maybeSpanHttpMethod && (!parentSpan || _optionalChain([parentContext, 'optionalAccess', _3 => _3.isRemote]))) {
2078
+ if (spanKind === SpanKind.CLIENT && maybeSpanHttpMethod && (!parentSpan || parentContext?.isRemote)) {
2146
2079
  return wrapSamplingDecision({ decision: undefined, context, spanAttributes });
2147
2080
  }
2148
2081
 
@@ -2179,40 +2112,76 @@ class SentrySampler {
2179
2112
  return wrapSamplingDecision({ decision: undefined, context, spanAttributes });
2180
2113
  }
2181
2114
 
2182
- const [sampled, sampleRate] = sampleSpan(options, {
2183
- name: inferredSpanName,
2184
- attributes: mergedAttributes,
2185
- transactionContext: {
2186
- name: inferredSpanName,
2187
- parentSampled,
2188
- },
2189
- parentSampled,
2190
- });
2115
+ const isRootSpan = !parentSpan || parentContext?.isRemote;
2191
2116
 
2192
- const attributes = {
2193
- [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: sampleRate,
2194
- };
2117
+ // We only sample based on parameters (like tracesSampleRate or tracesSampler) for root spans (which is done in sampleSpan).
2118
+ // Non-root-spans simply inherit the sampling decision from their parent.
2119
+ if (isRootSpan) {
2120
+ const { isolationScope } = getScopesFromContext(context) ?? {};
2195
2121
 
2196
- const method = `${maybeSpanHttpMethod}`.toUpperCase();
2197
- if (method === 'OPTIONS' || method === 'HEAD') {
2198
- DEBUG_BUILD && logger.log(`[Tracing] Not sampling span because HTTP method is '${method}' for ${spanName}`);
2122
+ const dscString = parentContext?.traceState ? parentContext.traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;
2123
+ const dsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : undefined;
2124
+
2125
+ const sampleRand = parseSampleRate(dsc?.sample_rand) ?? Math.random();
2126
+
2127
+ const [sampled, sampleRate, localSampleRateWasApplied] = sampleSpan(
2128
+ options,
2129
+ {
2130
+ name: inferredSpanName,
2131
+ attributes: mergedAttributes,
2132
+ normalizedRequest: isolationScope?.getScopeData().sdkProcessingMetadata.normalizedRequest,
2133
+ parentSampled,
2134
+ parentSampleRate: parseSampleRate(dsc?.sample_rate),
2135
+ },
2136
+ sampleRand,
2137
+ );
2138
+
2139
+ const method = `${maybeSpanHttpMethod}`.toUpperCase();
2140
+ if (method === 'OPTIONS' || method === 'HEAD') {
2141
+ DEBUG_BUILD && logger.log(`[Tracing] Not sampling span because HTTP method is '${method}' for ${spanName}`);
2142
+
2143
+ return {
2144
+ ...wrapSamplingDecision({
2145
+ decision: SamplingDecision.NOT_RECORD,
2146
+ context,
2147
+ spanAttributes,
2148
+ sampleRand,
2149
+ downstreamTraceSampleRate: 0, // we don't want to sample anything in the downstream trace either
2150
+ }),
2151
+ };
2152
+ }
2153
+
2154
+ if (
2155
+ !sampled &&
2156
+ // We check for `parentSampled === undefined` because we only want to record client reports for spans that are trace roots (ie. when there was incoming trace)
2157
+ parentSampled === undefined
2158
+ ) {
2159
+ DEBUG_BUILD && logger.log('[Tracing] Discarding root span because its trace was not chosen to be sampled.');
2160
+ this._client.recordDroppedEvent('sample_rate', 'transaction');
2161
+ }
2199
2162
 
2200
2163
  return {
2201
- ...wrapSamplingDecision({ decision: SamplingDecision.NOT_RECORD, context, spanAttributes }),
2202
- attributes,
2164
+ ...wrapSamplingDecision({
2165
+ decision: sampled ? SamplingDecision.RECORD_AND_SAMPLED : SamplingDecision.NOT_RECORD,
2166
+ context,
2167
+ spanAttributes,
2168
+ sampleRand,
2169
+ downstreamTraceSampleRate: localSampleRateWasApplied ? sampleRate : undefined,
2170
+ }),
2171
+ attributes: {
2172
+ // We set the sample rate on the span when a local sample rate was applied to better understand how traces were sampled in Sentry
2173
+ [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: localSampleRateWasApplied ? sampleRate : undefined,
2174
+ },
2203
2175
  };
2204
- }
2205
-
2206
- if (!sampled) {
2176
+ } else {
2207
2177
  return {
2208
- ...wrapSamplingDecision({ decision: SamplingDecision.NOT_RECORD, context, spanAttributes }),
2209
- attributes,
2178
+ ...wrapSamplingDecision({
2179
+ decision: parentSampled ? SamplingDecision.RECORD_AND_SAMPLED : SamplingDecision.NOT_RECORD,
2180
+ context,
2181
+ spanAttributes,
2182
+ }),
2210
2183
  };
2211
2184
  }
2212
- return {
2213
- ...wrapSamplingDecision({ decision: SamplingDecision.RECORD_AND_SAMPLED, context, spanAttributes }),
2214
- attributes,
2215
- };
2216
2185
  }
2217
2186
 
2218
2187
  /** Returns the sampler name or short description with the configuration. */
@@ -2221,14 +2190,6 @@ class SentrySampler {
2221
2190
  }
2222
2191
  }
2223
2192
 
2224
- function getParentRemoteSampled(parentSpan) {
2225
- const traceId = parentSpan.spanContext().traceId;
2226
- const traceparentData = getPropagationContextFromSpan(parentSpan);
2227
-
2228
- // Only inherit sampled if `traceId` is the same
2229
- return traceparentData && traceId === traceparentData.traceId ? traceparentData.sampled : undefined;
2230
- }
2231
-
2232
2193
  function getParentSampled(parentSpan, traceId, spanName) {
2233
2194
  const parentContext = parentSpan.spanContext();
2234
2195
 
@@ -2236,7 +2197,7 @@ function getParentSampled(parentSpan, traceId, spanName) {
2236
2197
  // Note for testing: `isSpanContextValid()` checks the format of the traceId/spanId, so we need to pass valid ones
2237
2198
  if (isSpanContextValid(parentContext) && parentContext.traceId === traceId) {
2238
2199
  if (parentContext.isRemote) {
2239
- const parentSampled = getParentRemoteSampled(parentSpan);
2200
+ const parentSampled = getSamplingDecision(parentSpan.spanContext());
2240
2201
  DEBUG_BUILD &&
2241
2202
  logger.log(`[Tracing] Inheriting remote parent's sampled decision for ${spanName}: ${parentSampled}`);
2242
2203
  return parentSampled;
@@ -2259,8 +2220,24 @@ function wrapSamplingDecision({
2259
2220
  decision,
2260
2221
  context,
2261
2222
  spanAttributes,
2262
- }) {
2263
- const traceState = getBaseTraceState(context, spanAttributes);
2223
+ sampleRand,
2224
+ downstreamTraceSampleRate,
2225
+ }
2226
+
2227
+ ) {
2228
+ let traceState = getBaseTraceState(context, spanAttributes);
2229
+
2230
+ // We will override the propagated sample rate downstream when
2231
+ // - the tracesSampleRate is applied
2232
+ // - the tracesSampler is invoked
2233
+ // Since unsampled OTEL spans (NonRecordingSpans) cannot hold attributes we need to store this on the (trace)context.
2234
+ if (downstreamTraceSampleRate !== undefined) {
2235
+ traceState = traceState.set(SENTRY_TRACE_STATE_SAMPLE_RATE, `${downstreamTraceSampleRate}`);
2236
+ }
2237
+
2238
+ if (sampleRand !== undefined) {
2239
+ traceState = traceState.set(SENTRY_TRACE_STATE_SAMPLE_RAND, `${sampleRand}`);
2240
+ }
2264
2241
 
2265
2242
  // If the decision is undefined, we treat it as NOT_RECORDING, but we don't propagate this decision to downstream SDKs
2266
2243
  // Which is done by not setting `SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING` traceState
@@ -2277,9 +2254,9 @@ function wrapSamplingDecision({
2277
2254
 
2278
2255
  function getBaseTraceState(context, spanAttributes) {
2279
2256
  const parentSpan = trace.getSpan(context);
2280
- const parentContext = _optionalChain([parentSpan, 'optionalAccess', _4 => _4.spanContext, 'call', _5 => _5()]);
2257
+ const parentContext = parentSpan?.spanContext();
2281
2258
 
2282
- let traceState = _optionalChain([parentContext, 'optionalAccess', _6 => _6.traceState]) || new TraceState();
2259
+ let traceState = parentContext?.traceState || new TraceState();
2283
2260
 
2284
2261
  // We always keep the URL on the trace state, so we can access it in the propagator
2285
2262
  // `ATTR_URL_FULL` is the new attribute, but we still support the old one, `ATTR_HTTP_URL`, for now.
@@ -2301,18 +2278,5 @@ function getValidSpan(context) {
2301
2278
  return span && isSpanContextValid(span.spanContext()) ? span : undefined;
2302
2279
  }
2303
2280
 
2304
- /**
2305
- * This method takes an OpenTelemetry instrumentation or
2306
- * array of instrumentations and registers them with OpenTelemetry.
2307
- *
2308
- * @deprecated This method will be removed in the next major version of the SDK.
2309
- * Use the `openTelemetryInstrumentations` option in `Sentry.init()` or your custom Sentry Client instead.
2310
- */
2311
- function addOpenTelemetryInstrumentation(...instrumentations) {
2312
- registerInstrumentations({
2313
- instrumentations,
2314
- });
2315
- }
2316
-
2317
- export { SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION, SentryPropagator, SentrySampler, SentrySpanProcessor, addOpenTelemetryInstrumentation, continueTrace, enhanceDscWithOpenTelemetryRootSpanName, generateSpanContextForPropagationContext, getActiveSpan, getPropagationContextFromSpan, getRequestSpanData, getScopesFromContext, getSpanKind, getTraceContextForScope, isSentryRequestSpan, openTelemetrySetupCheck, setOpenTelemetryContextAsyncContextStrategy, setupEventContextTrace, shouldPropagateTraceForUrl, spanHasAttributes, spanHasEvents, spanHasKind, spanHasName, spanHasParentId, spanHasStatus, startInactiveSpan, startSpan, startSpanManual, suppressTracing, withActiveSpan, wrapClientClass, wrapContextManagerClass, wrapSamplingDecision };
2281
+ export { SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION, SentryPropagator, SentrySampler, SentrySpanProcessor, continueTrace, enhanceDscWithOpenTelemetryRootSpanName, getActiveSpan, getRequestSpanData, getScopesFromContext, getSpanKind, getTraceContextForScope, isSentryRequestSpan, openTelemetrySetupCheck, setOpenTelemetryContextAsyncContextStrategy, setupEventContextTrace, shouldPropagateTraceForUrl, spanHasAttributes, spanHasEvents, spanHasKind, spanHasName, spanHasParentId, spanHasStatus, startInactiveSpan, startSpan, startSpanManual, suppressTracing, withActiveSpan, wrapClientClass, wrapContextManagerClass, wrapSamplingDecision };
2318
2282
  //# sourceMappingURL=index.js.map