@temps-sdk/react-analytics 0.0.1-beta.2 → 0.0.1-beta.21
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 +74 -8
- package/dist/SessionRecorder.d.ts +21 -0
- package/dist/SessionRecorder.d.ts.map +1 -0
- package/dist/SessionRecorder.js +391 -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 +65 -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 +60 -0
- package/dist/utils.d.ts +1 -0
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +43 -2
- package/package.json +19 -6
|
@@ -0,0 +1,391 @@
|
|
|
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
|
+
visitor_id: generateVisitorId(),
|
|
32
|
+
domain: domain || window.location.hostname,
|
|
33
|
+
request_path: window.location.pathname,
|
|
34
|
+
request_query: window.location.search,
|
|
35
|
+
referrer: document.referrer,
|
|
36
|
+
user_agent: navigator.userAgent,
|
|
37
|
+
screen_width: screen.width,
|
|
38
|
+
screen_height: screen.height,
|
|
39
|
+
viewport_width: window.innerWidth,
|
|
40
|
+
viewport_height: window.innerHeight,
|
|
41
|
+
device_pixel_ratio: window.devicePixelRatio || 1,
|
|
42
|
+
language: navigator.language,
|
|
43
|
+
platform: navigator.platform,
|
|
44
|
+
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
45
|
+
started_at: new Date().toISOString(),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
export function SessionRecorder({ basePath = "/_temps", domain, enabled = false, excludedPaths = [], sessionSampleRate = 1.0, maskAllInputs = true, maskTextSelector = "[data-mask]", blockClass = "rr-block", ignoreClass = "rr-ignore", maskTextClass = "rr-mask", recordCanvas = false, collectFonts = false, slimDOMOptions = {
|
|
49
|
+
script: false,
|
|
50
|
+
comment: false,
|
|
51
|
+
headFavicon: false,
|
|
52
|
+
headWhitespace: false,
|
|
53
|
+
headMetaSocial: false,
|
|
54
|
+
headMetaRobots: false,
|
|
55
|
+
headMetaHttpEquiv: false,
|
|
56
|
+
headMetaVerification: false,
|
|
57
|
+
headMetaDescKeywords: false
|
|
58
|
+
}, batchSize = 100, flushInterval = 5000, }) {
|
|
59
|
+
const stopFnRef = useRef(null);
|
|
60
|
+
const eventsRef = useRef([]);
|
|
61
|
+
const sessionIdRef = useRef("");
|
|
62
|
+
const sessionInitializedRef = useRef(false);
|
|
63
|
+
const flushTimeoutRef = useRef(null);
|
|
64
|
+
const initRetryCountRef = useRef(0);
|
|
65
|
+
const initFailedRef = useRef(false); // Track if init has permanently failed
|
|
66
|
+
const maxInitRetries = 3;
|
|
67
|
+
const [isInitializing, setIsInitializing] = useState(false);
|
|
68
|
+
const shouldRecord = useCallback(() => {
|
|
69
|
+
if (!enabled)
|
|
70
|
+
return false;
|
|
71
|
+
if (typeof window === "undefined")
|
|
72
|
+
return false;
|
|
73
|
+
// Check if current path should be excluded
|
|
74
|
+
const currentPath = window.location.pathname;
|
|
75
|
+
const isExcluded = excludedPaths.some(path => {
|
|
76
|
+
// Support wildcards in path patterns
|
|
77
|
+
const regex = new RegExp(`^${path.replace(/\*/g, '.*')}$`);
|
|
78
|
+
return regex.test(currentPath);
|
|
79
|
+
});
|
|
80
|
+
if (isExcluded)
|
|
81
|
+
return false;
|
|
82
|
+
// Apply sampling rate
|
|
83
|
+
if (sessionSampleRate < 1.0) {
|
|
84
|
+
const random = Math.random();
|
|
85
|
+
if (random > sessionSampleRate)
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
return true;
|
|
89
|
+
}, [enabled, excludedPaths, sessionSampleRate]);
|
|
90
|
+
const initializeSession = useCallback(async () => {
|
|
91
|
+
// If already initialized or currently initializing, return current state
|
|
92
|
+
if (sessionInitializedRef.current || isInitializing)
|
|
93
|
+
return sessionInitializedRef.current;
|
|
94
|
+
// If we've permanently failed, don't try again
|
|
95
|
+
if (initFailedRef.current) {
|
|
96
|
+
console.warn("[SessionRecorder] Initialization has permanently failed, not retrying");
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
// Check if we've exceeded retry limit
|
|
100
|
+
if (initRetryCountRef.current >= maxInitRetries) {
|
|
101
|
+
console.error(`[SessionRecorder] Exceeded maximum initialization retries (${maxInitRetries})`);
|
|
102
|
+
initFailedRef.current = true; // Mark as permanently failed
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
setIsInitializing(true);
|
|
106
|
+
initRetryCountRef.current++;
|
|
107
|
+
console.log(`[SessionRecorder] Attempting to initialize session (attempt ${initRetryCountRef.current}/${maxInitRetries})`);
|
|
108
|
+
const sessionId = generateSessionId();
|
|
109
|
+
sessionIdRef.current = sessionId;
|
|
110
|
+
try {
|
|
111
|
+
const metadata = {
|
|
112
|
+
session_id: sessionId,
|
|
113
|
+
...getSessionMetadata(domain),
|
|
114
|
+
};
|
|
115
|
+
const response = await fetch(`${basePath}/${SESSION_RECORDER_ENDPOINT}/init`, {
|
|
116
|
+
method: "POST",
|
|
117
|
+
headers: {
|
|
118
|
+
"Content-Type": "application/json",
|
|
119
|
+
},
|
|
120
|
+
body: JSON.stringify(metadata),
|
|
121
|
+
});
|
|
122
|
+
if (response.status === 201) {
|
|
123
|
+
sessionInitializedRef.current = true;
|
|
124
|
+
initRetryCountRef.current = 0; // Reset retry count on success
|
|
125
|
+
initFailedRef.current = false; // Reset failed flag on success
|
|
126
|
+
// Store session ID in localStorage for reference
|
|
127
|
+
if (typeof localStorage !== "undefined") {
|
|
128
|
+
localStorage.setItem("currentRecordingSessionId", sessionId);
|
|
129
|
+
}
|
|
130
|
+
console.log("[SessionRecorder] Session initialized successfully:", sessionId);
|
|
131
|
+
return true;
|
|
132
|
+
}
|
|
133
|
+
else {
|
|
134
|
+
console.error(`[SessionRecorder] Failed to initialize session: ${response.status} (attempt ${initRetryCountRef.current}/${maxInitRetries})`);
|
|
135
|
+
sessionIdRef.current = ""; // Clear invalid session ID
|
|
136
|
+
// Mark as permanently failed if we've hit the retry limit
|
|
137
|
+
if (initRetryCountRef.current >= maxInitRetries) {
|
|
138
|
+
initFailedRef.current = true;
|
|
139
|
+
}
|
|
140
|
+
return false;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
console.error(`[SessionRecorder] Failed to initialize session: ${error} (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
|
+
finally {
|
|
153
|
+
setIsInitializing(false);
|
|
154
|
+
}
|
|
155
|
+
}, [basePath, domain, isInitializing]);
|
|
156
|
+
const sendEvents = useCallback(async (isReliable = false) => {
|
|
157
|
+
if (!sessionInitializedRef.current) {
|
|
158
|
+
console.warn("[SessionRecorder] Cannot send events - session not initialized");
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const events = eventsRef.current;
|
|
162
|
+
if (events.length === 0)
|
|
163
|
+
return;
|
|
164
|
+
const eventsToSend = [...events];
|
|
165
|
+
eventsRef.current = [];
|
|
166
|
+
try {
|
|
167
|
+
// Pack the events for more efficient transmission
|
|
168
|
+
const packedEvents = pack(eventsToSend);
|
|
169
|
+
// Base64 encode the packed string for safe JSON transmission
|
|
170
|
+
const encodedEvents = btoa(packedEvents);
|
|
171
|
+
const payload = {
|
|
172
|
+
session_id: sessionIdRef.current,
|
|
173
|
+
events: encodedEvents,
|
|
174
|
+
};
|
|
175
|
+
const url = `${basePath}/${SESSION_RECORDER_ENDPOINT}/events`;
|
|
176
|
+
if (isReliable) {
|
|
177
|
+
// Use sendBeacon for reliable sending on page unload
|
|
178
|
+
if (navigator.sendBeacon) {
|
|
179
|
+
const blob = new Blob([JSON.stringify(payload)], { type: "application/json" });
|
|
180
|
+
const sent = navigator.sendBeacon(url, blob);
|
|
181
|
+
if (!sent) {
|
|
182
|
+
// Fallback to fetch with keepalive
|
|
183
|
+
await fetch(url, {
|
|
184
|
+
method: "POST",
|
|
185
|
+
headers: { "Content-Type": "application/json" },
|
|
186
|
+
body: JSON.stringify(payload),
|
|
187
|
+
keepalive: true,
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
// Fallback to fetch with keepalive
|
|
193
|
+
await fetch(url, {
|
|
194
|
+
method: "POST",
|
|
195
|
+
headers: { "Content-Type": "application/json" },
|
|
196
|
+
body: JSON.stringify(payload),
|
|
197
|
+
keepalive: true,
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
else {
|
|
202
|
+
const response = await fetch(url, {
|
|
203
|
+
method: "POST",
|
|
204
|
+
headers: { "Content-Type": "application/json" },
|
|
205
|
+
body: JSON.stringify(payload),
|
|
206
|
+
});
|
|
207
|
+
if (response.status === 404) {
|
|
208
|
+
// Session not found, mark as not initialized but don't auto-reinitialize
|
|
209
|
+
console.error("[SessionRecorder] Session not found on server, stopping recording");
|
|
210
|
+
sessionInitializedRef.current = false;
|
|
211
|
+
sessionIdRef.current = "";
|
|
212
|
+
// Clear the session from localStorage
|
|
213
|
+
if (typeof localStorage !== "undefined") {
|
|
214
|
+
localStorage.removeItem("currentRecordingSessionId");
|
|
215
|
+
}
|
|
216
|
+
// Stop recording to prevent further errors
|
|
217
|
+
if (stopFnRef.current) {
|
|
218
|
+
stopFnRef.current();
|
|
219
|
+
stopFnRef.current = null;
|
|
220
|
+
}
|
|
221
|
+
// Don't restore events - they're lost
|
|
222
|
+
}
|
|
223
|
+
else if (!response.ok) {
|
|
224
|
+
console.error("[SessionRecorder] Failed to send events:", response.status);
|
|
225
|
+
// Restore events on failure
|
|
226
|
+
eventsRef.current.unshift(...eventsToSend);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
catch (error) {
|
|
231
|
+
console.error("[SessionRecorder] Failed to send session events:", error);
|
|
232
|
+
// Restore events on failure
|
|
233
|
+
eventsRef.current.unshift(...eventsToSend);
|
|
234
|
+
}
|
|
235
|
+
}, [basePath, initializeSession]);
|
|
236
|
+
const scheduleFlush = useCallback(() => {
|
|
237
|
+
if (flushTimeoutRef.current) {
|
|
238
|
+
clearTimeout(flushTimeoutRef.current);
|
|
239
|
+
}
|
|
240
|
+
flushTimeoutRef.current = setTimeout(() => {
|
|
241
|
+
sendEvents(false);
|
|
242
|
+
}, flushInterval);
|
|
243
|
+
}, [sendEvents, flushInterval]);
|
|
244
|
+
const startRecording = useCallback(async () => {
|
|
245
|
+
if (stopFnRef.current)
|
|
246
|
+
return; // Already recording
|
|
247
|
+
if (!shouldRecord())
|
|
248
|
+
return;
|
|
249
|
+
// If initialization has permanently failed, don't try to start
|
|
250
|
+
if (initFailedRef.current) {
|
|
251
|
+
console.warn("[SessionRecorder] Not starting recording - initialization has permanently failed");
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
// Initialize session first
|
|
255
|
+
const initialized = await initializeSession();
|
|
256
|
+
if (!initialized) {
|
|
257
|
+
console.error("[SessionRecorder] Failed to initialize session, not starting recording");
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
eventsRef.current = [];
|
|
261
|
+
const stopFn = record({
|
|
262
|
+
emit(event) {
|
|
263
|
+
eventsRef.current.push(event);
|
|
264
|
+
// Batch send when we reach the batch size
|
|
265
|
+
if (eventsRef.current.length >= batchSize) {
|
|
266
|
+
sendEvents(false);
|
|
267
|
+
scheduleFlush();
|
|
268
|
+
}
|
|
269
|
+
},
|
|
270
|
+
sampling: {
|
|
271
|
+
scroll: 150,
|
|
272
|
+
media: 800,
|
|
273
|
+
input: "last"
|
|
274
|
+
},
|
|
275
|
+
recordCanvas,
|
|
276
|
+
collectFonts,
|
|
277
|
+
maskAllInputs,
|
|
278
|
+
maskTextSelector,
|
|
279
|
+
blockClass,
|
|
280
|
+
ignoreClass,
|
|
281
|
+
maskTextClass,
|
|
282
|
+
slimDOMOptions,
|
|
283
|
+
});
|
|
284
|
+
if (stopFn) {
|
|
285
|
+
stopFnRef.current = stopFn;
|
|
286
|
+
}
|
|
287
|
+
// Start the flush interval
|
|
288
|
+
scheduleFlush();
|
|
289
|
+
}, [shouldRecord, initializeSession, sendEvents, scheduleFlush, batchSize, recordCanvas, collectFonts, maskAllInputs, maskTextSelector, blockClass, ignoreClass, maskTextClass, slimDOMOptions]);
|
|
290
|
+
const stopRecording = useCallback(() => {
|
|
291
|
+
if (stopFnRef.current) {
|
|
292
|
+
stopFnRef.current();
|
|
293
|
+
stopFnRef.current = null;
|
|
294
|
+
// Clear flush timeout
|
|
295
|
+
if (flushTimeoutRef.current) {
|
|
296
|
+
clearTimeout(flushTimeoutRef.current);
|
|
297
|
+
flushTimeoutRef.current = null;
|
|
298
|
+
}
|
|
299
|
+
// Send any remaining events reliably
|
|
300
|
+
sendEvents(true);
|
|
301
|
+
// Clear session state
|
|
302
|
+
sessionInitializedRef.current = false;
|
|
303
|
+
sessionIdRef.current = "";
|
|
304
|
+
// Clear session ID from localStorage
|
|
305
|
+
if (typeof localStorage !== "undefined") {
|
|
306
|
+
localStorage.removeItem("currentRecordingSessionId");
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
// Reset retry counters when explicitly stopping
|
|
310
|
+
initRetryCountRef.current = 0;
|
|
311
|
+
initFailedRef.current = false;
|
|
312
|
+
}, [sendEvents]);
|
|
313
|
+
// Effect to handle recording lifecycle
|
|
314
|
+
useEffect(() => {
|
|
315
|
+
// Early return if we shouldn't record or have permanently failed
|
|
316
|
+
if (!enabled || initFailedRef.current || stopFnRef.current || sessionInitializedRef.current) {
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
// Check if current path should be excluded
|
|
320
|
+
const currentPath = window.location.pathname;
|
|
321
|
+
const isExcluded = excludedPaths.some(path => {
|
|
322
|
+
const regex = new RegExp(`^${path.replace(/\*/g, '.*')}$`);
|
|
323
|
+
return regex.test(currentPath);
|
|
324
|
+
});
|
|
325
|
+
if (isExcluded) {
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
// Apply sampling rate
|
|
329
|
+
if (sessionSampleRate < 1.0) {
|
|
330
|
+
const random = Math.random();
|
|
331
|
+
if (random > sessionSampleRate) {
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
// Now we can start recording
|
|
336
|
+
startRecording();
|
|
337
|
+
// Handle page unload
|
|
338
|
+
const handleUnload = () => {
|
|
339
|
+
if (sessionInitializedRef.current && eventsRef.current.length > 0) {
|
|
340
|
+
sendEvents(true);
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
window.addEventListener("beforeunload", handleUnload);
|
|
344
|
+
window.addEventListener("pagehide", handleUnload);
|
|
345
|
+
return () => {
|
|
346
|
+
window.removeEventListener("beforeunload", handleUnload);
|
|
347
|
+
window.removeEventListener("pagehide", handleUnload);
|
|
348
|
+
};
|
|
349
|
+
// Dependencies that should trigger re-evaluation
|
|
350
|
+
}, [enabled, excludedPaths, sessionSampleRate, startRecording, sendEvents]);
|
|
351
|
+
// Monitor location changes to stop/start recording based on excluded paths
|
|
352
|
+
useEffect(() => {
|
|
353
|
+
const checkPathAndToggleRecording = () => {
|
|
354
|
+
if (!enabled || initFailedRef.current) {
|
|
355
|
+
if (!enabled) {
|
|
356
|
+
stopRecording();
|
|
357
|
+
}
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
const currentPath = window.location.pathname;
|
|
361
|
+
const isExcluded = excludedPaths.some(path => {
|
|
362
|
+
const regex = new RegExp(`^${path.replace(/\*/g, '.*')}$`);
|
|
363
|
+
return regex.test(currentPath);
|
|
364
|
+
});
|
|
365
|
+
if (isExcluded && stopFnRef.current) {
|
|
366
|
+
stopRecording();
|
|
367
|
+
}
|
|
368
|
+
else if (!isExcluded && !stopFnRef.current && !initFailedRef.current) {
|
|
369
|
+
startRecording();
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
// Listen for route changes
|
|
373
|
+
const originalPushState = window.history.pushState;
|
|
374
|
+
const originalReplaceState = window.history.replaceState;
|
|
375
|
+
window.history.pushState = function (...args) {
|
|
376
|
+
originalPushState.apply(window.history, args);
|
|
377
|
+
checkPathAndToggleRecording();
|
|
378
|
+
};
|
|
379
|
+
window.history.replaceState = function (...args) {
|
|
380
|
+
originalReplaceState.apply(window.history, args);
|
|
381
|
+
checkPathAndToggleRecording();
|
|
382
|
+
};
|
|
383
|
+
window.addEventListener("popstate", checkPathAndToggleRecording);
|
|
384
|
+
return () => {
|
|
385
|
+
window.history.pushState = originalPushState;
|
|
386
|
+
window.history.replaceState = originalReplaceState;
|
|
387
|
+
window.removeEventListener("popstate", checkPathAndToggleRecording);
|
|
388
|
+
};
|
|
389
|
+
}, [enabled, excludedPaths, startRecording, stopRecording]);
|
|
390
|
+
return null;
|
|
391
|
+
}
|
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,SAAS,EAAE,GAAG;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAAC;AAEnF,MAAM,WAAW,kBAAkB;IACjC,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;CACxC;AAED,MAAM,WAAW,sBAAsB;IACrC,
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"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"}
|
|
@@ -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"}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useEffect, useRef } from "react";
|
|
3
|
+
import { EngagementTracker } from "./EngagementTracker";
|
|
4
|
+
import { useTempsAnalytics } from "./Provider";
|
|
5
|
+
/**
|
|
6
|
+
* Hook to manually control engagement tracking for specific components or pages.
|
|
7
|
+
* This is useful when you want fine-grained control over engagement tracking
|
|
8
|
+
* or need to track engagement for specific sections of your app.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```tsx
|
|
12
|
+
* function ArticlePage() {
|
|
13
|
+
* const { engagementData } = useEngagementTracking({
|
|
14
|
+
* heartbeatInterval: 15000, // Send heartbeat every 15 seconds
|
|
15
|
+
* engagementThreshold: 5000, // Consider engaged after 5 seconds
|
|
16
|
+
* onEngagementUpdate: (data) => {
|
|
17
|
+
* console.log('Engagement updated:', data);
|
|
18
|
+
* }
|
|
19
|
+
* });
|
|
20
|
+
*
|
|
21
|
+
* return <article>...</article>;
|
|
22
|
+
* }
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
export function useEngagementTracking(options = {}) {
|
|
26
|
+
const analytics = useTempsAnalytics();
|
|
27
|
+
const trackerRef = useRef(null);
|
|
28
|
+
const engagementDataRef = useRef({
|
|
29
|
+
engagement_time_seconds: 0,
|
|
30
|
+
total_time_seconds: 0,
|
|
31
|
+
heartbeat_count: 0,
|
|
32
|
+
is_engaged: false,
|
|
33
|
+
is_visible: true,
|
|
34
|
+
time_since_last_activity: 0,
|
|
35
|
+
});
|
|
36
|
+
const { enabled = true, onEngagementUpdate, onPageLeave, ...trackerOptions } = options;
|
|
37
|
+
useEffect(() => {
|
|
38
|
+
if (!enabled || !analytics.enabled) {
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
// Create tracker instance
|
|
42
|
+
trackerRef.current = new EngagementTracker({
|
|
43
|
+
...trackerOptions,
|
|
44
|
+
onHeartbeat: (data) => {
|
|
45
|
+
engagementDataRef.current = data;
|
|
46
|
+
onEngagementUpdate?.(data);
|
|
47
|
+
},
|
|
48
|
+
onPageLeave: (data) => {
|
|
49
|
+
engagementDataRef.current = data;
|
|
50
|
+
onPageLeave?.(data);
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
// Cleanup on unmount
|
|
54
|
+
return () => {
|
|
55
|
+
if (trackerRef.current) {
|
|
56
|
+
trackerRef.current.destroy();
|
|
57
|
+
trackerRef.current = null;
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
}, [enabled, analytics.enabled]);
|
|
61
|
+
return {
|
|
62
|
+
engagementData: engagementDataRef.current,
|
|
63
|
+
isTracking: Boolean(trackerRef.current),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { JsonValue } from "./types";
|
|
2
|
+
export interface UsePageLeaveOptions {
|
|
3
|
+
/** Custom event name. Defaults to "page_leave" */
|
|
4
|
+
eventName?: string;
|
|
5
|
+
/** Additional data to send with the page leave event */
|
|
6
|
+
eventData?: Record<string, JsonValue>;
|
|
7
|
+
/** Whether to enable page leave tracking. Defaults to true */
|
|
8
|
+
enabled?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export declare function usePageLeave(options?: UsePageLeaveOptions): {
|
|
11
|
+
triggerPageLeave: () => Promise<void> | undefined;
|
|
12
|
+
};
|
|
13
|
+
//# sourceMappingURL=usePageLeave.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"usePageLeave.d.ts","sourceRoot":"","sources":["../src/usePageLeave.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAEzC,MAAM,WAAW,mBAAmB;IAClC,kDAAkD;IAClD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,wDAAwD;IACxD,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;IACtC,8DAA8D;IAC9D,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,wBAAgB,YAAY,CAAC,OAAO,GAAE,mBAAwB;;EA2E7D"}
|