@rejourneyco/react-native 1.0.0

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