@temps-sdk/react-analytics 0.0.1-beta.15 → 0.0.1-beta.17

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.
@@ -1 +1 @@
1
- {"version":3,"file":"SessionRecorder.d.ts","sourceRoot":"","sources":["../src/SessionRecorder.tsx"],"names":[],"mappings":"AAMA,eAAO,MAAM,yBAAyB,mBAAmB,CAAC;AAE1D,UAAU,oBAAoB;IAC5B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACzC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AA0BD,wBAAgB,eAAe,CAAC,EAC9B,QAAwB,EACxB,MAAM,EACN,OAAe,EACf,aAAkB,EAClB,iBAAuB,EACvB,aAAoB,EACpB,gBAAgC,EAChC,UAAuB,EACvB,WAAyB,EACzB,aAAyB,EACzB,YAAoB,EACpB,YAAoB,EACpB,cAUC,EACD,SAAe,EACf,aAAoB,GACrB,EAAE,oBAAoB,QA6MtB"}
1
+ {"version":3,"file":"SessionRecorder.d.ts","sourceRoot":"","sources":["../src/SessionRecorder.tsx"],"names":[],"mappings":"AAMA,eAAO,MAAM,yBAAyB,mBAAmB,CAAC;AAE1D,UAAU,oBAAoB;IAC5B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACzC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AA+CD,wBAAgB,eAAe,CAAC,EAC9B,QAAwB,EACxB,MAAM,EACN,OAAe,EACf,aAAkB,EAClB,iBAAuB,EACvB,aAAoB,EACpB,gBAAgC,EAChC,UAAuB,EACvB,WAAyB,EACzB,aAAyB,EACzB,YAAoB,EACpB,YAAoB,EACpB,cAUC,EACD,SAAe,EACf,aAAoB,GACrB,EAAE,oBAAoB,QA8StB"}
@@ -5,24 +5,44 @@ import { pack } from "@rrweb/packer";
5
5
  import { sendAnalytics, sendAnalyticsReliable, getRequestId } from "./utils";
6
6
  export const SESSION_RECORDER_ENDPOINT = "session-replay";
