@logbrew/react-native 0.1.39 → 0.1.41

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 (99) hide show
  1. package/README.md +3 -3
  2. package/android-native-diagnostics.d.ts +15 -5
  3. package/android-native-diagnostics.js +170 -94
  4. package/apollo.cjs +435 -226
  5. package/apollo.d.cts +2 -70
  6. package/apollo.d.ts +24 -12
  7. package/apollo.js +438 -221
  8. package/apple-native-diagnostics-config.js +176 -0
  9. package/apple-native-diagnostics-context.js +232 -0
  10. package/apple-native-diagnostics-module.js +229 -0
  11. package/apple-native-diagnostics.d.ts +42 -11
  12. package/apple-native-diagnostics.js +60 -389
  13. package/expo.cjs +29 -16
  14. package/expo.d.ts +10 -9
  15. package/expo.js +4 -3
  16. package/fatal-admission.cjs +113 -0
  17. package/fatal-record.cjs +317 -0
  18. package/fatal-replay.cjs +297 -508
  19. package/global-errors-capture.cjs +369 -0
  20. package/global-errors-event.cjs +174 -0
  21. package/global-errors-support.cjs +128 -0
  22. package/global-errors.cjs +75 -351
  23. package/global-errors.d.cts +29 -278
  24. package/global-errors.d.ts +57 -27
  25. package/global-errors.js +7 -2
  26. package/global-errors.native.js +83 -48
  27. package/index-breadcrumbs.cjs +139 -0
  28. package/index-errors.cjs +167 -0
  29. package/index-events.cjs +365 -0
  30. package/index-navigation.cjs +327 -0
  31. package/index-random.cjs +120 -0
  32. package/index-react.cjs +189 -0
  33. package/index-spans.cjs +190 -0
  34. package/index-trace-fetch.cjs +322 -0
  35. package/index-trace.cjs +335 -0
  36. package/index-transport.cjs +201 -0
  37. package/index-values.cjs +232 -0
  38. package/index.cjs +97 -1245
  39. package/index.d.cts +2 -505
  40. package/index.d.ts +130 -469
  41. package/index.native.d.ts +146 -22
  42. package/index.native.js +184 -159
  43. package/instrumentation-fetch.cjs +113 -0
  44. package/instrumentation-install.cjs +241 -0
  45. package/instrumentation-runtime.cjs +65 -0
  46. package/instrumentation-teardown.cjs +93 -0
  47. package/instrumentation-values.cjs +282 -0
  48. package/instrumentation-xhr-request.cjs +298 -0
  49. package/instrumentation-xhr.cjs +233 -0
  50. package/instrumentation.cjs +110 -599
  51. package/instrumentation.d.cts +2 -84
  52. package/instrumentation.d.ts +22 -8
  53. package/ios/AppleDiagnostics/LBRNAppleNativeDiagnostics.swift +1 -1
  54. package/ios/GeneratedAppleDiagnostics/LogBrew/DeliveryLifecycle.swift +1 -1
  55. package/ios/GeneratedAppleDiagnostics/SOURCE-MANIFEST.json +1 -1
  56. package/lifecycle.cjs +181 -78
  57. package/lifecycle.d.cts +1 -50
  58. package/lifecycle.d.ts +17 -6
  59. package/metadata.cjs +279 -114
  60. package/metro-debug-id.cjs +296 -0
  61. package/metro-serializer.cjs +219 -0
  62. package/metro.cjs +153 -297
  63. package/metro.d.cts +2 -57
  64. package/metro.d.ts +27 -13
  65. package/metro.js +2 -3
  66. package/native-bridge-async.cjs +165 -0
  67. package/native-bridge-scope.cjs +148 -0
  68. package/native-bridge.cjs +83 -186
  69. package/native-bridge.d.cts +2 -94
  70. package/native-bridge.d.ts +28 -15
  71. package/native-client-bindings.js +230 -0
  72. package/native-diagnostics-values.js +120 -0
  73. package/native-module-lookup.js +31 -0
  74. package/native-null.js +3 -0
  75. package/null-value.cjs +4 -0
  76. package/package.json +43 -1
  77. package/persistent-delivery-store.js +247 -0
  78. package/persistent-delivery.native.js +183 -261
  79. package/promise-rejection-handlers.cjs +368 -0
  80. package/promise-rejections.cjs +169 -361
  81. package/react-native.config.js +3 -1
  82. package/release-artifacts-files.cjs +94 -0
  83. package/release-artifacts-options.cjs +182 -0
  84. package/release-artifacts.cjs +278 -207
  85. package/release-artifacts.d.cts +2 -55
  86. package/release-artifacts.d.ts +18 -7
  87. package/release-artifacts.js +2 -4
  88. package/resource-fetch-graphql.cjs +265 -0
  89. package/resource-fetch-size.cjs +156 -0
  90. package/resource-fetch.cjs +227 -428
  91. package/resource-fetch.d.cts +1 -60
  92. package/resource-fetch.d.ts +17 -6
  93. package/scripts/sync-apple-native-sources.mjs +101 -53
  94. package/types/capture.d.ts +95 -0
  95. package/types/config.d.ts +85 -0
  96. package/types/defaults.d.ts +55 -0
  97. package/types/events.d.ts +203 -0
  98. package/types/provider.d.ts +81 -0
  99. package/types/trace.d.ts +104 -0
package/index.cjs CHANGED
@@ -1,36 +1,57 @@
1
- const React = require("react");
1
+ const { LogBrewClient, SdkError } = require("@logbrew/sdk");
2
+ const { createReactNativeErrorEvent, captureReactNativeError } = require("./index-errors.cjs");
2
3
  const {
3
- createIssueAttributesFromError,
4
- createTraceparent,
5
- LogBrewClient,
6
- parseTraceparent,
7
- PRODUCT_ANALYTICS_SCHEMA_VERSION,
8
- SdkError,
9
- TransportError
10
- } = require("@logbrew/sdk");
4
+ captureAppStateChange,
5
+ captureReactNativeAction,
6
+ captureReactNativeNetwork,
7
+ captureScreenView,
8
+ createAppStateListener,
9
+ createReactNativeActionEvent,
10
+ createReactNativeNetworkEvent
11
+ } = require("./index-events.cjs");
12
+ const { createReactNavigationSpanListener } = require("./index-navigation.cjs");
13
+ const { LogBrewNativeProvider, useLogBrewNative, useLogBrewNativeActions } = require("./index-react.cjs");
11
14
  const {
12
- runtimeReactNativeDebugIdMap,
13
- sanitizeReactNativeIssueExceptionChain,
14
- sanitizeReactNativeIssueMetadata,
15
- sanitizeReactNativeIssueStackFrames
16
- } = require("./metadata.cjs");
15
+ captureReactNativeNavigationSpan,
16
+ captureReactNativeResourceSpan,
17
+ createReactNativeNavigationSpanEvent,
18
+ createReactNativeResourceSpanEvent
19
+ } = require("./index-spans.cjs");
20
+ const { createTraceparentFetch, shouldPropagateTraceparent } = require("./index-trace-fetch.cjs");
21
+ const {
22
+ bindLogBrewTrace,
23
+ createReactNativeSpanAttributes,
24
+ createReactNativeTraceContext,
25
+ createReactNativeTraceHeaders,
26
+ createReactNativeTraceparent,
27
+ getActiveLogBrewTrace,
28
+ getReactNativeTraceMetadata,
29
+ withLogBrewTrace
30
+ } = require("./index-trace.cjs");
31
+ const { createReactNativeFetchTransport } = require("./index-transport.cjs");
32
+ const { getReactNativeContext } = require("./index-values.cjs");
33
+
34
+ /**
35
+ * @import { CreateLogBrewReactNativeClientConfig } from "./index.cjs"
36
+ */
17
37
 
