@sentry/opentelemetry 10.48.0 → 10.50.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +3 -6
  2. package/build/cjs/debug-build-ntZrglYX.js +9 -0
  3. package/build/cjs/debug-build-ntZrglYX.js.map +1 -0
  4. package/build/cjs/index.js +328 -64
  5. package/build/cjs/index.js.map +1 -1
  6. package/build/cjs/tracingChannel.js +68 -0
  7. package/build/cjs/tracingChannel.js.map +1 -0
  8. package/build/esm/debug-build-DcLzdrV_.js +9 -0
  9. package/build/esm/debug-build-DcLzdrV_.js.map +1 -0
  10. package/build/esm/index.js +322 -60
  11. package/build/esm/index.js.map +1 -1
  12. package/build/esm/package.json +1 -1
  13. package/build/esm/tracingChannel.js +66 -0
  14. package/build/esm/tracingChannel.js.map +1 -0
  15. package/build/types/asyncLocalStorageContextManager.d.ts +31 -0
  16. package/build/types/asyncLocalStorageContextManager.d.ts.map +1 -0
  17. package/build/types/contextManager.d.ts +2 -0
  18. package/build/types/contextManager.d.ts.map +1 -1
  19. package/build/types/index.d.ts +2 -0
  20. package/build/types/index.d.ts.map +1 -1
  21. package/build/types/resource.d.ts +23 -0
  22. package/build/types/resource.d.ts.map +1 -0
  23. package/build/types/sampler.d.ts.map +1 -1
  24. package/build/types/spanExporter.d.ts.map +1 -1
  25. package/build/types/trace.d.ts.map +1 -1
  26. package/build/types/tracingChannel.d.ts +39 -0
  27. package/build/types/tracingChannel.d.ts.map +1 -0
  28. package/build/types/utils/buildContextWithSentryScopes.d.ts +12 -0
  29. package/build/types/utils/buildContextWithSentryScopes.d.ts.map +1 -0
  30. package/build/types/utils/contextData.d.ts +7 -0
  31. package/build/types/utils/contextData.d.ts.map +1 -1
  32. package/build/types-ts3.8/asyncLocalStorageContextManager.d.ts +31 -0
  33. package/build/types-ts3.8/contextManager.d.ts +2 -0
  34. package/build/types-ts3.8/index.d.ts +2 -0
  35. package/build/types-ts3.8/resource.d.ts +26 -0
  36. package/build/types-ts3.8/tracingChannel.d.ts +39 -0
  37. package/build/types-ts3.8/utils/buildContextWithSentryScopes.d.ts +12 -0
  38. package/build/types-ts3.8/utils/contextData.d.ts +7 -0
  39. package/package.json +12 -4
