@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
package/README.md CHANGED
@@ -43,7 +43,7 @@ This is how you can use this in your app:
43
43
  2. Call `setupEventContextTrace(client)`
44
44
  3. Add `SentrySampler` as sampler
45
45
  4. Add `SentrySpanProcessor` as span processor
46
- 5. Add a context manager wrapped via `wrapContextManagerClass`
46
+ 5. Register the Sentry context manager (`SentryAsyncLocalStorageContextManager`, or `wrapContextManagerClass` for a custom base)
47
47
  6. Add `SentryPropagator` as propagator
48
48
  7. Setup OTEL-powered async context strategy for Sentry via `setOpenTelemetryContextAsyncContextStrategy()`
49
49
 
@@ -52,14 +52,13 @@ For example, you could set this up as follows:
52
52
  ```js
53
53
  import * as Sentry from '@sentry/node';
54
54
  import {
55
+ SentryAsyncLocalStorageContextManager,
55
56
  SentryPropagator,
56
57
  SentrySampler,
57
58
  SentrySpanProcessor,
58
59
  setupEventContextTrace,
59
- wrapContextManagerClass,
60
60
  setOpenTelemetryContextAsyncContextStrategy,
61
61
  } from '@sentry/opentelemetry';
62
- import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';
63
62
  import { context, propagation, trace } from '@opentelemetry/api';
64
63
 
65
64
  function setupSentry() {
@@ -75,12 +74,10 @@ function setupSentry() {
75
74
  });
76
75
  provider.addSpanProcessor(new SentrySpanProcessor());
77
76
 
78
- const SentryContextManager = wrapContextManagerClass(AsyncLocalStorageContextManager);
79
-
80
77
  // Initialize the provider
81
78
  trace.setGlobalTracerProvider(provider);
82
79
  propagation.setGlobalPropagator(new SentryPropagator());
83
- context.setGlobalContextManager(new SentryContextManager());
80
+ context.setGlobalContextManager(new SentryAsyncLocalStorageContextManager());
84
81
 
85
82
  setOpenTelemetryContextAsyncContextStrategy();
86
83
  }
@@ -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
+ exports.DEBUG_BUILD = DEBUG_BUILD;
9
+ //# sourceMappingURL=debug-build-ntZrglYX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"debug-build-ntZrglYX.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;;;;"}
@@ -4,6 +4,9 @@ const semanticConventions = require('@opentelemetry/semantic-conventions');
4
4
  const core = require('@sentry/core');
5
5
  const api = require('@opentelemetry/api');
6
6
  const core$1 = require('@opentelemetry/core');
7
+ const debugBuild = require('./debug-build-ntZrglYX.js');
8
+ const node_async_hooks = require('node:async_hooks');
9
+ const node_events = require('node:events');
7
10
  const sdkTraceBase = require('@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
- core.addNonEnumerableProperty(scope, SCOPE_CONTEXT_FIELD, context);
272
+ core.addNonEnumerableProperty(scope, SCOPE_CONTEXT_FIELD, core.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 core.derefWeakRef((scope )[SCOPE_CONTEXT_FIELD]);
271
281
  }
272
282
 
273
283
  /**
@@ -645,13 +655,6 @@ function getActiveSpan() {
645
655
  return api.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
  */
@@ -704,7 +707,7 @@ class SentryPropagator extends core$1.W3CBaggagePropagator {
704
707
  */
705
708
  inject(context, carrier, setter) {
706
709
  if (core$1.isTracingSuppressed(context)) {
707
- DEBUG_BUILD && core.debug.log('[Tracing] Not injecting trace data for url because tracing is suppressed.');
710
+ debugBuild.DEBUG_BUILD && core.debug.log('[Tracing] Not injecting trace data for url because tracing is suppressed.');
708
711
  return;
709
712
  }
710
713
 
@@ -713,7 +716,7 @@ class SentryPropagator extends core$1.W3CBaggagePropagator {
713
716
 
714
717
  const { tracePropagationTargets, propagateTraceparent } = core.getClient()?.getOptions() || {};
715
718
  if (!core.shouldPropagateTraceForUrl(url, tracePropagationTargets, this._urlMatchesTargetsMap)) {
716
- DEBUG_BUILD &&
719
+ debugBuild.DEBUG_BUILD &&
717
720
  core.debug.log('[Tracing] Not injecting trace data for url because it does not match tracePropagationTargets:', url);
718
721
  return;
719
722
  }
@@ -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 && !api.trace.getSpan(activeCtx);
986
- const ctx = shouldSkipSpan ? core$1.suppressTracing(activeCtx) : activeCtx;
988
+ const missingRequiredParent = options.onlyIfParent && !api.trace.getSpan(activeCtx);
989
+ const ctx = missingRequiredParent ? core$1.suppressTracing(activeCtx) : activeCtx;
990
+
991
+ if (missingRequiredParent) {
992
+ core.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 && !api.trace.getSpan(activeCtx);
1089
- let ctx = shouldSkipSpan ? core$1.suppressTracing(activeCtx) : activeCtx;
1095
+ const missingRequiredParent = options.onlyIfParent && !api.trace.getSpan(activeCtx);
1096
+ let ctx = missingRequiredParent ? core$1.suppressTracing(activeCtx) : activeCtx;
1097
+
1098
+ if (missingRequiredParent) {
1099
+ core.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 = api.trace.getSpan(context);
1473
+ let effectiveContext;
1474
+ if (span?.spanContext().traceState?.get(SENTRY_TRACE_STATE_CHILD_IGNORED) === '1') {
1475
+ const contextWithoutSpan = api.trace.deleteSpan(context);
1476
+ const parentSpan = api.trace.getSpan(activeContext);
1477
+ effectiveContext = parentSpan ? api.trace.setSpan(contextWithoutSpan, parentSpan) : contextWithoutSpan;
1478
+ } else {
1479
+ effectiveContext = context;
1480
+ }
1481
+
1482
+ const currentScopes = getScopesFromContext(effectiveContext);
1483
+ const currentScope = currentScopes?.scope || core.getCurrentScope();
1484
+ const currentIsolationScope = currentScopes?.isolationScope || core.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 = api.trace.getSpan(context);
1491
- let effectiveContext;
1492
- if (span?.spanContext().traceState?.get(SENTRY_TRACE_STATE_CHILD_IGNORED) === '1') {
1493
- const contextWithoutSpan = api.trace.deleteSpan(context);
1494
- const parentSpan = api.trace.getSpan(this.active());
1495
- effectiveContext = parentSpan ? api.trace.setSpan(contextWithoutSpan, parentSpan) : contextWithoutSpan;
1496
- } else {
1497
- effectiveContext = context;
1498
- }
1499
-
1500
- const currentScopes = getScopesFromContext(effectiveContext);
1501
- const currentScope = currentScopes?.scope || core.getCurrentScope();
1502
- const currentIsolationScope = currentScopes?.isolationScope || core.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 node_async_hooks.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() ?? api.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 node_events.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.
@@ -1761,7 +1957,7 @@ class SentrySpanExporter {
1761
1957
  }
1762
1958
  });
1763
1959
  if (droppedSpanCount > 0) {
1764
- DEBUG_BUILD &&
1960
+ debugBuild.DEBUG_BUILD &&
1765
1961
  core.debug.log(
1766
1962
  `SpanExporter dropped ${droppedSpanCount} spans because they were pending for more than ${this._finishedSpanBucketSize} seconds.`,
1767
1963
  );
@@ -1798,7 +1994,7 @@ class SentrySpanExporter {
1798
1994
 
1799
1995
  const sentSpanCount = sentSpans.size;
1800
1996
  const remainingOpenSpanCount = finishedSpans.length - sentSpanCount;
1801
- DEBUG_BUILD &&
1997
+ debugBuild.DEBUG_BUILD &&
1802
1998
  core.debug.log(
1803
1999
  `SpanExporter exported ${sentSpanCount} spans, ${remainingOpenSpanCount} spans are waiting for their parent spans to finish`,
1804
2000
  );
@@ -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 = core.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 === api.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
 
@@ -2339,7 +2556,7 @@ class SentrySampler {
2339
2556
 
2340
2557
  const method = `${maybeSpanHttpMethod}`.toUpperCase();
2341
2558
  if (method === 'OPTIONS' || method === 'HEAD') {
2342
- DEBUG_BUILD && core.debug.log(`[Tracing] Not sampling span because HTTP method is '${method}' for ${spanName}`);
2559
+ debugBuild.DEBUG_BUILD && core.debug.log(`[Tracing] Not sampling span because HTTP method is '${method}' for ${spanName}`);
2343
2560
 
2344
2561
  return wrapSamplingDecision({
2345
2562
  decision: sdkTraceBase.SamplingDecision.NOT_RECORD,
@@ -2355,7 +2572,7 @@ class SentrySampler {
2355
2572
  // 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)
2356
2573
  parentSampled === undefined
2357
2574
  ) {
2358
- DEBUG_BUILD && core.debug.log('[Tracing] Discarding root span because its trace was not chosen to be sampled.');
2575
+ debugBuild.DEBUG_BUILD && core.debug.log('[Tracing] Discarding root span because its trace was not chosen to be sampled.');
2359
2576
  this._client.recordDroppedEvent('sample_rate', this._isSpanStreaming ? 'span' : 'transaction');
2360
2577
  }
2361
2578
 
@@ -2388,13 +2605,13 @@ function getParentSampled(parentSpan, traceId, spanName) {
2388
2605
  if (api.isSpanContextValid(parentContext) && parentContext.traceId === traceId) {
2389
2606
  if (parentContext.isRemote) {
2390
2607
  const parentSampled = getSamplingDecision(parentSpan.spanContext());
2391
- DEBUG_BUILD &&
2608
+ debugBuild.DEBUG_BUILD &&
2392
2609
  core.debug.log(`[Tracing] Inheriting remote parent's sampled decision for ${spanName}: ${parentSampled}`);
