@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,155 @@
1
+ /**
2
+ * Copyright 2026 Rejourney
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ /**
18
+ * Rejourney SDK Constants
19
+ */
20
+
21
+ // Import version from auto-generated file (generated from package.json by scripts/generate-version.js)
22
+ import { SDK_VERSION } from './version';
23
+
24
+ export { SDK_VERSION };
25
+
26
+ /** Default configuration values */
27
+ export const DEFAULT_CONFIG = {
28
+ enabled: true,
29
+ captureFPS: 0.5,
30
+ captureOnEvents: true,
31
+ maxSessionDuration: 10 * 60 * 1000,
32
+ maxStorageSize: 50 * 1024 * 1024,
33
+ autoScreenTracking: true,
34
+ autoGestureTracking: true,
35
+ privacyOcclusion: true,
36
+ enableCompression: true,
37
+ inactivityThreshold: 5000,
38
+ disableInDev: false,
39
+ detectRageTaps: true,
40
+ detectDeadTaps: true,
41
+ rageTapThreshold: 3,
42
+ rageTapTimeWindow: 1000,
43
+ debug: false,
44
+ autoStartRecording: true,
45
+ collectDeviceInfo: true,
46
+ collectGeoLocation: true,
47
+ postNavigationDelay: 300,
48
+ postGestureDelay: 200,
49
+ postModalDelay: 400,
50
+ } as const;
51
+
52
+ /** Event type constants */
53
+ export const EVENT_TYPES = {
54
+ GESTURE: 'gesture',
55
+ SCREEN_CHANGE: 'screen_change',
56
+ CUSTOM: 'custom',
57
+ APP_STATE: 'app_state',
58
+ FRUSTRATION: 'frustration',
59
+ ERROR: 'error',
60
+ } as const;
61
+
62
+ /** Gesture type constants */
63
+ export const GESTURE_TYPES = {
64
+ TAP: 'tap',
65
+ DOUBLE_TAP: 'double_tap',
66
+ LONG_PRESS: 'long_press',
67
+ SWIPE_LEFT: 'swipe_left',
68
+ SWIPE_RIGHT: 'swipe_right',
69
+ SWIPE_UP: 'swipe_up',
70
+ SWIPE_DOWN: 'swipe_down',
71
+ PINCH: 'pinch',
72
+ SCROLL: 'scroll',
73
+ RAGE_TAP: 'rage_tap',
74
+ DEAD_TAP: 'dead_tap',
75
+ } as const;
76
+
77
+ /** Playback speeds */
78
+ export const PLAYBACK_SPEEDS = [0.5, 1, 2, 4] as const;
79
+
80
+ /** Capture settings */
81
+ export const CAPTURE_SETTINGS = {
82
+ DEFAULT_FPS: 0.5,
83
+ MIN_FPS: 0.1,
84
+ MAX_FPS: 2,
85
+ CAPTURE_SCALE: 0.25,
86
+ MIN_CAPTURE_DELTA_TIME: 0.5,
87
+ } as const;
88
+
89
+ /** Memory management settings */
90
+ export const MEMORY_SETTINGS = {
91
+ /** Maximum events to keep in memory before flushing */
92
+ MAX_EVENTS_IN_MEMORY: 100,
93
+ /** Memory warning threshold in MB (flush when exceeded) */
94
+ MEMORY_WARNING_THRESHOLD_MB: 100,
95
+ /** Enable aggressive memory cleanup during low memory */
96
+ AGGRESSIVE_CLEANUP_ENABLED: true,
97
+ /** Bitmap pool size for reusing bitmaps (Android) */
98
+ BITMAP_POOL_SIZE: 3,
99
+ } as const;
100
+
101
+ /** CPU throttling settings */
102
+ export const CPU_SETTINGS = {
103
+ /** Throttle captures when CPU usage exceeds this percentage */
104
+ CPU_THROTTLE_THRESHOLD: 80,
105
+ /** Minimum interval between captures when throttled (seconds) */
106
+ THROTTLED_MIN_INTERVAL: 2.0,
107
+ /** Skip captures when battery is below this level (0-100) */
108
+ LOW_BATTERY_THRESHOLD: 15,
109
+ /** Skip captures when device is thermally throttled */
110
+ THERMAL_THROTTLE_ENABLED: true,
111
+ /** Maximum consecutive captures before forced cooldown */
112
+ MAX_CONSECUTIVE_CAPTURES: 10,
113
+ /** Cooldown period after max consecutive captures (ms) */
114
+ CAPTURE_COOLDOWN_MS: 1000,
115
+ } as const;
116
+
117
+ /** Storage management settings */
118
+ export const STORAGE_SETTINGS = {
119
+ /** Maximum total storage for session data (bytes) */
120
+ MAX_STORAGE_SIZE: 50 * 1024 * 1024, // 50MB
121
+ /** Storage warning threshold - start cleanup at this level */
122
+ STORAGE_WARNING_THRESHOLD: 0.8, // 80% of max
123
+ /** Number of old sessions to keep */
124
+ MAX_SESSIONS_TO_KEEP: 5,
125
+ /** Auto-delete sessions older than this (hours) */
126
+ SESSION_EXPIRY_HOURS: 24,
127
+ /** Use efficient binary storage format */
128
+ USE_BINARY_FORMAT: true,
129
+ } as const;
130
+
131
+ /** Network/Upload settings */
132
+ export const UPLOAD_SETTINGS = {
133
+ /** Batch upload interval (ms) */
134
+ BATCH_INTERVAL_MS: 30000, // 30 seconds
135
+ /** Max retry attempts for failed uploads */
136
+ MAX_RETRY_ATTEMPTS: 3,
137
+ /** Retry delay multiplier (exponential backoff) */
138
+ RETRY_DELAY_MULTIPLIER: 2,
139
+ /** Initial retry delay (ms) */
140
+ INITIAL_RETRY_DELAY_MS: 1000,
141
+ /** Max events per upload batch */
142
+ MAX_EVENTS_PER_BATCH: 50,
143
+ /** Skip uploads when on cellular and battery is low */
144
+ CELLULAR_BATTERY_AWARE: true,
145
+ } as const;
146
+
147
+ /** Privacy constants */
148
+ export const PRIVACY = {
149
+ OCCLUSION_COLOR: '#808080',
150
+ SENSITIVE_COMPONENT_TYPES: [
151
+ 'TextInput',
152
+ 'SecureTextEntry',
153
+ 'PasswordField',
154
+ ],
155
+ } as const;
@@ -0,0 +1,231 @@
1
+ /**
2
+ * Copyright 2026 Rejourney
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ /**
18
+ * Error Tracking Module for Rejourney SDK
19
+ *
20
+ * Handles JS error capture, React Native ErrorUtils, and unhandled promise rejections.
21
+ * Split from autoTracking.ts for better code organization.
22
+ */
23
+
24
+ import type { ErrorEvent } from '../types';
25
+
26
+ type OnErrorEventHandler = ((
27
+ event: Event | string,
28
+ source?: string,
29
+ lineno?: number,
30
+ colno?: number,
31
+ error?: Error
32
+ ) => boolean | void) | null;
33
+
34
+ interface PromiseRejectionEvent {
35
+ reason?: any;
36
+ promise?: Promise<any>;
37
+ }
38
+
39
+ const _globalThis = globalThis as typeof globalThis & {
40
+ onerror?: OnErrorEventHandler;
41
+ addEventListener?: (type: string, handler: (event: any) => void) => void;
42
+ removeEventListener?: (type: string, handler: (event: any) => void) => void;
43
+ ErrorUtils?: {
44
+ getGlobalHandler: () => ((error: Error, isFatal: boolean) => void) | undefined;
45
+ setGlobalHandler: (handler: (error: Error, isFatal: boolean) => void) => void;
46
+ };
47
+ };
48
+
49
+ let originalErrorHandler: ((error: Error, isFatal: boolean) => void) | undefined;
50
+ let originalOnError: OnErrorEventHandler | null = null;
51
+ let originalOnUnhandledRejection: ((event: PromiseRejectionEvent) => void) | null = null;
52
+ let onErrorCallback: ((error: ErrorEvent) => void) | null = null;
53
+
54
+ let errorCount = 0;
55
+
56
+ /**
57
+ * Setup error tracking with the given callback
58
+ */
59
+ export function setupErrorTracking(
60
+ config: {
61
+ trackJSErrors?: boolean;
62
+ trackPromiseRejections?: boolean;
63
+ trackReactNativeErrors?: boolean;
64
+ },
65
+ onError: (error: ErrorEvent) => void
66
+ ): void {
67
+ onErrorCallback = onError;
68
+ errorCount = 0;
69
+
70
+ if (config.trackReactNativeErrors !== false) {
71
+ setupReactNativeErrorHandler();
72
+ }
73
+
74
+ if (config.trackJSErrors !== false && typeof _globalThis !== 'undefined') {
75
+ setupJSErrorHandler();
76
+ }
77
+
78
+ if (config.trackPromiseRejections !== false && typeof _globalThis !== 'undefined') {
79
+ setupPromiseRejectionHandler();
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Cleanup error tracking and restore original handlers
85
+ */
86
+ export function cleanupErrorTracking(): void {
87
+ if (originalErrorHandler) {
88
+ try {
89
+ const ErrorUtils = _globalThis.ErrorUtils;
90
+ if (ErrorUtils) {
91
+ ErrorUtils.setGlobalHandler(originalErrorHandler);
92
+ }
93
+ } catch {
94
+ // Ignore
95
+ }
96
+ originalErrorHandler = undefined;
97
+ }
98
+
99
+ if (originalOnError !== null) {
100
+ _globalThis.onerror = originalOnError;
101
+ originalOnError = null;
102
+ }
103
+
104
+ if (originalOnUnhandledRejection && typeof _globalThis.removeEventListener !== 'undefined') {
105
+ _globalThis.removeEventListener!('unhandledrejection', originalOnUnhandledRejection);
106
+ originalOnUnhandledRejection = null;
107
+ }
108
+
109
+ onErrorCallback = null;
110
+ }
111
+
112
+ /**
113
+ * Get current error count
114
+ */
115
+ export function getErrorCount(): number {
116
+ return errorCount;
117
+ }
118
+
119
+ /**
120
+ * Reset error count
121
+ */
122
+ export function resetErrorCount(): void {
123
+ errorCount = 0;
124
+ }
125
+
126
+ /**
127
+ * Manually capture an error
128
+ */
129
+ export function captureError(
130
+ message: string,
131
+ stack?: string,
132
+ name?: string
133
+ ): void {
134
+ trackError({
135
+ type: 'error',
136
+ timestamp: Date.now(),
137
+ message,
138
+ stack,
139
+ name: name || 'Error',
140
+ });
141
+ }
142
+
143
+ /**
144
+ * Track an error internally
145
+ */
146
+ function trackError(error: ErrorEvent): void {
147
+ errorCount++;
148
+
149
+ if (onErrorCallback) {
150
+ onErrorCallback(error);
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Setup React Native ErrorUtils handler
156
+ */
157
+ function setupReactNativeErrorHandler(): void {
158
+ try {
159
+ const ErrorUtils = _globalThis.ErrorUtils;
160
+ if (!ErrorUtils) return;
161
+
162
+ originalErrorHandler = ErrorUtils.getGlobalHandler();
163
+
164
+ ErrorUtils.setGlobalHandler((error: Error, isFatal: boolean) => {
165
+ trackError({
166
+ type: 'error',
167
+ timestamp: Date.now(),
168
+ message: error.message || String(error),
169
+ stack: error.stack,
170
+ name: error.name || 'Error',
171
+ });
172
+
173
+ if (originalErrorHandler) {
174
+ originalErrorHandler(error, isFatal);
175
+ }
176
+ });
177
+ } catch {
178
+ // Ignore
179
+ }
180
+ }
181
+
182
+ /**
183
+ * Setup global JS error handler
184
+ */
185
+ function setupJSErrorHandler(): void {
186
+ if (typeof _globalThis.onerror !== 'undefined') {
187
+ originalOnError = _globalThis.onerror;
188
+
189
+ _globalThis.onerror = (
190
+ message: string | Event,
191
+ source?: string,
192
+ lineno?: number,
193
+ colno?: number,
194
+ error?: Error
195
+ ) => {
196
+ trackError({
197
+ type: 'error',
198
+ timestamp: Date.now(),
199
+ message: typeof message === 'string' ? message : 'Unknown error',
200
+ stack: error?.stack || `${source}:${lineno}:${colno}`,
201
+ name: error?.name || 'Error',
202
+ });
203
+
204
+ if (originalOnError) {
205
+ return originalOnError(message, source, lineno, colno, error);
206
+ }
207
+ return false;
208
+ };
209
+ }
210
+ }
211
+
212
+ /**
213
+ * Setup unhandled promise rejection handler
214
+ */
215
+ function setupPromiseRejectionHandler(): void {
216
+ if (typeof _globalThis.addEventListener !== 'undefined') {
217
+ const handler = (event: PromiseRejectionEvent) => {
218
+ const reason = event.reason;
219
+ trackError({
220
+ type: 'error',
221
+ timestamp: Date.now(),
222
+ message: reason?.message || String(reason) || 'Unhandled Promise Rejection',
223
+ stack: reason?.stack,
224
+ name: reason?.name || 'UnhandledRejection',
225
+ });
226
+ };
227
+
228
+ originalOnUnhandledRejection = handler;
229
+ _globalThis.addEventListener!('unhandledrejection', handler);
230
+ }
231
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Copyright 2026 Rejourney
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ /**
18
+ * Rejourney SDK
19
+ * Session recording and replay for React Native
20
+ */
21
+
22
+ export * from './constants';
23
+ export * from './utils';
24
+ export * from './autoTracking';
25
+ export * from './networkInterceptor';
@@ -0,0 +1,227 @@
1
+ /**
2
+ * Copyright 2026 Rejourney
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ /**
18
+ * Session Metrics Module for Rejourney SDK
19
+ *
20
+ * Tracks and calculates session metrics including interaction scores,
21
+ * API performance, and user engagement metrics.
22
+ * Split from autoTracking.ts for better code organization.
23
+ */
24
+
25
+ /**
26
+ * Session metrics structure
27
+ */
28
+ export interface SessionMetrics {
29
+ totalEvents: number;
30
+ touchCount: number;
31
+ scrollCount: number;
32
+ gestureCount: number;
33
+ inputCount: number;
34
+ navigationCount: number;
35
+ errorCount: number;
36
+ rageTapCount: number;
37
+ deadTapCount: number;
38
+ apiSuccessCount: number;
39
+ apiErrorCount: number;
40
+ apiTotalCount: number;
41
+ netTotalDurationMs: number;
42
+ netTotalBytes: number;
43
+ screensVisited: string[];
44
+ uniqueScreensCount: number;
45
+ interactionScore: number;
46
+ explorationScore: number;
47
+ uxScore: number;
48
+ }
49
+
50
+ let metrics: SessionMetrics = createEmptyMetrics();
51
+ let sessionStartTime = 0;
52
+ let maxSessionDurationMs = 10 * 60 * 1000;
53
+
54
+ /**
55
+ * Create empty metrics object
56
+ */
57
+ export function createEmptyMetrics(): SessionMetrics {
58
+ return {
59
+ totalEvents: 0,
60
+ touchCount: 0,
61
+ scrollCount: 0,
62
+ gestureCount: 0,
63
+ inputCount: 0,
64
+ navigationCount: 0,
65
+ errorCount: 0,
66
+ rageTapCount: 0,
67
+ deadTapCount: 0,
68
+ apiSuccessCount: 0,
69
+ apiErrorCount: 0,
70
+ apiTotalCount: 0,
71
+ netTotalDurationMs: 0,
72
+ netTotalBytes: 0,
73
+ screensVisited: [],
74
+ uniqueScreensCount: 0,
75
+ interactionScore: 100,
76
+ explorationScore: 100,
77
+ uxScore: 100,
78
+ };
79
+ }
80
+
81
+ /**
82
+ * Reset all metrics
83
+ */
84
+ export function resetMetrics(): void {
85
+ metrics = createEmptyMetrics();
86
+ sessionStartTime = 0;
87
+ }
88
+
89
+ /**
90
+ * Initialize metrics for new session
91
+ */
92
+ export function initMetrics(): void {
93
+ metrics = createEmptyMetrics();
94
+ sessionStartTime = Date.now();
95
+ }
96
+
97
+ /**
98
+ * Get current session metrics with calculated scores
99
+ */
100
+ export function getSessionMetrics(): SessionMetrics {
101
+ const rawDuration = Date.now() - sessionStartTime;
102
+ const durationMs = Math.min(rawDuration, maxSessionDurationMs);
103
+
104
+ const interactionScore = calculateInteractionScore(durationMs);
105
+ const explorationScore = calculateExplorationScore();
106
+ const uxScore = calculateUXScore();
107
+
108
+ return {
109
+ ...metrics,
110
+ interactionScore,
111
+ explorationScore,
112
+ uxScore,
113
+ };
114
+ }
115
+
116
+ /**
117
+ * Set max session duration (in minutes)
118
+ */
119
+ export function setMaxSessionDurationMinutes(minutes?: number): void {
120
+ if (minutes !== undefined && minutes > 0) {
121
+ // Clamp to 1-10 minutes
122
+ const clampedMinutes = Math.max(1, Math.min(10, minutes));
123
+ maxSessionDurationMs = clampedMinutes * 60 * 1000;
124
+ }
125
+ }
126
+
127
+ export function incrementTouchCount(): void {
128
+ metrics.touchCount++;
129
+ metrics.totalEvents++;
130
+ }
131
+
132
+ export function incrementScrollCount(): void {
133
+ metrics.scrollCount++;
134
+ metrics.totalEvents++;
135
+ }
136
+
137
+ export function incrementNavigationCount(): void {
138
+ metrics.navigationCount++;
139
+ metrics.totalEvents++;
140
+ }
141
+
142
+ export function incrementRageTapCount(): void {
143
+ metrics.rageTapCount++;
144
+ }
145
+
146
+ export function incrementDeadTapCount(): void {
147
+ metrics.deadTapCount++;
148
+ }
149
+
150
+ export function incrementErrorCount(): void {
151
+ metrics.errorCount++;
152
+ metrics.totalEvents++;
153
+ }
154
+
155
+ export function addScreenVisited(screenName: string): void {
156
+ metrics.screensVisited.push(screenName);
157
+ metrics.uniqueScreensCount = new Set(metrics.screensVisited).size;
158
+ }
159
+
160
+ export function trackAPIMetrics(
161
+ success: boolean,
162
+ durationMs: number = 0,
163
+ responseBytes: number = 0
164
+ ): void {
165
+ metrics.apiTotalCount++;
166
+
167
+ if (durationMs > 0) {
168
+ metrics.netTotalDurationMs += durationMs;
169
+ }
170
+ if (responseBytes > 0) {
171
+ metrics.netTotalBytes += responseBytes;
172
+ }
173
+
174
+ if (success) {
175
+ metrics.apiSuccessCount++;
176
+ } else {
177
+ metrics.apiErrorCount++;
178
+ metrics.errorCount++;
179
+ }
180
+ }
181
+
182
+ /**
183
+ * Calculate interaction score based on engagement with app
184
+ * Higher = more engaged (more interactions per minute)
185
+ */
186
+ function calculateInteractionScore(durationMs: number): number {
187
+ if (durationMs <= 0) return 100;
188
+
189
+ const durationMinutes = durationMs / 60000;
190
+ const interactionsPerMinute = metrics.touchCount / Math.max(0.5, durationMinutes);
191
+
192
+ if (interactionsPerMinute < 2) return 20;
193
+ if (interactionsPerMinute < 5) return 50;
194
+ if (interactionsPerMinute < 10) return 70;
195
+ if (interactionsPerMinute <= 30) return 100;
196
+ if (interactionsPerMinute <= 60) return 80;
197
+ return 50;
198
+ }
199
+
200
+ /**
201
+ * Calculate exploration score based on screens visited
202
+ * Higher = user explored more of the app
203
+ */
204
+ function calculateExplorationScore(): number {
205
+ const uniqueScreens = metrics.uniqueScreensCount;
206
+
207
+ if (uniqueScreens >= 10) return 100;
208
+ if (uniqueScreens >= 7) return 90;
209
+ if (uniqueScreens >= 5) return 80;
210
+ if (uniqueScreens >= 3) return 60;
211
+ if (uniqueScreens >= 2) return 40;
212
+ return 20;
213
+ }
214
+
215
+ /**
216
+ * Calculate UX score based on errors and frustration
217
+ * Higher = better experience (fewer issues)
218
+ */
219
+ function calculateUXScore(): number {
220
+ let score = 100;
221
+
222
+ score -= metrics.errorCount * 10;
223
+ score -= metrics.rageTapCount * 20;
224
+ score -= metrics.deadTapCount * 10;
225
+ score -= metrics.apiErrorCount * 5;
226
+ return Math.max(0, Math.min(100, score));
227
+ }