@@ -0,0 +1,68 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+
3
+ const node_diagnostics_channel = require('node:diagnostics_channel');
4
+ const api = require('@opentelemetry/api');
5
+ const core = require('@sentry/core');
6
+ const debugBuild = require('./debug-build-ntZrglYX.js');
7
+
8
+ /**
9
+ * Transform function that creates a span from the channel data.
10
+ */
11
+
12
+ /**
13
+ * Creates a new tracing channel with proper OTel context propagation.
14
+ *
15
+ * When the channel's `tracePromise` / `traceSync` / `traceCallback` is called,
16
+ * the `transformStart` function runs inside `bindStore` so that:
17
+ * 1. A new span is created from the channel data.
18
+ * 2. The span is set on the OTel context stored in AsyncLocalStorage.
19
+ * 3. Downstream code (including Sentry's span processor) sees the correct parent.
20
+ *
21
+ * @param channelNameOrInstance - Either a channel name string or an existing TracingChannel instance.
22
+ * @param transformStart - Function that creates an OpenTelemetry span from the channel data.
23
+ * @returns The tracing channel with OTel context bound.
24
+ */
25
+ function tracingChannel(
26
+ channelNameOrInstance,
27
+ transformStart,
28
+ ) {
29
+ const channel = node_diagnostics_channel.tracingChannel(
30
+ channelNameOrInstance,
31
+ ) ;
32
+
33
+ let lookup;
34
+ try {
35
+ const contextManager = (api.context )._getContextManager();
36
+ lookup = contextManager.getAsyncLocalStorageLookup();
37
+ } catch {
38
+ // getAsyncLocalStorageLookup may not exist if using a non-Sentry context manager
39
+ }
40
+
41
+ if (!lookup) {
42
+ debugBuild.DEBUG_BUILD &&
43
+ core.logger.warn(
44
+ '[TracingChannel] Could not access OpenTelemetry AsyncLocalStorage, context propagation will not work.',
45
+ );
46
+ return channel;
47
+ }
48
+
49
+ const otelStorage = lookup.asyncLocalStorage;
50
+
51
+ // Bind the start channel so that each trace invocation runs the transform
52
+ // and stores the resulting context (with span) in AsyncLocalStorage.
53
+ // @ts-expect-error bindStore types don't account for AsyncLocalStorage of a different generic type
54
+ channel.start.bindStore(otelStorage, (data) => {
55
+ const span = transformStart(data);
56
+
57
+ // Store the span on data so downstream event handlers (asyncEnd, error, etc.) can access it.
58
+ data._sentrySpan = span;
59
+
60
+ // Return the context with the span set — this is what gets stored in AsyncLocalStorage.
61
+ return api.trace.setSpan(api.context.active(), span);
62
+ });
63
+
64
+ return channel;
65
+ }
66
+
67
+ exports.tracingChannel = tracingChannel;
68
+ //# sourceMappingURL=tracingChannel.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracingChannel.js","sources":["../../src/tracingChannel.ts"],"sourcesContent":["/**\n * Vendored and adapted from https://github.com/logaretm/otel-tracing-channel\n *\n * Creates a TracingChannel with proper OpenTelemetry context propagation\n * using Node.js diagnostic_channel's `bindStore` mechanism.\n */\nimport type { TracingChannel, TracingChannelSubscribers } from 'node:diagnostics_channel';\nimport { tracingChannel as nativeTracingChannel } from 'node:diagnostics_channel';\nimport type { Span } from '@opentelemetry/api';\nimport { context, trace } from '@opentelemetry/api';\nimport { logger } from '@sentry/core';\nimport type { SentryAsyncLocalStorageContextManager } from './asyncLocalStorageContextManager';\nimport type { AsyncLocalStorageLookup } from './contextManager';\nimport { DEBUG_BUILD } from './debug-build';\n\n/**\n * Transform function that creates a span from the channel data.\n */\nexport type OtelTracingChannelTransform<TData = object> = (data: TData) => Span;\n\ntype WithSpan<TData = object> = TData & { _sentrySpan?: Span };\n\n/**\n * A TracingChannel whose `subscribe` / `unsubscribe` accept partial subscriber\n * objects — you only need to provide handlers for the events you care about.\n */\nexport interface OtelTracingChannel<\n TData extends object = object,\n TDataWithSpan extends object = WithSpan<TData>,\n> extends Omit<TracingChannel<TData, TDataWithSpan>, 'subscribe' | 'unsubscribe'> {\n subscribe(subscribers: Partial<TracingChannelSubscribers<TDataWithSpan>>): void;\n unsubscribe(subscribers: Partial<TracingChannelSubscribers<TDataWithSpan>>): void;\n}\n\ninterface ContextApi {\n _getContextManager(): SentryAsyncLocalStorageContextManager;\n}\n\n/**\n * Creates a new tracing channel with proper OTel context propagation.\n *\n * When the channel's `tracePromise` / `traceSync` / `traceCallback` is called,\n * the `transformStart` function runs inside `bindStore` so that:\n * 1. A new span is created from the channel data.\n * 2. The span is set on the OTel context stored in AsyncLocalStorage.\n * 3. Downstream code (including Sentry's span processor) sees the correct parent.\n *\n * @param channelNameOrInstance - Either a channel name string or an existing TracingChannel instance.\n * @param transformStart - Function that creates an OpenTelemetry span from the channel data.\n * @returns The tracing channel with OTel context bound.\n */\nexport function tracingChannel<TData extends object = object>(\n channelNameOrInstance: string,\n transformStart: OtelTracingChannelTransform<TData>,\n): OtelTracingChannel<TData, WithSpan<TData>> {\n const channel = nativeTracingChannel<WithSpan<TData>, WithSpan<TData>>(\n channelNameOrInstance,\n ) as unknown as OtelTracingChannel<TData, WithSpan<TData>>;\n\n let lookup: AsyncLocalStorageLookup | undefined;\n try {\n const contextManager = (context as unknown as ContextApi)._getContextManager();\n lookup = contextManager.getAsyncLocalStorageLookup();\n } catch {\n // getAsyncLocalStorageLookup may not exist if using a non-Sentry context manager\n }\n\n if (!lookup) {\n DEBUG_BUILD &&\n logger.warn(\n '[TracingChannel] Could not access OpenTelemetry AsyncLocalStorage, context propagation will not work.',\n );\n return channel;\n }\n\n const otelStorage = lookup.asyncLocalStorage;\n\n // Bind the start channel so that each trace invocation runs the transform\n // and stores the resulting context (with span) in AsyncLocalStorage.\n // @ts-expect-error bindStore types don't account for AsyncLocalStorage of a different generic type\n channel.start.bindStore(otelStorage, (data: WithSpan<TData>) => {\n const span = transformStart(data);\n\n // Store the span on data so downstream event handlers (asyncEnd, error, etc.) can access it.\n data._sentrySpan = span;\n\n // Return the context with the span set — this is what gets stored in AsyncLocalStorage.\n return trace.setSpan(context.active(), span);\n });\n\n return channel;\n}\n"],"names":["nativeTracingChannel","context","DEBUG_BUILD","logger","trace"],"mappings":";;;;;;;AAeA;AACA;AACA;;AAqBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,cAAc;AAC9B,EAAE,qBAAqB;AACvB,EAAE,cAAc;AAChB,EAA8C;AAC9C,EAAE,MAAM,OAAA,GAAUA,uCAAoB;AACtC,IAAI,qBAAqB;AACzB,GAAE;;AAEF,EAAE,IAAI,MAAM;AACZ,EAAE,IAAI;AACN,IAAI,MAAM,iBAAiB,CAACC,cAAkC,kBAAkB,EAAE;AAClF,IAAI,SAAS,cAAc,CAAC,0BAA0B,EAAE;AACxD,EAAE,EAAE,MAAM;AACV;AACA,EAAE;;AAEF,EAAE,IAAI,CAAC,MAAM,EAAE;AACf,IAAIC,sBAAA;AACJ,MAAMC,WAAM,CAAC,IAAI;AACjB,QAAQ,uGAAuG;AAC/G,OAAO;AACP,IAAI,OAAO,OAAO;AAClB,EAAE;;AAEF,EAAE,MAAM,WAAA,GAAc,MAAM,CAAC,iBAAiB;;AAE9C;AACA;AACA;AACA,EAAE,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC,WAAW,EAAE,CAAC,IAAI,KAAsB;AAClE,IAAI,MAAM,IAAA,GAAO,cAAc,CAAC,IAAI,CAAC;;AAErC;AACA,IAAI,IAAI,CAAC,WAAA,GAAc,IAAI;;AAE3B;AACA,IAAI,OAAOC,SAAK,CAAC,OAAO,CAACH,WAAO,CAAC,MAAM,EAAE,EAAE,IAAI,CAAC;AAChD,EAAE,CAAC,CAAC;;AAEJ,EAAE,OAAO,OAAO;AAChB;;;;"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * 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.
3
+ *
4
+ * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
5
+ */
6
+ const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);
7
+
8
+ export { DEBUG_BUILD as D };
9
+ //# sourceMappingURL=debug-build-DcLzdrV_.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"debug-build-DcLzdrV_.js","sources":["../../src/debug-build.ts"],"sourcesContent":["declare const __DEBUG_BUILD__: boolean;\n\n/**\n * 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.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n"],"names":[],"mappings":"AAEA;AACA;AACA;AACA;AACA;AACO,MAAM,WAAA,IAAc,OAAA,gBAAA,KAAA,WAAA,IAAA,gBAAA;;;;"}
@@ -1,9 +1,12 @@
1
- import { ATTR_URL_FULL, SEMATTRS_HTTP_URL, ATTR_HTTP_REQUEST_METHOD, SEMATTRS_HTTP_METHOD, ATTR_DB_SYSTEM_NAME, 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';
2
- import { parseUrl, getSanitizedUrlString, SDK_VERSION, addNonEnumerableProperty, isSentryRequestUrl, getClient, baggageHeaderToDynamicSamplingContext, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME, stripUrlQueryAndFragment, spanToJSON, hasSpansEnabled, dynamicSamplingContextToSentryBaggageHeader, LRUMap, debug, shouldPropagateTraceForUrl, parseBaggageHeader, SENTRY_BAGGAGE_KEY_PREFIX, generateSentryTraceHeader, generateTraceparentHeader, getDynamicSamplingContextFromSpan, getCurrentScope, getDynamicSamplingContextFromScope, getIsolationScope, propagationContextFromHeaders, shouldContinueTrace, spanToTraceContext, getTraceContextFromScope, generateTraceId, generateSpanId, _INTERNAL_safeMathRandom, getRootSpan, handleCallbackErrors, getCapturedScopesOnSpan, setAsyncContextStrategy, getDefaultIsolationScope, getDefaultCurrentScope, SPAN_STATUS_OK, SPAN_STATUS_ERROR, getSpanStatusFromHttpCode, _INTERNAL_safeDateNow, debounce, timedEventsToMeasurements, captureEvent, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, convertSpanLinksForEnvelope, getStatusMessage, spanTimeInputToSeconds, addChildSpanToSpan, setCapturedScopesOnSpan, logSpanStart, logSpanEnd, hasSpanStreamingEnabled, shouldIgnoreSpan, parseSampleRate, sampleSpan } from '@sentry/core';
1
+ import { ATTR_URL_FULL, SEMATTRS_HTTP_URL, ATTR_HTTP_REQUEST_METHOD, SEMATTRS_HTTP_METHOD, ATTR_DB_SYSTEM_NAME, 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, ATTR_TELEMETRY_SDK_VERSION, ATTR_TELEMETRY_SDK_NAME, ATTR_TELEMETRY_SDK_LANGUAGE, ATTR_SERVICE_VERSION, SEMRESATTRS_SERVICE_NAMESPACE, ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions';
2
+ import { parseUrl, getSanitizedUrlString, SDK_VERSION, derefWeakRef, addNonEnumerableProperty, makeWeakRef, isSentryRequestUrl, getClient, baggageHeaderToDynamicSamplingContext, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME, stripUrlQueryAndFragment, spanToJSON, hasSpansEnabled, dynamicSamplingContextToSentryBaggageHeader, LRUMap, debug, shouldPropagateTraceForUrl, parseBaggageHeader, SENTRY_BAGGAGE_KEY_PREFIX, generateSentryTraceHeader, generateTraceparentHeader, getDynamicSamplingContextFromSpan, getCurrentScope, getDynamicSamplingContextFromScope, getIsolationScope, propagationContextFromHeaders, shouldContinueTrace, spanToTraceContext, getTraceContextFromScope, generateTraceId, generateSpanId, _INTERNAL_safeMathRandom, getRootSpan, handleCallbackErrors, getCapturedScopesOnSpan, setAsyncContextStrategy, getDefaultIsolationScope, getDefaultCurrentScope, SPAN_STATUS_OK, SPAN_STATUS_ERROR, getSpanStatusFromHttpCode, _INTERNAL_safeDateNow, debounce, timedEventsToMeasurements, captureEvent, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, convertSpanLinksForEnvelope, getStatusMessage, spanTimeInputToSeconds, addChildSpanToSpan, setCapturedScopesOnSpan, logSpanStart, logSpanEnd, hasSpanStreamingEnabled, shouldIgnoreSpan, parseSampleRate, sampleSpan } from '@sentry/core';
3
3
  export { getClient, getDynamicSamplingContextFromSpan, shouldPropagateTraceForUrl, withStreamedSpan } from '@sentry/core';
4
4
  import * as api from '@opentelemetry/api';
5
5
  import { trace, SpanKind, createContextKey, TraceFlags, propagation, INVALID_TRACEID, context, SpanStatusCode, ROOT_CONTEXT, isSpanContextValid } from '@opentelemetry/api';
6
- import { TraceState, W3CBaggagePropagator, isTracingSuppressed, suppressTracing as suppressTracing$1 } from '@opentelemetry/core';
6
+ import { TraceState, W3CBaggagePropagator, isTracingSuppressed, suppressTracing as suppressTracing$1, SDK_INFO } from '@opentelemetry/core';
7
+ import { D as DEBUG_BUILD } from './debug-build-DcLzdrV_.js';
8
+ import { AsyncLocalStorage } from 'node:async_hooks';
9
+ import { EventEmitter } from 'node:events';
7
10
  import { SamplingDecision } from '@opentelemetry/sdk-trace-base';
8
11
 
9
12
  /** If this attribute is true, it means that the parent is a remote span. */
@@ -258,16 +261,23 @@ function setScopesOnContext(context, scopes) {
258
261
  /**
259
262
  * Set the context on the scope so we can later look it up.
260
263
  * We need this to get the context from the scope in the `trace` functions.
264
+ *
265
+ * We use WeakRef to avoid a circular reference between the scope and the context.
266
+ * The context holds scopes (via SENTRY_SCOPES_CONTEXT_KEY), and if the scope held
267
+ * a strong reference back to the context, neither could be garbage collected even
268
+ * when the context is no longer reachable from application code (e.g., after a
269
+ * request completes but pooled connections retain patched callbacks).
261
270
  */
262
271
  function setContextOnScope(scope, context) {
263
- addNonEnumerableProperty(scope, SCOPE_CONTEXT_FIELD, context);
272
+ addNonEnumerableProperty(scope, SCOPE_CONTEXT_FIELD, makeWeakRef(context));
264
273
  }
265
274
 
266
275
  /**
267
276
  * Get the context related to a scope.
277
+ * Returns undefined if the context has been garbage collected (when WeakRef is used).
268
278
  */
269
279
  function getContextFromScope(scope) {
270
- return (scope )[SCOPE_CONTEXT_FIELD];
280
+ return derefWeakRef((scope )[SCOPE_CONTEXT_FIELD]);
271
281
  }
272
282
 
273
283
  /**
@@ -645,13 +655,6 @@ function getActiveSpan() {
645
655
  return trace.getActiveSpan();
646
656
  }
647
657
 
648
- /**
649
- * 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.
650
- *
651
- * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
652
- */
653
- const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);
654
-
655
658
  /**
656
659
  * Generate a TraceState for the given data.
657
660
  */
@@ -982,8 +985,12 @@ function _startSpan(options, callback, autoEnd) {
982
985
 
983
986
  return wrapper(() => {
984
987
  const activeCtx = getContext(options.scope, options.forceTransaction);
985
- const shouldSkipSpan = options.onlyIfParent && !trace.getSpan(activeCtx);
986
- const ctx = shouldSkipSpan ? suppressTracing$1(activeCtx) : activeCtx;
988
+ const missingRequiredParent = options.onlyIfParent && !trace.getSpan(activeCtx);
989
+ const ctx = missingRequiredParent ? suppressTracing$1(activeCtx) : activeCtx;
990
+
991
+ if (missingRequiredParent) {
992
+ getClient()?.recordDroppedEvent('no_parent_span', 'span');
993
+ }
987
994
 
988
995
  const spanOptions = getSpanOptions(options);
989
996
 
@@ -1085,8 +1092,12 @@ function startInactiveSpan(options) {
1085
1092
 
1086
1093
  return wrapper(() => {
1087
1094
  const activeCtx = getContext(options.scope, options.forceTransaction);
1088
- const shouldSkipSpan = options.onlyIfParent && !trace.getSpan(activeCtx);
1089
- let ctx = shouldSkipSpan ? suppressTracing$1(activeCtx) : activeCtx;
1095
+ const missingRequiredParent = options.onlyIfParent && !trace.getSpan(activeCtx);
1096
+ let ctx = missingRequiredParent ? suppressTracing$1(activeCtx) : activeCtx;
1097
+
1098
+ if (missingRequiredParent) {
1099
+ getClient()?.recordDroppedEvent('no_parent_span', 'span');
1100
+ }
1090
1101
 
1091
1102
  const spanOptions = getSpanOptions(options);
1092
1103
 
@@ -1448,6 +1459,51 @@ function setOpenTelemetryContextAsyncContextStrategy() {
1448
1459
  });
1449
1460
  }
1450
1461
 
1462
+ /**
1463
+ * Merge Sentry scopes into an OpenTelemetry {@link Context} and apply trace-context adjustments
1464
+ * used by Sentry OpenTelemetry context manager(s).
1465
+ *
1466
+ * @param context - Context passed into `ContextManager.with`.
1467
+ * @param activeContext - Context that was active before entering `with` (e.g. `this.active()`), used
1468
+ * to restore the parent span when the incoming span is marked ignored for children.
1469
+ * @returns A new context ready for `super.with` / `AsyncLocalStorage.run`.
1470
+ */
1471
+ function buildContextWithSentryScopes(context, activeContext) {
1472
+ const span = trace.getSpan(context);
1473
+ let effectiveContext;
1474
+ if (span?.spanContext().traceState?.get(SENTRY_TRACE_STATE_CHILD_IGNORED) === '1') {
1475
+ const contextWithoutSpan = trace.deleteSpan(context);
1476
+ const parentSpan = trace.getSpan(activeContext);
1477
+ effectiveContext = parentSpan ? trace.setSpan(contextWithoutSpan, parentSpan) : contextWithoutSpan;
1478
+ } else {
1479
+ effectiveContext = context;
1480
+ }
1481
+
1482
+ const currentScopes = getScopesFromContext(effectiveContext);
1483
+ const currentScope = currentScopes?.scope || getCurrentScope();
1484
+ const currentIsolationScope = currentScopes?.isolationScope || getIsolationScope();
1485
+
1486
+ const shouldForkIsolationScope = effectiveContext.getValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY) === true;
1487
+ const scope = effectiveContext.getValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY) ;
1488
+ const isolationScope = effectiveContext.getValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY) ;
1489
+
1490
+ const newCurrentScope = scope || currentScope.clone();
1491
+ const newIsolationScope =
1492
+ isolationScope || (shouldForkIsolationScope ? currentIsolationScope.clone() : currentIsolationScope);
1493
+ const scopes = { scope: newCurrentScope, isolationScope: newIsolationScope };
1494
+
1495
+ const ctx1 = setScopesOnContext(effectiveContext, scopes);
1496
+
1497
+ const ctx2 = ctx1
1498
+ .deleteValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY)
1499
+ .deleteValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY)
1500
+ .deleteValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY);
1501
+
1502
+ setContextOnScope(newCurrentScope, ctx2);
1503
+
1504
+ return ctx2;
1505
+ }
1506
+
1451
1507
  /**
1452
1508
  * Wrap an OpenTelemetry ContextManager in a way that ensures the context is kept in sync with the Sentry Scope.
1453
1509
  *
@@ -1455,6 +1511,8 @@ function setOpenTelemetryContextAsyncContextStrategy() {
1455
1511
  * import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';
1456
1512
  * const SentryContextManager = wrapContextManagerClass(AsyncLocalStorageContextManager);
1457
1513
  * const contextManager = new SentryContextManager();
1514
+ *
1515
+ * @deprecated Use {@link SentryAsyncLocalStorageContextManager} instead.
1458
1516
  */