2393
2610
  return parentSampled;
2394
2611
  }
2395
2612
 
2396
2613
  const parentSampled = getSamplingDecision(parentContext);
2397
- DEBUG_BUILD && core.debug.log(`[Tracing] Inheriting parent's sampled decision for ${spanName}: ${parentSampled}`);
2614
+ debugBuild.DEBUG_BUILD && core.debug.log(`[Tracing] Inheriting parent's sampled decision for ${spanName}: ${parentSampled}`);
2398
2615
  return parentSampled;
2399
2616
  }
2400
2617
 
@@ -2478,11 +2695,57 @@ function getValidSpan(context) {
2478
2695
  return span && api.isSpanContextValid(span.spanContext()) ? span : undefined;
2479
2696
  }
2480
2697
 
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
+ [semanticConventions.ATTR_SERVICE_NAME]: serviceName,
2734
+ // eslint-disable-next-line deprecation/deprecation
2735
+ [semanticConventions.SEMRESATTRS_SERVICE_NAMESPACE]: 'sentry',
2736
+ [semanticConventions.ATTR_SERVICE_VERSION]: core.SDK_VERSION,
2737
+ [semanticConventions.ATTR_TELEMETRY_SDK_LANGUAGE]: core$1.SDK_INFO[semanticConventions.ATTR_TELEMETRY_SDK_LANGUAGE],
2738
+ [semanticConventions.ATTR_TELEMETRY_SDK_NAME]: core$1.SDK_INFO[semanticConventions.ATTR_TELEMETRY_SDK_NAME],
2739
+ [semanticConventions.ATTR_TELEMETRY_SDK_VERSION]: core$1.SDK_INFO[semanticConventions.ATTR_TELEMETRY_SDK_VERSION],
2740
+ });
2741
+ }
2742
+
2481
2743
  exports.getClient = core.getClient;