7
7
  function generateSessionId() {
8
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
9
+ return crypto.randomUUID();
10
+ }
8
11
  return `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
9
12
  }
10
- function getVisitorInfo() {
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) {
11
26
  if (typeof window === "undefined")
12
27
  return {};
13
28
  const screen = window.screen || {};
14
29
  const navigator = window.navigator || {};
15
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,
16
37
  screen_width: screen.width,
17
38
  screen_height: screen.height,
18
39
  viewport_width: window.innerWidth,
19
40
  viewport_height: window.innerHeight,
20
41
  device_pixel_ratio: window.devicePixelRatio || 1,
21
- user_agent: navigator.userAgent,
22
42
  language: navigator.language,
23
43
  platform: navigator.platform,
24
44
  timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
25
- referrer: document.referrer,
45
+ started_at: new Date().toISOString(),
26
46
  };
27
47
  }
28
48
  export function SessionRecorder({ basePath = "/api/_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 = {
@@ -39,7 +59,9 @@ export function SessionRecorder({ basePath = "/api/_temps", domain, enabled = fa
39
59
  const stopFnRef = useRef(null);
40
60
  const eventsRef = useRef([]);
41
61
  const sessionIdRef = useRef("");
62
+ const sessionInitializedRef = useRef(false);
42
63
  const flushTimeoutRef = useRef(null);
64
+ const [isInitializing, setIsInitializing] = useState(false);
43
65
  const shouldRecord = useCallback(() => {
44
66
  if (!enabled)
45
67
  return false;
@@ -47,7 +69,11 @@ export function SessionRecorder({ basePath = "/api/_temps", domain, enabled = fa
47
69
  return false;
48
70
  // Check if current path should be excluded
49
71
  const currentPath = window.location.pathname;
50
- const isExcluded = excludedPaths.some(path => currentPath.startsWith(path));
72
+ const isExcluded = excludedPaths.some(path => {
73
+ // Support wildcards in path patterns
74
+ const regex = new RegExp(`^${path.replace(/\*/g, '.*')}$`);
75
+ return regex.test(currentPath);
76
+ });
51
77
  if (isExcluded)
52
78
  return false;
53
79
  // Apply sampling rate
@@ -58,7 +84,50 @@ export function SessionRecorder({ basePath = "/api/_temps", domain, enabled = fa
58
84
  }
59
85
  return true;
60
86
  }, [enabled, excludedPaths, sessionSampleRate]);
87
+ const initializeSession = useCallback(async () => {
88
+ if (sessionInitializedRef.current || isInitializing)
89
+ return false;
90
+ setIsInitializing(true);
91
+ const sessionId = generateSessionId();
92
+ sessionIdRef.current = sessionId;
93
+ try {
94
+ const metadata = {
95
+ session_id: sessionId,
96
+ ...getSessionMetadata(domain),
97
+ };
98
+ const response = await fetch(`${basePath}/${SESSION_RECORDER_ENDPOINT}/init`, {
99
+ method: "POST",
100
+ headers: {
101
+ "Content-Type": "application/json",
102
+ },
103
+ body: JSON.stringify(metadata),
104
+ });
105
+ if (response.status === 201) {
106
+ sessionInitializedRef.current = true;
107
+ // Store session ID in localStorage for reference
108
+ if (typeof localStorage !== "undefined") {
109
+ localStorage.setItem("currentRecordingSessionId", sessionId);
110
+ }
111
+ return true;
112
+ }
113
+ else {
114
+ console.error("[SessionRecorder] Failed to initialize session:", response.status);
115
+ return false;
116
+ }
117
+ }
118
+ catch (error) {
119
+ console.error("[SessionRecorder] Failed to initialize session:", error);
120
+ return false;
121
+ }
122
+ finally {
123
+ setIsInitializing(false);
124
+ }
125
+ }, [basePath, domain, isInitializing]);
61
126
  const sendEvents = useCallback(async (isReliable = false) => {
127
+ if (!sessionInitializedRef.current) {
128
+ console.warn("[SessionRecorder] Cannot send events - session not initialized");
129
+ return;
130
+ }
62
131
  const events = eventsRef.current;
63
132
  if (events.length === 0)
64
133
  return;
@@ -72,28 +141,64 @@ export function SessionRecorder({ basePath = "/api/_temps", domain, enabled = fa
72
141
  const payload = {
73
142
  session_id: sessionIdRef.current,
74
143
  events: encodedEvents,
75
- is_packed: true,
76
- metadata: {
77
- ...getVisitorInfo(),
78
- url: window.location.href,
79
- domain: domain || window.location.hostname,
80
- request_id: getRequestId() || null,
81
- timestamp: new Date().toISOString(),
82
- },
83
144
  };
145
+ const url = `${basePath}/${SESSION_RECORDER_ENDPOINT}/events`;
84
146
  if (isReliable) {
85
- sendAnalyticsReliable(SESSION_RECORDER_ENDPOINT, payload, basePath);
147
+ // Use sendBeacon for reliable sending on page unload
148
+ if (navigator.sendBeacon) {
149
+ const blob = new Blob([JSON.stringify(payload)], { type: "application/json" });
150
+ const sent = navigator.sendBeacon(url, blob);
151
+ if (!sent) {
152
+ // Fallback to fetch with keepalive
153
+ await fetch(url, {
154
+ method: "POST",
155
+ headers: { "Content-Type": "application/json" },
156
+ body: JSON.stringify(payload),
157
+ keepalive: true,
158
+ });
159
+ }
160
+ }
161
+ else {
162
+ // Fallback to fetch with keepalive
163
+ await fetch(url, {
164
+ method: "POST",
165
+ headers: { "Content-Type": "application/json" },
166
+ body: JSON.stringify(payload),
167
+ keepalive: true,
168
+ });
169
+ }
86
170
  }
87
171
  else {
88
- await sendAnalytics(SESSION_RECORDER_ENDPOINT, payload, "POST", basePath);
172
+ const response = await fetch(url, {
173
+ method: "POST",
174
+ headers: { "Content-Type": "application/json" },
175
+ body: JSON.stringify(payload),
176
+ });
177
+ if (response.status === 404) {
178
+ // Session not found, need to reinitialize
179
+ console.warn("[SessionRecorder] Session not found, reinitializing...");
180
+ sessionInitializedRef.current = false;
181
+ // Try to reinitialize and resend events
182
+ const reinitialized = await initializeSession();
183
+ if (reinitialized) {
184
+ // Restore events and try again
185
+ eventsRef.current.unshift(...eventsToSend);
186
+ await sendEvents(false);
187
+ }
188
+ }
189
+ else if (!response.ok) {
190
+ console.error("[SessionRecorder] Failed to send events:", response.status);
191
+ // Restore events on failure
192
+ eventsRef.current.unshift(...eventsToSend);
193
+ }
89
194
  }
90
195
  }
91
196
  catch (error) {
92
- console.error("Failed to send session events:", error);
197
+ console.error("[SessionRecorder] Failed to send session events:", error);
93
198
  // Restore events on failure
94
199
  eventsRef.current.unshift(...eventsToSend);
95
200
  }
96
- }, [basePath, domain]);
201
+ }, [basePath, initializeSession]);
97
202
  const scheduleFlush = useCallback(() => {
98
203
  if (flushTimeoutRef.current) {
99
204
  clearTimeout(flushTimeoutRef.current);
@@ -102,18 +207,18 @@ export function SessionRecorder({ basePath = "/api/_temps", domain, enabled = fa
102
207
  sendEvents(false);
103
208
  }, flushInterval);
104
209
  }, [sendEvents, flushInterval]);
105
- const startRecording = useCallback(() => {
210
+ const startRecording = useCallback(async () => {
106
211
  if (stopFnRef.current)
107
212
  return; // Already recording
108
213
  if (!shouldRecord())
109
214
  return;
110
- const sessionId = generateSessionId();
111
- sessionIdRef.current = sessionId;
112
- eventsRef.current = [];
113
- // Store session ID in localStorage for reference
114
- if (typeof localStorage !== "undefined") {
115
- localStorage.setItem("currentRecordingSessionId", sessionId);
215
+ // Initialize session first
216
+ const initialized = await initializeSession();
217
+ if (!initialized) {
218
+ console.error("[SessionRecorder] Failed to initialize session, not starting recording");
219
+ return;
116
220
  }
221
+ eventsRef.current = [];
117
222
  const stopFn = record({
118
223
  emit(event) {
119
224
  eventsRef.current.push(event);
@@ -142,7 +247,7 @@ export function SessionRecorder({ basePath = "/api/_temps", domain, enabled = fa
142
247
  }
143
248
  // Start the flush interval
144
249
  scheduleFlush();
145
- }, [shouldRecord, sendEvents, scheduleFlush, batchSize, recordCanvas, collectFonts, maskAllInputs, maskTextSelector, blockClass, ignoreClass, maskTextClass, slimDOMOptions]);
250
+ }, [shouldRecord, initializeSession, sendEvents, scheduleFlush, batchSize, recordCanvas, collectFonts, maskAllInputs, maskTextSelector, blockClass, ignoreClass, maskTextClass, slimDOMOptions]);
146
251
  const stopRecording = useCallback(() => {
147
252
  if (stopFnRef.current) {
148
253
  stopFnRef.current();
@@ -154,6 +259,9 @@ export function SessionRecorder({ basePath = "/api/_temps", domain, enabled = fa
154
259
  }
155
260
  // Send any remaining events reliably
156
261
  sendEvents(true);
262
+ // Clear session state
263
+ sessionInitializedRef.current = false;
264
+ sessionIdRef.current = "";
157
265
  // Clear session ID from localStorage
158
266
  if (typeof localStorage !== "undefined") {
159
267
  localStorage.removeItem("currentRecordingSessionId");
@@ -187,7 +295,10 @@ export function SessionRecorder({ basePath = "/api/_temps", domain, enabled = fa
187
295
  return;
188
296
  }
189
297
  const currentPath = window.location.pathname;
190
- const isExcluded = excludedPaths.some(path => currentPath.startsWith(path));
298
+ const isExcluded = excludedPaths.some(path => {
299
+ const regex = new RegExp(`^${path.replace(/\*/g, '.*')}$`);
300
+ return regex.test(currentPath);
301
+ });
191
302
  if (isExcluded && stopFnRef.current) {
192
303
  stopRecording();
193
304
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@temps-sdk/react-analytics",
3
- "version": "0.0.1-beta.15",
3
+ "version": "0.0.1-beta.17",
4
4
  "private": false,
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -46,6 +46,8 @@
46
46
  "@types/react-dom": "^18.2.19",
47
47
  "@vitest/coverage-v8": "^1.3.1",
48
48
  "jsdom": "^24.0.0",
49
+ "react": "^18.2.0",
50
+ "react-dom": "^18.2.0",
49
51
  "typescript": "^5.5.4",
50
52
  "vitest": "^1.3.1"
51
53
  },