1459
1517
  function wrapContextManagerClass(
1460
1518
  ContextManagerClass,
@@ -1483,45 +1541,7 @@ function wrapContextManagerClass(
1483
1541
  thisArg,
1484
1542
  ...args
1485
1543
  ) {
1486
- // Remove ignored spans from context and restore the parent span so children
1487
- // naturally parent to the grandparent instead of starting a new trace.
1488
- // At this point, this.active() still holds the outer context (before super.with()
1489
- // updates AsyncLocalStorage), which has the grandparent span we want to restore.
1490
- const span = trace.getSpan(context);
1491
- let effectiveContext;
1492
- if (span?.spanContext().traceState?.get(SENTRY_TRACE_STATE_CHILD_IGNORED) === '1') {
1493
- const contextWithoutSpan = trace.deleteSpan(context);
1494
- const parentSpan = trace.getSpan(this.active());
1495
- effectiveContext = parentSpan ? trace.setSpan(contextWithoutSpan, parentSpan) : contextWithoutSpan;
1496
- } else {
1497
- effectiveContext = context;
1498
- }
1499
-
1500
- const currentScopes = getScopesFromContext(effectiveContext);
1501
- const currentScope = currentScopes?.scope || getCurrentScope();
1502
- const currentIsolationScope = currentScopes?.isolationScope || getIsolationScope();
1503
-
1504
- const shouldForkIsolationScope = effectiveContext.getValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY) === true;
1505
- const scope = effectiveContext.getValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY) ;
1506
- const isolationScope = effectiveContext.getValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY)
1507
-
1508
- ;
1509
-
1510
- const newCurrentScope = scope || currentScope.clone();
1511
- const newIsolationScope =
1512
- isolationScope || (shouldForkIsolationScope ? currentIsolationScope.clone() : currentIsolationScope);
1513
- const scopes = { scope: newCurrentScope, isolationScope: newIsolationScope };
1514
-
1515
- const ctx1 = setScopesOnContext(effectiveContext, scopes);
1516
-
1517
- // Remove the unneeded values again
1518
- const ctx2 = ctx1
1519
- .deleteValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY)
1520
- .deleteValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY)
1521
- .deleteValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY);
1522
-
1523
- setContextOnScope(newCurrentScope, ctx2);
1524
-
1544
+ const ctx2 = buildContextWithSentryScopes(context, this.active());
1525
1545
  return super.with(ctx2, fn, thisArg, ...args);
