@rejourneyco/react-native 1.0.7

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