@rejourneyco/react-native 1.0.7

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 (105) hide show
  1. package/README.md +29 -0
  2. package/android/build.gradle.kts +135 -0
  3. package/android/consumer-rules.pro +10 -0
  4. package/android/proguard-rules.pro +1 -0
  5. package/android/src/main/AndroidManifest.xml +15 -0
  6. package/android/src/main/java/com/rejourney/RejourneyModuleImpl.kt +860 -0
  7. package/android/src/main/java/com/rejourney/engine/DeviceRegistrar.kt +290 -0
  8. package/android/src/main/java/com/rejourney/engine/DiagnosticLog.kt +385 -0
  9. package/android/src/main/java/com/rejourney/engine/RejourneyImpl.kt +512 -0
  10. package/android/src/main/java/com/rejourney/platform/OEMDetector.kt +173 -0
  11. package/android/src/main/java/com/rejourney/platform/PerfTiming.kt +384 -0
  12. package/android/src/main/java/com/rejourney/platform/SessionLifecycleService.kt +160 -0
  13. package/android/src/main/java/com/rejourney/platform/Telemetry.kt +301 -0
  14. package/android/src/main/java/com/rejourney/platform/WindowUtils.kt +100 -0
  15. package/android/src/main/java/com/rejourney/recording/AnrSentinel.kt +129 -0
  16. package/android/src/main/java/com/rejourney/recording/EventBuffer.kt +330 -0
  17. package/android/src/main/java/com/rejourney/recording/InteractionRecorder.kt +519 -0
  18. package/android/src/main/java/com/rejourney/recording/ReplayOrchestrator.kt +740 -0
  19. package/android/src/main/java/com/rejourney/recording/SegmentDispatcher.kt +559 -0
  20. package/android/src/main/java/com/rejourney/recording/StabilityMonitor.kt +238 -0
  21. package/android/src/main/java/com/rejourney/recording/TelemetryPipeline.kt +633 -0
  22. package/android/src/main/java/com/rejourney/recording/ViewHierarchyScanner.kt +232 -0
  23. package/android/src/main/java/com/rejourney/recording/VisualCapture.kt +474 -0
  24. package/android/src/main/java/com/rejourney/utility/DataCompression.kt +63 -0
  25. package/android/src/main/java/com/rejourney/utility/ImageBlur.kt +412 -0
  26. package/android/src/main/java/com/rejourney/utility/ViewIdentifier.kt +169 -0
  27. package/android/src/newarch/java/com/rejourney/RejourneyModule.kt +232 -0
  28. package/android/src/newarch/java/com/rejourney/RejourneyPackage.kt +40 -0
  29. package/android/src/oldarch/java/com/rejourney/RejourneyModule.kt +268 -0
  30. package/android/src/oldarch/java/com/rejourney/RejourneyPackage.kt +23 -0
  31. package/ios/Engine/DeviceRegistrar.swift +288 -0
  32. package/ios/Engine/DiagnosticLog.swift +387 -0
  33. package/ios/Engine/RejourneyImpl.swift +719 -0
  34. package/ios/Recording/AnrSentinel.swift +142 -0
  35. package/ios/Recording/EventBuffer.swift +326 -0
  36. package/ios/Recording/InteractionRecorder.swift +428 -0
  37. package/ios/Recording/ReplayOrchestrator.swift +624 -0
  38. package/ios/Recording/SegmentDispatcher.swift +492 -0
  39. package/ios/Recording/StabilityMonitor.swift +223 -0
  40. package/ios/Recording/TelemetryPipeline.swift +547 -0
  41. package/ios/Recording/ViewHierarchyScanner.swift +156 -0
  42. package/ios/Recording/VisualCapture.swift +675 -0
  43. package/ios/Rejourney.h +38 -0
  44. package/ios/Rejourney.mm +375 -0
  45. package/ios/Utility/DataCompression.swift +55 -0
  46. package/ios/Utility/ImageBlur.swift +89 -0
  47. package/ios/Utility/RuntimeMethodSwap.swift +41 -0
  48. package/ios/Utility/ViewIdentifier.swift +37 -0
  49. package/lib/commonjs/NativeRejourney.js +40 -0
  50. package/lib/commonjs/components/Mask.js +88 -0
  51. package/lib/commonjs/index.js +1443 -0
  52. package/lib/commonjs/sdk/autoTracking.js +1087 -0
  53. package/lib/commonjs/sdk/constants.js +166 -0
  54. package/lib/commonjs/sdk/errorTracking.js +187 -0
  55. package/lib/commonjs/sdk/index.js +50 -0
  56. package/lib/commonjs/sdk/metricsTracking.js +205 -0
  57. package/lib/commonjs/sdk/navigation.js +128 -0
  58. package/lib/commonjs/sdk/networkInterceptor.js +375 -0
  59. package/lib/commonjs/sdk/utils.js +433 -0
  60. package/lib/commonjs/sdk/version.js +13 -0
  61. package/lib/commonjs/types/expo-router.d.js +2 -0
  62. package/lib/commonjs/types/index.js +2 -0
  63. package/lib/module/NativeRejourney.js +38 -0
  64. package/lib/module/components/Mask.js +83 -0
  65. package/lib/module/index.js +1341 -0
  66. package/lib/module/sdk/autoTracking.js +1059 -0
  67. package/lib/module/sdk/constants.js +154 -0
  68. package/lib/module/sdk/errorTracking.js +177 -0
  69. package/lib/module/sdk/index.js +26 -0
  70. package/lib/module/sdk/metricsTracking.js +187 -0
  71. package/lib/module/sdk/navigation.js +120 -0
  72. package/lib/module/sdk/networkInterceptor.js +364 -0
  73. package/lib/module/sdk/utils.js +412 -0
  74. package/lib/module/sdk/version.js +7 -0
  75. package/lib/module/types/expo-router.d.js +2 -0
  76. package/lib/module/types/index.js +2 -0
  77. package/lib/typescript/NativeRejourney.d.ts +160 -0
  78. package/lib/typescript/components/Mask.d.ts +54 -0
  79. package/lib/typescript/index.d.ts +117 -0
  80. package/lib/typescript/sdk/autoTracking.d.ts +226 -0
  81. package/lib/typescript/sdk/constants.d.ts +138 -0
  82. package/lib/typescript/sdk/errorTracking.d.ts +47 -0
  83. package/lib/typescript/sdk/index.d.ts +24 -0
  84. package/lib/typescript/sdk/metricsTracking.d.ts +75 -0
  85. package/lib/typescript/sdk/navigation.d.ts +48 -0
  86. package/lib/typescript/sdk/networkInterceptor.d.ts +62 -0
  87. package/lib/typescript/sdk/utils.d.ts +193 -0
  88. package/lib/typescript/sdk/version.d.ts +6 -0
  89. package/lib/typescript/types/index.d.ts +618 -0
  90. package/package.json +122 -0
  91. package/rejourney.podspec +23 -0
  92. package/src/NativeRejourney.ts +185 -0
  93. package/src/components/Mask.tsx +93 -0
  94. package/src/index.ts +1555 -0
  95. package/src/sdk/autoTracking.ts +1245 -0
  96. package/src/sdk/constants.ts +155 -0
  97. package/src/sdk/errorTracking.ts +231 -0
  98. package/src/sdk/index.ts +25 -0
  99. package/src/sdk/metricsTracking.ts +227 -0
  100. package/src/sdk/navigation.ts +152 -0
  101. package/src/sdk/networkInterceptor.ts +423 -0
  102. package/src/sdk/utils.ts +442 -0
  103. package/src/sdk/version.ts +6 -0
  104. package/src/types/expo-router.d.ts +7 -0
  105. package/src/types/index.ts +709 -0
