@coralogix/react-native-plugin 0.14.2 → 0.15.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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,15 @@
1
+ ## 0.15.0 (2026-11-01)
2
+
3
+ ### 🚀 Features
4
+
5
+ - `excludeFromSampling` now accepts `navigation` and `lifecycle`, so it takes the same values on React Native, iOS, and Android.
6
+ - The `traceparent` header now ends in `00` for a sampled-out session and `01` for a sampled-in one, matching the native SDKs.
7
+ - An unrecognized `excludeFromSampling` value is now logged as a warning instead of being ignored silently.
8
+
9
+ ### ⬆️ Dependency Updates
10
+
11
+ - Native iOS SDK bumped to **2.22.0** and native Android SDK to **2.25.0**.
12
+
1
13
  ## 0.14.2 (2026-10-20)
2
14
 
3
15
  ### 🩹 Fixes
package/CxSdk.podspec CHANGED
@@ -16,9 +16,9 @@ Pod::Spec.new do |s|
16
16
 
17
17
  s.source_files = "ios/**/*.{h,m,mm,swift}"
18
18
 
19
- s.dependency 'Coralogix','2.20.2'
20
- s.dependency 'CoralogixInternal','2.20.2'
21
- s.dependency 'SessionReplay','2.20.2'
19
+ s.dependency 'Coralogix','2.22.0'
20
+ s.dependency 'CoralogixInternal','2.22.0'
21
+ s.dependency 'SessionReplay','2.22.0'
22
22
 
23
23
  # Use install_modules_dependencies helper to install the dependencies if React Native version >=0.71.0.
24
24
  # See https://github.com/facebook/react-native/blob/febf6b7f33fdb4904669f99d795eba4c0f95d7bf/scripts/cocoapods/new_architecture.rb#L79.