1526
1546
  }
1527
1547
 
@@ -1540,6 +1560,182 @@ function wrapContextManagerClass(
1540
1560
  return SentryContextManager ;
1541
1561
  }
1542
1562
 
1563
+ const ADD_LISTENER_METHODS = ['addListener', 'on', 'once', 'prependListener', 'prependOnceListener'] ;
1564
+
1565
+ /**
1566
+ * OpenTelemetry-compatible context manager using Node.js `AsyncLocalStorage`.
1567
+ * Semantics match `@opentelemetry/context-async-hooks` (function `bind` + `EventEmitter` patching).
1568
+ */
1569
+ class SentryAsyncLocalStorageContextManager {
1570
+ __init() {this._asyncLocalStorage = new AsyncLocalStorage();}
1571
+
1572
+ __init2() {this._kOtListeners = Symbol('OtListeners');}
1573
+ __init3() {this._wrapped = false;}
1574
+
1575
+ constructor() {SentryAsyncLocalStorageContextManager.prototype.__init.call(this);SentryAsyncLocalStorageContextManager.prototype.__init2.call(this);SentryAsyncLocalStorageContextManager.prototype.__init3.call(this);
1576
+ setIsSetup('SentryContextManager');
1577
+ }
1578
+
1579
+ active() {
1580
+ return this._asyncLocalStorage.getStore() ?? ROOT_CONTEXT;
1581
+ }
1582
+
1583
+ with(
1584
+ context,
1585
+ fn,
1586
+ thisArg,
1587
+ ...args
1588
+ ) {
1589
+ const ctx2 = buildContextWithSentryScopes(context, this.active());
1590
+ const cb = thisArg == null ? fn : fn.bind(thisArg);
1591
+ return this._asyncLocalStorage.run(ctx2, cb , ...args);
1592
+ }
1593
+
1594
+ enable() {
1595
+ return this;
1596
+ }
1597
+
1598
+ disable() {
1599
+ this._asyncLocalStorage.disable();
1600
+ return this;
1601
+ }
1602
+
1603
+ bind(context, target) {
1604
+ if (target instanceof EventEmitter) {
1605
+ return this._bindEventEmitter(context, target);
1606
+ }
1607
+ if (typeof target === 'function') {
1608
+ return this._bindFunction(context, target ) ;
1609
+ }
1610
+ return target;
1611
+ }
1612
+
1613
+ /**
1614
+ * Gets underlying AsyncLocalStorage and symbol to allow lookup of scope.
1615
+ * This is Sentry-specific.
1616
+ */
1617
+ getAsyncLocalStorageLookup() {
1618
+ return {
1619
+ asyncLocalStorage: this._asyncLocalStorage,
1620
+ contextSymbol: SENTRY_SCOPES_CONTEXT_KEY,
1621
+ };
1622
+ }
1623
+
1624
+ _bindFunction(context, target) {
1625
+ const managerWith = this.with.bind(this);
1626
+ const contextWrapper = function ( ...args) {
1627
+ return managerWith(context, () => target.apply(this, args));
1628
+ };
1629
+ Object.defineProperty(contextWrapper, 'length', {
1630
+ enumerable: false,
1631
+ configurable: true,
1632
+ writable: false,
1633
+ value: target.length,
1634
+ });
1635
+ return contextWrapper;
1636
+ }
1637
+
1638
+ _bindEventEmitter(context, ee) {
1639
+ if (this._getPatchMap(ee) !== undefined) {
1640
+ return ee;
1641
+ }
1642
+ this._createPatchMap(ee);
1643
+
1644
+ for (const methodName of ADD_LISTENER_METHODS) {
1645
+ if (ee[methodName] === undefined) continue;
1646
+ ee[methodName] = this._patchAddListener(
1647
+ ee,
1648
+ ee[methodName] ,
1649
+ context,
1650
+ );
1651
+ }
1652
+ if (typeof ee.removeListener === 'function') {
1653
+ // oxlint-disable-next-line @typescript-eslint/unbound-method -- patched like upstream OTel context manager
1654
+ ee.removeListener = this._patchRemoveListener(ee, ee.removeListener );
1655
+ }
1656
+ if (typeof ee.off === 'function') {
1657
+ // oxlint-disable-next-line @typescript-eslint/unbound-method
1658
+ ee.off = this._patchRemoveListener(ee, ee.off );
1659
+ }
1660
+ if (typeof ee.removeAllListeners === 'function') {
1661
+ ee.removeAllListeners = this._patchRemoveAllListeners(
1662
+ ee,
1663
+ // oxlint-disable-next-line @typescript-eslint/unbound-method
1664
+ ee.removeAllListeners ,
1665
+ );
1666
+ }
1667
+ return ee;
1668
+ }
1669
+
1670
+ _patchRemoveListener(ee, original) {
1671
+ // oxlint-disable-next-line @typescript-eslint/no-this-alias
1672
+ const contextManager = this;
1673
+ return function ( event, listener) {
1674
+ const events = contextManager._getPatchMap(ee)?.[event];
1675
+ if (events === undefined) {
1676
+ return original.call(this, event, listener);
1677
+ }
1678
+ const patchedListener = events.get(listener);
1679
+ return original.call(this, event, patchedListener || listener);
1680
+ };
1681
+ }
1682
+
1683
+ _patchRemoveAllListeners(ee, original) {
1684
+ // oxlint-disable-next-line @typescript-eslint/no-this-alias
1685
+ const contextManager = this;
1686
+ return function ( event) {
1687
+ const map = contextManager._getPatchMap(ee);
1688
+ if (map !== undefined) {
1689
+ if (arguments.length === 0) {
1690
+ contextManager._createPatchMap(ee);
1691
+ } else if (event !== undefined && map[event] !== undefined) {
1692
+ // oxlint-disable-next-line @typescript-eslint/no-dynamic-delete -- event-keyed listener map
1693
+ delete map[event];
1694
+ }
1695
+ }
1696
+ return original.apply(this, arguments);
1697
+ };
1698
+ }
1699
+
1700
+ _patchAddListener(ee, original, context) {
1701
+ // oxlint-disable-next-line @typescript-eslint/no-this-alias
1702
+ const contextManager = this;
1703
+ return function ( event, listener) {
1704
+ if (contextManager._wrapped) {
1705
+ return original.call(this, event, listener);
1706
+ }
1707
+ let map = contextManager._getPatchMap(ee);
1708
+ if (map === undefined) {
1709
+ map = contextManager._createPatchMap(ee);
1710
+ }
1711
+ let listeners = map[event];
1712
+ if (listeners === undefined) {
1713
+ listeners = new WeakMap();
1714
+ map[event] = listeners;
1715
+ }
1716
+ const patchedListener = contextManager.bind(context, listener);
1717
+ listeners.set(listener, patchedListener);
1718
+
1719
+ contextManager._wrapped = true;
1720
+ try {
1721
+ return original.call(this, event, patchedListener);
1722
+ } finally {
1723
+ contextManager._wrapped = false;
1724
+ }
1725
+ };
1726
+ }
1727
+
1728
+ _createPatchMap(ee) {
1729
+ const map = Object.create(null) ;
1730
+ (ee )[this._kOtListeners] = map;
1731
+ return map;
1732
+ }
1733
+
1734
+ _getPatchMap(ee) {
1735
+ return (ee )[this._kOtListeners];
1736
+ }
1737
+ }
1738
+
1543
1739
  /**
1544
1740
  * This function runs through a list of OTEL Spans, and wraps them in an `SpanNode`
1545
1741
  * where each node holds a reference to their parent node.
@@ -1859,8 +2055,11 @@ class SentrySpanExporter {
1859
2055
  // We'll recursively add all the child spans to this array
1860
2056
  const spans = transactionEvent.spans || [];
1861
2057
 
2058
+ let hasGenAiSpans = false;
1862
2059
  for (const child of root.children) {
1863
- createAndFinishSpanForOtelSpan(child, spans, sentSpans);
2060
+ if (createAndFinishSpanForOtelSpan(child, spans, sentSpans)) {
2061
+ hasGenAiSpans = true;
2062
+ }
1864
2063
  }
1865
2064
 
1866
2065
  // spans.sort() mutates the array, but we do not use this anymore after this point
@@ -1870,6 +2069,13 @@ class SentrySpanExporter {
1870
2069
  ? spans.sort((a, b) => a.start_timestamp - b.start_timestamp).slice(0, MAX_SPAN_COUNT)
1871
2070
  : spans;
1872
2071
 
2072
+ if (hasGenAiSpans) {
2073
+ transactionEvent.sdkProcessingMetadata = {
2074
+ ...transactionEvent.sdkProcessingMetadata,
2075
+ hasGenAiSpans: true,
2076
+ };
2077
+ }
2078
+
1873
2079
  const measurements = timedEventsToMeasurements(span.events);
1874
2080
  if (measurements) {
1875
2081
  transactionEvent.measurements = measurements;
@@ -1986,6 +2192,9 @@ function createTransactionForOtelSpan(span) {
1986
2192
  return transactionEvent;
1987
2193
  }
1988
2194
 
2195
+ /**
2196
+ * Returns `true` if this span or any descendant is a gen_ai span.
2197
+ */
1989
2198
  function createAndFinishSpanForOtelSpan(node, spans, sentSpans) {
1990
2199
  const span = node.span;
1991
2200
 
@@ -1997,10 +2206,13 @@ function createAndFinishSpanForOtelSpan(node, spans, sentSpans) {
1997
2206
 
1998
2207
  // If this span should be dropped, we still want to create spans for the children of this
1999
2208
  if (shouldDrop) {
2209
+ let hasGenAiSpans = false;
2000
2210
  node.children.forEach(child => {
2001
- createAndFinishSpanForOtelSpan(child, spans, sentSpans);
2211
+ if (createAndFinishSpanForOtelSpan(child, spans, sentSpans)) {
2212
+ hasGenAiSpans = true;
2213
+ }
2002
2214
  });
2003
- return;
2215
+ return hasGenAiSpans;
2004
2216
  }
2005
2217
 
2006
2218
  const span_id = span.spanContext().spanId;
@@ -2037,9 +2249,13 @@ function createAndFinishSpanForOtelSpan(node, spans, sentSpans) {
2037
2249
 
2038
2250
  spans.push(spanJSON);
2039
2251
 
2252
+ let hasGenAiSpans = !!op?.startsWith('gen_ai.');
2040
2253
  node.children.forEach(child => {
2041
- createAndFinishSpanForOtelSpan(child, spans, sentSpans);
2254
+ if (createAndFinishSpanForOtelSpan(child, spans, sentSpans)) {
2255
+ hasGenAiSpans = true;
2256
+ }
2042
2257
  });
2258
+ return hasGenAiSpans;
2043
2259
  }
2044
2260
 
2045
2261
  function getSpanData(span)
@@ -2224,6 +2440,7 @@ class SentrySampler {
2224
2440
  // If we have a http.client span that has no local parent, we never want to sample it
2225
2441
  // but we want to leave downstream sampling decisions up to the server
2226
2442
  if (spanKind === SpanKind.CLIENT && maybeSpanHttpMethod && (!parentSpan || parentContext?.isRemote)) {
2443
+ this._client.recordDroppedEvent('no_parent_span', 'span');
2227
2444
  return wrapSamplingDecision({ decision: undefined, context, spanAttributes });
2228
2445
  }
2229
2446
 
@@ -2478,5 +2695,50 @@ function getValidSpan(context) {
2478
2695
  return span && isSpanContextValid(span.spanContext()) ? span : undefined;
2479
2696
  }
2480
2697
 
2481
- export { SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION, SentryPropagator, SentrySampler, SentrySpanProcessor, continueTrace, enhanceDscWithOpenTelemetryRootSpanName, getActiveSpan, getRequestSpanData, getScopesFromContext, getSpanKind, getTraceContextForScope, isSentryRequestSpan, openTelemetrySetupCheck, setOpenTelemetryContextAsyncContextStrategy, setupEventContextTrace, spanHasAttributes, spanHasEvents, spanHasKind, spanHasName, spanHasParentId, spanHasStatus, startInactiveSpan, startSpan, startSpanManual, suppressTracing, withActiveSpan, wrapClientClass, wrapContextManagerClass, wrapSamplingDecision };
2698
+ /**
2699
+ * Minimal Resource implementation that satisfies the OpenTelemetry Resource interface
2700
+ * used by BasicTracerProvider, without depending on `@opentelemetry/resources`.
2701
+ */
2702
+ class SentryResource {
2703
+
2704
+ constructor(attributes) {
2705
+ this._attributes = attributes;
2706
+ }
2707
+
2708
+ get attributes() {
2709
+ return this._attributes;
2710
+ }
2711
+
2712
+ merge(other) {
2713
+ if (!other) {
2714
+ return this;
2715
+ }
2716
+ return new SentryResource({ ...this._attributes, ...other.attributes });
2717
+ }
2718
+
2719
+ getRawAttributes() {
2720
+ return Object.entries(this._attributes);
2721
+ }
2722
+ }
2723
+
2724
+ /**
2725
+ * Returns a Resource for use in Sentry's OpenTelemetry TracerProvider setup.
2726
+ *
2727
+ * Combines the default OTel SDK telemetry attributes with Sentry-specific
2728
+ * service attributes, equivalent to what was previously done via:
2729
+ * `defaultResource().merge(resourceFromAttributes({ ... }))`
2730
+ */
2731
+ function getSentryResource(serviceName) {
2732
+ return new SentryResource({
2733
+ [ATTR_SERVICE_NAME]: serviceName,
2734
+ // eslint-disable-next-line deprecation/deprecation
2735
+ [SEMRESATTRS_SERVICE_NAMESPACE]: 'sentry',
2736
+ [ATTR_SERVICE_VERSION]: SDK_VERSION,
2737
+ [ATTR_TELEMETRY_SDK_LANGUAGE]: SDK_INFO[ATTR_TELEMETRY_SDK_LANGUAGE],
2738
+ [ATTR_TELEMETRY_SDK_NAME]: SDK_INFO[ATTR_TELEMETRY_SDK_NAME],
2739
+ [ATTR_TELEMETRY_SDK_VERSION]: SDK_INFO[ATTR_TELEMETRY_SDK_VERSION],
2740
+ });
2741
+ }
2742
+
2743
+ export { SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION, SentryAsyncLocalStorageContextManager, SentryPropagator, SentrySampler, SentrySpanProcessor, continueTrace, enhanceDscWithOpenTelemetryRootSpanName, getActiveSpan, getRequestSpanData, getScopesFromContext, getSentryResource, getSpanKind, getTraceContextForScope, isSentryRequestSpan, openTelemetrySetupCheck, setOpenTelemetryContextAsyncContextStrategy, setupEventContextTrace, spanHasAttributes, spanHasEvents, spanHasKind, spanHasName, spanHasParentId, spanHasStatus, startInactiveSpan, startSpan, startSpanManual, suppressTracing, withActiveSpan, wrapClientClass, wrapContextManagerClass, wrapSamplingDecision };
2482
2744
  //# sourceMappingURL=index.js.map