2482
2744
  exports.getDynamicSamplingContextFromSpan = core.getDynamicSamplingContextFromSpan;
2483
2745
  exports.shouldPropagateTraceForUrl = core.shouldPropagateTraceForUrl;
2484
2746
  exports.withStreamedSpan = core.withStreamedSpan;
2485
2747
  exports.SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION = SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION;
2748
+ exports.SentryAsyncLocalStorageContextManager = SentryAsyncLocalStorageContextManager;
2486
2749
  exports.SentryPropagator = SentryPropagator;
2487
2750
  exports.SentrySampler = SentrySampler;
2488
2751
  exports.SentrySpanProcessor = SentrySpanProcessor;
@@ -2491,6 +2754,7 @@ exports.enhanceDscWithOpenTelemetryRootSpanName = enhanceDscWithOpenTelemetryRoo
2491
2754
  exports.getActiveSpan = getActiveSpan;
2492
2755
  exports.getRequestSpanData = getRequestSpanData;
2493
2756
  exports.getScopesFromContext = getScopesFromContext;
2757
+ exports.getSentryResource = getSentryResource;
2494
2758
  exports.getSpanKind = getSpanKind;
2495
2759
  exports.getTraceContextForScope = getTraceContextForScope;
2496
2760
  exports.isSentryRequestSpan = isSentryRequestSpan;