package/README.md CHANGED
@@ -287,7 +287,10 @@ await CoralogixRum.init({
287
287
  ```
288
288
 
289
289
  Allowed values: `'errors'`, `'logs'`, `'network'`, `'userInteractions'`,
290
- `'mobileVitals'`, `'customSpan'`, `'customMeasurement'`.
290
+ `'mobileVitals'`, `'customSpan'`, `'customMeasurement'`, `'navigation'`, and
291
+ `'lifecycle'`. `'navigation'` and `'lifecycle'` are available from version 0.15.0.
292
+ These are the same values the native iOS and Android SDKs accept. The plugin ignores
293
+ an unrecognized value and logs a warning that names it.
291
294
 
292
295
  `excludeFromSampling` only affects sampled-out sessions; a sampled-in session
293
296
  reports everything that is enabled. It never re-enables an instrumentation you
@@ -335,6 +338,21 @@ await CoralogixRum.init({
335
338
  > you set `instrumentations.network` to `false`, no trace headers are sent even with
336
339
  > `enabled: true`.
337
340
 
341
+ From version 0.15.0, the trace flags at the end of `traceparent` follow the session's
342
+ sampling decision, on iOS and Android alike:
343
+
344
+ - `01` (sampled) when the session is sampled in, or when it is sampled out and
345
+ `excludeFromSampling` includes `'network'`.
346
+ - `00` (not sampled) when the session is sampled out and `'network'` is not excluded.
347
+
348
+ A request that starts before `CoralogixRum.init` completes carries no `traceparent` header.
349
+
350
+ If your Android app doesn't apply the Coralogix Gradle plugin, the plugin adds the header
351
+ from JavaScript. Each `fetch` that gets a `traceparent` then waits up to 500 ms for the
352
+ native SDK's sampling decision, and goes out without the header if the decision doesn't
353
+ arrive in time. To keep that wait off requests you don't need to trace, list only your own
354
+ services in `traceParentInHeader.options.allowedTracingUrls`.
355
+
338
356
  <!-- /split -->
339
357
  <!-- split title="Custom instrumentation" path="features/custom-instrumentation.md" -->
340
358
  ### Custom Spans
@@ -89,7 +89,9 @@ dependencies {
89
89
  // 2.22.0 is the first release exposing View.isCoralogixMasked() and
90
90
  // View.isInsideCoralogixMaskedSubtree(), which the masked-interaction walk in
91
91
  // reportUserInteraction reads instead of reimplementing the SDK's mask rule here.
92
- implementation "com.coralogix:android-sdk:2.24.1"
92
+ // 2.25.0 adds CoralogixRum.networkRequestSampling() and the traceparent echo fields on
93
+ // NetworkRequestDetails, which the JS traceparent flag depends on.
94
+ implementation "com.coralogix:android-sdk:2.25.0"
93
95
 
94
96
  testImplementation "org.jetbrains.kotlin:kotlin-test:$kotlin_version"
95
97
  testImplementation "org.mockito:mockito-core:5.12.0"
@@ -51,12 +51,15 @@ import org.json.JSONObject
51
51
  import com.facebook.react.bridge.UiThreadUtil
52
52
  import com.facebook.react.uimanager.UIManagerHelper
53
53
  import java.util.concurrent.ConcurrentHashMap
54
+ import java.util.concurrent.Executors
55
+ import java.util.concurrent.RejectedExecutionException
54
56
 
55
57
  class CxSdkModule(reactContext: ReactApplicationContext) :
56
58
  ReactContextBaseJavaModule(reactContext), RUMClient, SessionReplayClient {
57
59
 
58
60
  private val globalSpans = ConcurrentHashMap<String, CoralogixGlobalSpan>()
59
61
  private val customSpans = ConcurrentHashMap<String, CoralogixCustomSpan>()
62
+ private val samplingExecutor = Executors.newSingleThreadExecutor()
60
63
 
61
64
  override fun getName(): String {
62
65
  return NAME
@@ -263,6 +266,34 @@ class CxSdkModule(reactContext: ReactApplicationContext) :
263
266
  promise.resolve(applied)
264
267
  }
265
268
 
269
+ @ReactMethod
270
+ override fun networkRequestSampling(promise: Promise) {
271
+ // Off the JS thread: answering may rotate a session that is due, which does real work.
272
+ try {
273
+ samplingExecutor.execute { promise.resolve(networkRequestSamplingAnswer()) }
274
+ } catch (e: RejectedExecutionException) {
275
+ // The bridge is being torn down.
276
+ promise.resolve(unknownNetworkRequestSampling())
277
+ }
278
+ }
279
+
280
+ private fun networkRequestSamplingAnswer(): WritableMap = try {
281
+ val sampling = CoralogixRum.networkRequestSampling()
282
+ Arguments.createMap().apply {
283
+ putBoolean("isSampled", sampling.isSampled)
284
+ putString("sessionId", sampling.sessionId)
285
+ }
286
+ } catch (e: Throwable) {
287
+ // Never reject: JS reads a null session as "unknown" and sends no traceparent.
288
+ Log.w(NAME, "networkRequestSampling failed — $e")
289
+ unknownNetworkRequestSampling()
290
+ }
291
+
292
+ private fun unknownNetworkRequestSampling(): WritableMap = Arguments.createMap().apply {
293
+ putBoolean("isSampled", false)
294
+ putNull("sessionId")
295
+ }
296
+
266
297
  @ReactMethod
267
298
  override fun shutdown(promise: Promise) {
268
299
  Handler(Looper.getMainLooper()).post {
@@ -563,6 +594,7 @@ class CxSdkModule(reactContext: ReactApplicationContext) :
563
594
  super.invalidate()
564
595
  globalSpans.clear()
565
596
  customSpans.clear()
597
+ samplingExecutor.shutdown()
566
598
  Handler(Looper.getMainLooper()).post {
567
599
  Log.d("CxSdkModule", "Bridge destroyed — shutting down CoralogixRum")
568
600
  CoralogixRum.shutdown()
@@ -1008,7 +1040,11 @@ class CxSdkModule(reactContext: ReactApplicationContext) :
1008
1040
  requestPayload = if (hasKey("request_payload") && !isNull("request_payload"))
1009
1041
  getString("request_payload") else null,
1010
1042
  responsePayload = if (hasKey("response_payload") && !isNull("response_payload"))
1011
- getString("response_payload") else null
1043
+ getString("response_payload") else null,
1044
+ traceparentSampled = if (hasKey("traceparentSampled") && getType("traceparentSampled") == ReadableType.Boolean)
1045
+ getBoolean("traceparentSampled") else null,
1046
+ traceparentSessionId = if (hasKey("traceparentSessionId") && !isNull("traceparentSessionId"))
1047
+ getString("traceparentSessionId") else null
1012
1048
  ).also { Log.d("CxSdkModule", "toNetworkRequestDetails: $it") }
1013
1049
 
1014
1050
  private fun ReadableArray.toNetworkCaptureRuleList(): List<NetworkCaptureRule> {
@@ -1051,23 +1087,10 @@ class CxSdkModule(reactContext: ReactApplicationContext) :
1051
1087
  return set
1052
1088
  }
1053
1089
 
1054
- private fun ReadableArray.toExcludeFromSamplingList(): List<ExcludableInstrumentation> {
1055
- val set = LinkedHashSet<ExcludableInstrumentation>()
1056
- for (i in 0 until size()) {
1057
- val value = getString(i)
1058
- when (value) {
1059
- "errors" -> set.add(ExcludableInstrumentation.Errors)
1060
- "logs" -> set.add(ExcludableInstrumentation.Logs)
1061
- "network" -> set.add(ExcludableInstrumentation.Network)
1062
- "userInteractions" -> set.add(ExcludableInstrumentation.UserInteractions)
1063
- "mobileVitals" -> set.add(ExcludableInstrumentation.MobileVitals)
1064
- "customSpan" -> set.add(ExcludableInstrumentation.CustomSpan)
1065
- "customMeasurement" -> set.add(ExcludableInstrumentation.CustomMeasurement)
1066
- else -> Log.w("CxSdkModule", "excludeFromSampling: unrecognized value '$value' — native enum may have drifted")
1067
- }
1068
- }
1069
- return set.toList()
1070
- }
1090
+ private fun ReadableArray.toExcludeFromSamplingList(): List<ExcludableInstrumentation> =
1091
+ toExcludeFromSamplingList((0 until size()).map { i ->
1092
+ if (getType(i) == ReadableType.String) getString(i) else null
1093
+ })
1071
1094
 
1072
1095
  private fun ReadableArray.toHybridMetricList(): List<HybridMetric> {
1073
1096
  val out = ArrayList<HybridMetric>(size())
@@ -1111,6 +1134,29 @@ class CxSdkModule(reactContext: ReactApplicationContext) :
1111
1134
  "user_interaction" to Instrumentation.UserInteraction,
1112
1135
  )
1113
1136
 
1137
+ // The JS `ExcludableInstrumentation` strings. Spelled out here because the native enum's
1138
+ // `rawValue` is internal; ExcludeFromSamplingTest fails when a native case has no entry.
1139
+ internal val EXCLUDABLE_INSTRUMENTATIONS = mapOf(
1140
+ "errors" to ExcludableInstrumentation.Errors,
1141
+ "logs" to ExcludableInstrumentation.Logs,
1142
+ "network" to ExcludableInstrumentation.Network,
1143
+ "userInteractions" to ExcludableInstrumentation.UserInteractions,
1144
+ "mobileVitals" to ExcludableInstrumentation.MobileVitals,
1145
+ "customSpan" to ExcludableInstrumentation.CustomSpan,
1146
+ "customMeasurement" to ExcludableInstrumentation.CustomMeasurement,
1147
+ "navigation" to ExcludableInstrumentation.Navigation,
1148
+ "lifecycle" to ExcludableInstrumentation.Lifecycle,
1149
+ )
1150
+
1151
+ /** Maps the JS values, warning once about any it does not know (`null` is a non-string). */
1152
+ internal fun toExcludeFromSamplingList(values: List<String?>): List<ExcludableInstrumentation> {
1153
+ val (known, dropped) = values.partition { it in EXCLUDABLE_INSTRUMENTATIONS }
1154
+ if (dropped.isNotEmpty()) {
1155
+ Log.w(NAME, "excludeFromSampling: ignoring unrecognized values $dropped")
1156
+ }
1157
+ return known.mapNotNull { EXCLUDABLE_INSTRUMENTATIONS[it] }.distinct()
1158
+ }
1159
+
1114
1160
  internal fun toInstrumentationMap(map: ReadableMap): Map<Instrumentation, Boolean> =
1115
1161
  INSTRUMENTATION_KEYS.entries.associate { (key, instrumentation) ->
1116
1162
  // Only an explicit boolean switches an instrumentation; null or a wrong type keeps the default.
@@ -24,6 +24,7 @@ interface RUMClient {
24
24
  fun reportMobileVitalsMeasurement(type: String, value: Double, units: String)
25
25
  fun reportMobileVitalsMeasurementSet(type: String, metrics: ReadableArray)
26
26
  fun isCoralogixGradlePluginApplied(promise: Promise)
27
+ fun networkRequestSampling(promise: Promise)
27
28
  fun shutdown(promise: Promise)
28
29
  fun createNewSession(promise: Promise)
29
30
 
@@ -0,0 +1,52 @@
1
+ package com.cxsdk
2
+
3
+ import com.coralogix.android.sdk.model.ExcludableInstrumentation
4
+ import kotlin.test.Test
5
+ import kotlin.test.assertEquals
6
+ import kotlin.test.assertTrue
7
+
8
+ class ExcludeFromSamplingTest {
9
+
10
+ // The JS `EXCLUDABLE_INSTRUMENTATIONS`, asserted on the TS side too; change both together.
11
+ private val jsValues = listOf(
12
+ "errors",
13
+ "logs",
14
+ "network",
15
+ "userInteractions",
16
+ "mobileVitals",
17
+ "customSpan",
18
+ "customMeasurement",
19
+ "navigation",
20
+ "lifecycle",
21
+ )
22
+
23
+ @Test
24
+ fun `every native case is produced by some JS string`() {
25
+ val produced = CxSdkModule.toExcludeFromSamplingList(jsValues).toSet()
26
+
27
+ for (case in ExcludableInstrumentation.entries) {
28
+ assertTrue(case in produced, "no JS string maps to $case")
29
+ }
30
+ }
31
+
32
+ @Test
33
+ fun `every JS string maps to a native case`() {
34
+ for (value in jsValues) {
35
+ assertEquals(1, CxSdkModule.toExcludeFromSamplingList(listOf(value)).size, "'$value' does not map")
36
+ }
37
+ }
38
+
39
+ @Test
40
+ fun `unknown and non-string values are dropped without failing`() {
41
+ val result = CxSdkModule.toExcludeFromSamplingList(listOf("network", "sessionReplay", null))
42
+
43
+ assertEquals(listOf(ExcludableInstrumentation.Network), result)
44
+ }
45
+
46
+ @Test
47
+ fun `duplicates collapse to one entry`() {
48
+ val result = CxSdkModule.toExcludeFromSamplingList(listOf("logs", "logs"))
49
+
50
+ assertEquals(listOf(ExcludableInstrumentation.Logs), result)
51
+ }
52
+ }
package/index.cjs.js CHANGED
@@ -4,6 +4,7 @@ var reactNative = require('react-native');
4
4
  var React = require('react');
5
5
  var instrumentation = require('@opentelemetry/instrumentation');
6
6
  var instrumentationFetch = require('@opentelemetry/instrumentation-fetch');
7
+ var api = require('@opentelemetry/api');
7
8
  var sdkTraceWeb = require('@opentelemetry/sdk-trace-web');
8
9
  var core = require('@opentelemetry/core');
9
10
 
@@ -48,47 +49,10 @@ let CoralogixLogSeverity = /*#__PURE__*/function (CoralogixLogSeverity) {
48
49
  return CoralogixLogSeverity;
49
50
  }({});
50
51
 
51
- /**
52
- * `interaction_context` as it appears on a user-interaction RUM event — the
53
- * shape `beforeSend` receives. Built natively (field names differ from the
54
- * {@link InteractionContext} payload JS hands to the bridge).
55
- *
56
- * Intentionally editable in `beforeSend` (except `is_masked_element`): a
57
- * callback may blank the coordinates in `attributes`, redact text fields, or
58
- * drop the whole event to enforce a masking policy stricter than the default.
59
- */
60
-
61
- /** Versions of the plugin and the underlying native SDK that produced an event. */
62
-
63
- /**
64
- * A RUM event as it goes on the wire.
65
- *
66
- * Fields marked `readonly` are SDK-owned: span identity, dedup keys, SDK-owned
67
- * counters and the SDK's own observations. `beforeSend` may read them, but the
68
- * SDK's value is always restored after the callback returns — assigning to one
69
- * has no effect on the sent event.
70
- */
71
-
72
- /**
73
- * The view of an event that `beforeSend` receives.
74
- *
75
- * Only the user fields of `session_context` are editable — session identity, the
76
- * sampling decision and the recording flag are SDK-owned and are restored from
77
- * the SDK's own values after the callback returns. The same holds for the
78
- * `readonly` fields inherited from {@link CxRumEvent}. Nothing a callback writes
79
- * to those can reach the wire, so they cannot be forged.
80
- */
81
-
82
- /**
83
- * Instrumentation names that can be excluded from a custom tracer's span context.
84
- * Pass one or more values to `getCustomTracer()` to prevent those event types from
85
- * being linked to spans created by that tracer.
86
- */
87
-
88
52
  /**
89
53
  * Event categories that can opt out of session sampling. When the session is
90
54
  * sampled out, events whose category is listed in `excludeFromSampling` are still
91
- * emitted; everything else is dropped. Mirrors the iOS/Android native enums.
55
+ * emitted; everything else is dropped.
92
56
  */
93
57
 
94
58
  /** OTLP JSON-format trace data delivered to the `tracesExporter` callback. */
@@ -1140,7 +1104,7 @@ function stopJsRefreshRateSampler() {
1140
1104
  appStateSub = null;
1141
1105
  }
1142
1106
 
1143
- var version = "0.14.2";
1107
+ var version = "0.15.0";
1144
1108
  var pkg = {
1145
1109
  version: version};
1146
1110
 
@@ -1419,6 +1383,157 @@ function serializeNetworkCaptureRules(rules) {
1419
1383
  });
1420
1384
  }
1421
1385
 
1386
+ /**
1387
+ * The native module, or a proxy that throws on first use when it is missing.
1388
+ *
1389
+ * Lives in its own leaf module so anything needing the bridge — the masking
1390
+ * components included — can reach it without importing the SDK entry point and
1391
+ * cycling back through it. `CxSdkClient` is imported as a type only, so the
1392
+ * declaration site stays in `index.ts` with nothing cycling at runtime.
1393
+ */
1394
+
1395
+ const LINKING_ERROR = `The package 'cx-plugin' doesn't seem to be linked. Make sure: \n\n` + reactNative.Platform.select({
1396
+ ios: "- You have run 'pod install'\n",
1397
+ default: ''
1398
+ }) + '- You rebuilt the app after installing the package\n' + '- You are not using Expo Go\n';
1399
+ function createErrorProxy(errorMessage) {
1400
+ return new Proxy({}, {
1401
+ get() {
1402
+ throw new Error(errorMessage);
1403
+ }
1404
+ });
1405
+ }
1406
+ const CxSdk = reactNative.NativeModules.CxSdk ? reactNative.NativeModules.CxSdk : createErrorProxy(LINKING_ERROR);
1407
+
1408
+ /**
1409
+ * How long a request waits for the native sampling answer. Past it the answer is treated
1410
+ * as unknown: no `traceparent`, and nothing echoed on the report.
1411
+ */
1412
+ const NETWORK_SAMPLING_TIMEOUT_MS = 500;
1413
+
1414
+ /** The native `networkRequestSampling()` answer, for a session that exists. */
1415
+
1416
+ /** `undefined` is the unknown answer: before init, a bridge failure, or a timeout. */
1417
+
1418
+ /**
1419
+ * What one request carries through the OTel context: the pending answer, and the
1420
+ * settled one when the request waited for it before starting.
1421
+ */
1422
+
1423
+ const REQUEST_SAMPLING_KEY = api.createContextKey('coralogix.network_request_sampling');
1424
+
1425
+ /** Pending answers by span, read once by the report path. */
1426
+ const pendingBySpan = new WeakMap();
1427
+
1428
+ /**
1429
+ * Asks native whether a request starting now is sampled, and for which session. Ask once
1430
+ * per request and never cache the answer: the session can rotate at any moment. Never
1431
+ * rejects; anything but a well-formed answer for a live session resolves to unknown.
1432
+ */
1433
+ function requestNetworkSampling() {
1434
+ let timer;
1435
+ const timeout = new Promise(resolve => {
1436
+ timer = setTimeout(() => resolve(undefined), NETWORK_SAMPLING_TIMEOUT_MS);
1437
+ });
1438
+ // Through `then` so a synchronous throw (an unlinked module) also lands in the catch.
1439
+ const call = Promise.resolve().then(() => CxSdk.networkRequestSampling()).then(toKnownAnswer, () => undefined);
1440
+ return Promise.race([call, timeout]).finally(() => clearTimeout(timer));
1441
+ }
1442
+ function toKnownAnswer(raw) {
1443
+ if (typeof raw !== 'object' || raw === null) return undefined;
1444
+ const {
1445
+ isSampled,
1446
+ sessionId
1447
+ } = raw;
1448
+ if (typeof isSampled !== 'boolean') return undefined;
1449
+ if (typeof sessionId !== 'string' || sessionId.length === 0) return undefined;
1450
+ return {
1451
+ isSampled,
1452
+ sessionId
1453
+ };
1454
+ }
1455
+
1456
+ /** `context` with this request's sampling attached, for the sampler, propagator and processor. */
1457
+ function withRequestSampling(context, pending, answer) {
1458
+ const value = {
1459
+ pending,
1460
+ answer
1461
+ };
1462
+ return context.setValue(REQUEST_SAMPLING_KEY, value);
1463
+ }
1464
+ function requestSamplingOf(context) {
1465
+ return context.getValue(REQUEST_SAMPLING_KEY);
1466
+ }
1467
+
1468
+ /**
1469
+ * The answer a request was reported with: the one it started with, awaited now if the
1470
+ * request did not wait for it. `undefined` when the request carried none.
1471
+ */
1472
+ function takeNetworkSampling(span) {
1473
+ const pending = pendingBySpan.get(span);
1474
+ pendingBySpan.delete(span);
1475
+ return pending != null ? pending : Promise.resolve(undefined);
1476
+ }
1477
+
1478
+ /**
1479
+ * Sets the span's sampled flag from the native answer, so the W3C propagator writes the
1480
+ * flag byte native would: `01` sampled, `00` not. A sampled-out span still records,
1481
+ * because the report path reads its attributes, and native drops the event itself.
1482
+ */
1483
+ class NetworkRequestSampler {
1484
+ shouldSample(context) {
1485
+ var _requestSamplingOf;
1486
+ const sampled = ((_requestSamplingOf = requestSamplingOf(context)) == null || (_requestSamplingOf = _requestSamplingOf.answer) == null ? void 0 : _requestSamplingOf.isSampled) !== false;
1487
+ return {
1488
+ decision: sampled ? sdkTraceWeb.SamplingDecision.RECORD_AND_SAMPLED : sdkTraceWeb.SamplingDecision.RECORD
1489
+ };
1490
+ }
1491
+ toString() {
1492
+ return 'NetworkRequestSampler';
1493
+ }
1494
+ }
1495
+
1496
+ /**
1497
+ * W3C trace context. A request the plugin's fetch wrapper started gets it only once
1498
+ * native has answered: without an answer (before init, a bridge failure, or a timeout)
1499
+ * no `traceparent` is sent, as native instruments nothing before it is initialized.
1500
+ * Anything else injecting through the global propagator is passed through untouched.
1501
+ */
1502
+ class NetworkSamplingPropagator {
1503
+ constructor() {
1504
+ this.w3c = new core.W3CTraceContextPropagator();
1505
+ }
1506
+ inject(context, carrier, setter) {
1507
+ const sampling = requestSamplingOf(context);
1508
+ if (sampling && !sampling.answer) return;
1509
+ this.w3c.inject(context, carrier, setter);
1510
+ }
1511
+ extract(context, carrier, getter) {
1512
+ return this.w3c.extract(context, carrier, getter);
1513
+ }
1514
+ fields() {
1515
+ return this.w3c.fields();
1516
+ }
1517
+ }
1518
+
1519
+ /** Remembers each request span's pending answer so the report path can echo it. */
1520
+ class NetworkSamplingSpanProcessor {
1521
+ onStart(span, parentContext) {
1522
+ const sampling = requestSamplingOf(parentContext);
1523
+ if (sampling) pendingBySpan.set(span, sampling.pending);
1524
+ }
1525
+ onEnd() {}
1526
+ forceFlush() {
1527
+ return Promise.resolve();
1528
+ }
1529
+ shutdown() {
1530
+ return Promise.resolve();
1531
+ }
1532
+ }
1533
+
1534
+ // Module state rather than fields: the OTel base constructor calls `enable()` before a
1535
+ // subclass's fields exist.
1536
+ let samplingWrapper;
1422
1537
  class CoralogixFetchInstrumentation extends instrumentationFetch.FetchInstrumentation {
1423
1538
  constructor(config) {
1424
1539
  var _traceParentInHeader$;
@@ -1427,10 +1542,11 @@ class CoralogixFetchInstrumentation extends instrumentationFetch.FetchInstrument
1427
1542
  } = config;
1428
1543
  const enabled = (traceParentInHeader == null ? void 0 : traceParentInHeader.enabled) === true;
1429
1544
  const urls = traceParentInHeader == null || (_traceParentInHeader$ = traceParentInHeader.options) == null ? void 0 : _traceParentInHeader$.allowedTracingUrls;
1545
+ const propagateTraceHeaderCorsUrls = enabled ? urls != null ? urls : /.*/ : allowNone();
1430
1546
  const fetchConfig = {
1431
1547
  // If disabled -> match nothing -> no traceparent injection
1432
1548
  // If enabled and user didn't provide urls -> match all
1433
- propagateTraceHeaderCorsUrls: enabled ? urls != null ? urls : /.*/ : allowNone()
1549
+ propagateTraceHeaderCorsUrls
1434
1550
  };
1435
1551
  fetchConfig.applyCustomAttributesOnSpan = async function (span, request, result) {
1436
1552
  // span.end() must remain synchronous and first — this completes the OTel span
@@ -1523,13 +1639,79 @@ class CoralogixFetchInstrumentation extends instrumentationFetch.FetchInstrument
1523
1639
  }
1524
1640
  }
