@logbrew/react-native 0.1.38 → 0.1.40

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