@temps-sdk/react-analytics 0.0.1-beta.3 → 0.0.1-beta.31
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.
- package/dist/EngagementTracker.d.ts +55 -0
- package/dist/EngagementTracker.d.ts.map +1 -0
- package/dist/EngagementTracker.js +223 -0
- package/dist/Provider.d.ts +1 -1
- package/dist/Provider.d.ts.map +1 -1
- package/dist/Provider.js +73 -8
- package/dist/SessionRecorder.d.ts +43 -0
- package/dist/SessionRecorder.d.ts.map +1 -0
- package/dist/SessionRecorder.js +452 -0
- package/dist/constants.d.ts +2 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/constants.js +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -0
- package/dist/types.d.ts +58 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/useEngagementTracking.d.ts +34 -0
- package/dist/useEngagementTracking.d.ts.map +1 -0
- package/dist/useEngagementTracking.js +65 -0
- package/dist/usePageLeave.d.ts +13 -0
- package/dist/usePageLeave.d.ts.map +1 -0
- package/dist/usePageLeave.js +66 -0
- package/dist/useSessionRecording.d.ts +23 -0
- package/dist/useSessionRecording.d.ts.map +1 -0
- package/dist/useSessionRecording.js +99 -0
- package/dist/useSpeedAnalytics.d.ts +8 -0
- package/dist/useSpeedAnalytics.d.ts.map +1 -0
- package/dist/useSpeedAnalytics.js +79 -0
- package/dist/utils.d.ts +2 -1
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +35 -1
- package/package.json +19 -6
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useEffect, useRef, useCallback, useState } from "react";
|
|
3
|
+
import { record } from "rrweb";
|
|
4
|
+
import { pack } from "@rrweb/packer";
|
|
5
|
+
import { sendAnalytics, sendAnalyticsReliable, getRequestId } from "./utils";
|
|
6
|
+
export const SESSION_RECORDER_ENDPOINT = "session-replay";
|
|
7
|
+
function generateSessionId() {
|
|
8
|
+
if (typeof crypto !== "undefined" && crypto.randomUUID) {
|
|
9
|
+
return crypto.randomUUID();
|
|
10
|
+
}
|
|
11
|
+
return `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
12
|
+
}
|
|
13
|
+
function generateVisitorId() {
|
|
14
|
+
// Try to get a persistent visitor ID from localStorage
|
|
15
|
+
if (typeof localStorage !== "undefined") {
|
|
16
|
+
let visitorId = localStorage.getItem("temps_visitor_id");
|
|
17
|
+
if (!visitorId) {
|
|
18
|
+
visitorId = `visitor_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
19
|
+
localStorage.setItem("temps_visitor_id", visitorId);
|
|
20
|
+
}
|
|
21
|
+
return visitorId;
|
|
22
|
+
}
|
|
23
|
+
return `visitor_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
24
|
+
}
|
|
25
|
+
function getSessionMetadata(domain) {
|
|
26
|
+
if (typeof window === "undefined")
|
|
27
|
+
return {};
|
|
28
|
+
const screen = window.screen || {};
|
|
29
|
+
const navigator = window.navigator || {};
|
|
30
|
+
return {
|
|
31
|
+
visitorId: generateVisitorId(),
|
|
32
|
+
userAgent: navigator.userAgent,
|
|
33
|
+
language: navigator.language,
|
|
34
|
+
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
35
|
+
screenWidth: screen.width,
|
|
36
|
+
screenHeight: screen.height,
|
|
37
|
+
colorDepth: screen.colorDepth || 24,
|
|
38
|
+
viewportWidth: window.innerWidth,
|
|
39
|
+
viewportHeight: window.innerHeight,
|
|
40
|
+
url: window.location.href,
|
|
41
|
+
timestamp: new Date().toISOString(),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
export function SessionRecorder({ basePath, // Required, no default
|
|
45
|
+
domain, enabled = false, excludedPaths = [], sessionSampleRate = 1.0, maskAllInputs = true, maskTextSelector = "[data-mask]", blockClass = "rr-block", ignoreClass = "rr-ignore", maskTextClass = "rr-mask", ignoreSelector = "[data-ignore]", blockSelector = "[data-private]", recordCanvas = false, collectFonts = false, slimDOMOptions = {
|
|
46
|
+
script: false,
|
|
47
|
+
comment: false,
|
|
48
|
+
headFavicon: false,
|
|
49
|
+
headWhitespace: false,
|
|
50
|
+
headMetaSocial: false,
|
|
51
|
+
headMetaRobots: false,
|
|
52
|
+
headMetaHttpEquiv: false,
|
|
53
|
+
headMetaVerification: false,
|
|
54
|
+
headMetaDescKeywords: false
|
|
55
|
+
}, batchSize = 200, flushInterval = 30000, sampling = {}, }) {
|
|
56
|
+
const stopFnRef = useRef(null);
|
|
57
|
+
const eventsRef = useRef([]);
|
|
58
|
+
const sessionIdRef = useRef("");
|
|
59
|
+
const sessionInitializedRef = useRef(false);
|
|
60
|
+
const flushTimeoutRef = useRef(null);
|
|
61
|
+
const initRetryCountRef = useRef(0);
|
|
62
|
+
const initFailedRef = useRef(false); // Track if init has permanently failed
|
|
63
|
+
const maxInitRetries = 3;
|
|
64
|
+
const [isInitializing, setIsInitializing] = useState(false);
|
|
65
|
+
// Deep merge sampling defaults with proper handling of mouseInteraction
|
|
66
|
+
const defaultSampling = {
|
|
67
|
+
scroll: 150,
|
|
68
|
+
media: 800,
|
|
69
|
+
mouseInteraction: true,
|
|
70
|
+
mousemove: true,
|
|
71
|
+
input: "last",
|
|
72
|
+
};
|
|
73
|
+
// Merge sampling configs, handling mouseInteraction specially
|
|
74
|
+
const samplingConfig = {
|
|
75
|
+
...defaultSampling,
|
|
76
|
+
...sampling,
|
|
77
|
+
};
|
|
78
|
+
const shouldRecord = useCallback(() => {
|
|
79
|
+
if (!enabled)
|
|
80
|
+
return false;
|
|
81
|
+
if (typeof window === "undefined")
|
|
82
|
+
return false;
|
|
83
|
+
// Check if current path should be excluded
|
|
84
|
+
const currentPath = window.location.pathname;
|
|
85
|
+
const isExcluded = excludedPaths.some(path => {
|
|
86
|
+
// Support wildcards in path patterns
|
|
87
|
+
const regex = new RegExp(`^${path.replace(/\*/g, '.*')}$`);
|
|
88
|
+
return regex.test(currentPath);
|
|
89
|
+
});
|
|
90
|
+
if (isExcluded)
|
|
91
|
+
return false;
|
|
92
|
+
// Apply sampling rate
|
|
93
|
+
if (sessionSampleRate < 1.0) {
|
|
94
|
+
const random = Math.random();
|
|
95
|
+
if (random > sessionSampleRate)
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
return true;
|
|
99
|
+
}, [enabled, excludedPaths, sessionSampleRate]);
|
|
100
|
+
const initializeSession = useCallback(async () => {
|
|
101
|
+
// If already initialized or currently initializing, return current state
|
|
102
|
+
if (sessionInitializedRef.current || isInitializing)
|
|
103
|
+
return sessionInitializedRef.current;
|
|
104
|
+
// If we've permanently failed, don't try again
|
|
105
|
+
if (initFailedRef.current) {
|
|
106
|
+
console.warn("[SessionRecorder] Initialization has permanently failed, not retrying");
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
// Check if we've exceeded retry limit
|
|
110
|
+
if (initRetryCountRef.current >= maxInitRetries) {
|
|
111
|
+
console.error(`[SessionRecorder] Exceeded maximum initialization retries (${maxInitRetries})`);
|
|
112
|
+
initFailedRef.current = true; // Mark as permanently failed
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
setIsInitializing(true);
|
|
116
|
+
initRetryCountRef.current++;
|
|
117
|
+
console.log(`[SessionRecorder] Attempting to initialize session (attempt ${initRetryCountRef.current}/${maxInitRetries})`);
|
|
118
|
+
const sessionId = generateSessionId();
|
|
119
|
+
sessionIdRef.current = sessionId;
|
|
120
|
+
try {
|
|
121
|
+
const metadata = {
|
|
122
|
+
sessionId: sessionId,
|
|
123
|
+
...getSessionMetadata(domain),
|
|
124
|
+
};
|
|
125
|
+
const response = await fetch(`${basePath}/${SESSION_RECORDER_ENDPOINT}/init`, {
|
|
126
|
+
method: "POST",
|
|
127
|
+
headers: {
|
|
128
|
+
"Content-Type": "application/json",
|
|
129
|
+
},
|
|
130
|
+
body: JSON.stringify(metadata),
|
|
131
|
+
});
|
|
132
|
+
if (response.status === 201) {
|
|
133
|
+
sessionInitializedRef.current = true;
|
|
134
|
+
initRetryCountRef.current = 0; // Reset retry count on success
|
|
135
|
+
initFailedRef.current = false; // Reset failed flag on success
|
|
136
|
+
// Store session ID in localStorage for reference
|
|
137
|
+
if (typeof localStorage !== "undefined") {
|
|
138
|
+
localStorage.setItem("currentRecordingSessionId", sessionId);
|
|
139
|
+
}
|
|
140
|
+
console.log("[SessionRecorder] Session initialized successfully:", sessionId);
|
|
141
|
+
return true;
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
console.error(`[SessionRecorder] Failed to initialize session: ${response.status} (attempt ${initRetryCountRef.current}/${maxInitRetries})`);
|
|
145
|
+
sessionIdRef.current = ""; // Clear invalid session ID
|
|
146
|
+
// Mark as permanently failed if we've hit the retry limit
|
|
147
|
+
if (initRetryCountRef.current >= maxInitRetries) {
|
|
148
|
+
initFailedRef.current = true;
|
|
149
|
+
}
|
|
150
|
+
return false;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
console.error(`[SessionRecorder] Failed to initialize session: ${error} (attempt ${initRetryCountRef.current}/${maxInitRetries})`);
|
|
155
|
+
sessionIdRef.current = ""; // Clear invalid session ID
|
|
156
|
+
// Mark as permanently failed if we've hit the retry limit
|
|
157
|
+
if (initRetryCountRef.current >= maxInitRetries) {
|
|
158
|
+
initFailedRef.current = true;
|
|
159
|
+
}
|
|
160
|
+
return false;
|
|
161
|
+
}
|
|
162
|
+
finally {
|
|
163
|
+
setIsInitializing(false);
|
|
164
|
+
}
|
|
165
|
+
}, [basePath, domain, isInitializing]);
|
|
166
|
+
const sendEvents = useCallback(async (isReliable = false) => {
|
|
167
|
+
if (!sessionInitializedRef.current) {
|
|
168
|
+
console.warn("[SessionRecorder] Cannot send events - session not initialized");
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
const events = eventsRef.current;
|
|
172
|
+
if (events.length === 0)
|
|
173
|
+
return;
|
|
174
|
+
const eventsToSend = [...events];
|
|
175
|
+
// Don't clear the array immediately - clear only after successful send
|
|
176
|
+
// eventsRef.current = [];
|
|
177
|
+
try {
|
|
178
|
+
// Pack the events for more efficient transmission
|
|
179
|
+
const packedEvents = pack(eventsToSend);
|
|
180
|
+
// Base64 encode the packed string for safe JSON transmission
|
|
181
|
+
const encodedEvents = btoa(packedEvents);
|
|
182
|
+
const payload = {
|
|
183
|
+
sessionId: sessionIdRef.current,
|
|
184
|
+
events: encodedEvents,
|
|
185
|
+
};
|
|
186
|
+
const url = `${basePath}/${SESSION_RECORDER_ENDPOINT}/events`;
|
|
187
|
+
if (isReliable) {
|
|
188
|
+
// Use sendBeacon for reliable sending on page unload
|
|
189
|
+
if (navigator.sendBeacon) {
|
|
190
|
+
const blob = new Blob([JSON.stringify(payload)], { type: "application/json" });
|
|
191
|
+
const sent = navigator.sendBeacon(url, blob);
|
|
192
|
+
if (!sent) {
|
|
193
|
+
// Fallback to fetch with keepalive
|
|
194
|
+
await fetch(url, {
|
|
195
|
+
method: "POST",
|
|
196
|
+
headers: { "Content-Type": "application/json" },
|
|
197
|
+
body: JSON.stringify(payload),
|
|
198
|
+
keepalive: true,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
// For reliable sends, we don't clear events as they're sent via beacon
|
|
202
|
+
// which doesn't provide response feedback
|
|
203
|
+
eventsRef.current = [];
|
|
204
|
+
}
|
|
205
|
+
else {
|
|
206
|
+
// Fallback to fetch with keepalive
|
|
207
|
+
await fetch(url, {
|
|
208
|
+
method: "POST",
|
|
209
|
+
headers: { "Content-Type": "application/json" },
|
|
210
|
+
body: JSON.stringify(payload),
|
|
211
|
+
keepalive: true,
|
|
212
|
+
});
|
|
213
|
+
// Clear events after successful send
|
|
214
|
+
eventsRef.current = [];
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
else {
|
|
218
|
+
const response = await fetch(url, {
|
|
219
|
+
method: "POST",
|
|
220
|
+
headers: { "Content-Type": "application/json" },
|
|
221
|
+
body: JSON.stringify(payload),
|
|
222
|
+
});
|
|
223
|
+
if (response.status === 404) {
|
|
224
|
+
// Session not found, mark as not initialized but don't auto-reinitialize
|
|
225
|
+
console.error("[SessionRecorder] Session not found on server, stopping recording");
|
|
226
|
+
sessionInitializedRef.current = false;
|
|
227
|
+
sessionIdRef.current = "";
|
|
228
|
+
// Clear the session from localStorage
|
|
229
|
+
if (typeof localStorage !== "undefined") {
|
|
230
|
+
localStorage.removeItem("currentRecordingSessionId");
|
|
231
|
+
}
|
|
232
|
+
// Stop recording to prevent further errors
|
|
233
|
+
if (stopFnRef.current) {
|
|
234
|
+
stopFnRef.current();
|
|
235
|
+
stopFnRef.current = null;
|
|
236
|
+
}
|
|
237
|
+
// Don't restore events - they're lost
|
|
238
|
+
eventsRef.current = [];
|
|
239
|
+
}
|
|
240
|
+
else if (!response.ok) {
|
|
241
|
+
console.error("[SessionRecorder] Failed to send events:", response.status);
|
|
242
|
+
// Don't restore events - keep them for next attempt
|
|
243
|
+
// eventsRef.current.unshift(...eventsToSend);
|
|
244
|
+
}
|
|
245
|
+
else {
|
|
246
|
+
// Clear events after successful send
|
|
247
|
+
eventsRef.current = [];
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
catch (error) {
|
|
252
|
+
console.error("[SessionRecorder] Failed to send session events:", error);
|
|
253
|
+
// Don't restore events - keep them for next attempt
|
|
254
|
+
// eventsRef.current.unshift(...eventsToSend);
|
|
255
|
+
}
|
|
256
|
+
}, [basePath]);
|
|
257
|
+
const scheduleFlush = useCallback(() => {
|
|
258
|
+
if (flushTimeoutRef.current) {
|
|
259
|
+
clearTimeout(flushTimeoutRef.current);
|
|
260
|
+
}
|
|
261
|
+
const flushAndReschedule = () => {
|
|
262
|
+
sendEvents(false);
|
|
263
|
+
// Always schedule the next flush, even if the current send fails
|
|
264
|
+
// This ensures continuous retry attempts
|
|
265
|
+
scheduleNextFlush();
|
|
266
|
+
};
|
|
267
|
+
const scheduleNextFlush = () => {
|
|
268
|
+
if (flushTimeoutRef.current) {
|
|
269
|
+
clearTimeout(flushTimeoutRef.current);
|
|
270
|
+
}
|
|
271
|
+
flushTimeoutRef.current = setTimeout(flushAndReschedule, flushInterval);
|
|
272
|
+
};
|
|
273
|
+
scheduleNextFlush();
|
|
274
|
+
}, [sendEvents, flushInterval]);
|
|
275
|
+
const startRecording = useCallback(async () => {
|
|
276
|
+
if (stopFnRef.current)
|
|
277
|
+
return; // Already recording
|
|
278
|
+
if (!shouldRecord())
|
|
279
|
+
return;
|
|
280
|
+
// If initialization has permanently failed, don't try to start
|
|
281
|
+
if (initFailedRef.current) {
|
|
282
|
+
console.warn("[SessionRecorder] Not starting recording - initialization has permanently failed");
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
// Initialize session first
|
|
286
|
+
const initialized = await initializeSession();
|
|
287
|
+
if (!initialized) {
|
|
288
|
+
console.error("[SessionRecorder] Failed to initialize session, not starting recording");
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
// Don't clear events buffer on restart - preserve any pending events
|
|
292
|
+
if (!eventsRef.current) {
|
|
293
|
+
eventsRef.current = [];
|
|
294
|
+
}
|
|
295
|
+
const stopFn = record({
|
|
296
|
+
emit(event) {
|
|
297
|
+
eventsRef.current.push(event);
|
|
298
|
+
// Send when we have accumulated a full batch
|
|
299
|
+
if (eventsRef.current.length >= batchSize) {
|
|
300
|
+
sendEvents(false);
|
|
301
|
+
// scheduleFlush() is now called automatically after each send
|
|
302
|
+
}
|
|
303
|
+
},
|
|
304
|
+
sampling: samplingConfig,
|
|
305
|
+
blockSelector,
|
|
306
|
+
ignoreSelector,
|
|
307
|
+
recordCanvas,
|
|
308
|
+
collectFonts,
|
|
309
|
+
maskAllInputs,
|
|
310
|
+
maskTextSelector,
|
|
311
|
+
blockClass,
|
|
312
|
+
ignoreClass,
|
|
313
|
+
maskTextClass,
|
|
314
|
+
slimDOMOptions,
|
|
315
|
+
// Add checkoutEveryNms to force periodic full snapshots
|
|
316
|
+
// This helps with route changes by ensuring we get fresh snapshots
|
|
317
|
+
checkoutEveryNms: 60000, // Take a full snapshot every minute
|
|
318
|
+
// Add recordCrossOriginIframes for better iframe support
|
|
319
|
+
recordCrossOriginIframes: false,
|
|
320
|
+
});
|
|
321
|
+
if (stopFn) {
|
|
322
|
+
stopFnRef.current = stopFn;
|
|
323
|
+
}
|
|
324
|
+
// Start the flush interval
|
|
325
|
+
scheduleFlush();
|
|
326
|
+
}, [shouldRecord, initializeSession, sendEvents, scheduleFlush, batchSize, recordCanvas, collectFonts, maskAllInputs, maskTextSelector, blockClass, ignoreClass, maskTextClass, slimDOMOptions, samplingConfig]);
|
|
327
|
+
const stopRecording = useCallback(() => {
|
|
328
|
+
if (stopFnRef.current) {
|
|
329
|
+
stopFnRef.current();
|
|
330
|
+
stopFnRef.current = null;
|
|
331
|
+
// Clear flush timeout
|
|
332
|
+
if (flushTimeoutRef.current) {
|
|
333
|
+
clearTimeout(flushTimeoutRef.current);
|
|
334
|
+
flushTimeoutRef.current = null;
|
|
335
|
+
}
|
|
336
|
+
// Send any remaining events reliably
|
|
337
|
+
sendEvents(true);
|
|
338
|
+
// Clear session state
|
|
339
|
+
sessionInitializedRef.current = false;
|
|
340
|
+
sessionIdRef.current = "";
|
|
341
|
+
// Clear session ID from localStorage
|
|
342
|
+
if (typeof localStorage !== "undefined") {
|
|
343
|
+
localStorage.removeItem("currentRecordingSessionId");
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
// Reset retry counters when explicitly stopping
|
|
347
|
+
initRetryCountRef.current = 0;
|
|
348
|
+
initFailedRef.current = false;
|
|
349
|
+
}, [sendEvents]);
|
|
350
|
+
// Effect to handle recording lifecycle
|
|
351
|
+
useEffect(() => {
|
|
352
|
+
// Early return if we shouldn't record or have permanently failed
|
|
353
|
+
if (!enabled || initFailedRef.current || stopFnRef.current || sessionInitializedRef.current) {
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
// Check if current path should be excluded
|
|
357
|
+
const currentPath = window.location.pathname;
|
|
358
|
+
const isExcluded = excludedPaths.some(path => {
|
|
359
|
+
const regex = new RegExp(`^${path.replace(/\*/g, '.*')}$`);
|
|
360
|
+
return regex.test(currentPath);
|
|
361
|
+
});
|
|
362
|
+
if (isExcluded) {
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
// Apply sampling rate
|
|
366
|
+
if (sessionSampleRate < 1.0) {
|
|
367
|
+
const random = Math.random();
|
|
368
|
+
if (random > sessionSampleRate) {
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
// Now we can start recording
|
|
373
|
+
startRecording();
|
|
374
|
+
// Handle page unload
|
|
375
|
+
const handleUnload = () => {
|
|
376
|
+
if (sessionInitializedRef.current && eventsRef.current.length > 0) {
|
|
377
|
+
sendEvents(true);
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
window.addEventListener("beforeunload", handleUnload);
|
|
381
|
+
window.addEventListener("pagehide", handleUnload);
|
|
382
|
+
return () => {
|
|
383
|
+
window.removeEventListener("beforeunload", handleUnload);
|
|
384
|
+
window.removeEventListener("pagehide", handleUnload);
|
|
385
|
+
};
|
|
386
|
+
// Dependencies that should trigger re-evaluation
|
|
387
|
+
}, [enabled, excludedPaths, sessionSampleRate, startRecording, sendEvents]);
|
|
388
|
+
// Monitor location changes to stop/start recording based on excluded paths
|
|
389
|
+
useEffect(() => {
|
|
390
|
+
const checkPathAndToggleRecording = () => {
|
|
391
|
+
if (!enabled || initFailedRef.current) {
|
|
392
|
+
if (!enabled) {
|
|
393
|
+
stopRecording();
|
|
394
|
+
}
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
const currentPath = window.location.pathname;
|
|
398
|
+
const isExcluded = excludedPaths.some(path => {
|
|
399
|
+
const regex = new RegExp(`^${path.replace(/\*/g, '.*')}$`);
|
|
400
|
+
return regex.test(currentPath);
|
|
401
|
+
});
|
|
402
|
+
// Only stop/start recording if we're actually changing exclusion status
|
|
403
|
+
// This prevents unnecessary restarts during normal navigation
|
|
404
|
+
const isCurrentlyRecording = stopFnRef.current !== null;
|
|
405
|
+
if (isExcluded && isCurrentlyRecording) {
|
|
406
|
+
// Path is excluded and we're recording - stop
|
|
407
|
+
stopRecording();
|
|
408
|
+
}
|
|
409
|
+
else if (!isExcluded && !isCurrentlyRecording && !initFailedRef.current) {
|
|
410
|
+
// Path is not excluded and we're not recording - start
|
|
411
|
+
startRecording();
|
|
412
|
+
}
|
|
413
|
+
// If the path exclusion status hasn't changed, keep recording continuously
|
|
414
|
+
};
|
|
415
|
+
// Listen for route changes
|
|
416
|
+
const originalPushState = window.history.pushState;
|
|
417
|
+
const originalReplaceState = window.history.replaceState;
|
|
418
|
+
window.history.pushState = function (...args) {
|
|
419
|
+
// Flush current events before route change to ensure they're captured
|
|
420
|
+
if (stopFnRef.current && eventsRef.current.length > 0) {
|
|
421
|
+
sendEvents(false);
|
|
422
|
+
}
|
|
423
|
+
originalPushState.apply(window.history, args);
|
|
424
|
+
// Use setTimeout to allow DOM updates to complete before checking
|
|
425
|
+
setTimeout(checkPathAndToggleRecording, 0);
|
|
426
|
+
};
|
|
427
|
+
window.history.replaceState = function (...args) {
|
|
428
|
+
// Flush current events before route change to ensure they're captured
|
|
429
|
+
if (stopFnRef.current && eventsRef.current.length > 0) {
|
|
430
|
+
sendEvents(false);
|
|
431
|
+
}
|
|
432
|
+
originalReplaceState.apply(window.history, args);
|
|
433
|
+
// Use setTimeout to allow DOM updates to complete before checking
|
|
434
|
+
setTimeout(checkPathAndToggleRecording, 0);
|
|
435
|
+
};
|
|
436
|
+
const handlePopState = () => {
|
|
437
|
+
// Flush current events before route change to ensure they're captured
|
|
438
|
+
if (stopFnRef.current && eventsRef.current.length > 0) {
|
|
439
|
+
sendEvents(false);
|
|
440
|
+
}
|
|
441
|
+
// Use setTimeout to allow DOM updates to complete before checking
|
|
442
|
+
setTimeout(checkPathAndToggleRecording, 0);
|
|
443
|
+
};
|
|
444
|
+
window.addEventListener("popstate", handlePopState);
|
|
445
|
+
return () => {
|
|
446
|
+
window.history.pushState = originalPushState;
|
|
447
|
+
window.history.replaceState = originalReplaceState;
|
|
448
|
+
window.removeEventListener("popstate", handlePopState);
|
|
449
|
+
};
|
|
450
|
+
}, [enabled, excludedPaths, startRecording, stopRecording, sendEvents]);
|
|
451
|
+
return null;
|
|
452
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,iBAAiB,gBAAgB,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const DEFAULT_BASE_PATH = "/api/_temps";
|
package/dist/index.d.ts
CHANGED
|
@@ -3,4 +3,10 @@ export * from "./Provider";
|
|
|
3
3
|
export * from "./useAnalytics";
|
|
4
4
|
export * from "./useTrackEvent";
|
|
5
5
|
export * from "./useTrackPageview";
|
|
6
|
+
export * from "./usePageLeave";
|
|
7
|
+
export * from "./useSpeedAnalytics";
|
|
8
|
+
export * from "./useEngagementTracking";
|
|
9
|
+
export { EngagementTracker, type EngagementTrackerOptions, type EngagementData } from "./EngagementTracker";
|
|
10
|
+
export { SessionRecorder, SESSION_RECORDER_ENDPOINT } from "./SessionRecorder";
|
|
11
|
+
export { SessionRecordingProvider, useSessionRecording, useSessionRecordingControl } from "./useSessionRecording";
|
|
6
12
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,cAAc,SAAS,CAAC;AACxB,cAAc,YAAY,CAAC;AAC3B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,cAAc,SAAS,CAAC;AACxB,cAAc,YAAY,CAAC;AAC3B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC;AACnC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,qBAAqB,CAAC;AACpC,cAAc,yBAAyB,CAAC;AACxC,OAAO,EAAE,iBAAiB,EAAE,KAAK,wBAAwB,EAAE,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC5G,OAAO,EAAE,eAAe,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AAC/E,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,0BAA0B,EAC3B,MAAM,uBAAuB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -4,3 +4,9 @@ export * from "./Provider";
|
|
|
4
4
|
export * from "./useAnalytics";
|
|
5
5
|
export * from "./useTrackEvent";
|
|
6
6
|
export * from "./useTrackPageview";
|
|
7
|
+
export * from "./usePageLeave";
|
|
8
|
+
export * from "./useSpeedAnalytics";
|
|
9
|
+
export * from "./useEngagementTracking";
|
|
10
|
+
export { EngagementTracker } from "./EngagementTracker";
|
|
11
|
+
export { SessionRecorder, SESSION_RECORDER_ENDPOINT } from "./SessionRecorder";
|
|
12
|
+
export { SessionRecordingProvider, useSessionRecording, useSessionRecordingControl } from "./useSessionRecording";
|
package/dist/types.d.ts
CHANGED
|
@@ -10,12 +10,14 @@ export interface AnalyticsEventBase {
|
|
|
10
10
|
event_data?: Record<string, JsonValue>;
|
|
11
11
|
}
|
|
12
12
|
export interface AnalyticsClientOptions {
|
|
13
|
-
/** Base endpoint path. Defaults to `/
|
|
13
|
+
/** Base endpoint path. Defaults to `/_temps`. */
|
|
14
14
|
basePath?: string;
|
|
15
15
|
/** Set to true to disable analytics (e.g., for tests). */
|
|
16
16
|
disabled?: boolean;
|
|
17
17
|
/** Ignore localhost/test env automatically. Defaults to true. */
|
|
18
18
|
ignoreLocalhost?: boolean;
|
|
19
|
+
/** Custom domain to use for analytics. Defaults to window.location.hostname. */
|
|
20
|
+
domain?: string;
|
|
19
21
|
}
|
|
20
22
|
export interface AnalyticsContextValue {
|
|
21
23
|
/** Send a custom event. */
|
|
@@ -30,7 +32,62 @@ export interface AnalyticsContextValue {
|
|
|
30
32
|
export interface TempsAnalyticsProviderProps extends AnalyticsClientOptions {
|
|
31
33
|
/** Auto track pageviews on route changes. Defaults to true. */
|
|
32
34
|
autoTrackPageviews?: boolean;
|
|
35
|
+
/** Auto track page leave events. Defaults to true. */
|
|
36
|
+
autoTrackPageLeave?: boolean;
|
|
37
|
+
/** Custom event name for page leave events. Defaults to "page_leave". */
|
|
38
|
+
pageLeaveEventName?: string;
|
|
39
|
+
/** Auto track speed analytics (Web Vitals). Defaults to true. */
|
|
40
|
+
autoTrackSpeedAnalytics?: boolean;
|
|
41
|
+
/** Auto track engagement with heartbeats. Defaults to true. */
|
|
42
|
+
autoTrackEngagement?: boolean;
|
|
43
|
+
/** Heartbeat interval in milliseconds. Defaults to 30000 (30 seconds). */
|
|
44
|
+
heartbeatInterval?: number;
|
|
45
|
+
/** Inactivity timeout in milliseconds. Defaults to 30000 (30 seconds). */
|
|
46
|
+
inactivityTimeout?: number;
|
|
47
|
+
/** Engagement threshold in milliseconds to consider session engaged. Defaults to 10000 (10 seconds). */
|
|
48
|
+
engagementThreshold?: number;
|
|
49
|
+
/** Enable session recording. Defaults to false. */
|
|
50
|
+
enableSessionRecording?: boolean;
|
|
51
|
+
/** Session recording configuration. */
|
|
52
|
+
sessionRecordingConfig?: {
|
|
53
|
+
/** Paths to exclude from recording. */
|
|
54
|
+
excludedPaths?: string[];
|
|
55
|
+
/** Sample rate for recording sessions (0.0 to 1.0). Defaults to 1.0. */
|
|
56
|
+
sessionSampleRate?: number;
|
|
57
|
+
/** Mask all inputs. Defaults to true. */
|
|
58
|
+
maskAllInputs?: boolean;
|
|
59
|
+
/** CSS selector for masking text. Defaults to "[data-mask]". */
|
|
60
|
+
maskTextSelector?: string;
|
|
61
|
+
/** CSS class to block from recording. Defaults to "rr-block". */
|
|
62
|
+
blockClass?: string;
|
|
63
|
+
/** CSS class to ignore from recording. Defaults to "rr-ignore". */
|
|
64
|
+
ignoreClass?: string;
|
|
65
|
+
/** CSS class to mask text. Defaults to "rr-mask". */
|
|
66
|
+
maskTextClass?: string;
|
|
67
|
+
/** Record canvas elements. Defaults to false. */
|
|
68
|
+
recordCanvas?: boolean;
|
|
69
|
+
/** Collect fonts. Defaults to false. */
|
|
70
|
+
collectFonts?: boolean;
|
|
71
|
+
/** Number of events to batch before sending. Defaults to 100. */
|
|
72
|
+
batchSize?: number;
|
|
73
|
+
/** Interval in ms to flush events. Defaults to 5000. */
|
|
74
|
+
flushInterval?: number;
|
|
75
|
+
};
|
|
33
76
|
/** Children to render inside the provider. */
|
|
34
77
|
children: React.ReactNode;
|
|
35
78
|
}
|
|
79
|
+
export interface WebVitalMetric {
|
|
80
|
+
value: number;
|
|
81
|
+
rating: "good" | "needs-improvement" | "poor";
|
|
82
|
+
}
|
|
83
|
+
export interface SpeedMetric {
|
|
84
|
+
ttfb?: number | null;
|
|
85
|
+
lcp?: number | null;
|
|
86
|
+
fid?: number | null;
|
|
87
|
+
fcp?: number | null;
|
|
88
|
+
cls?: number | null;
|
|
89
|
+
inp?: number | null;
|
|
90
|
+
path?: string | null;
|
|
91
|
+
query?: string | null;
|
|
92
|
+
}
|
|
36
93
|
//# sourceMappingURL=types.d.ts.map
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,CAAC;AAC7D,MAAM,MAAM,SAAS,GAAG,aAAa,GAAG,S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AiD;QACjD,YAAY,CAAC,EAAE,OAAO,CAAC;QACvB,wCAAwC;QACxC,YAAY,CAAC,EAAE,OAAO,CAAC;QACvB,iEAAiE;QACjE,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,wDAAwD;QACxD,aAAa,CAAC,EAAE,MAAM,CAAC;KACxB,CAAC;IACF,8CAA8C;IAC9C,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC;CAC3B;AAED,MAAM,WAAW,cAAc;IAC7B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,GAAG,mBAAmB,GAAG,MAAM,CAAC;CAC/C;AAED,MAAM,WAAW,WAAW;IAC1B,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACvB"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type EngagementTrackerOptions, type EngagementData } from "./EngagementTracker";
|
|
2
|
+
export interface UseEngagementTrackingOptions extends Omit<EngagementTrackerOptions, "basePath" | "domain"> {
|
|
3
|
+
/** Whether to enable engagement tracking. Defaults to true. */
|
|
4
|
+
enabled?: boolean;
|
|
5
|
+
/** Callback when engagement data is updated via heartbeat */
|
|
6
|
+
onEngagementUpdate?: (data: EngagementData) => void;
|
|
7
|
+
/** Callback when page leave is triggered */
|
|
8
|
+
onPageLeave?: (data: EngagementData) => void;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Hook to manually control engagement tracking for specific components or pages.
|
|
12
|
+
* This is useful when you want fine-grained control over engagement tracking
|
|
13
|
+
* or need to track engagement for specific sections of your app.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```tsx
|
|
17
|
+
* function ArticlePage() {
|
|
18
|
+
* const { engagementData } = useEngagementTracking({
|
|
19
|
+
* heartbeatInterval: 15000, // Send heartbeat every 15 seconds
|
|
20
|
+
* engagementThreshold: 5000, // Consider engaged after 5 seconds
|
|
21
|
+
* onEngagementUpdate: (data) => {
|
|
22
|
+
* console.log('Engagement updated:', data);
|
|
23
|
+
* }
|
|
24
|
+
* });
|
|
25
|
+
*
|
|
26
|
+
* return <article>...</article>;
|
|
27
|
+
* }
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
export declare function useEngagementTracking(options?: UseEngagementTrackingOptions): {
|
|
31
|
+
engagementData: EngagementData;
|
|
32
|
+
isTracking: boolean;
|
|
33
|
+
};
|
|
34
|
+
//# sourceMappingURL=useEngagementTracking.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useEngagementTracking.d.ts","sourceRoot":"","sources":["../src/useEngagementTracking.ts"],"names":[],"mappings":"AAEA,OAAO,EAAqB,KAAK,wBAAwB,EAAE,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAG5G,MAAM,WAAW,4BAA6B,SAAQ,IAAI,CAAC,wBAAwB,EAAE,UAAU,GAAG,QAAQ,CAAC;IACzG,+DAA+D;IAC/D,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,6DAA6D;IAC7D,kBAAkB,CAAC,EAAE,CAAC,IAAI,EAAE,cAAc,KAAK,IAAI,CAAC;IACpD,4CAA4C;IAC5C,WAAW,CAAC,EAAE,CAAC,IAAI,EAAE,cAAc,KAAK,IAAI,CAAC;CAC9C;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,GAAE,4BAAiC;;;EAkD/E"}
|