1525
1641
 
1642
+ // Echo the answer the request started with, header or not, so native reports it in that
1643
+ // session or drops it. Unknown leaves both out: native then uses the live session.
1644
+ const sampling = await takeNetworkSampling(span);
1645
+ if (sampling) {
1646
+ details.traceparentSampled = sampling.isSampled;
1647
+ details.traceparentSessionId = sampling.sessionId;
1648
+ }
1649
+
1526
1650
  // reportNetworkRequest must always be last, after all awaits
1527
1651
  CoralogixRum.reportNetworkRequest(details);
1528
1652
  };
1529
1653
  super(fetchConfig);
1530
1654
  }
1531
1655
  enable() {
1656
+ // OTel re-patches only a fetch it recognizes as its own, so take ours off first and put
1657
+ // it back outermost: the sampling answer has to be in the context before OTel's patch
1658
+ // starts the span and writes the header.
1659
+ removeSamplingWrapper();
1532
1660
  super.enable();
1661
+ installSamplingWrapper(this.getConfig().propagateTraceHeaderCorsUrls);
1662
+ }
1663
+ disable() {
1664
+ removeSamplingWrapper();
1665
+ super.disable();
1666
+ }
1667
+ }
1668
+
1669
+ /**
1670
+ * Wraps `fetch` so every request asks native for its sampling answer as it starts. Only a
1671
+ * request that will carry a `traceparent` waits for it; any other starts at once, and the
1672
+ * report path, which runs after the response, waits instead.
1673
+ */
1674
+ function installSamplingWrapper(corsUrls) {
1675
+ const inner = globalThis.fetch;
1676
+ if (typeof inner !== 'function') return;
1677
+
1678
+ // Typed off `fetch` itself: the build's DOM lib takes `RequestInfo`, newer ones `RequestInfo | URL`.
1679
+ const wrapper = function wrapper(...args) {
1680
+ // Removed but still in a chain something else wrapped over it: pass straight through.
1681
+ if (!state.active) return inner.apply(this, args);
1682
+ const pending = requestNetworkSampling();
1683
+ const send = answer => api.context.with(withRequestSampling(api.context.active(), pending, answer), () => inner.apply(this, args));
1684
+ const url = requestUrl(args[0]);
1685
+ if (url === undefined || !sdkTraceWeb.shouldPropagateTraceHeaders(url, corsUrls)) return send();
1686
+ return pending.then(send);
1687
+ };
1688
+ const state = {
1689
+ wrapper,
1690
+ inner,
1691
+ active: true
1692
+ };
1693
+ globalThis.fetch = wrapper;
1694
+ samplingWrapper = state;
1695
+ }
1696
+ function removeSamplingWrapper() {
1697
+ if (!samplingWrapper) return;
1698
+ samplingWrapper.active = false;
1699
+ // Something else may have wrapped fetch over ours since; leave that chain alone.
1700
+ if (globalThis.fetch === samplingWrapper.wrapper) globalThis.fetch = samplingWrapper.inner;
1701
+ samplingWrapper = undefined;
1702
+ }
1703
+
1704
+ /**
1705
+ * The URL as OTel's fetch patch matches it against the allow list: normalized, so the
1706
+ * wrapper waits for exactly the requests OTel will write a header on. `undefined` when it
1707
+ * does not parse; OTel's patch then fails the request the same way, and nothing waits.
1708
+ */
1709
+ function requestUrl(input) {
1710
+ const raw = typeof Request !== 'undefined' && input instanceof Request ? input.url : String(input);
1711
+ try {
1712
+ return sdkTraceWeb.parseUrl(raw).href;
1713
+ } catch (_unused3) {
1714
+ return undefined;
1533
1715
  }
1534
1716
  }