18
38
  const DEFAULT_SDK_NAME = "logbrew-react-native";
19
- const DEFAULT_SDK_VERSION = "0.1.39";
20
- const DEFAULT_ENDPOINT = "https://api.logbrew.co/v1/events";
21
- const RATE_LIMIT_BODY_LIMIT_BYTES = 4096;
22
- const NATIVE_RANDOM_HEX = Symbol.for("co.logbrew.react-native.secure-random-hex");
23
- const MAX_ACTION_NAME_LENGTH = 64;
24
- const MAX_PRODUCT_ANALYTICS_SURFACE_LENGTH = 256;
25
- const SCREEN_ACTION_PREFIX = "screen:";
26
- const LAST_ROUTE = Symbol.for("co.logbrew.react-native.last-route");
27
- const BACKGROUND_APP_STATES = new Set(["background", "inactive"]);
28
- // Mobile keeps a 5-second interval to save battery and radio wakeups; flushOnBackground sends the rest.
29
- const DEFAULT_REACT_NATIVE_DELIVERY_INTERVAL_MS = 5000;
30
- const LogBrewNativeContext = React.createContext(null);
31
- const activeTraceScopes = [];
32
- let nextTraceScopeId = 0;
33
-
39
+ const DEFAULT_SDK_VERSION = "0.1.41";
40
+ const DEFAULT_REACT_NATIVE_DELIVERY_INTERVAL_MS = 1000;
41
+ const DEFAULT_MAX_RETRIES = 2;
42
+
43
+ /**
44
+ * @param {string | undefined} key
45
+ * @returns {key is string}
46
+ */
47
+ function isPresentKey(key) {
48
+ return key !== undefined && Boolean(key);
49
+ }
50
+
51
+ /**
52
+ * @param {CreateLogBrewReactNativeClientConfig} options
53
+ * @returns {LogBrewClient}
54
+ */
34
55
  function createLogBrewReactNativeClient({
35
56
  automaticDelivery,
36
57
  apiKey,
@@ -46,1237 +67,68 @@ function createLogBrewReactNativeClient({
46
67
  onEventDropped,
47
68
  sdkName = DEFAULT_SDK_NAME,
48
69
  sdkVersion = DEFAULT_SDK_VERSION,
49
- maxRetries = 2,
70
+ maxRetries = DEFAULT_MAX_RETRIES,
50
71
  transport
51
72
  }) {
52
73
  const authKey = clientKey ?? apiKey;
53
- if (!authKey) {
74
+ if (!isPresentKey(authKey)) {
54
75
  throw new SdkError("configuration_error", "createLogBrewReactNativeClient requires clientKey or apiKey");
55
76
  }
56
77
  return LogBrewClient.create({
57
78
  apiKey: authKey,
58
- automaticDelivery,
59
- context,
60
79
  deliveryIntervalMs: deliveryIntervalMs ?? DEFAULT_REACT_NATIVE_DELIVERY_INTERVAL_MS,
61
- deliveryQueueThreshold,
62
- eventStore,
63
- maxBatchBytes,
64
- maxBatchEvents,
65
- maxQueueBytes,
66
- maxQueueSize,
67
80
  maxRetries,
68
- onEventDropped,
69
81
  sdkName,
70
82
  sdkVersion,
71
- transport
72
- });
73
- }
74
-
75
- function createReactNativeFetchTransport({
76
- endpoint = DEFAULT_ENDPOINT,
77
- fetchImpl = defaultFetch(),
78
- headers = {}
79
- } = {}) {
80
- validateDeliveryEndpoint(endpoint);
81
- if (typeof fetchImpl !== "function") {
82
- throw new SdkError("configuration_error", "createReactNativeFetchTransport requires fetch");
83
- }
84
- if (!headers || Array.isArray(headers) || typeof headers !== "object") {
85
- throw new SdkError("configuration_error", "createReactNativeFetchTransport headers must be an object");
86
- }
87
-
88
- return Object.freeze({
89
- async send(apiKey, body) {
90
- try {
91
- const response = await fetchImpl(endpoint, {
92
- body,
93
- headers: {
94
- ...headers,
95
- authorization: `Bearer ${apiKey}`,
96
- "content-type": "application/json"
97
- },
98
- method: "POST"
99
- });
100
- const retryAfterMs = retryAfterMsFromHeaders(response?.headers);
101
- const errorCode = response?.status === 429 ? await rateLimitCode(response) : undefined;
102
- return {
103
- statusCode: response?.status,
104
- attempts: 1,
105
- ...(retryAfterMs === undefined ? {} : { retryAfterMs }),
106
- ...(errorCode === undefined ? {} : { errorCode })
107
- };
108
- } catch {
109
- throw TransportError.network("LogBrew React Native delivery failed");
110
- }
111
- }
83
+ ...(automaticDelivery === undefined ? {} : { automaticDelivery }),
84
+ ...(context === undefined ? {} : { context }),
85
+ ...(deliveryQueueThreshold === undefined ? {} : { deliveryQueueThreshold }),
86
+ ...(eventStore === undefined ? {} : { eventStore }),
87
+ ...(maxBatchBytes === undefined ? {} : { maxBatchBytes }),
88
+ ...(maxBatchEvents === undefined ? {} : { maxBatchEvents }),
89
+ ...(maxQueueBytes === undefined ? {} : { maxQueueBytes }),
90
+ ...(maxQueueSize === undefined ? {} : { maxQueueSize }),
91
+ ...(onEventDropped === undefined ? {} : { onEventDropped }),
92
+ ...(transport === undefined ? {} : { transport })
112
93
  });
113
94
  }
114
95
 
115
- function createReactNativeTraceparent({ randomValues = defaultRandomValues, spanId, traceFlags = "01", traceId } = {}) {
116
- return createTraceparent({
117
- spanId: spanId ?? randomHex(8, randomValues),
118
- traceFlags,
119
- traceId: traceId ?? randomHex(16, randomValues)
120
- });
121
- }
122
-
123
- function createReactNativeTraceContext({
124
- parentSpanId, randomValues = defaultRandomValues, spanId, traceFlags = "01", traceId, traceparent
125
- } = {}) {
126
- if (traceparent !== undefined && traceparent !== null && String(traceparent).trim() !== "") {
127
- try {
128
- const parsed = parseTraceparent(traceparent);
129
- const localSpanId = spanId ?? randomHex(8, randomValues);
130
- createTraceparent({ traceId: parsed.traceId, spanId: localSpanId, traceFlags: parsed.traceFlags });
131
- return freezeTraceContext({
132
- parentSpanId: parsed.parentSpanId,
133
- sampled: parsed.sampled,
134
- spanId: localSpanId,
135
- traceFlags: parsed.traceFlags,
136
- traceId: parsed.traceId
137
- });
138
- } catch {
139
- // Bad upstream propagation should not break mobile app flows.
140
- }
141
- }
142
-
143
- const localTraceId = traceId ?? randomHex(16, randomValues);
144
- const localSpanId = spanId ?? randomHex(8, randomValues);
145
- createTraceparent({ traceId: localTraceId, spanId: localSpanId, traceFlags });
146
- if (parentSpanId !== undefined) {
147
- createTraceparent({ traceId: localTraceId, spanId: parentSpanId, traceFlags });
148
- }
149
- return freezeTraceContext({
150
- parentSpanId,
151
- sampled: sampledFromTraceFlags(traceFlags),
152
- spanId: localSpanId,
153
- traceFlags,
154
- traceId: localTraceId
155
- });
156
- }
157
-
158
- function getActiveLogBrewTrace() {
159
- return activeTraceScopes.length === 0 ? undefined : activeTraceScopes[activeTraceScopes.length - 1].trace;
160
- }
161
-
162
- function withLogBrewTrace(trace, callback) {
163
- if (typeof callback !== "function") {
164
- throw new SdkError("configuration_error", "withLogBrewTrace requires a callback");
165
- }
166
- const context = resolveTraceContext(trace) ?? createReactNativeTraceContext();
167
- const scope = {
168
- id: ++nextTraceScopeId,
169
- trace: context
170
- };
171
- activeTraceScopes.push(scope);
172
- try {
173
- return callback(context);
174
- } finally {
175
- removeActiveTraceScope(scope.id);
176
- }
177
- }
178
-
179
- function bindLogBrewTrace(trace, callback) {
180
- if (typeof callback !== "function") {
181
- throw new SdkError("configuration_error", "bindLogBrewTrace requires a callback");
182
- }
183
- const context = resolveTraceContext(trace) ?? createReactNativeTraceContext();
184
- return function logBrewTracedCallback(...args) {
185
- return withLogBrewTrace(context, () => callback(...args));
186
- };
187
- }
188
-
189
- function getReactNativeTraceMetadata(trace = getActiveLogBrewTrace()) {
190
- const context = resolveTraceContext(trace);
191
- if (!context) {
192
- return {};
193
- }
194
- return compactMetadata({
195
- parentSpanId: context.parentSpanId,
196
- spanId: context.spanId,
197
- traceFlags: context.traceFlags,
198
- traceId: context.traceId,
199
- traceSampled: context.sampled
200
- });
201
- }
202
-
203
- function createReactNativeSpanAttributes({
204
- durationMs,
205
- metadata = {},
206
- name,
207
- spanId,
208
- status = "ok",
209
- trace = getActiveLogBrewTrace()
210
- } = {}) {
211
- const context = resolveTraceContext(trace) ?? createReactNativeTraceContext();
212
- return {
213
- name,
214
- traceId: context.traceId,
215
- spanId: spanId ?? context.spanId,
216
- status,
217
- durationMs,
218
- metadata: compactMetadata({
219
- ...metadata,
220
- ...getReactNativeTraceMetadata(context)
221
- })
222
- };
223
- }
224
-
225
- function createReactNativeTraceHeaders(trace = getActiveLogBrewTrace()) {
226
- const context = resolveTraceContext(trace) ?? createReactNativeTraceContext();
227
- return {
228
- traceparent: createTraceparent({
229
- traceFlags: context.traceFlags,
230
- traceId: context.traceId,
231
- spanId: context.spanId
232
- })
233
- };
234
- }
235
-
236
- function createTraceparentFetch({
237
- fetchImpl = defaultFetch(),
238
- randomValues = defaultRandomValues,
239
- trace,
240
- traceFlags = "01",
241
- traceparent,
242
- traceparentFactory,
243
- tracePropagationTargets = []
244
- } = {}) {
245
- if (typeof fetchImpl !== "function") {
246
- throw new SdkError("configuration_error", "createTraceparentFetch requires fetch");
247
- }
248
- if (!Array.isArray(tracePropagationTargets)) {
249
- throw new SdkError("configuration_error", "tracePropagationTargets must be an array");
250
- }
251
- if (traceparentFactory !== undefined && typeof traceparentFactory !== "function") {
252
- throw new SdkError("configuration_error", "traceparentFactory must be a function");
253
- }
254
-
255
- return async function tracedFetch(input, init) {
256
- const url = requestUrl(input);
257
- if (!shouldPropagateTraceparent(url, tracePropagationTargets)) {
258
- return init === undefined ? fetchImpl(input) : fetchImpl(input, init);
259
- }
260
-
261
- const requestInit = init ?? {};
262
- const nextTraceparent = traceparentForRequest({ init, input, randomValues, trace, traceFlags, traceparent, traceparentFactory, url });
263
- const nextInit = {
264
- ...requestInit,
265
- headers: headersWithTraceparent(requestHeaders(input, requestInit), nextTraceparent)
266
- };
267
- return fetchImpl(input, nextInit);
268
- };
269
- }
270
-
271
- function shouldPropagateTraceparent(url, tracePropagationTargets = []) {
272
- if (!Array.isArray(tracePropagationTargets)) {
273
- throw new SdkError("configuration_error", "tracePropagationTargets must be an array");
274
- }
275
- return tracePropagationTargets.some((target) => {
276
- if (typeof target === "string") {
277
- return shouldPropagateToStringTarget(url, target);
278
- }
279
- if (target instanceof RegExp) {
280
- target.lastIndex = 0;
281
- const matched = target.test(url);
282
- target.lastIndex = 0;
283
- return matched;
284
- }
285
- if (typeof target === "function") {
286
- return target(url) === true;
287
- }
288
- throw new SdkError("configuration_error", "tracePropagationTargets entries must be strings, RegExp values, or functions");
289
- });
290
- }
291
-
292
- function getReactNativeContext({ platform, appState, metadata = {} } = {}) {
293
- return {
294
- platform: platform?.OS ?? "unknown",
295
- platformVersion: normalizeMetadataValue(platform?.Version),
296
- appState: normalizeMetadataValue(appState?.currentState),
297
- isPad: normalizeMetadataValue(platform?.isPad),
298
- isTesting: normalizeMetadataValue(platform?.constants?.isTesting),
299
- ...metadata
300
- };
301
- }
302
-
303
- function captureScreenView(client, screenName, {
304
- id,
305
- timestamp = new Date().toISOString(),
306
- status = "success",
307
- platform,
308
- appState,
309
- trace,
310
- metadata = {}
311
- } = {}) {
312
- requireClient(client);
313
- requireNonEmpty("screen name", screenName);
314
- client.action(id ?? defaultEventId("screen"), timestamp, {
315
- name: screenActionName(screenName),
316
- status,
317
- metadata: {
318
- ...getReactNativeContext({ platform, appState }),
319
- screen: screenName,
320
- ...metadata,
321
- ...getReactNativeTraceMetadata(trace ?? getActiveLogBrewTrace()),
322
- ...productAnalyticsMetadata("screen_view", screenName)
323
- }
324
- });
325
- recordIssueBreadcrumb(client, {
326
- timestamp,
327
- attributes: { name: screenActionName(screenName), status }
328
- }, "navigation", "navigation");
329
- }
330
-
331
- function captureAppStateChange(client, state, {
332
- id,
333
- timestamp = new Date().toISOString(),
334
- platform,
335
- appState,
336
- trace,
337
- metadata = {}
338
- } = {}) {
339
- requireClient(client);
340
- requireNonEmpty("app state", state);
341
- client.action(id ?? defaultEventId("app_state"), timestamp, {
342
- name: "app_state_change",
343
- status: "success",
344
- metadata: {
345
- ...getReactNativeContext({ platform, appState }),
346
- appState: state,
347
- ...metadata,
348
- ...getReactNativeTraceMetadata(trace ?? getActiveLogBrewTrace())
349
- }
350
- });
351
- recordIssueBreadcrumb(client, {
352
- timestamp,
353
- attributes: { name: "app_state_change", status: "success" }
354
- }, "app.state", "state");
355
- }
356
-
357
- function createReactNativeActionEvent({
358
- id,
359
- idFactory = defaultActionEventId,
360
- metadata = {},
361
- name,
362
- now = () => new Date().toISOString(),
363
- platform,
364
- appState,
365
- screen,
366
- sessionId,
367
- status = "success",
368
- timestamp,
369
- trace,
370
- traceId
371
- } = {}) {
372
- return {
373
- id: id ?? idFactory({ name, screen }),
374
- timestamp: timestamp ?? now(),
375
- attributes: {
376
- name,
377
- status,
378
- metadata: compactMetadata({
379
- ...getReactNativeContext({ platform, appState }),
380
- source: "react-native.action",
381
- screen,
382
- sessionId,
383
- traceId,
384
- ...metadata,
385
- ...getReactNativeTraceMetadata(trace ?? getActiveLogBrewTrace()),
386
- ...productAnalyticsMetadata("interaction", screen)
387
- })
388
- }
389
- };
390
- }
391
-
392
- function captureReactNativeAction(client, input = {}) {
393
- requireClient(client);
394
- const event = createReactNativeActionEvent(input);
395
- client.action(event.id, event.timestamp, event.attributes);
396
- recordIssueBreadcrumb(client, event, "ui.action", "user");
397
- return event;
398
- }
399
-
400
- function createReactNativeNetworkEvent({
401
- durationMs,
402
- id,
403
- idFactory = defaultNetworkEventId,
404
- metadata = {},
405
- method,
406
- name,
407
- now = () => new Date().toISOString(),
408
- platform,
409
- appState,
410
- routeTemplate,
411
- screen,
412
- sessionId,
413
- status,
414
- statusCode,
415
- timestamp,
416
- trace,
417
- traceId
418
- } = {}) {
419
- const safeRouteTemplate = stripQueryAndHash(routeTemplate);
420
- const safeMethod = method === undefined ? undefined : String(method).toUpperCase();
421
- const actionName = name ?? [safeMethod, safeRouteTemplate].filter(Boolean).join(" ");
422
- return {
423
- id: id ?? idFactory({ method: safeMethod, routeTemplate: safeRouteTemplate, screen }),
424
- timestamp: timestamp ?? now(),
425
- attributes: {
426
- name: actionName,
427
- status: status ?? statusFromStatusCode(statusCode),
428
- metadata: compactMetadata({
429
- ...getReactNativeContext({ platform, appState }),
430
- source: "react-native.network",
431
- durationMs,
432
- method: safeMethod,
433
- routeTemplate: safeRouteTemplate,
434
- screen,
435
- sessionId,
436
- statusCode,
437
- traceId,
438
- ...metadata,
439
- ...getReactNativeTraceMetadata(trace ?? getActiveLogBrewTrace())
440
- })
441
- }
442
- };
443
- }
444
-
445
- function captureReactNativeNetwork(client, input = {}) {
446
- requireClient(client);
447
- const event = createReactNativeNetworkEvent(input);
448
- client.action(event.id, event.timestamp, event.attributes);
449
- recordIssueBreadcrumb(client, event, "http", "http");
450
- return event;
451
- }
452
-
453
- function createReactNativeNavigationSpanEvent({
454
- actionType, durationMs, id, idFactory = defaultNavigationSpanEventId, includeRouteKey = false, metadata = {},
455
- name, now = () => new Date().toISOString(), platform, appState, previousRouteKey, previousRouteName,
456
- routeKey, routeName, routePath, screen, status = "ok", timestamp, trace
457
- } = {}) {
458
- const safeRoutePath = stripQueryAndHash(routePath);
459
- const spanName = name ?? `navigation:${routeName ?? safeRoutePath ?? screen ?? "route"}`;
460
- const context = resolveTraceContext(trace) ?? getActiveLogBrewTrace() ?? createReactNativeTraceContext();
461
- return {
462
- id: id ?? idFactory({ routeName, routePath: safeRoutePath, screen }),
463
- timestamp: timestamp ?? now(),
464
- attributes: createReactNativeSpanAttributes({
465
- name: spanName,
466
- status,
467
- durationMs,
468
- trace: context,
469
- metadata: {
470
- ...getReactNativeContext({ platform, appState }),
471
- source: "react-native.navigation",
472
- actionType,
473
- previousRouteName,
474
- routeName,
475
- routePath: safeRoutePath,
476
- screen: screen ?? routeName,
477
- ...(includeRouteKey ? { previousRouteKey, routeKey } : {}),
478
- ...metadata
479
- }
480
- })
481
- };
482
- }
483
-
484
- function captureReactNativeNavigationSpan(client, input = {}) {
485
- requireClient(client);
486
- const event = createReactNativeNavigationSpanEvent(input);
487
- client.span(event.id, event.timestamp, event.attributes);
488
- recordIssueBreadcrumb(client, event, "navigation", "navigation");
489
- return event;
490
- }
491
-
492
- function createReactNativeResourceSpanEvent({
493
- durationMs, id, idFactory = defaultResourceSpanEventId, kind = "fetch", metadata = {}, method, name,
494
- now = () => new Date().toISOString(), platform, appState, responseSizeBytes, routeTemplate, screen,
495
- sessionId, status, statusCode, timestamp, trace
496
- } = {}) {
497
- const safeRouteTemplate = stripQueryAndHash(routeTemplate);
498
- const safeMethod = method === undefined ? undefined : String(method).toUpperCase();
499
- const defaultName = [safeMethod, safeRouteTemplate].filter(Boolean).join(" ");
500
- const spanName = name ?? (defaultName || "mobile.resource");
501
- const context = resolveTraceContext(trace) ?? getActiveLogBrewTrace() ?? createReactNativeTraceContext();
502
- return {
503
- id: id ?? idFactory({ method: safeMethod, routeTemplate: safeRouteTemplate, screen }),
504
- timestamp: timestamp ?? now(),
505
- attributes: createReactNativeSpanAttributes({
506
- name: spanName,
507
- status: status ?? spanStatusFromStatusCode(statusCode),
508
- durationMs,
509
- trace: context,
510
- metadata: {
511
- ...getReactNativeContext({ platform, appState }),
512
- source: "react-native.resource",
513
- durationMs,
514
- method: safeMethod,
515
- resourceKind: kind,
516
- responseSizeBytes,
517
- routeTemplate: safeRouteTemplate,
518
- screen,
519
- sessionId,
520
- statusCode,
521
- ...metadata
522
- }
523
- })
524
- };
525
- }
526
-
527
- function captureReactNativeResourceSpan(client, input = {}) {
528
- requireClient(client);
529
- const event = createReactNativeResourceSpanEvent(input);
530
- client.span(event.id, event.timestamp, event.attributes);
531
- return event;
532
- }
533
-
534
- function createReactNavigationSpanListener(client, navigationContainer, {
535
- captureInitialRoute = false, includeRouteKey = false, metadata = {}, now = () => new Date().toISOString(),
536
- nowMs = () => Date.now(), onError, platform, appState, trace
537
- } = {}) {
538
- requireClient(client);
539
- const container = resolveNavigationContainer(navigationContainer);
540
- if (!container || typeof container.addListener !== "function" || typeof container.getCurrentRoute !== "function") {
541
- throw new SdkError("configuration_error", "createReactNavigationSpanListener requires a React Navigation container ref with addListener and getCurrentRoute");
542
- }
543
-
544
- let previousRoute = captureInitialRoute ? {} : routeSnapshot(container.getCurrentRoute());
545
- let pendingNavigation;
546
- const removers = [];
547
- const captureCurrentRoute = () => {
548
- try {
549
- const route = routeSnapshot(container.getCurrentRoute());
550
- if (!route.name && !route.path) {
551
- return;
552
- }
553
- const startedAtMs = pendingNavigation?.startedAtMs;
554
- const durationMs = startedAtMs === undefined ? undefined : Math.max(0, nowMs() - startedAtMs);
555
- captureReactNativeNavigationSpan(client, {
556
- actionType: pendingNavigation?.actionType,
557
- durationMs,
558
- includeRouteKey,
559
- metadata,
560
- now,
561
- platform,
562
- appState,
563
- previousRouteKey: previousRoute.key,
564
- previousRouteName: previousRoute.name,
565
- routeKey: route.key,
566
- routeName: route.name,
567
- routePath: route.path,
568
- timestamp: pendingNavigation?.timestamp,
569
- trace
570
- });
571
- previousRoute = route;
572
- pendingNavigation = undefined;
573
- } catch (error) {
574
- if (typeof onError === "function") {
575
- onError(error);
576
- } else {
577
- throw error;
578
- }
579
- }
580
- };
581
-
582
- const removeListeners = () => {
583
- const failures = [];
584
- const failedRemovers = [];
585
- for (const remove of removers.splice(0).reverse()) {
586
- try {
587
- remove();
588
- } catch (error) {
589
- failedRemovers.unshift(remove);
590
- failures.push(error);
591
- }
592
- }
593
- removers.push(...failedRemovers);
594
- if (failures.length > 0) {
595
- throw failures[0];
596
- }
597
- };
598
-
599
- try {
600
- const actionSubscription = safeNavigationListener(container, "__unsafe_action__", (event) => {
601
- pendingNavigation = {
602
- actionType: navigationActionType(event),
603
- startedAtMs: nowMs(),
604
- timestamp: now()
605
- };
606
- });
607
- if (actionSubscription) {
608
- removers.push(actionSubscription);
609
- }
610
- removers.push(addNavigationListener(container, "state", captureCurrentRoute));
611
- if (captureInitialRoute) {
612
- captureCurrentRoute();
613
- }
614
- } catch (error) {
615
- try {
616
- removeListeners();
617
- } catch {
618
- // Preserve the setup failure after attempting both listener removals.
619
- }
620
- throw error;
621
- }
622
- return removeListeners;
623
- }
624
-
625
- function createReactNativeErrorEvent(error, {
626
- debugIdMap,
627
- evidence,
628
- environment,
629
- fingerprint,
630
- handled = true,
631
- id,
632
- idFactory = defaultErrorEventId,
633
- includeStack = false,
634
- level = "error",
635
- mechanism = "react-native.error",
636
- metadata = {},
637
- now = () => new Date().toISOString(),
638
- platform,
639
- appState,
640
- release,
641
- runtime,
642
- screen,
643
- service,
644
- timestamp,
645
- trace
646
- } = {}) {
647
- const details = errorDetails(error);
648
- const traceContext = resolveTraceContext(trace ?? getActiveLogBrewTrace());
649
- const attributes = createIssueAttributesFromError(error?.reason ?? error?.error ?? error, {
650
- debugIdMap: debugIdMap === undefined ? runtimeReactNativeDebugIdMap() : debugIdMap,
651
- evidence,
652
- environment,
653
- fingerprint,
654
- handled,
655
- includeErrorStack: includeStack,
656
- level,
657
- mechanism,
658
- metadata: {
659
- ...getReactNativeContext({ platform, appState }),
660
- errorValueType: details.valueType,
661
- screen,
662
- ...metadata
663
- },
664
- release,
665
- runtime,
666
- service,
667
- source: "react-native.error",
668
- trace: traceContext
669
- });
670
- const stackFrames = sanitizeReactNativeIssueStackFrames(attributes.stackFrames);
671
- const exceptionChain = sanitizeReactNativeIssueExceptionChain(attributes.exceptionChain);
672
- return {
673
- id: id ?? idFactory({ error, message: details.message, screen }),
674
- timestamp: timestamp ?? now(),
675
- attributes: {
676
- ...attributes,
677
- ...(exceptionChain ? { exceptionChain } : {}),
678
- ...(stackFrames ? { stackFrames } : {}),
679
- title: `React Native error: ${details.message}`,
680
- message: details.message,
681
- metadata: sanitizeReactNativeIssueMetadata(attributes.metadata, compactMetadata, stackFrames)
682
- }
683
- };
684
- }
685
-
686
- function captureReactNativeError(client, error, options = {}) {
687
- requireClient(client);
688
- const event = createReactNativeErrorEvent(error, options);
689
- client.issue(event.id, event.timestamp, event.attributes);
690
- return event;
691
- }
692
-
693
- function createAppStateListener(client, appState, options = {}) {
694
- requireClient(client);
695
- if (!appState || typeof appState.addEventListener !== "function") {
696
- throw new SdkError("configuration_error", "createAppStateListener requires AppState.addEventListener");
697
- }
698
- const {
699
- flushOnBackground = false,
700
- onFlushError,
701
- ...captureOptions
702
- } = options;
703
- if (typeof flushOnBackground !== "boolean") {
704
- throw new SdkError("configuration_error", "createAppStateListener flushOnBackground must be a boolean");
705
- }
706
- if (onFlushError !== undefined && typeof onFlushError !== "function") {
707
- throw new SdkError("configuration_error", "createAppStateListener onFlushError must be a function");
708
- }
709
-
710
- const subscription = appState.addEventListener("change", (nextState) => {
711
- captureAppStateChange(client, nextState, {
712
- ...captureOptions,
713
- appState
714
- });
715
- if (flushOnBackground && BACKGROUND_APP_STATES.has(nextState)) {
716
- void client.flush().catch((error) => {
717
- if (typeof onFlushError === "function") {
718
- try {
719
- onFlushError(error);
720
- } catch {
721
- // Delivery diagnostics must not interrupt the app-state callback.
722
- }
723
- }
724
- });
725
- }
726
- });
727
-
728
- return subscriptionRemover(subscription);
729
- }
730
-
731
- function LogBrewNativeProvider({ client, platform, appState, trace, children }) {
732
- requireClient(client);
733
- const value = React.useMemo(() => ({
734
- client,
735
- platform,
736
- appState,
737
- trace: resolveTraceContext(trace)
738
- }), [appState, client, platform, trace]);
739
- return React.createElement(LogBrewNativeContext.Provider, { value }, children);
740
- }
741
-
742
- function useLogBrewNative() {
743
- const value = React.useContext(LogBrewNativeContext);
744
- if (!value?.client) {
745
- throw new SdkError("configuration_error", "useLogBrewNative must be used inside LogBrewNativeProvider");
746
- }
747
- return value;
748
- }
749
-
750
- function useLogBrewNativeActions() {
751
- const { client, platform, appState, trace } = useLogBrewNative();
752
- const scoped = (options = {}) => ({ platform, appState, trace, ...options });
753
- return {
754
- release: client.release.bind(client),
755
- environment: client.environment.bind(client),
756
- issue: (id, timestamp, attributes) => client.issue(id, timestamp, attributesWithTrace(attributes, trace)),
757
- log: (id, timestamp, attributes) => client.log(id, timestamp, attributesWithTrace(attributes, trace)),
758
- span: client.span.bind(client),
759
- action: (id, timestamp, attributes) => client.action(id, timestamp, attributesWithTrace(attributes, trace)),
760
- flush: client.flush.bind(client),
761
- shutdown: client.shutdown.bind(client),
762
- deliveryHealth: client.deliveryHealth.bind(client),
763
- droppedEvents: client.droppedEvents.bind(client),
764
- pendingBytes: client.pendingBytes.bind(client),
765
- previewJson: client.previewJson.bind(client),
766
- pendingEvents: client.pendingEvents.bind(client),
767
- trace,
768
- captureScreenView: (screenName, options = {}) => captureScreenView(client, screenName, scoped(options)),
769
- captureAppStateChange: (state, options = {}) => captureAppStateChange(client, state, scoped(options)),
770
- captureReactNativeAction: (input = {}) => captureReactNativeAction(client, scoped(input)),
771
- captureReactNativeNetwork: (input = {}) => captureReactNativeNetwork(client, scoped(input)),
772
- captureReactNativeNavigationSpan: (input = {}) => captureReactNativeNavigationSpan(client, scoped(input)),
773
- captureReactNativeResourceSpan: (input = {}) => captureReactNativeResourceSpan(client, scoped(input)),
774
- captureReactNativeError: (error, options = {}) => captureReactNativeError(client, error, scoped(options))
775
- };
776
- }
777
-
778
- function requireClient(client) {
779
- if (!client) {
780
- throw new SdkError("configuration_error", "LogBrew React Native helpers require a client");
781
- }
782
- }
783
-
784
- function requireNonEmpty(label, value) {
785
- if (typeof value !== "string" || value.trim() === "") {
786
- throw new SdkError("validation_error", `${label} must be non-empty`);
787
- }
788
- }
789
-
790
- function normalizeMetadataValue(value) {
791
- if (value === undefined) {
792
- return null;
793
- }
794
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null) {
795
- return value;
796
- }
797
- return String(value);
798
- }
799
-
800
- function compactMetadata(metadata) {
801
- const compacted = {};
802
- for (const [key, value] of Object.entries(metadata)) {
803
- if (value === undefined) {
804
- continue;
805
- }
806
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null) {
807
- compacted[key] = value;
808
- }
809
- }
810
- return compacted;
811
- }
812
-
813
- function attributesWithTrace(attributes, trace) {
814
- const context = resolveTraceContext(trace) ?? getActiveLogBrewTrace();
815
- if (!context) {
816
- return attributes;
817
- }
818
- return {
819
- ...attributes,
820
- metadata: compactMetadata({
821
- ...(attributes?.metadata ?? {}),
822
- ...getReactNativeTraceMetadata(context)
823
- })
824
- };
825
- }
826
-
827
- function errorDetails(error) {
828
- const candidate = error?.reason ?? error?.error ?? error;
829
- return {
830
- message: errorMessage(candidate),
831
- valueType: candidate === null ? "null" : typeof candidate
832
- };
833
- }
834
-
835
- function errorMessage(error) {
836
- if (error instanceof Error && typeof error.message === "string" && error.message.trim() !== "") {
837
- return error.message;
838
- }
839
- if (typeof error?.message === "string" && error.message.trim() !== "") {
840
- return error.message;
841
- }
842
- if (typeof error === "string" && error.trim() !== "") {
843
- return error;
844
- }
845
- return String(error ?? "unknown error");
846
- }
847
-
848
- function validateDeliveryEndpoint(endpoint) {
849
- if (typeof endpoint !== "string" || endpoint.trim() === "") {
850
- throw new SdkError("configuration_error", "createReactNativeFetchTransport requires a non-empty endpoint");
851
- }
852
- let parsed;
853
- try {
854
- parsed = new URL(endpoint);
855
- } catch {
856
- throw new SdkError("configuration_error", "createReactNativeFetchTransport endpoint must be an absolute URL");
857
- }
858
- if (parsed.protocol !== "https:") {
859
- throw new SdkError("configuration_error", "createReactNativeFetchTransport endpoint must use HTTPS");
860
- }
861
- if (endpoint !== `${parsed.origin}${parsed.pathname}`) {
862
- throw new SdkError("configuration_error", "createReactNativeFetchTransport endpoint must be a plain HTTPS path");
863
- }
864
- }
865
-
866
- function retryAfterMsFromHeaders(headers) {
867
- if (!headers || typeof headers.get !== "function") {
868
- return undefined;
869
- }
870
- return retryAfterMsFromHeader(headers.get("retry-after"));
871
- }
872
-
873
- // Reads a 429 body only when it declares at most 4 KiB, and only to find a known `code`.
874
- async function rateLimitCode(response) {
875
- try {
876
- const length = Number(response.headers?.get?.("content-length"));
877
- if (!Number.isSafeInteger(length) || length > RATE_LIMIT_BODY_LIMIT_BYTES || typeof response.text !== "function") {
878
- return undefined;
879
- }
880
- const text = await response.text();
881
- const code = text.length <= RATE_LIMIT_BODY_LIMIT_BYTES ? JSON.parse(text)?.code : undefined;
882
- return code === "rate_limited" || code === "usage_limit_exceeded" ? code : undefined;
883
- } catch {
884
- return undefined;
885
- }
886
- }
887
-
888
- function retryAfterMsFromHeader(value, now = Date.now()) {
889
- if (typeof value !== "string" || value.trim() === "") {
890
- return undefined;
891
- }
892
- const trimmed = value.trim();
893
- if (/^\d+$/u.test(trimmed)) {
894
- const milliseconds = Number(trimmed) * 1000;
895
- return Number.isSafeInteger(milliseconds) ? milliseconds : undefined;
896
- }
897
- // Only an HTTP date counts; a repeated header arrives comma-joined and is ignored.
898
- const timestamp = /^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/u.test(trimmed)
899
- ? Date.parse(trimmed)
900
- : Number.NaN;
901
- return Number.isFinite(timestamp) ? Math.max(0, timestamp - now) : undefined;
902
- }
903
-
904
- function defaultEventId(kind) {
905
- return `evt_native_${kind}_${randomHex(16, defaultRandomValues)}`;
906
- }
907
-
908
- const defaultErrorEventId = () => defaultEventId("error");
909
- const defaultActionEventId = () => defaultEventId("action");
910
- const defaultNetworkEventId = () => defaultEventId("network");
911
- const defaultNavigationSpanEventId = () => defaultEventId("navigation");
912
- const defaultResourceSpanEventId = () => defaultEventId("resource");
913
-
914
- function defaultFetch() {
915
- return typeof globalThis.fetch === "function" ? globalThis.fetch.bind(globalThis) : undefined;
916
- }
917
-
918
- function recordIssueBreadcrumb(client, event, category, type) {
919
- if (typeof client?.addBreadcrumb !== "function") {
920
- return;
921
- }
922
- const status = typeof event?.attributes?.status === "string"
923
- ? event.attributes.status
924
- : undefined;
925
- const message = boundedBreadcrumbMessage(event?.attributes?.name);
926
- client.addBreadcrumb({
927
- category,
928
- type,
929
- level: status === "failure" || status === "error" ? "error" : "info",
930
- ...(message === undefined ? {} : { message }),
931
- ...(status === undefined ? {} : { data: { status } })
932
- }, event.timestamp);
933
- if (category === "navigation" && message !== undefined) {
934
- // Global error reports keep the last route even after breadcrumb eviction.
935
- client[LAST_ROUTE] = message;
936
- }
937
- }
938
-
939
- function boundedBreadcrumbMessage(value) {
940
- if (typeof value !== "string" || value.trim() === "") {
941
- return undefined;
942
- }
943
- const characters = Array.from(value);
944
- if (
945
- characters.length > 512
946
- || characters.some((character) => {
947
- const code = character.codePointAt(0);
948
- return code !== undefined && (code <= 31 || (code >= 127 && code <= 159));
949
- })
950
- ) {
951
- return undefined;
952
- }
953
- return value;
954
- }
955
-
956
- function defaultRandomValues(length) {
957
- const bytes = new Uint8Array(length);
958
- if (typeof globalThis.crypto?.getRandomValues === "function") {
959
- return globalThis.crypto.getRandomValues(bytes);
960
- }
961
- if (typeof globalThis.expo?.modules?.ExpoCrypto?.getRandomValues === "function") {
962
- globalThis.expo.modules.ExpoCrypto.getRandomValues(bytes);
963
- return bytes;
964
- }
965
- const nativeRandom = globalThis[NATIVE_RANDOM_HEX];
966
- if (typeof nativeRandom !== "function") {
967
- throw secureRandomError();
968
- }
969
- let nativeHex;
970
- try {
971
- nativeHex = nativeRandom(length);
972
- } catch {
973
- throw secureRandomError();
974
- }
975
- if (typeof nativeHex !== "string" || nativeHex.length !== length * 2 || !/^[0-9a-f]+$/iu.test(nativeHex)) {
976
- throw secureRandomError();
977
- }
978
- return Uint8Array.from({ length }, (_, index) => Number.parseInt(nativeHex.slice(index * 2, index * 2 + 2), 16));
979
- }
980
-
981
- function secureRandomError() {
982
- return new SdkError("configuration_error", "React Native secure random values are unavailable");
983
- }
984
-
985
- function headersWithTraceparent(headers, traceparent) {
986
- const nextHeaders = {};
987
- for (const [key, value] of headerEntries(headers)) {
988
- if (String(key).toLowerCase() !== "traceparent") {
989
- nextHeaders[key] = value;
990
- }
991
- }
992
- nextHeaders.traceparent = traceparent;
993
- return nextHeaders;
994
- }
995
-
996
- function headerEntries(headers) {
997
- if (headers === undefined || headers === null) {
998
- return [];
999
- }
1000
- const HeadersConstructor = globalThis.Headers;
1001
- if (typeof HeadersConstructor === "function" && headers instanceof HeadersConstructor) {
1002
- const entries = [];
1003
- headers.forEach((value, key) => {
1004
- entries.push([key, value]);
1005
- });
1006
- return entries;
1007
- }
1008
- if (Array.isArray(headers)) {
1009
- return headers;
1010
- }
1011
- if (typeof headers !== "string" && typeof headers[Symbol.iterator] === "function") {
1012
- return Array.from(headers);
1013
- }
1014
- if (typeof headers === "object") {
1015
- return Object.entries(headers);
1016
- }
1017
- return [];
1018
- }
1019
-
1020
- function randomHex(length, randomValues) {
1021
- if (typeof randomValues !== "function") {
1022
- throw new SdkError("configuration_error", "randomValues must be a function");
1023
- }
1024
- const bytes = Array.from(randomValues(length));
1025
- if (bytes.length !== length || bytes.some((value) => !Number.isInteger(value) || value < 0 || value > 255)) {
1026
- throw new SdkError("configuration_error", "randomValues must return byte values for the requested length");
1027
- }
1028
- return bytes.map((value) => value.toString(16).padStart(2, "0")).join("");
1029
- }
1030
-
1031
- function resolveTraceContext(trace) {
1032
- if (trace === undefined || trace === null) {
1033
- return undefined;
1034
- }
1035
- if (typeof trace === "string") {
1036
- return createReactNativeTraceContext({ traceparent: trace });
1037
- }
1038
- if (typeof trace === "object") {
1039
- const {
1040
- parentSpanId,
1041
- sampled,
1042
- spanId,
1043
- traceFlags = "01",
1044
- traceId
1045
- } = trace;
1046
- if (typeof traceId !== "string" || typeof spanId !== "string") {
1047
- throw new SdkError("validation_error", "trace context requires traceId and spanId");
1048
- }
1049
- createTraceparent({ traceId, spanId, traceFlags });
1050
- if (parentSpanId !== undefined) {
1051
- createTraceparent({ traceId, spanId: parentSpanId, traceFlags });
1052
- }
1053
- return freezeTraceContext({
1054
- parentSpanId,
1055
- sampled: sampled ?? sampledFromTraceFlags(traceFlags),
1056
- spanId,
1057
- traceFlags,
1058
- traceId
1059
- });
1060
- }
1061
- throw new SdkError("validation_error", "trace must be a trace context or traceparent string");
1062
- }
1063
-
1064
- function freezeTraceContext({ parentSpanId, sampled, spanId, traceFlags, traceId }) {
1065
- const normalized = {
1066
- traceId: String(traceId).toLowerCase(),
1067
- spanId: String(spanId).toLowerCase(),
1068
- parentSpanId: parentSpanId === undefined ? undefined : String(parentSpanId).toLowerCase(),
1069
- traceFlags: String(traceFlags).toLowerCase(),
1070
- sampled: Boolean(sampled)
1071
- };
1072
- return Object.freeze(normalized);
1073
- }
1074
-
1075
- function sampledFromTraceFlags(traceFlags) {
1076
- return (Number.parseInt(traceFlags, 16) & 1) === 1;
1077
- }
1078
-
1079
- function removeActiveTraceScope(scopeId) {
1080
- const index = activeTraceScopes.findIndex((scope) => scope.id === scopeId);
1081
- if (index >= 0) {
1082
- activeTraceScopes.splice(index, 1);
1083
- }
1084
- }
1085
-
1086
- function shouldPropagateToStringTarget(url, target) {
1087
- const targetText = target.trim();
1088
- if (targetText === "") {
1089
- return false;
1090
- }
1091
- if (targetText.startsWith("/")) {
1092
- return url.startsWith(targetText);
1093
- }
1094
-
1095
- const URLConstructor = globalThis.URL;
1096
- if (typeof URLConstructor === "function") {
1097
- try {
1098
- const targetUrl = new URLConstructor(targetText);
1099
- if (!hasUrlScheme(url)) {
1100
- return false;
1101
- }
1102
- const requestUrl = new URLConstructor(url, targetUrl.origin);
1103
- if (requestUrl.origin !== targetUrl.origin) {
1104
- return false;
1105
- }
1106
- const targetPath = targetUrl.pathname || "/";
1107
- return requestUrl.pathname === targetPath || requestUrl.pathname.startsWith(pathPrefix(targetPath));
1108
- } catch {
1109
- return url.startsWith(targetText);
1110
- }
1111
- }
1112
-
1113
- return url.startsWith(targetText);
1114
- }
1115
-
1116
- function pathPrefix(pathname) {
1117
- return pathname.endsWith("/") ? pathname : `${pathname}/`;
1118
- }
1119
-
1120
- function hasUrlScheme(url) {
1121
- return /^[a-z][a-z0-9+.-]*:/iu.test(url);
1122
- }
1123
-
1124
- function requestHeaders(input, init) {
1125
- if (init && init.headers !== undefined) {
1126
- return init.headers;
1127
- }
1128
- return input?.headers;
1129
- }
1130
-
1131
- function requestUrl(input) {
1132
- if (typeof input === "string") {
1133
- return input;
1134
- }
1135
- const URLConstructor = globalThis.URL;
1136
- if (typeof URLConstructor === "function" && input instanceof URLConstructor) {
1137
- return input.toString();
1138
- }
1139
- if (typeof input?.url === "string") {
1140
- return input.url;
1141
- }
1142
- return String(input);
1143
- }
1144
-
1145
- function slugify(value) {
1146
- return String(value)
1147
- .toLowerCase()
1148
- .replace(/[^a-z0-9]+/g, "_")
1149
- .replace(/^_+|_+$/g, "") || "event";
1150
- }
1151
-
1152
- function screenActionName(screenName) {
1153
- const directName = `${SCREEN_ACTION_PREFIX}${screenName}`;
1154
- if (
1155
- directName.length <= MAX_ACTION_NAME_LENGTH
1156
- && /^[a-z0-9_.:-]+$/i.test(directName)
1157
- ) {
1158
- return directName;
1159
- }
1160
-
1161
- const maxScreenSegmentLength = MAX_ACTION_NAME_LENGTH - SCREEN_ACTION_PREFIX.length;
1162
- const screenSegment = slugify(screenName)
1163
- .slice(0, maxScreenSegmentLength)
1164
- .replace(/_+$/g, "") || "event";
1165
- return `${SCREEN_ACTION_PREFIX}${screenSegment}`;
1166
- }
1167
-
1168
- function productAnalyticsMetadata(kind, surface) {
1169
- return {
1170
- analyticsSchemaVersion: PRODUCT_ANALYTICS_SCHEMA_VERSION,
1171
- analyticsKind: kind,
1172
- analyticsSurface: boundedProductAnalyticsSurface(surface)
1173
- };
1174
- }
1175
-
1176
- function boundedProductAnalyticsSurface(surface) {
1177
- if (typeof surface !== "string") {
1178
- return undefined;
1179
- }
1180
- const normalized = surface.trim();
1181
- const characters = Array.from(normalized);
1182
- if (
1183
- normalized === ""
1184
- || characters.length > MAX_PRODUCT_ANALYTICS_SURFACE_LENGTH
1185
- || characters.some((character) => {
1186
- const code = character.codePointAt(0);
1187
- return code !== undefined && (code <= 31 || (code >= 127 && code <= 159));
1188
- })
1189
- ) {
1190
- return undefined;
1191
- }
1192
- return normalized;
1193
- }
1194
-
1195
- function statusFromStatusCode(statusCode) {
1196
- if (typeof statusCode === "number" && Number.isFinite(statusCode) && statusCode >= 400) {
1197
- return "failure";
1198
- }
1199
- return "success";
1200
- }
1201
-
1202
- function spanStatusFromStatusCode(statusCode) {
1203
- if (typeof statusCode === "number" && Number.isFinite(statusCode) && statusCode >= 400) {
1204
- return "error";
1205
- }
1206
- return "ok";
1207
- }
1208
-
1209
- function stripQueryAndHash(value) {
1210
- if (value === undefined || value === null) {
1211
- return undefined;
1212
- }
1213
- return String(value).split(/[?#]/u, 1)[0];
1214
- }
1215
-
1216
- function resolveNavigationContainer(navigationContainer) {
1217
- if (navigationContainer && typeof navigationContainer === "object" && "current" in navigationContainer) {
1218
- return navigationContainer.current;
1219
- }
1220
- return navigationContainer;
1221
- }
1222
-
1223
- function addNavigationListener(container, eventName, listener) {
1224
- const subscription = container.addListener(eventName, listener);
1225
- return subscriptionRemover(subscription);
1226
- }
1227
-
1228
- function subscriptionRemover(subscription) {
1229
- if (typeof subscription === "function") {
1230
- return subscription;
1231
- }
1232
- if (subscription && typeof subscription.remove === "function") {
1233
- return () => subscription.remove();
1234
- }
1235
- return () => {};
1236
- }
1237
-
1238
- function safeNavigationListener(container, eventName, listener) {
1239
- try {
1240
- return addNavigationListener(container, eventName, listener);
1241
- } catch {
1242
- return undefined;
1243
- }
1244
- }
1245
-
1246
- function routeSnapshot(route) {
1247
- return {
1248
- key: normalizeMetadataValue(route?.key),
1249
- name: typeof route?.name === "string" && route.name.trim() !== "" ? route.name : undefined,
1250
- path: stripQueryAndHash(route?.path)
1251
- };
1252
- }
1253
-
1254
- function navigationActionType(event) {
1255
- const action = event?.data?.action ?? event?.action ?? event;
1256
- return typeof action?.type === "string" && action.type.trim() !== "" ? action.type : undefined;
1257
- }
1258
-
1259
- function traceparentForRequest({
1260
- init, input, randomValues, trace, traceFlags, traceparent, traceparentFactory, url
1261
- }) {
1262
- const context = resolveTraceContext(trace) ?? getActiveLogBrewTrace();
1263
- const nextTraceparent = typeof traceparentFactory === "function"
1264
- ? traceparentFactory({ init, input, url })
1265
- : traceparent ?? (context ? createReactNativeTraceHeaders(context).traceparent : createReactNativeTraceparent({ randomValues, traceFlags }));
1266
- parseTraceparent(nextTraceparent);
1267
- return nextTraceparent;
1268
- }
1269
-
1270
96
  const defaultExport = {
1271
- LogBrewNativeProvider, captureAppStateChange, captureReactNativeAction, captureReactNativeError,
1272
- captureReactNativeNetwork, captureReactNativeNavigationSpan, captureReactNativeResourceSpan, captureScreenView,
1273
- bindLogBrewTrace, createAppStateListener, createLogBrewReactNativeClient, createReactNavigationSpanListener,
1274
- createReactNativeFetchTransport, createReactNativeSpanAttributes, createReactNativeTraceContext,
1275
- createReactNativeTraceHeaders, createReactNativeActionEvent,
1276
- createReactNativeErrorEvent, createReactNativeNetworkEvent, createReactNativeNavigationSpanEvent,
1277
- createReactNativeResourceSpanEvent, createReactNativeTraceparent, createTraceparentFetch, getActiveLogBrewTrace,
1278
- getReactNativeContext, getReactNativeTraceMetadata, shouldPropagateTraceparent, useLogBrewNative,
1279
- useLogBrewNativeActions, withLogBrewTrace
97
+ LogBrewNativeProvider,
98
+ captureAppStateChange,
99
+ captureReactNativeAction,
100
+ captureReactNativeError,
101
+ captureReactNativeNetwork,
102
+
103
+ captureReactNativeNavigationSpan,
104
+ captureReactNativeResourceSpan,
105
+ captureScreenView,
106
+
107
+ bindLogBrewTrace,
108
+ createAppStateListener,
109
+ createLogBrewReactNativeClient,
110
+ createReactNavigationSpanListener,
111
+
112
+ createReactNativeFetchTransport,
113
+ createReactNativeSpanAttributes,
114
+ createReactNativeTraceContext,
115
+ createReactNativeTraceHeaders,
116
+
117
+ createReactNativeActionEvent,
118
+ createReactNativeErrorEvent,
119
+ createReactNativeNetworkEvent,
120
+
121
+ createReactNativeNavigationSpanEvent,
122
+ createReactNativeResourceSpanEvent,
123
+ createReactNativeTraceparent,
124
+ createTraceparentFetch,
125
+ getActiveLogBrewTrace,
126
+ getReactNativeContext,
127
+ getReactNativeTraceMetadata,
128
+ shouldPropagateTraceparent,
129
+ useLogBrewNative,
130
+ useLogBrewNativeActions,
131
+ withLogBrewTrace
1280
132
  };
1281
133
 
1282
134
  module.exports = { ...defaultExport, default: defaultExport };