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