1535
1717
  function allowNone() {
@@ -1551,28 +1733,6 @@ function isSessionReplayOptionsValid(options) {
1551
1733
  return scaleValid && sampleRateValid && qualityValid;
1552
1734
  }
1553
1735
 
1554
- /**
1555
- * The native module, or a proxy that throws on first use when it is missing.
1556
- *
1557
- * Lives in its own leaf module so anything needing the bridge — the masking
1558
- * components included — can reach it without importing the SDK entry point and
1559
- * cycling back through it. `CxSdkClient` is imported as a type only, so the
1560
- * declaration site stays in `index.ts` with nothing cycling at runtime.
1561
- */
1562
-
1563
- const LINKING_ERROR = `The package 'cx-plugin' doesn't seem to be linked. Make sure: \n\n` + reactNative.Platform.select({
1564
- ios: "- You have run 'pod install'\n",
1565
- default: ''
1566
- }) + '- You rebuilt the app after installing the package\n' + '- You are not using Expo Go\n';
1567
- function createErrorProxy(errorMessage) {
1568
- return new Proxy({}, {
1569
- get() {
1570
- throw new Error(errorMessage);
1571
- }
1572
- });
1573
- }
1574
- const CxSdk = reactNative.NativeModules.CxSdk ? reactNative.NativeModules.CxSdk : createErrorProxy(LINKING_ERROR);
1575
-
1576
1736
  const reportFailure = viewTag => error => {
1577
1737
  // Dropped from the registry so a later layout pass retries rather than
1578
1738
  // being deduped against a registration that did not take.
@@ -2272,9 +2432,15 @@ async function registerCoralogixInstrumentations(options) {
2272
2432
  if (options.beforeSend) {
2273
2433
  beforeSendCallback = options.beforeSend;
2274
2434
  }
2275
- const tracerProvider = new sdkTraceWeb.WebTracerProvider();
2435
+
2436
+ // The sampler and propagator take the flag from native's per-request answer, so a
2437
+ // `traceparent` JS writes carries the same `00`/`01` native would write itself.
2438
+ const tracerProvider = new sdkTraceWeb.WebTracerProvider({
2439
+ sampler: new NetworkRequestSampler(),
2440
+ spanProcessors: [new NetworkSamplingSpanProcessor()]
2441
+ });
2276
2442
  tracerProvider.register({
2277
- propagator: new core.W3CTraceContextPropagator()
2443
+ propagator: new NetworkSamplingPropagator()
2278
2444
  });
2279
2445
  const instrumentations = [];
2280
2446
  const instrumentationsOptions = options.instrumentations;
package/index.esm.js CHANGED
@@ -2,7 +2,8 @@ import { findNodeHandle, AppState, Platform, NativeModules, View, NativeEventEmi
2
2
  import React from 'react';
3
3
  import { InstrumentationBase, registerInstrumentations } from '@opentelemetry/instrumentation';
4
4
  import { FetchInstrumentation } from '@opentelemetry/instrumentation-fetch';
5
- import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';
5
+ import { createContextKey, context } from '@opentelemetry/api';
6
+ import { SamplingDecision, shouldPropagateTraceHeaders, parseUrl, WebTracerProvider } from '@opentelemetry/sdk-trace-web';
6
7
  import { W3CTraceContextPropagator } from '@opentelemetry/core';
7
8
 
8
9
  function _extends() {
@@ -46,47 +47,10 @@ let CoralogixLogSeverity = /*#__PURE__*/function (CoralogixLogSeverity) {
46
47
  return CoralogixLogSeverity;
47
48
  }({});
48
49
 
49
- /**
50
- * `interaction_context` as it appears on a user-interaction RUM event — the
51
- * shape `beforeSend` receives. Built natively (field names differ from the
52
- * {@link InteractionContext} payload JS hands to the bridge).
53
- *
54
- * Intentionally editable in `beforeSend` (except `is_masked_element`): a
55
- * callback may blank the coordinates in `attributes`, redact text fields, or
56
- * drop the whole event to enforce a masking policy stricter than the default.
57
- */
58
-
59
- /** Versions of the plugin and the underlying native SDK that produced an event. */
60
-
61
- /**
62
- * A RUM event as it goes on the wire.
63
- *
64
- * Fields marked `readonly` are SDK-owned: span identity, dedup keys, SDK-owned
65
- * counters and the SDK's own observations. `beforeSend` may read them, but the
66
- * SDK's value is always restored after the callback returns — assigning to one
67
- * has no effect on the sent event.
68
- */
69
-
70
- /**
71
- * The view of an event that `beforeSend` receives.
72
- *
73
- * Only the user fields of `session_context` are editable — session identity, the
74
- * sampling decision and the recording flag are SDK-owned and are restored from
75
- * the SDK's own values after the callback returns. The same holds for the
76
- * `readonly` fields inherited from {@link CxRumEvent}. Nothing a callback writes
77
- * to those can reach the wire, so they cannot be forged.
78
- */
79
-
80
- /**
81
- * Instrumentation names that can be excluded from a custom tracer's span context.
82
- * Pass one or more values to `getCustomTracer()` to prevent those event types from
83
- * being linked to spans created by that tracer.
84
- */
85
-
86
50
  /**
87
51
  * Event categories that can opt out of session sampling. When the session is
88
52
  * sampled out, events whose category is listed in `excludeFromSampling` are still
89
- * emitted; everything else is dropped. Mirrors the iOS/Android native enums.
53
+ * emitted; everything else is dropped.
90
54
  */
91
55
 
92
56
  /** OTLP JSON-format trace data delivered to the `tracesExporter` callback. */
@@ -1138,7 +1102,7 @@ function stopJsRefreshRateSampler() {
1138
1102
  appStateSub = null;
1139
1103
  }
1140
1104
 
1141
- var version = "0.14.2";
1105
+ var version = "0.15.0";
1142
1106
  var pkg = {
1143
1107
  version: version};
1144
1108
 
@@ -1417,6 +1381,157 @@ function serializeNetworkCaptureRules(rules) {
1417
1381
  });
1418
1382
  }
1419
1383
 
1384
+ /**
1385
+ * The native module, or a proxy that throws on first use when it is missing.
1386
+ *
1387
+ * Lives in its own leaf module so anything needing the bridge — the masking
1388
+ * components included — can reach it without importing the SDK entry point and
1389
+ * cycling back through it. `CxSdkClient` is imported as a type only, so the
1390
+ * declaration site stays in `index.ts` with nothing cycling at runtime.
1391
+ */
1392
+
1393
+ const LINKING_ERROR = `The package 'cx-plugin' doesn't seem to be linked. Make sure: \n\n` + Platform.select({
1394
+ ios: "- You have run 'pod install'\n",
1395
+ default: ''
1396
+ }) + '- You rebuilt the app after installing the package\n' + '- You are not using Expo Go\n';
1397
+ function createErrorProxy(errorMessage) {
1398
+ return new Proxy({}, {
1399
+ get() {
1400
+ throw new Error(errorMessage);
1401
+ }
1402
+ });
1403
+ }
1404
+ const CxSdk = NativeModules.CxSdk ? NativeModules.CxSdk : createErrorProxy(LINKING_ERROR);
1405
+
1406
+ /**
1407
+ * How long a request waits for the native sampling answer. Past it the answer is treated
1408
+ * as unknown: no `traceparent`, and nothing echoed on the report.
1409
+ */
1410
+ const NETWORK_SAMPLING_TIMEOUT_MS = 500;
1411
+
1412
+ /** The native `networkRequestSampling()` answer, for a session that exists. */
1413
+
1414
+ /** `undefined` is the unknown answer: before init, a bridge failure, or a timeout. */
1415
+
1416
+ /**
1417
+ * What one request carries through the OTel context: the pending answer, and the
1418
+ * settled one when the request waited for it before starting.
1419
+ */
1420
+
1421
+ const REQUEST_SAMPLING_KEY = createContextKey('coralogix.network_request_sampling');
1422
+
1423
+ /** Pending answers by span, read once by the report path. */
1424
+ const pendingBySpan = new WeakMap();
1425
+
1426
+ /**
1427
+ * Asks native whether a request starting now is sampled, and for which session. Ask once
1428
+ * per request and never cache the answer: the session can rotate at any moment. Never
1429
+ * rejects; anything but a well-formed answer for a live session resolves to unknown.
1430
+ */
1431
+ function requestNetworkSampling() {
1432
+ let timer;
1433
+ const timeout = new Promise(resolve => {
1434
+ timer = setTimeout(() => resolve(undefined), NETWORK_SAMPLING_TIMEOUT_MS);
1435
+ });
1436
+ // Through `then` so a synchronous throw (an unlinked module) also lands in the catch.
1437
+ const call = Promise.resolve().then(() => CxSdk.networkRequestSampling()).then(toKnownAnswer, () => undefined);
1438
+ return Promise.race([call, timeout]).finally(() => clearTimeout(timer));
1439
+ }
1440
+ function toKnownAnswer(raw) {
1441
+ if (typeof raw !== 'object' || raw === null) return undefined;
1442
+ const {
1443
+ isSampled,
1444
+ sessionId
1445
+ } = raw;
1446
+ if (typeof isSampled !== 'boolean') return undefined;
1447
+ if (typeof sessionId !== 'string' || sessionId.length === 0) return undefined;
1448
+ return {
1449
+ isSampled,
1450
+ sessionId
1451
+ };
1452
+ }
1453
+
1454
+ /** `context` with this request's sampling attached, for the sampler, propagator and processor. */
1455
+ function withRequestSampling(context, pending, answer) {
1456
+ const value = {
1457
+ pending,
1458
+ answer
1459
+ };
1460
+ return context.setValue(REQUEST_SAMPLING_KEY, value);
1461
+ }
1462
+ function requestSamplingOf(context) {
1463
+ return context.getValue(REQUEST_SAMPLING_KEY);
1464
+ }
1465
+
1466
+ /**
1467
+ * The answer a request was reported with: the one it started with, awaited now if the
1468
+ * request did not wait for it. `undefined` when the request carried none.
1469
+ */
1470
+ function takeNetworkSampling(span) {
1471
+ const pending = pendingBySpan.get(span);
1472
+ pendingBySpan.delete(span);
1473
+ return pending != null ? pending : Promise.resolve(undefined);
1474
+ }
1475
+
1476
+ /**
1477
+ * Sets the span's sampled flag from the native answer, so the W3C propagator writes the
1478
+ * flag byte native would: `01` sampled, `00` not. A sampled-out span still records,
1479
+ * because the report path reads its attributes, and native drops the event itself.
1480
+ */
1481
+ class NetworkRequestSampler {
1482
+ shouldSample(context) {
1483
+ var _requestSamplingOf;
1484
+ const sampled = ((_requestSamplingOf = requestSamplingOf(context)) == null || (_requestSamplingOf = _requestSamplingOf.answer) == null ? void 0 : _requestSamplingOf.isSampled) !== false;
1485
+ return {
1486
+ decision: sampled ? SamplingDecision.RECORD_AND_SAMPLED : SamplingDecision.RECORD
1487
+ };
1488
+ }
1489
+ toString() {
1490
+ return 'NetworkRequestSampler';
1491
+ }
1492
+ }
1493
+
1494
+ /**
1495
+ * W3C trace context. A request the plugin's fetch wrapper started gets it only once
1496
+ * native has answered: without an answer (before init, a bridge failure, or a timeout)
1497
+ * no `traceparent` is sent, as native instruments nothing before it is initialized.
1498
+ * Anything else injecting through the global propagator is passed through untouched.
1499
+ */
1500
+ class NetworkSamplingPropagator {
1501
+ constructor() {
1502
+ this.w3c = new W3CTraceContextPropagator();
1503
+ }
1504
+ inject(context, carrier, setter) {
1505
+ const sampling = requestSamplingOf(context);
1506
+ if (sampling && !sampling.answer) return;
1507
+ this.w3c.inject(context, carrier, setter);
1508
+ }
1509
+ extract(context, carrier, getter) {
1510
+ return this.w3c.extract(context, carrier, getter);
1511
+ }
1512
+ fields() {
1513
+ return this.w3c.fields();
1514
+ }
1515
+ }
1516
+
1517
+ /** Remembers each request span's pending answer so the report path can echo it. */
1518
+ class NetworkSamplingSpanProcessor {
1519
+ onStart(span, parentContext) {
1520
+ const sampling = requestSamplingOf(parentContext);
1521
+ if (sampling) pendingBySpan.set(span, sampling.pending);
1522
+ }
1523
+ onEnd() {}
1524
+ forceFlush() {
1525
+ return Promise.resolve();
1526
+ }
1527
+ shutdown() {
1528
+ return Promise.resolve();
1529
+ }
1530
+ }
1531
+
1532
+ // Module state rather than fields: the OTel base constructor calls `enable()` before a
1533
+ // subclass's fields exist.
1534
+ let samplingWrapper;
1420
1535
  class CoralogixFetchInstrumentation extends FetchInstrumentation {
1421
1536
  constructor(config) {
1422
1537
  var _traceParentInHeader$;
@@ -1425,10 +1540,11 @@ class CoralogixFetchInstrumentation extends FetchInstrumentation {
1425
1540
  } = config;
1426
1541
  const enabled = (traceParentInHeader == null ? void 0 : traceParentInHeader.enabled) === true;
1427
1542
  const urls = traceParentInHeader == null || (_traceParentInHeader$ = traceParentInHeader.options) == null ? void 0 : _traceParentInHeader$.allowedTracingUrls;
1543
+ const propagateTraceHeaderCorsUrls = enabled ? urls != null ? urls : /.*/ : allowNone();
1428
1544
  const fetchConfig = {
1429
1545
  // If disabled -> match nothing -> no traceparent injection
1430
1546
  // If enabled and user didn't provide urls -> match all
1431
- propagateTraceHeaderCorsUrls: enabled ? urls != null ? urls : /.*/ : allowNone()
1547
+ propagateTraceHeaderCorsUrls
1432
1548
  };
1433
1549
  fetchConfig.applyCustomAttributesOnSpan = async function (span, request, result) {
1434
1550
  // span.end() must remain synchronous and first — this completes the OTel span
@@ -1521,13 +1637,79 @@ class CoralogixFetchInstrumentation extends FetchInstrumentation {
1521
1637
  }
1522
1638
  }
1523
1639
 
1640
+ // Echo the answer the request started with, header or not, so native reports it in that
1641
+ // session or drops it. Unknown leaves both out: native then uses the live session.
1642
+ const sampling = await takeNetworkSampling(span);
1643
+ if (sampling) {
1644
+ details.traceparentSampled = sampling.isSampled;
1645
+ details.traceparentSessionId = sampling.sessionId;
1646
+ }
1647
+
1524
1648
  // reportNetworkRequest must always be last, after all awaits
1525
1649
  CoralogixRum.reportNetworkRequest(details);
1526
1650
  };
1527
1651
  super(fetchConfig);
1528
1652
  }
1529
1653
  enable() {
1654
+ // OTel re-patches only a fetch it recognizes as its own, so take ours off first and put
1655
+ // it back outermost: the sampling answer has to be in the context before OTel's patch
1656
+ // starts the span and writes the header.
1657
+ removeSamplingWrapper();
1530
1658
  super.enable();
1659
+ installSamplingWrapper(this.getConfig().propagateTraceHeaderCorsUrls);
1660
+ }
1661
+ disable() {
1662
+ removeSamplingWrapper();
1663
+ super.disable();
1664
+ }
1665
+ }
1666
+
1667
+ /**
1668
+ * Wraps `fetch` so every request asks native for its sampling answer as it starts. Only a
1669
+ * request that will carry a `traceparent` waits for it; any other starts at once, and the
1670
+ * report path, which runs after the response, waits instead.
1671
+ */
1672
+ function installSamplingWrapper(corsUrls) {
1673
+ const inner = globalThis.fetch;
1674
+ if (typeof inner !== 'function') return;
1675
+
1676
+ // Typed off `fetch` itself: the build's DOM lib takes `RequestInfo`, newer ones `RequestInfo | URL`.
1677
+ const wrapper = function wrapper(...args) {
1678
+ // Removed but still in a chain something else wrapped over it: pass straight through.
1679
+ if (!state.active) return inner.apply(this, args);
1680
+ const pending = requestNetworkSampling();
1681
+ const send = answer => context.with(withRequestSampling(context.active(), pending, answer), () => inner.apply(this, args));
1682
+ const url = requestUrl(args[0]);
1683
+ if (url === undefined || !shouldPropagateTraceHeaders(url, corsUrls)) return send();
1684
+ return pending.then(send);
1685
+ };
1686
+ const state = {
1687
+ wrapper,
1688
+ inner,
1689
+ active: true
1690
+ };
1691
+ globalThis.fetch = wrapper;
1692
+ samplingWrapper = state;
1693
+ }
1694
+ function removeSamplingWrapper() {
1695
+ if (!samplingWrapper) return;
1696
+ samplingWrapper.active = false;
1697
+ // Something else may have wrapped fetch over ours since; leave that chain alone.
1698
+ if (globalThis.fetch === samplingWrapper.wrapper) globalThis.fetch = samplingWrapper.inner;
1699
+ samplingWrapper = undefined;
1700
+ }
1701
+
1702
+ /**
1703
+ * The URL as OTel's fetch patch matches it against the allow list: normalized, so the
1704
+ * wrapper waits for exactly the requests OTel will write a header on. `undefined` when it
1705
+ * does not parse; OTel's patch then fails the request the same way, and nothing waits.
1706
+ */
1707
+ function requestUrl(input) {
1708
+ const raw = typeof Request !== 'undefined' && input instanceof Request ? input.url : String(input);
1709
+ try {
1710
+ return parseUrl(raw).href;
1711
+ } catch (_unused3) {
1712
+ return undefined;
1531
1713
  }
1532
1714
  }
1533
1715
  function allowNone() {
@@ -1549,28 +1731,6 @@ function isSessionReplayOptionsValid(options) {
1549
1731
  return scaleValid && sampleRateValid && qualityValid;
1550
1732
  }
1551
1733
 
1552
- /**
1553
- * The native module, or a proxy that throws on first use when it is missing.
1554
- *
1555
- * Lives in its own leaf module so anything needing the bridge — the masking
1556
- * components included — can reach it without importing the SDK entry point and
1557
- * cycling back through it. `CxSdkClient` is imported as a type only, so the
1558
- * declaration site stays in `index.ts` with nothing cycling at runtime.
1559
- */
1560
-
1561
- const LINKING_ERROR = `The package 'cx-plugin' doesn't seem to be linked. Make sure: \n\n` + Platform.select({
1562
- ios: "- You have run 'pod install'\n",
1563
- default: ''
1564
- }) + '- You rebuilt the app after installing the package\n' + '- You are not using Expo Go\n';
1565
- function createErrorProxy(errorMessage) {
1566
- return new Proxy({}, {
1567
- get() {
1568
- throw new Error(errorMessage);
1569
- }
1570
- });
1571
- }
1572
- const CxSdk = NativeModules.CxSdk ? NativeModules.CxSdk : createErrorProxy(LINKING_ERROR);
1573
-
1574
1734
  const reportFailure = viewTag => error => {
1575
1735
  // Dropped from the registry so a later layout pass retries rather than
1576
1736
  // being deduped against a registration that did not take.
@@ -2270,9 +2430,15 @@ async function registerCoralogixInstrumentations(options) {
2270
2430
  if (options.beforeSend) {
2271
2431
  beforeSendCallback = options.beforeSend;
2272
2432
  }
2273
- const tracerProvider = new WebTracerProvider();
2433
+
2434
+ // The sampler and propagator take the flag from native's per-request answer, so a
2435
+ // `traceparent` JS writes carries the same `00`/`01` native would write itself.
2436
+ const tracerProvider = new WebTracerProvider({
2437
+ sampler: new NetworkRequestSampler(),
2438
+ spanProcessors: [new NetworkSamplingSpanProcessor()]
2439
+ });
2274
2440
  tracerProvider.register({
2275
- propagator: new W3CTraceContextPropagator()
2441
+ propagator: new NetworkSamplingPropagator()
2276
2442
  });
2277
2443
  const instrumentations = [];
2278
2444
  const instrumentationsOptions = options.instrumentations;
package/ios/CxSdk.mm CHANGED
@@ -44,6 +44,9 @@ RCT_EXTERN_METHOD(setApplicationContext:(NSDictionary *)applicationContext
44
44
  RCT_EXTERN_METHOD(getSessionId:(RCTPromiseResolveBlock)resolve
45
45
  withRejecter:(RCTPromiseRejectBlock)reject)
46
46
 
47
+ RCT_EXTERN_METHOD(networkRequestSampling:(RCTPromiseResolveBlock)resolve
48
+ withRejecter:(RCTPromiseRejectBlock)reject)
49
+
47
50
  RCT_EXTERN_METHOD(reportUserInteraction:(NSDictionary *)interaction)
48
51
 
49
52
  RCT_EXTERN_METHOD(shutdown:(RCTPromiseResolveBlock)resolve
package/ios/CxSdk.swift CHANGED
@@ -193,6 +193,20 @@ class CxSdk: RCTEventEmitter {
193
193
  resolve(sessionId)
194
194
  }
195
195
 
196
+ @objc(networkRequestSampling:withRejecter:)
197
+ func networkRequestSampling(resolve: @escaping RCTPromiseResolveBlock,
198
+ reject: @escaping RCTPromiseRejectBlock) -> Void {
199
+ // Off the JS thread: answering may rotate a session that is due. Never rejects — a nil
200
+ // session tells JS the answer is unknown, so it sends no traceparent.
201
+ DispatchQueue.global(qos: .userInitiated).async { [weak self] in
202
+ let sampling = self?.coralogixRum?.networkRequestSampling()
203
+ resolve([
204
+ "isSampled": sampling?.isSampled ?? false,
205
+ "sessionId": sampling?.sessionId ?? NSNull(),
206
+ ])
207
+ }
208
+ }
209
+
196
210
  @objc(reportNetworkRequest:withResolver:withRejecter:)
197
211
  func reportNetworkRequest(networkRequestDictionary:NSDictionary,
198
212
  resolve:RCTPromiseResolveBlock,
@@ -588,6 +602,14 @@ class CxSdk: RCTEventEmitter {
588
602
  if let v = dictionary["response_headers"] as? [String: String] { result["response_headers"] = v }
589
603
  if let v = dictionary["request_payload"] as? String { result["request_payload"] = v }
590
604
  if let v = dictionary["response_payload"] as? String { result["response_payload"] = v }
605
+ // The `networkRequestSampling()` answer taken when the request started. Camel case, unlike
606
+ // the keys above, because that is how the native SDK spells them.
607
+ if let v = dictionary[Keys.traceparentSampled.rawValue] as? Bool {
608
+ result[Keys.traceparentSampled.rawValue] = v
609
+ }
610
+ if let v = dictionary[Keys.traceparentSessionId.rawValue] as? String {
611
+ result[Keys.traceparentSessionId.rawValue] = v
612
+ }
591
613
  return result
592
614
  }
593
615
 
@@ -766,19 +788,20 @@ class CxSdk: RCTEventEmitter {
766
788
  }
767
789
  }
768
790
 
791
+ /// Maps the JS `excludeFromSampling` strings, warning once about any the native enum does not know.
769
792
  private func toExcludeFromSampling(_ raw: [Any]?) -> Set<ExcludableInstrumentation> {
770
793
  guard let raw = raw else { return [] }
771
794
  var result: Set<ExcludableInstrumentation> = []
795
+ var dropped: [String] = []
772
796
  for value in raw {
773
- guard let key = value as? String else {
774
- debugPrint("[CxSdk] excludeFromSampling: ignoring non-string value \(value)")
775
- continue
776
- }
777
- guard let instrumentation = ExcludableInstrumentation(rawValue: key) else {
778
- debugPrint("[CxSdk] excludeFromSampling: unrecognized value '\(key)' — native enum may have drifted")
779
- continue
797
+ if let key = value as? String, let instrumentation = ExcludableInstrumentation(rawValue: key) {
798
+ result.insert(instrumentation)
799
+ } else {
800
+ dropped.append(String(describing: value))
780
801
  }
781
- result.insert(instrumentation)
802
+ }
803
+ if !dropped.isEmpty {
804
+ debugPrint("[CxSdk] excludeFromSampling: ignoring unrecognized values \(dropped)")
782
805
  }
783
806
  return result
784
807
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coralogix/react-native-plugin",
3
- "version": "0.14.2",
3
+ "version": "0.15.0",
4
4
  "description": "Official Coralogix React Native plugin",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Coralogix",
@@ -25,6 +25,7 @@
25
25
  },
26
26
  "main": "./index.cjs.js",
27
27
  "dependencies": {
28
+ "@opentelemetry/api": "^1.9.0",
28
29
  "@opentelemetry/context-zone": "^2.5.0",
29
30
  "@opentelemetry/core": "^2.5.0",
30
31
  "@opentelemetry/instrumentation": "0.48.0",
package/src/index.d.ts CHANGED
@@ -46,6 +46,14 @@ export interface CxSdkClient {
46
46
  reportMobileVitalsMeasurement(type: string, value: number, units: string): void;
47
47
  reportMobileVitalsMeasurementSet(type: string, metrics: HybridMetric[]): void;
48
48
  isCoralogixGradlePluginApplied(): Promise<boolean>;
49
+ /**
50
+ * Whether a network request starting now is sampled, and for which session. Never
51
+ * rejects; `sessionId` is null before the SDK is initialized.
52
+ */
53
+ networkRequestSampling(): Promise<{
54
+ isSampled: boolean;
55
+ sessionId: string | null;
56
+ }>;
49
57
  addListener(): void;
50
58
  removeListeners(): void;
51
59
  initializeSessionReplay(options: SessionReplayOptions): Promise<boolean>;
@@ -2,4 +2,5 @@ import { FetchInstrumentation, FetchInstrumentationConfig } from '@opentelemetry
2
2
  export declare class CoralogixFetchInstrumentation extends FetchInstrumentation {
3
3
  constructor(config: FetchInstrumentationConfig);
4
4
  enable(): void;
5
+ disable(): void;
5
6
  }
@@ -0,0 +1,55 @@
1
+ import { Context, TextMapPropagator, TextMapGetter, TextMapSetter } from '@opentelemetry/api';
2
+ import { Sampler, SamplingResult, Span, SpanProcessor } from '@opentelemetry/sdk-trace-web';
3
+ /**
4
+ * How long a request waits for the native sampling answer. Past it the answer is treated
5
+ * as unknown: no `traceparent`, and nothing echoed on the report.
6
+ */
7
+ export declare const NETWORK_SAMPLING_TIMEOUT_MS = 500;
8
+ /** The native `networkRequestSampling()` answer, for a session that exists. */
9
+ export type NetworkRequestSampling = {
10
+ isSampled: boolean;
11
+ sessionId: string;
12
+ };
13
+ /** `undefined` is the unknown answer: before init, a bridge failure, or a timeout. */
14
+ export type NetworkSamplingAnswer = NetworkRequestSampling | undefined;
15
+ /**
16
+ * Asks native whether a request starting now is sampled, and for which session. Ask once
17
+ * per request and never cache the answer: the session can rotate at any moment. Never
18
+ * rejects; anything but a well-formed answer for a live session resolves to unknown.
19
+ */
20
+ export declare function requestNetworkSampling(): Promise<NetworkSamplingAnswer>;
21
+ /** `context` with this request's sampling attached, for the sampler, propagator and processor. */
22
+ export declare function withRequestSampling(context: Context, pending: Promise<NetworkSamplingAnswer>, answer?: NetworkSamplingAnswer): Context;
23
+ /**
24
+ * The answer a request was reported with: the one it started with, awaited now if the
25
+ * request did not wait for it. `undefined` when the request carried none.
26
+ */
27
+ export declare function takeNetworkSampling(span: object): Promise<NetworkSamplingAnswer>;
28
+ /**
29
+ * Sets the span's sampled flag from the native answer, so the W3C propagator writes the
30
+ * flag byte native would: `01` sampled, `00` not. A sampled-out span still records,
31
+ * because the report path reads its attributes, and native drops the event itself.
32
+ */
33
+ export declare class NetworkRequestSampler implements Sampler {
34
+ shouldSample(context: Context): SamplingResult;
35
+ toString(): string;
36
+ }
37
+ /**
38
+ * W3C trace context. A request the plugin's fetch wrapper started gets it only once
39
+ * native has answered: without an answer (before init, a bridge failure, or a timeout)
40
+ * no `traceparent` is sent, as native instruments nothing before it is initialized.
41
+ * Anything else injecting through the global propagator is passed through untouched.
42
+ */
43
+ export declare class NetworkSamplingPropagator implements TextMapPropagator {
44
+ private readonly w3c;
45
+ inject(context: Context, carrier: unknown, setter: TextMapSetter): void;
46
+ extract(context: Context, carrier: unknown, getter: TextMapGetter): Context;
47
+ fields(): string[];
48
+ }
49
+ /** Remembers each request span's pending answer so the report path can echo it. */
50
+ export declare class NetworkSamplingSpanProcessor implements SpanProcessor {
51
+ onStart(span: Span, parentContext: Context): void;
52
+ onEnd(): void;
53
+ forceFlush(): Promise<void>;
54
+ shutdown(): Promise<void>;
55
+ }
@@ -20,4 +20,14 @@ export type NetworkRequestDetails = {
20
20
  response_headers?: Record<string, string>;
21
21
  request_payload?: string;
22
22
  response_payload?: string;
23
+ /**
24
+ * The sampled flag native gave this request when it started (`false` → `00`). Native
25
+ * drops the event when it is `false`. Absent when the answer was unknown.
26
+ */
27
+ traceparentSampled?: boolean;
28
+ /**
29
+ * The session that answer was for. Native reports the request in that session, or drops
30
+ * it once the session is no longer known. Absent when the answer was unknown.
31
+ */
32
+ traceparentSessionId?: string;
23
33
  };
@@ -374,12 +374,17 @@ export type HybridMetric = {
374
374
  * being linked to spans created by that tracer.
375
375
  */
376
376
  export type CoralogixIgnoredInstrument = 'networkRequests' | 'userInteractions' | 'errors';
377
+ /**
378
+ * Every value `excludeFromSampling` accepts. Mirrors the iOS and Android native enums,
379
+ * whose bridges map these exact strings.
380
+ */
381
+ export declare const EXCLUDABLE_INSTRUMENTATIONS: readonly ["errors", "logs", "network", "userInteractions", "mobileVitals", "customSpan", "customMeasurement", "navigation", "lifecycle"];
377
382
  /**
378
383
  * Event categories that can opt out of session sampling. When the session is
379
384
  * sampled out, events whose category is listed in `excludeFromSampling` are still
380
- * emitted; everything else is dropped. Mirrors the iOS/Android native enums.
385
+ * emitted; everything else is dropped.
381
386
  */
382
- export type ExcludableInstrumentation = 'errors' | 'logs' | 'network' | 'userInteractions' | 'mobileVitals' | 'customSpan' | 'customMeasurement';
387
+ export type ExcludableInstrumentation = (typeof EXCLUDABLE_INSTRUMENTATIONS)[number];
383
388
  /** OTLP JSON-format trace data delivered to the `tracesExporter` callback. */
384
389
  export interface TraceExporterData {
385
390
  resource_spans: Record<string, unknown>[];