@@ -0,0 +1,1443 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ var _exportNames = {
7
+ initRejourney: true,
8
+ startRejourney: true,
9
+ stopRejourney: true,
10
+ setLogLevel: true,
11
+ trackTap: true,
12
+ trackScroll: true,
13
+ trackGesture: true,
14
+ trackInput: true,
15
+ trackScreen: true,
16
+ captureError: true,
17
+ getSessionMetrics: true,
18
+ trackNavigationState: true,
19
+ useNavigationTracking: true,
20
+ LogLevel: true,
21
+ Mask: true
22
+ };
23
+ Object.defineProperty(exports, "LogLevel", {
24
+ enumerable: true,
25
+ get: function () {
26
+ return _utils.LogLevel;
27
+ }
28
+ });
29
+ Object.defineProperty(exports, "Mask", {
30
+ enumerable: true,
31
+ get: function () {
32
+ return _Mask.Mask;
33
+ }
34
+ });
35
+ Object.defineProperty(exports, "captureError", {
36
+ enumerable: true,
37
+ get: function () {
38
+ return _autoTracking2.captureError;
39
+ }
40
+ });
41
+ exports.default = void 0;
42
+ Object.defineProperty(exports, "getSessionMetrics", {
43
+ enumerable: true,
44
+ get: function () {
45
+ return _autoTracking2.getSessionMetrics;
46
+ }
47
+ });
48
+ exports.initRejourney = initRejourney;
49
+ exports.setLogLevel = setLogLevel;
50
+ exports.startRejourney = startRejourney;
51
+ exports.stopRejourney = stopRejourney;
52
+ Object.defineProperty(exports, "trackGesture", {
53
+ enumerable: true,
54
+ get: function () {
55
+ return _autoTracking2.trackGesture;
56
+ }
57
+ });
58
+ Object.defineProperty(exports, "trackInput", {
59
+ enumerable: true,
60
+ get: function () {
61
+ return _autoTracking2.trackInput;
62
+ }
63
+ });
64
+ Object.defineProperty(exports, "trackNavigationState", {
65
+ enumerable: true,
66
+ get: function () {
67
+ return _autoTracking2.trackNavigationState;
68
+ }
69
+ });
70
+ Object.defineProperty(exports, "trackScreen", {
71
+ enumerable: true,
72
+ get: function () {
73
+ return _autoTracking2.trackScreen;
74
+ }
75
+ });
76
+ Object.defineProperty(exports, "trackScroll", {
77
+ enumerable: true,
78
+ get: function () {
79
+ return _autoTracking2.trackScroll;
80
+ }
81
+ });
82
+ Object.defineProperty(exports, "trackTap", {
83
+ enumerable: true,
84
+ get: function () {
85
+ return _autoTracking2.trackTap;
86
+ }
87
+ });
88
+ Object.defineProperty(exports, "useNavigationTracking", {
89
+ enumerable: true,
90
+ get: function () {
91
+ return _autoTracking2.useNavigationTracking;
92
+ }
93
+ });
94
+ var _constants = require("./sdk/constants");
95
+ var _types = require("./types");
96
+ Object.keys(_types).forEach(function (key) {
97
+ if (key === "default" || key === "__esModule") return;
98
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
99
+ if (key in exports && exports[key] === _types[key]) return;
100
+ Object.defineProperty(exports, key, {
101
+ enumerable: true,
102
+ get: function () {
103
+ return _types[key];
104
+ }
105
+ });
106
+ });
107
+ var _autoTracking2 = require("./sdk/autoTracking");
108
+ var _utils = require("./sdk/utils");
109
+ var _Mask = require("./components/Mask");
110
+ /**
111
+ * Rejourney - Session Recording and Replay SDK for React Native
112
+ *
113
+ * Captures user interactions, gestures, and screen states for replay and analysis.
114
+ *
115
+ * Just call initRejourney() - everything else is automatic!
116
+ *
117
+ * Copyright (c) 2026 Rejourney
118
+ *
119
+ * Licensed under the Apache License, Version 2.0 (the "License");
120
+ * you may not use this file except in compliance with the License.
121
+ * See LICENSE-APACHE for full terms.
122
+ *
123
+ * @example
124
+ * ```typescript
125
+ * import { initRejourney } from 'rejourney';
126
+ *
127
+ * // Initialize the SDK with your public key - that's it!
128
+ * initRejourney('pk_live_xxxxxxxxxxxx');
129
+ *
130
+ * // Or with options:
131
+ * initRejourney('pk_live_xxxxxxxxxxxx', { debug: true });
132
+ * ```
133
+ */
134
+
135
+ // =============================================================================
136
+ // CRITICAL: Safe Module Loading for React Native 0.81+
137
+ // =============================================================================
138
+ //
139
+ // On React Native 0.81+ with New Architecture (Bridgeless), importing from
140
+ // 'react-native' at module load time can fail with "PlatformConstants could
141
+ // not be found" because the TurboModule runtime may not be fully initialized.
142
+ //
143
+ // This wrapper ensures that all react-native imports happen after the runtime
144
+ // is ready, by catching any initialization errors and deferring actual SDK
145
+ // operations until initRejourney() is called.
146
+ // =============================================================================
147
+
148
+ // Module load confirmation - this runs when the module is first imported
149
+
150
+ // SDK disabled flag - set to true if we detect runtime issues
151
+ let _sdkDisabled = false;
152
+
153
+ // Type-only imports are safe - they're erased at compile time
154
+
155
+ // SDK version is safe - no react-native imports
156
+
157
+ // =============================================================================
158
+ // Lazy Module Loading
159
+ // =============================================================================
160
+ // All modules that import from 'react-native' are loaded lazily to avoid
161
+ // accessing TurboModuleRegistry before it's ready.
162
+
163
+ let _reactNativeLoaded = false;
164
+ let _RN = null;
165
+ function getReactNative() {
166
+ if (_sdkDisabled) return null;
167
+ if (_reactNativeLoaded) return _RN;
168
+ try {
169
+ _RN = require('react-native');
170
+ _reactNativeLoaded = true;
171
+ return _RN;
172
+ } catch (error) {
173
+ getLogger().warn('Failed to load react-native:', error?.message || error);
174
+ _sdkDisabled = true;
175
+ return null;
176
+ }
177
+ }
178
+ let _logger = null;
179
+ function getLogger() {
180
+ if (_logger) return _logger;
181
+ if (_sdkDisabled) {
182
+ return {
183
+ debug: () => {},
184
+ info: console.log.bind(console, '[Rejourney]'),
185
+ warn: console.warn.bind(console, '[Rejourney]'),
186
+ error: console.error.bind(console, '[Rejourney]'),
187
+ logSessionStart: () => {},
188
+ logSessionEnd: () => {},
189
+ logInitSuccess: () => {},
190
+ logInitFailure: () => {},
191
+ setLogLevel: () => {},
192
+ setDebugMode: () => {},
193
+ logObservabilityStart: () => {},
194
+ logRecordingStart: () => {},
195
+ logRecordingRemoteDisabled: () => {},
196
+ logInvalidProjectKey: () => {},
197
+ logPackageMismatch: () => {},
198
+ logNetworkRequest: () => {},
199
+ logFrustration: () => {},
200
+ logError: () => {},
201
+ logUploadStats: () => {},
202
+ logLifecycleEvent: () => {}
203
+ };
204
+ }
205
+ try {
206
+ const utils = require('./sdk/utils');
207
+ _logger = utils.logger;
208
+ return _logger;
209
+ } catch (error) {
210
+ console.warn('[Rejourney] Failed to load logger:', error?.message || error);
211
+ // Return fallback logger with working info
212
+ return {
213
+ debug: () => {},
214
+ info: console.log.bind(console, '[Rejourney]'),
215
+ warn: console.warn.bind(console, '[Rejourney]'),
216
+ error: console.error.bind(console, '[Rejourney]'),
217
+ logSessionStart: () => {},
218
+ logSessionEnd: () => {},
219
+ logInitSuccess: () => {},
220
+ logInitFailure: () => {},
221
+ setLogLevel: () => {},
222
+ setDebugMode: () => {},
223
+ logObservabilityStart: () => {},
224
+ logRecordingStart: () => {},
225
+ logRecordingRemoteDisabled: () => {},
226
+ logInvalidProjectKey: () => {},
227
+ logPackageMismatch: () => {},
228
+ logNetworkRequest: () => {},
229
+ logFrustration: () => {},
230
+ logError: () => {},
231
+ logUploadStats: () => {},
232
+ logLifecycleEvent: () => {}
233
+ };
234
+ }
235
+ }
236
+
237
+ // Lazy-loaded network interceptor
238
+ let _networkInterceptor = null;
239
+ function getNetworkInterceptor() {
240
+ if (_sdkDisabled) return {
241
+ initNetworkInterceptor: () => {},
242
+ disableNetworkInterceptor: () => {}
243
+ };
244
+ if (_networkInterceptor) return _networkInterceptor;
245
+ try {
246
+ _networkInterceptor = require('./sdk/networkInterceptor');
247
+ return _networkInterceptor;
248
+ } catch (error) {
249
+ getLogger().warn('Failed to load network interceptor:', error?.message || error);
250
+ return {
251
+ initNetworkInterceptor: () => {},
252
+ disableNetworkInterceptor: () => {}
253
+ };
254
+ }
255
+ }
256
+
257
+ // Lazy-loaded auto tracking module
258
+ let _autoTracking = null;
259
+
260
+ // No-op auto tracking for when SDK is disabled
261
+ const noopAutoTracking = {
262
+ initAutoTracking: () => {},
263
+ cleanupAutoTracking: () => {},
264
+ trackScroll: () => {},
265
+ trackScreen: () => {},
266
+ trackAPIRequest: () => {},
267
+ notifyStateChange: () => {},
268
+ getSessionMetrics: () => ({}),
269
+ resetMetrics: () => {},
270
+ collectDeviceInfo: async () => ({}),
271
+ ensurePersistentAnonymousId: async () => 'anonymous'
272
+ };
273
+ function getAutoTracking() {
274
+ if (_sdkDisabled) return noopAutoTracking;
275
+ if (_autoTracking) return _autoTracking;
276
+ try {
277
+ _autoTracking = require('./sdk/autoTracking');
278
+ return _autoTracking;
279
+ } catch (error) {
280
+ getLogger().warn('Failed to load auto tracking:', error?.message || error);
281
+ return noopAutoTracking;
282
+ }
283
+ }
284
+
285
+ // State
286
+ let _isInitialized = false;
287
+ let _isRecording = false;
288
+ let _initializationFailed = false;
289
+ let _metricsInterval = null;
290
+ let _appStateSubscription = null;
291
+ let _authErrorSubscription = null;
292
+ let _currentAppState = 'active'; // Default to active, will be updated on init
293
+ let _userIdentity = null;
294
+
295
+ // Scroll throttling - reduce native bridge calls from 60fps to at most 10/sec
296
+ let _lastScrollTime = 0;
297
+ let _lastScrollOffset = 0;
298
+ const SCROLL_THROTTLE_MS = 100;
299
+
300
+ // Helper to save/load user identity
301
+ // NOW HANDLED NATIVELY - No-op on JS side to avoid unnecessary bridge calls
302
+ async function persistUserIdentity(_identity) {
303
+ // Native module handles persistence automatically in setUserIdentity
304
+ }
305
+ async function loadPersistedUserIdentity() {
306
+ try {
307
+ const nativeModule = getRejourneyNative();
308
+ if (!nativeModule) return null;
309
+
310
+ // NATIVE STORAGE: Read directly from SharedPreferences/NSUserDefaults
311
+ return await nativeModule.getUserIdentity();
312
+ } catch {
313
+ return null;
314
+ }
315
+ }
316
+ let _storedConfig = null;
317
+
318
+ // Remote config from backend - controls sample rate and enable/disable
319
+
320
+ // Result type for fetchRemoteConfig - distinguishes network errors from access denial
321
+
322
+ // Abort recording (fail-closed)
323
+
324
+ let _remoteConfig = null;
325
+ let _sessionSampledOut = false; // True = telemetry only, no replay video
326
+
327
+ /**
328
+ * Fetch project configuration from backend
329
+ * This determines sample rate, enabled state, and other server-side settings
330
+ */
331
+ async function fetchRemoteConfig(apiUrl, publicKey) {
332
+ try {
333
+ const RN = getReactNative();
334
+ const platform = RN?.Platform?.OS || 'unknown';
335
+
336
+ // Read actual bundleId/packageName from native module instead of hardcoding
337
+ let bundleId;
338
+ let packageName;
339
+ try {
340
+ const nativeModule = getRejourneyNative();
341
+ if (nativeModule) {
342
+ const deviceInfo = await nativeModule.getDeviceInfo();
343
+ if (platform === 'ios' && deviceInfo?.bundleId && deviceInfo.bundleId !== 'unknown') {
344
+ bundleId = deviceInfo.bundleId;
345
+ } else if (platform === 'android' && deviceInfo?.bundleId && deviceInfo.bundleId !== 'unknown') {
346
+ packageName = deviceInfo.bundleId; // Android returns packageName as bundleId
347
+ }
348
+ }
349
+ } catch {
350
+ // If we can't get device info, skip bundle validation headers
351
+ getLogger().debug('Could not read bundleId from native module');
352
+ }
353
+ const headers = {
354
+ 'x-public-key': publicKey,
355
+ 'x-platform': platform
356
+ };
357
+ if (bundleId) headers['x-bundle-id'] = bundleId;
358
+ if (packageName) headers['x-package-name'] = packageName;
359
+ const response = await fetch(`${apiUrl}/api/sdk/config`, {
360
+ method: 'GET',
361
+ headers
362
+ });
363
+ if (!response.ok) {
364
+ // 401/403/404 = access denied (invalid key, project disabled, deleted, etc) - STOP recording
365
+ // Other errors (500, etc) = server issue - treat as network error, proceed with defaults
366
+ if (response.status === 401 || response.status === 403 || response.status === 404) {
367
+ getLogger().warn(`Access denied (${response.status}) - recording disabled`);
368
+ return {
369
+ status: 'access_denied',
370
+ httpStatus: response.status
371
+ };
372
+ }
373
+ getLogger().warn(`Config fetch failed: ${response.status}`);
374
+ return {
375
+ status: 'network_error'
376
+ };
377
+ }
378
+ const config = await response.json();
379
+ getLogger().debug('Remote config:', JSON.stringify(config));
380
+ return {
381
+ status: 'success',
382
+ config: config
383
+ };
384
+ } catch (error) {
385
+ // Network timeout, no connectivity, etc - proceed with defaults
386
+ getLogger().warn('Failed to fetch remote config:', error);
387
+ return {
388
+ status: 'network_error'
389
+ };
390
+ }
391
+ }
392
+
393
+ /**
394
+ * Determine if this session should be sampled (recorded)
395
+ * Returns true if recording should proceed, false if sampled out
396
+ */
397
+ function shouldRecordSession(sampleRate) {
398
+ // sampleRate is 0-100 (percentage)
399
+ if (sampleRate >= 100) return true;
400
+ if (sampleRate <= 0) return false;
401
+ const randomValue = Math.random() * 100;
402
+ return randomValue < sampleRate;
403
+ }
404
+
405
+ // Lazy-loaded native module reference
406
+ // We don't access TurboModuleRegistry at module load time to avoid
407
+ // "PlatformConstants could not be found" errors on RN 0.81+
408
+ let _rejourneyNative = undefined;
409
+ let _nativeModuleLogged = false;
410
+ let _runtimeReady = false;
411
+
412
+ /**
413
+ * Check if the React Native runtime is ready for native module access.
414
+ * This prevents crashes on RN 0.81+ where accessing modules too early fails.
415
+ */
416
+ function isRuntimeReady() {
417
+ if (_runtimeReady) return true;
418
+ try {
419
+ const RN = require('react-native');
420
+ if (RN.NativeModules) {
421
+ _runtimeReady = true;
422
+ return true;
423
+ }
424
+ } catch {
425
+ // Runtime not ready yet
426
+ }
427
+ return false;
428
+ }
429
+
430
+ /**
431
+ * Get the native Rejourney module lazily.
432
+ *
433
+ * This function defers access to TurboModuleRegistry/NativeModules until
434
+ * the first time it's actually needed. This is critical for React Native 0.81+
435
+ * where accessing TurboModuleRegistry at module load time can fail because
436
+ * PlatformConstants and other core modules aren't yet initialized.
437
+ *
438
+ * The function caches the result after the first call.
439
+ */
440
+ function getRejourneyNative() {
441
+ // Return cached result if already resolved
442
+ if (_rejourneyNative !== undefined) {
443
+ return _rejourneyNative;
444
+ }
445
+
446
+ // Check if runtime is ready before attempting to access native modules
447
+ if (!isRuntimeReady()) {
448
+ getLogger().debug('Rejourney: Runtime not ready, deferring native module access');
449
+ return null;
450
+ }
451
+ try {
452
+ const RN = require('react-native');
453
+ const {
454
+ NativeModules,
455
+ TurboModuleRegistry
456
+ } = RN;
457
+
458
+ // Track how the module was loaded
459
+ let loadedVia = 'none';
460
+ let nativeModule = null;
461
+
462
+ // Try TurboModuleRegistry first (New Architecture)
463
+ if (TurboModuleRegistry && typeof TurboModuleRegistry.get === 'function') {
464
+ try {
465
+ nativeModule = TurboModuleRegistry.get('Rejourney');
466
+ if (nativeModule) {
467
+ loadedVia = 'TurboModules';
468
+ }
469
+ } catch (turboError) {
470
+ // TurboModuleRegistry.get failed, will try NativeModules
471
+ getLogger().debug('TurboModuleRegistry.get failed:', turboError);
472
+ }
473
+ }
474
+
475
+ // Fall back to NativeModules (Old Architecture / Interop Layer)
476
+ if (!nativeModule && NativeModules) {
477
+ nativeModule = NativeModules.Rejourney ?? null;
478
+ if (nativeModule) {
479
+ loadedVia = 'NativeModules';
480
+ }
481
+ }
482
+ _rejourneyNative = nativeModule;
483
+
484
+ // Log which method was used to load the module
485
+ if (_rejourneyNative && !_nativeModuleLogged) {
486
+ _nativeModuleLogged = true;
487
+
488
+ // More accurate detection based on actual load method
489
+ if (loadedVia === 'TurboModules') {
490
+ getLogger().debug('Using New Architecture (TurboModules/JSI)');
491
+ } else if (loadedVia === 'NativeModules') {
492
+ // Check if we're in interop mode (New Arch with bridge fallback)
493
+ const hasTurboProxy = !!global.__turboModuleProxy;
494
+ if (hasTurboProxy) {
495
+ getLogger().debug('Using New Architecture (Interop Layer)');
496
+ } else {
497
+ getLogger().debug('Using Old Architecture (Bridge)');
498
+ }
499
+ }
500
+ }
501
+ } catch (error) {
502
+ getLogger().warn('Rejourney: Failed to access native modules:', error);
503
+ _rejourneyNative = null;
504
+ }
505
+ if (_rejourneyNative === undefined) {
506
+ _rejourneyNative = null;
507
+ }
508
+ return _rejourneyNative;
509
+ }
510
+
511
+ /**
512
+ * Safely call a native method with error handling
513
+ * Never throws - logs errors and returns gracefully
514
+ */
515
+ async function safeNativeCall(methodName, fn, defaultValue) {
516
+ const nativeModule = getRejourneyNative();
517
+ if (!nativeModule || _initializationFailed) {
518
+ return defaultValue;
519
+ }
520
+ try {
521
+ return await fn();
522
+ } catch (error) {
523
+ getLogger().error(`Rejourney.${methodName} failed:`, error);
524
+ return defaultValue;
525
+ }
526
+ }
527
+
528
+ /**
529
+ * Safely call a synchronous native method with error handling
530
+ * Never throws - logs errors and returns gracefully
531
+ */
532
+ function safeNativeCallSync(methodName, fn, defaultValue) {
533
+ const nativeModule = getRejourneyNative();
534
+ if (!nativeModule || _initializationFailed) {
535
+ return defaultValue;
536
+ }
537
+ try {
538
+ return fn();
539
+ } catch (error) {
540
+ getLogger().error(`Rejourney.${methodName} failed:`, error);
541
+ return defaultValue;
542
+ }
543
+ }
544
+
545
+ /**
546
+ * Main Rejourney API (Internal)
547
+ */
548
+ const Rejourney = {
549
+ /**
550
+ * SDK Version
551
+ */
552
+ version: _constants.SDK_VERSION,
553
+ /**
554
+ * Internal method to start recording session
555
+ * Called by startRejourney() after user consent
556
+ */
557
+ async _startSession() {
558
+ getLogger().debug('_startSession() entered');
559
+ if (!_storedConfig) {
560
+ throw new Error('SDK not initialized. Call initRejourney() first.');
561
+ }
562
+ const nativeModule = getRejourneyNative();
563
+ if (!nativeModule) {
564
+ // Common causes:
565
+ // - startRejourney() called too early (RN runtime not ready yet)
566
+ // - native module not linked (pods/gradle/autolinking issue)
567
+ getLogger().warn('Native module not available - cannot start recording');
568
+ return false;
569
+ }
570
+ getLogger().debug('Native module found, checking if already recording...');
571
+ if (_isRecording) {
572
+ getLogger().warn('Recording already started');
573
+ return false;
574
+ }
575
+ try {
576
+ const apiUrl = _storedConfig.apiUrl || 'https://api.rejourney.co';
577
+ const publicKey = _storedConfig.publicRouteKey || '';
578
+
579
+ // =========================================================
580
+ // STEP 1: Fetch remote config from backend
581
+ // This determines if recording is enabled and at what rate
582
+ // =========================================================
583
+ const configResult = await fetchRemoteConfig(apiUrl, publicKey);
584
+
585
+ // =========================================================
586
+ // CASE 0: Access denied (401/403) - abort immediately
587
+ // This means project disabled, invalid key, etc - HARD STOP
588
+ // =========================================================
589
+ if (configResult.status === 'access_denied') {
590
+ getLogger().info(`Recording disabled - access denied (${configResult.httpStatus})`);
591
+ return false;
592
+ }
593
+
594
+ // For success, extract the config; for network_error, proceed with null
595
+ _remoteConfig = configResult.status === 'success' ? configResult.config : null;
596
+ if (_remoteConfig) {
597
+ // =========================================================
598
+ // CASE 1: Rejourney completely disabled - abort early, nothing captured
599
+ // This is the most performant case - no native calls made
600
+ // =========================================================
601
+ if (!_remoteConfig.rejourneyEnabled) {
602
+ getLogger().logRecordingRemoteDisabled();
603
+ getLogger().info('Rejourney disabled by project settings - no data captured');
604
+ return false;
605
+ }
606
+
607
+ // =========================================================
608
+ // CASE 2: Billing blocked - abort early, nothing captured
609
+ // =========================================================
610
+ if (_remoteConfig.billingBlocked) {
611
+ getLogger().warn(`Recording blocked: ${_remoteConfig.billingReason || 'billing issue'}`);
612
+ return false;
613
+ }
614
+
615
+ // =========================================================
616
+ // CASE 3: Session sampled out - CONTINUE but disable REPLAY only
617
+ // Telemetry, events, and crash tracking still work
618
+ // =========================================================
619
+ _sessionSampledOut = !shouldRecordSession(_remoteConfig.sampleRate ?? 100);
620
+ if (_sessionSampledOut) {
621
+ getLogger().info(`Session sampled out (rate: ${_remoteConfig.sampleRate}%) - telemetry only, no replay video`);
622
+ }
623
+
624
+ // =========================================================
625
+ // CASE 4: recordingEnabled=false in dashboard - telemetry only
626
+ // Effective recording = dashboard setting AND not sampled out
627
+ // =========================================================
628
+ const effectiveRecordingEnabled = _remoteConfig.recordingEnabled && !_sessionSampledOut;
629
+
630
+ // Pass config to native - this controls visual capture on/off
631
+ await nativeModule.setRemoteConfig(_remoteConfig.rejourneyEnabled, effectiveRecordingEnabled, _remoteConfig.sampleRate, _remoteConfig.maxRecordingMinutes);
632
+ } else {
633
+ // Network error (not access denied) - proceed with defaults
634
+ // This is "fail-open" behavior for temporary network issues
635
+ getLogger().debug('Remote config unavailable (network issue), proceeding with defaults');
636
+ }
637
+ const deviceId = await getAutoTracking().ensurePersistentAnonymousId();
638
+ if (!_userIdentity) {
639
+ _userIdentity = await loadPersistedUserIdentity();
640
+ }
641
+ const userId = _userIdentity || deviceId;
642
+ getLogger().debug(`userId=${userId.substring(0, 8)}...`);
643
+ const result = await nativeModule.startSession(userId, apiUrl, publicKey);
644
+ getLogger().debug('Native startSession returned:', JSON.stringify(result));
645
+ if (!result?.success) {
646
+ const reason = result?.error || 'Native startSession returned success=false';
647
+ if (/disabled|blocked|not enabled/i.test(reason)) {
648
+ getLogger().logRecordingRemoteDisabled();
649
+ }
650
+ getLogger().error('Native startSession failed:', reason);
651
+ return false;
652
+ }
653
+ _isRecording = true;
654
+ getLogger().debug(`✅ Session started: ${result.sessionId}`);
655
+ getLogger().logSessionStart(result.sessionId);
656
+ // Start polling for upload stats in dev mode
657
+ if (__DEV__) {
658
+ _metricsInterval = setInterval(async () => {
659
+ if (!_isRecording) {
660
+ if (_metricsInterval) clearInterval(_metricsInterval);
661
+ return;
662
+ }
663
+ try {
664
+ const native = getRejourneyNative();
665
+ if (native) {
666
+ const metrics = await native.getSDKMetrics();
667
+ if (metrics) {
668
+ getLogger().logUploadStats(metrics);
669
+ }
670
+ }
671
+ } catch (e) {
672
+ getLogger().debug('Failed to fetch metrics:', e);
673
+ }
674
+ }, 10000); // Poll more frequently in dev (10s) for better feedback
675
+ }
676
+ getAutoTracking().initAutoTracking({
677
+ rageTapThreshold: _storedConfig?.rageTapThreshold ?? 3,
678
+ rageTapTimeWindow: _storedConfig?.rageTapTimeWindow ?? 500,
679
+ rageTapRadius: 50,
680
+ trackJSErrors: true,
681
+ trackPromiseRejections: true,
682
+ trackReactNativeErrors: true,
683
+ collectDeviceInfo: _storedConfig?.collectDeviceInfo !== false
684
+ }, {
685
+ // Rage tap callback - log as frustration event
686
+ onRageTap: (count, x, y) => {
687
+ this.logEvent('frustration', {
688
+ frustrationKind: 'rage_tap',
689
+ tapCount: count,
690
+ x,
691
+ y
692
+ });
693
+ getLogger().logFrustration(`Rage tap (${count} taps)`);
694
+ },
695
+ // Error callback - log as error event
696
+ onError: error => {
697
+ this.logEvent('error', {
698
+ message: error.message,
699
+ stack: error.stack,
700
+ name: error.name
701
+ });
702
+ getLogger().logError(error.message);
703
+ },
704
+ onScreen: (_screenName, _previousScreen) => {}
705
+ });
706
+ if (_storedConfig?.collectDeviceInfo !== false) {
707
+ try {
708
+ const deviceInfo = await getAutoTracking().collectDeviceInfo();
709
+ this.logEvent('device_info', deviceInfo);
710
+ } catch (deviceError) {
711
+ getLogger().warn('Failed to collect device info:', deviceError);
712
+ }
713
+ }
714
+ if (_storedConfig?.autoTrackNetwork !== false) {
715
+ try {
716
+ const ignoreUrls = [apiUrl, '/api/sdk/config', '/api/ingest/presign', '/api/ingest/batch/complete', '/api/ingest/session/end', ...(_storedConfig?.networkIgnoreUrls || [])];
717
+ getNetworkInterceptor().initNetworkInterceptor(request => {
718
+ getAutoTracking().trackAPIRequest(request.success || false, request.statusCode, request.duration || 0, request.responseBodySize || 0);
719
+ Rejourney.logNetworkRequest(request);
720
+ }, {
721
+ ignoreUrls,
722
+ captureSizes: _storedConfig?.networkCaptureSizes !== false
723
+ });
724
+ } catch (networkError) {
725
+ getLogger().warn('Failed to setup network interception:', networkError);
726
+ }
727
+ }
728
+ return true;
729
+ } catch (error) {
730
+ getLogger().error('Failed to start recording:', error);
731
+ _isRecording = false;
732
+ return false;
733
+ }
734
+ },
735
+ /**
736
+ * Stop the current recording session
737
+ */
738
+ async _stopSession() {
739
+ if (!_isRecording) {
740
+ getLogger().warn('No active recording to stop');
741
+ return;
742
+ }
743
+ try {
744
+ const metrics = getAutoTracking().getSessionMetrics();
745
+ this.logEvent('session_metrics', metrics);
746
+ getNetworkInterceptor().disableNetworkInterceptor();
747
+ getAutoTracking().cleanupAutoTracking();
748
+ getAutoTracking().resetMetrics();
749
+ await safeNativeCall('stopSession', () => getRejourneyNative().stopSession(), undefined);
750
+ if (_metricsInterval) {
751
+ clearInterval(_metricsInterval);
752
+ _metricsInterval = null;
753
+ }
754
+ _isRecording = false;
755
+ getLogger().logSessionEnd('current');
756
+ } catch (error) {
757
+ getLogger().error('Failed to stop recording:', error);
758
+ }
759
+ },
760
+ /**
761
+ * Log a custom event
762
+ *
763
+ * @param name - Event name
764
+ * @param properties - Optional event properties
765
+ * @example
766
+ * Rejourney.logEvent('button_click', { buttonId: 'submit' });
767
+ */
768
+ logEvent(name, properties) {
769
+ safeNativeCallSync('logEvent', () => {
770
+ getRejourneyNative().logEvent(name, properties || {}).catch(() => {});
771
+ }, undefined);
772
+ },
773
+ /**
774
+ * Set user identity for session correlation
775
+ * Associates current and future sessions with a user ID
776
+ *
777
+ * @param userId - User identifier (e.g., email, username, or internal ID)
778
+ * @example
779
+ * Rejourney.setUserIdentity('user_12345');
780
+ * Rejourney.setUserIdentity('john@example.com');
781
+ */
782
+ setUserIdentity(userId) {
783
+ _userIdentity = userId;
784
+ persistUserIdentity(userId).catch(() => {});
785
+ if (_isRecording && getRejourneyNative()) {
786
+ safeNativeCallSync('setUserIdentity', () => {
787
+ getRejourneyNative().setUserIdentity(userId).catch(() => {});
788
+ }, undefined);
789
+ }
790
+ },
791
+ /**
792
+ * Clear user identity
793
+ * Removes user association from future sessions
794
+ */
795
+ clearUserIdentity() {
796
+ _userIdentity = null;
797
+ persistUserIdentity(null).catch(() => {});
798
+ if (_isRecording && getRejourneyNative()) {
799
+ safeNativeCallSync('setUserIdentity', () => {
800
+ getRejourneyNative().setUserIdentity('anonymous').catch(() => {});
801
+ }, undefined);
802
+ }
803
+ },
804
+ /**
805
+ * Tag the current screen
806
+ *
807
+ * @param screenName - Screen name
808
+ * @param params - Optional screen parameters
809
+ */
810
+ tagScreen(screenName, _params) {
811
+ getAutoTracking().trackScreen(screenName);
812
+ getAutoTracking().notifyStateChange();
813
+ safeNativeCallSync('tagScreen', () => {
814
+ getRejourneyNative().screenChanged(screenName).catch(() => {});
815
+ }, undefined);
816
+ },
817
+ /**
818
+ * Mark a view as sensitive (will be occluded in recordings)
819
+ *
820
+ * @param viewRef - React ref to the view
821
+ * @param occluded - Whether to occlude (default: true)
822
+ */
823
+ setOccluded(_viewRef, _occluded = true) {
824
+ // No-op - occlusion handled automatically by native module
825
+ },
826
+ /**
827
+ * Add a tag to the current session
828
+ *
829
+ * @param tag - Tag string
830
+ */
831
+ addSessionTag(tag) {
832
+ this.logEvent('session_tag', {
833
+ tag
834
+ });
835
+ },
836
+ /**
837
+ * Get all recorded sessions
838
+ *
839
+ * @returns Array of session summaries (always empty - sessions on dashboard server)
840
+ */
841
+ async getSessions() {
842
+ return [];
843
+ },
844
+ /**
845
+ * Get session data for replay
846
+ *
847
+ * @param sessionId - Session ID
848
+ * @returns Session data (not implemented - use dashboard server)
849
+ */
850
+ async getSessionData(_sessionId) {
851
+ // Return empty session data - actual data should be fetched from dashboard server
852
+ getLogger().warn('getSessionData not implemented - fetch from dashboard server');
853
+ return {
854
+ metadata: {
855
+ sessionId: _sessionId,
856
+ startTime: 0,
857
+ endTime: 0,
858
+ duration: 0,
859
+ deviceInfo: {
860
+ model: '',
861
+ os: 'ios',
862
+ osVersion: '',
863
+ screenWidth: 0,
864
+ screenHeight: 0,
865
+ pixelRatio: 1
866
+ },
867
+ eventCount: 0,
868
+ videoSegmentCount: 0,
869
+ storageSize: 0,
870
+ sdkVersion: _constants.SDK_VERSION,
871
+ isComplete: false
872
+ },
873
+ events: []
874
+ };
875
+ },
876
+ /**
877
+ * Delete a session
878
+ *
879
+ * @param sessionId - Session ID
880
+ */
881
+ async deleteSession(_sessionId) {
882
+ // No-op - session deletion handled by dashboard server
883
+ },
884
+ /**
885
+ * Delete all sessions
886
+ */
887
+ async deleteAllSessions() {
888
+ // No-op - session deletion handled by dashboard server
889
+ },
890
+ /**
891
+ * Export session for sharing
892
+ *
893
+ * @param sessionId - Session ID
894
+ * @returns Path to export file (not implemented)
895
+ */
896
+ async exportSession(_sessionId) {
897
+ getLogger().warn('exportSession not implemented - export from dashboard server');
898
+ return '';
899
+ },
900
+ /**
901
+ * Check if currently recording
902
+ *
903
+ * @returns Whether recording is active
904
+ */
905
+ async isRecording() {
906
+ return _isRecording;
907
+ },
908
+ /**
909
+ * Get storage usage
910
+ *
911
+ * @returns Storage usage info (always 0 - storage on dashboard server)
912
+ */
913
+ async getStorageUsage() {
914
+ return {
915
+ used: 0,
916
+ max: 0
917
+ };
918
+ },
919
+ /**
920
+ * Mark a visual change that should be captured
921
+ *
922
+ * Use this when your app changes in a visually significant way that should be captured,
923
+ * like showing a success message, updating a cart badge, or displaying an error.
924
+ *
925
+ * @param reason - Description of what changed (e.g., 'cart_updated', 'error_shown')
926
+ * @param importance - How important is this change? 'low', 'medium', 'high', or 'critical'
927
+ *
928
+ * @example
929
+ * ```typescript
930
+ * // Mark that an error was shown (high importance)
931
+ * await Rejourney.markVisualChange('checkout_error', 'high');
932
+ *
933
+ * // Mark that a cart badge updated (medium importance)
934
+ * await Rejourney.markVisualChange('cart_badge_update', 'medium');
935
+ * ```
936
+ */
937
+ async markVisualChange(reason, importance = 'medium') {
938
+ return safeNativeCall('markVisualChange', async () => {
939
+ await getRejourneyNative().markVisualChange(reason, importance);
940
+ return true;
941
+ }, false);
942
+ },
943
+ /**
944
+ * Report a scroll event for video capture timing
945
+ *
946
+ * Call this from your ScrollView's onScroll handler to improve scroll capture.
947
+ * The SDK captures video at 2 FPS continuously, but this helps log scroll events
948
+ * for timeline correlation during replay.
949
+ *
950
+ * @param scrollOffset - Current scroll offset (vertical or horizontal)
951
+ *
952
+ * @example
953
+ * ```typescript
954
+ * <ScrollView
955
+ * onScroll={(e) => {
956
+ * Rejourney.onScroll(e.nativeEvent.contentOffset.y);
957
+ * }}
958
+ * scrollEventThrottle={16}
959
+ * >
960
+ * {content}
961
+ * </ScrollView>
962
+ * ```
963
+ */
964
+ async onScroll(scrollOffset) {
965
+ // Throttle scroll events to reduce native bridge traffic
966
+ // Scroll events can fire at 60fps, but we only need ~10/sec for smooth replay
967
+ const now = Date.now();
968
+ const offsetDelta = Math.abs(scrollOffset - _lastScrollOffset);
969
+
970
+ // Only forward to native if enough time passed OR significant scroll distance
971
+ if (now - _lastScrollTime < SCROLL_THROTTLE_MS && offsetDelta < 50) {
972
+ return;
973
+ }
974
+ _lastScrollTime = now;
975
+ _lastScrollOffset = scrollOffset;
976
+
977
+ // Track scroll for metrics
978
+ getAutoTracking().trackScroll();
979
+ await safeNativeCall('onScroll', () => getRejourneyNative().onScroll(scrollOffset), undefined);
980
+ },
981
+ /**
982
+ * Notify the SDK that an OAuth flow is starting
983
+ *
984
+ * Call this before opening an OAuth URL (e.g., before opening Safari for Google/Apple sign-in).
985
+ * This captures the current screen and marks the session as entering an OAuth flow.
986
+ *
987
+ * @param provider - The OAuth provider name (e.g., 'google', 'apple', 'facebook')
988
+ *
989
+ * @example
990
+ * ```typescript
991
+ * // Before opening OAuth URL
992
+ * await Rejourney.onOAuthStarted('google');
993
+ * await WebBrowser.openAuthSessionAsync(authUrl);
994
+ * ```
995
+ */
996
+ async onOAuthStarted(provider) {
997
+ return safeNativeCall('onOAuthStarted', async () => {
998
+ await getRejourneyNative().onOAuthStarted(provider);
999
+ return true;
1000
+ }, false);
1001
+ },
1002
+ /**
1003
+ * Notify the SDK that an OAuth flow has completed
1004
+ *
1005
+ * Call this after the user returns from an OAuth flow (successful or not).
1006
+ * This captures the result screen and logs the OAuth outcome.
1007
+ *
1008
+ * @param provider - The OAuth provider name (e.g., 'google', 'apple', 'facebook')
1009
+ * @param success - Whether the OAuth flow was successful
1010
+ *
1011
+ * @example
1012
+ * ```typescript
1013
+ * // After OAuth returns
1014
+ * const result = await WebBrowser.openAuthSessionAsync(authUrl);
1015
+ * await Rejourney.onOAuthCompleted('google', result.type === 'success');
1016
+ * ```
1017
+ */
1018
+ async onOAuthCompleted(provider, success) {
1019
+ return safeNativeCall('onOAuthCompleted', async () => {
1020
+ await getRejourneyNative().onOAuthCompleted(provider, success);
1021
+ return true;
1022
+ }, false);
1023
+ },
1024
+ /**
1025
+ * Notify the SDK that an external URL is being opened
1026
+ *
1027
+ * Call this when your app opens an external URL (browser, maps, phone, etc.).
1028
+ * This is automatically detected for app lifecycle events, but you can use this
1029
+ * for more granular tracking.
1030
+ *
1031
+ * @param urlScheme - The URL scheme being opened (e.g., 'https', 'tel', 'maps')
1032
+ *
1033
+ * @example
1034
+ * ```typescript
1035
+ * // Before opening external URL
1036
+ * await Rejourney.onExternalURLOpened('https');
1037
+ * Linking.openURL('https://example.com');
1038
+ * ```
1039
+ */
1040
+ async onExternalURLOpened(urlScheme) {
1041
+ return safeNativeCall('onExternalURLOpened', async () => {
1042
+ await getRejourneyNative().onExternalURLOpened(urlScheme);
1043
+ return true;
1044
+ }, false);
1045
+ },
1046
+ /**
1047
+ * Log a network request for API call timeline tracking
1048
+ *
1049
+ * This is a low-priority, efficient way to track API calls during session replay.
1050
+ * Network requests are stored separately and displayed in a collapsible timeline
1051
+ * in the dashboard for easy correlation with user actions.
1052
+ *
1053
+ * @param request - Network request parameters
1054
+ *
1055
+ * @example
1056
+ * ```typescript
1057
+ * // After a fetch completes
1058
+ * const startTime = Date.now();
1059
+ * const response = await fetch('https://api.example.com/users', {
1060
+ * method: 'POST',
1061
+ * body: JSON.stringify(userData),
1062
+ * });
1063
+ *
1064
+ * Rejourney.logNetworkRequest({
1065
+ * method: 'POST',
1066
+ * url: 'https://api.example.com/users',
1067
+ * statusCode: response.status,
1068
+ * duration: Date.now() - startTime,
1069
+ * requestBodySize: JSON.stringify(userData).length,
1070
+ * responseBodySize: (await response.text()).length,
1071
+ * });
1072
+ * ```
1073
+ */
1074
+ logNetworkRequest(request) {
1075
+ safeNativeCallSync('logNetworkRequest', () => {
1076
+ // Parse URL for efficient storage and grouping
1077
+ let urlPath = request.url;
1078
+ let urlHost = '';
1079
+ try {
1080
+ const parsedUrl = new URL(request.url);
1081
+ urlHost = parsedUrl.host;
1082
+ urlPath = parsedUrl.pathname + parsedUrl.search;
1083
+ } catch {
1084
+ // If URL parsing fails, use the full URL as path
1085
+ }
1086
+ const endTimestamp = request.endTimestamp || Date.now();
1087
+ const startTimestamp = request.startTimestamp || endTimestamp - request.duration;
1088
+ const success = request.statusCode >= 200 && request.statusCode < 400;
1089
+
1090
+ // Create the network request event
1091
+ const networkEvent = {
1092
+ type: 'network_request',
1093
+ requestId: request.requestId || `req_${startTimestamp}_${Math.random().toString(36).substr(2, 9)}`,
1094
+ timestamp: startTimestamp,
1095
+ method: request.method,
1096
+ url: request.url.length > 500 ? request.url.substring(0, 500) : request.url,
1097
+ // Truncate long URLs
1098
+ urlPath,
1099
+ urlHost,
1100
+ statusCode: request.statusCode,
1101
+ duration: request.duration,
1102
+ endTimestamp,
1103
+ success,
1104
+ requestBodySize: request.requestBodySize,
1105
+ responseBodySize: request.responseBodySize,
1106
+ requestContentType: request.requestContentType,
1107
+ responseContentType: request.responseContentType,
1108
+ errorMessage: request.errorMessage,
1109
+ cached: request.cached
1110
+ };
1111
+ getRejourneyNative().logEvent('network_request', networkEvent).catch(() => {});
1112
+ }, undefined);
1113
+ },
1114
+ /**
1115
+ * Get SDK telemetry metrics for observability
1116
+ *
1117
+ * Returns metrics about SDK health including upload success rates,
1118
+ * retry attempts, circuit breaker events, and memory pressure.
1119
+ *
1120
+ * @returns SDK telemetry metrics
1121
+ *
1122
+ * @example
1123
+ * ```typescript
1124
+ * const metrics = await Rejourney.getSDKMetrics();
1125
+ * console.log(`Upload success rate: ${(metrics.uploadSuccessRate * 100).toFixed(1)}%`);
1126
+ * console.log(`Circuit breaker opens: ${metrics.circuitBreakerOpenCount}`);
1127
+ * ```
1128
+ */
1129
+ async getSDKMetrics() {
1130
+ return safeNativeCall('getSDKMetrics', () => getRejourneyNative().getSDKMetrics(), {
1131
+ uploadSuccessCount: 0,
1132
+ uploadFailureCount: 0,
1133
+ retryAttemptCount: 0,
1134
+ circuitBreakerOpenCount: 0,
1135
+ memoryEvictionCount: 0,
1136
+ offlinePersistCount: 0,
1137
+ sessionStartCount: 0,
1138
+ crashCount: 0,
1139
+ uploadSuccessRate: 1.0,
1140
+ avgUploadDurationMs: 0,
1141
+ currentQueueDepth: 0,
1142
+ lastUploadTime: null,
1143
+ lastRetryTime: null,
1144
+ totalBytesUploaded: 0,
1145
+ totalBytesEvicted: 0
1146
+ });
1147
+ },
1148
+ /**
1149
+ * Trigger a debug ANR (Dev only)
1150
+ * Blocks the main thread for the specified duration
1151
+ */
1152
+ debugTriggerANR(durationMs) {
1153
+ if (__DEV__) {
1154
+ safeNativeCallSync('debugTriggerANR', () => {
1155
+ getRejourneyNative().debugTriggerANR(durationMs);
1156
+ }, undefined);
1157
+ } else {
1158
+ getLogger().warn('debugTriggerANR is only available in development mode');
1159
+ }
1160
+ },
1161
+ /**
1162
+ * Mask a view by its nativeID prop (will be occluded in recordings)
1163
+ *
1164
+ * Use this to mask any sensitive content that isn't a text input.
1165
+ * The view must have a `nativeID` prop set.
1166
+ *
1167
+ * @param nativeID - The nativeID prop of the view to mask
1168
+ * @example
1169
+ * ```tsx
1170
+ * // In your component
1171
+ * <View nativeID="sensitiveCard">...</View>
1172
+ *
1173
+ * // To mask it
1174
+ * Rejourney.maskView('sensitiveCard');
1175
+ * ```
1176
+ */
1177
+ maskView(nativeID) {
1178
+ safeNativeCallSync('maskView', () => {
1179
+ getRejourneyNative().maskViewByNativeID(nativeID).catch(() => {});
1180
+ }, undefined);
1181
+ },
1182
+ /**
1183
+ * Unmask a view by its nativeID prop
1184
+ *
1185
+ * Removes the mask from a view that was previously masked with maskView().
1186
+ *
1187
+ * @param nativeID - The nativeID prop of the view to unmask
1188
+ */
1189
+ unmaskView(nativeID) {
1190
+ safeNativeCallSync('unmaskView', () => {
1191
+ getRejourneyNative().unmaskViewByNativeID(nativeID).catch(() => {});
1192
+ }, undefined);
1193
+ }
1194
+ };
1195
+
1196
+ /**
1197
+ * Handle app state changes for automatic session management
1198
+ * - Pauses recording when app goes to background
1199
+ * - Resumes recording when app comes back to foreground
1200
+ * - Cleans up properly when app is terminated
1201
+ */
1202
+ function handleAppStateChange(nextAppState) {
1203
+ if (!_isInitialized || _initializationFailed) return;
1204
+ try {
1205
+ if (_currentAppState.match(/active/) && nextAppState === 'background') {
1206
+ // App going to background - native module handles this automatically
1207
+ getLogger().logLifecycleEvent('App moving to background');
1208
+ } else if (_currentAppState.match(/inactive|background/) && nextAppState === 'active') {
1209
+ // App coming back to foreground
1210
+ getLogger().logLifecycleEvent('App returning to foreground');
1211
+ }
1212
+ _currentAppState = nextAppState;
1213
+ } catch (error) {
1214
+ getLogger().warn('Error handling app state change:', error);
1215
+ }
1216
+ }
1217
+
1218
+ /**
1219
+ * Setup automatic lifecycle management
1220
+ * Handles cleanup when the app unmounts or goes to background
1221
+ */
1222
+ function setupLifecycleManagement() {
1223
+ if (_sdkDisabled) return;
1224
+ const RN = getReactNative();
1225
+ if (!RN) return;
1226
+ if (_appStateSubscription) {
1227
+ _appStateSubscription.remove();
1228
+ _appStateSubscription = null;
1229
+ }
1230
+ try {
1231
+ _currentAppState = RN.AppState.currentState || 'active';
1232
+ _appStateSubscription = RN.AppState.addEventListener('change', handleAppStateChange);
1233
+ setupAuthErrorListener();
1234
+ getLogger().debug('Lifecycle management enabled');
1235
+ } catch (error) {
1236
+ getLogger().warn('Failed to setup lifecycle management:', error);
1237
+ }
1238
+ }
1239
+
1240
+ /**
1241
+ * Setup listener for authentication errors from native module
1242
+ * This handles security errors like bundle ID mismatch
1243
+ */
1244
+ function setupAuthErrorListener() {
1245
+ if (_sdkDisabled) return;
1246
+ const RN = getReactNative();
1247
+ if (!RN) return;
1248
+ if (_authErrorSubscription) {
1249
+ _authErrorSubscription.remove();
1250
+ _authErrorSubscription = null;
1251
+ }
1252
+ try {
1253
+ const nativeModule = getRejourneyNative();
1254
+ if (nativeModule) {
1255
+ const maybeAny = nativeModule;
1256
+ const hasEventEmitterHooks = typeof maybeAny?.addListener === 'function' && typeof maybeAny?.removeListeners === 'function';
1257
+ const eventEmitter = hasEventEmitterHooks ? new RN.NativeEventEmitter(maybeAny) : new RN.NativeEventEmitter();
1258
+ _authErrorSubscription = eventEmitter.addListener('rejourneyAuthError', error => {
1259
+ getLogger().error('Authentication error from native:', error);
1260
+ if (error?.code === 403) {
1261
+ getLogger().logPackageMismatch();
1262
+ } else if (error?.code === 404) {
1263
+ getLogger().logInvalidProjectKey();
1264
+ }
1265
+ _isRecording = false;
1266
+ if (_storedConfig?.onAuthError) {
1267
+ try {
1268
+ _storedConfig.onAuthError(error);
1269
+ } catch (callbackError) {
1270
+ getLogger().warn('Error in onAuthError callback:', callbackError);
1271
+ }
1272
+ }
1273
+ });
1274
+ }
1275
+ } catch (error) {
1276
+ getLogger().debug('Auth error listener not available:', error);
1277
+ }
1278
+ }
1279
+
1280
+ /**
1281
+ * Cleanup lifecycle management
1282
+ */
1283
+ function cleanupLifecycleManagement() {
1284
+ if (_appStateSubscription) {
1285
+ _appStateSubscription.remove();
1286
+ _appStateSubscription = null;
1287
+ }
1288
+ if (_authErrorSubscription) {
1289
+ _authErrorSubscription.remove();
1290
+ _authErrorSubscription = null;
1291
+ }
1292
+ }
1293
+
1294
+ /**
1295
+ * Initialize Rejourney SDK - STEP 1 of 3
1296
+ *
1297
+ * This sets up the SDK, handles attestation, and prepares for recording,
1298
+ * but does NOT start recording automatically. Call startRejourney() after
1299
+ * obtaining user consent to begin recording.
1300
+ *
1301
+ * @param publicRouteKey - Your public route key from the Rejourney dashboard
1302
+ * @param options - Optional configuration options
1303
+ *
1304
+ * @example
1305
+ * ```typescript
1306
+ * import { initRejourney, startRejourney } from 'rejourney';
1307
+ *
1308
+ * // Step 1: Initialize SDK (safe to call on app start)
1309
+ * initRejourney('pk_live_xxxxxxxxxxxx');
1310
+ *
1311
+ * // Step 2: After obtaining user consent
1312
+ * startRejourney();
1313
+ *
1314
+ * // With options
1315
+ * initRejourney('pk_live_xxxxxxxxxxxx', {
1316
+ * debug: true,
1317
+ * apiUrl: 'https://api.yourdomain.com',
1318
+ * projectId: 'your-project-id',
1319
+ * });
1320
+ * ```
1321
+ */
1322
+ function initRejourney(publicRouteKey, options) {
1323
+ if (!publicRouteKey || typeof publicRouteKey !== 'string') {
1324
+ getLogger().warn('Rejourney: Invalid public route key provided. SDK will be disabled.');
1325
+ _initializationFailed = true;
1326
+ return;
1327
+ }
1328
+ _storedConfig = {
1329
+ ...options,
1330
+ publicRouteKey
1331
+ };
1332
+ if (options?.debug) {
1333
+ getLogger().setDebugMode(true);
1334
+ const nativeModule = getRejourneyNative();
1335
+ if (nativeModule) {
1336
+ nativeModule.setDebugMode(true).catch(() => {});
1337
+ }
1338
+ }
1339
+ _isInitialized = true;
1340
+ (async () => {
1341
+ try {
1342
+ setupLifecycleManagement();
1343
+ getLogger().logObservabilityStart();
1344
+ getLogger().logInitSuccess(_constants.SDK_VERSION);
1345
+ } catch (error) {
1346
+ const reason = error instanceof Error ? error.message : String(error);
1347
+ getLogger().logInitFailure(reason);
1348
+ _initializationFailed = true;
1349
+ _isInitialized = false;
1350
+ }
1351
+ })();
1352
+ }
1353
+
1354
+ /**
1355
+ * Start recording - STEP 2 of 3 (call after user consent)
1356
+ *
1357
+ * Begins session recording. Call this after obtaining user consent for recording.
1358
+ *
1359
+ * @example
1360
+ * ```typescript
1361
+ * import { initRejourney, startRejourney } from 'rejourney';
1362
+ *
1363
+ * initRejourney('pk_live_xxxxxxxxxxxx');
1364
+ *
1365
+ * // After user accepts consent dialog
1366
+ * startRejourney();
1367
+ * ```
1368
+ */
1369
+ function startRejourney() {
1370
+ getLogger().debug('startRejourney() called');
1371
+ if (!_isInitialized) {
1372
+ getLogger().warn('Not initialized - call initRejourney() first');
1373
+ return;
1374
+ }
1375
+ if (_initializationFailed) {
1376
+ getLogger().warn('Initialization failed - cannot start recording');
1377
+ return;
1378
+ }
1379
+ getLogger().logRecordingStart();
1380
+ getLogger().debug('Starting session...');
1381
+ (async () => {
1382
+ try {
1383
+ const started = await Rejourney._startSession();
1384
+ if (started) {
1385
+ getLogger().debug('✅ Recording started successfully');
1386
+ } else {
1387
+ getLogger().warn('Recording not started');
1388
+ }
1389
+ } catch (error) {
1390
+ getLogger().error('Failed to start recording:', error);
1391
+ }
1392
+ })();
1393
+ }
1394
+
1395
+ /**
1396
+ * Stop recording and cleanup all resources.
1397
+ *
1398
+ * Note: This is usually not needed as the SDK handles cleanup automatically.
1399
+ * Only call this if you want to explicitly stop recording.
1400
+ */
1401
+ function stopRejourney() {
1402
+ try {
1403
+ cleanupLifecycleManagement();
1404
+ Rejourney._stopSession();
1405
+ _isRecording = false;
1406
+ getLogger().debug('Rejourney stopped');
1407
+ } catch (error) {
1408
+ getLogger().warn('Error stopping Rejourney:', error);
1409
+ }
1410
+ }
1411
+ var _default = exports.default = Rejourney;
1412
+ /**
1413
+ * Configure SDK log verbosity.
1414
+ *
1415
+ * By default, the SDK logs minimally to avoid polluting your app's console:
1416
+ * - Production/Release: SILENT (no logs at all)
1417
+ * - Development/Debug: Only critical errors shown
1418
+ *
1419
+ * Essential lifecycle events (init success, session start/end) are automatically
1420
+ * logged in debug builds only - you don't need to configure anything.
1421
+ *
1422
+ * Use this function only if you need to troubleshoot SDK behavior.
1423
+ *
1424
+ * @param level - Minimum log level to display
1425
+ *
1426
+ * @example
1427
+ * ```typescript
1428
+ * import { setLogLevel, LogLevel } from 'rejourney';
1429
+ *
1430
+ * // Enable verbose logging for SDK debugging (not recommended for regular use)
1431
+ * setLogLevel(LogLevel.DEBUG);
1432
+ *
1433
+ * // Show warnings and errors (for troubleshooting)
1434
+ * setLogLevel(LogLevel.WARNING);
1435
+ *
1436
+ * // Silence all logs (default behavior in production)
1437
+ * setLogLevel(LogLevel.SILENT);
1438
+ * ```
1439
+ */
1440
+ function setLogLevel(level) {
1441
+ getLogger().setLogLevel(level);
1442
+ }
1443
+ //# sourceMappingURL=index.js.map