@temps-sdk/react-analytics 0.0.1-beta.16 → 0.0.1-beta.18

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,QAAoB,EACpB,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,QAuUtB"}
@@ -5,27 +5,47 @@ 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
- 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 = {
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 = {
29
49
  script: false,
30
50
  comment: false,
31
51
  headFavicon: false,
@@ -39,7 +59,11 @@ 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 initRetryCountRef = useRef(0);
65
+ const maxInitRetries = 3;
66
+ const [isInitializing, setIsInitializing] = useState(false);
43
67
  const shouldRecord = useCallback(() => {
44
68
  if (!enabled)
45
69
  return false;
@@ -47,7 +71,11 @@ export function SessionRecorder({ basePath = "/api/_temps", domain, enabled = fa
47
71
  return false;
48
72
  // Check if current path should be excluded
49
73
  const currentPath = window.location.pathname;
50
- const isExcluded = excludedPaths.some(path => currentPath.startsWith(path));
74
+ const isExcluded = excludedPaths.some(path => {
75
+ // Support wildcards in path patterns
76
+ const regex = new RegExp(`^${path.replace(/\*/g, '.*')}$`);
77
+ return regex.test(currentPath);
78
+ });
51
79
  if (isExcluded)
52
80
  return false;
53
81
  // Apply sampling rate
@@ -58,7 +86,60 @@ export function SessionRecorder({ basePath = "/api/_temps", domain, enabled = fa
58
86
  }
59
87
  return true;
60
88
  }, [enabled, excludedPaths, sessionSampleRate]);
89
+ const initializeSession = useCallback(async () => {
90
+ if (sessionInitializedRef.current || isInitializing)
91
+ return sessionInitializedRef.current;
92
+ // Check if we've exceeded retry limit
93
+ if (initRetryCountRef.current >= maxInitRetries) {
94
+ console.error("[SessionRecorder] Exceeded maximum initialization retries");
95
+ return false;
96
+ }
97
+ setIsInitializing(true);
98
+ initRetryCountRef.current++;
99
+ const sessionId = generateSessionId();
100
+ sessionIdRef.current = sessionId;
101
+ try {
102
+ const metadata = {
103
+ session_id: sessionId,
104
+ ...getSessionMetadata(domain),
105
+ };
106
+ const response = await fetch(`${basePath}/${SESSION_RECORDER_ENDPOINT}/init`, {
107
+ method: "POST",
108
+ headers: {
109
+ "Content-Type": "application/json",
110
+ },
111
+ body: JSON.stringify(metadata),
112
+ });
113
+ if (response.status === 201) {
114
+ sessionInitializedRef.current = true;
115
+ initRetryCountRef.current = 0; // Reset retry count on success
116
+ // Store session ID in localStorage for reference
117
+ if (typeof localStorage !== "undefined") {
118
+ localStorage.setItem("currentRecordingSessionId", sessionId);
119
+ }
120
+ console.log("[SessionRecorder] Session initialized successfully:", sessionId);
121
+ return true;
122
+ }
123
+ else {
124
+ console.error("[SessionRecorder] Failed to initialize session:", response.status);
125
+ sessionIdRef.current = ""; // Clear invalid session ID
126
+ return false;
127
+ }
128
+ }
129
+ catch (error) {
130
+ console.error("[SessionRecorder] Failed to initialize session:", error);
131
+ sessionIdRef.current = ""; // Clear invalid session ID
132
+ return false;
133
+ }
134
+ finally {
135
+ setIsInitializing(false);
136
+ }
137
+ }, [basePath, domain, isInitializing]);
61
138
  const sendEvents = useCallback(async (isReliable = false) => {
139
+ if (!sessionInitializedRef.current) {
140
+ console.warn("[SessionRecorder] Cannot send events - session not initialized");
141
+ return;
142
+ }
62
143
  const events = eventsRef.current;
63
144
  if (events.length === 0)
64
145
  return;
@@ -70,30 +151,70 @@ export function SessionRecorder({ basePath = "/api/_temps", domain, enabled = fa
70
151
  // Base64 encode the packed string for safe JSON transmission
71
152
  const encodedEvents = btoa(packedEvents);
72
153
  const payload = {
73
- sessionId: sessionIdRef.current,
154
+ session_id: sessionIdRef.current,
74
155
  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
156
  };
157
+ const url = `${basePath}/${SESSION_RECORDER_ENDPOINT}/events`;
84
158
  if (isReliable) {
85
- sendAnalyticsReliable(SESSION_RECORDER_ENDPOINT, payload, basePath);
159
+ // Use sendBeacon for reliable sending on page unload
160
+ if (navigator.sendBeacon) {
161
+ const blob = new Blob([JSON.stringify(payload)], { type: "application/json" });
162
+ const sent = navigator.sendBeacon(url, blob);
163
+ if (!sent) {
164
+ // Fallback to fetch with keepalive
165
+ await fetch(url, {
166
+ method: "POST",
167
+ headers: { "Content-Type": "application/json" },
168
+ body: JSON.stringify(payload),
169
+ keepalive: true,
170
+ });
171
+ }
172
+ }
173
+ else {
174
+ // Fallback to fetch with keepalive
175
+ await fetch(url, {
176
+ method: "POST",
177
+ headers: { "Content-Type": "application/json" },
178
+ body: JSON.stringify(payload),
179
+ keepalive: true,
180
+ });
181
+ }
86
182
  }
87
183
  else {
88
- await sendAnalytics(SESSION_RECORDER_ENDPOINT, payload, "POST", basePath);
184
+ const response = await fetch(url, {
185
+ method: "POST",
186
+ headers: { "Content-Type": "application/json" },
187
+ body: JSON.stringify(payload),
188
+ });
189
+ if (response.status === 404) {
190
+ // Session not found, mark as not initialized but don't auto-reinitialize
191
+ console.error("[SessionRecorder] Session not found on server, stopping recording");
192
+ sessionInitializedRef.current = false;
193
+ sessionIdRef.current = "";
194
+ // Clear the session from localStorage
195
+ if (typeof localStorage !== "undefined") {
196
+ localStorage.removeItem("currentRecordingSessionId");
197
+ }
198
+ // Stop recording to prevent further errors
199
+ if (stopFnRef.current) {
200
+ stopFnRef.current();
201
+ stopFnRef.current = null;
202
+ }
203
+ // Don't restore events - they're lost
204
+ }
205
+ else if (!response.ok) {
206
+ console.error("[SessionRecorder] Failed to send events:", response.status);
207
+ // Restore events on failure
208
+ eventsRef.current.unshift(...eventsToSend);
209
+ }
89
210
  }
90
211
  }
91
212
  catch (error) {
92
- console.error("Failed to send session events:", error);
213
+ console.error("[SessionRecorder] Failed to send session events:", error);
93
214
  // Restore events on failure
94
215
  eventsRef.current.unshift(...eventsToSend);
95
216
  }
96
- }, [basePath, domain]);
217
+ }, [basePath, initializeSession]);
97
218
  const scheduleFlush = useCallback(() => {
98
219
  if (flushTimeoutRef.current) {
99
220
  clearTimeout(flushTimeoutRef.current);
@@ -102,18 +223,22 @@ export function SessionRecorder({ basePath = "/api/_temps", domain, enabled = fa
102
223
  sendEvents(false);
103
224
  }, flushInterval);
104
225
  }, [sendEvents, flushInterval]);
105
- const startRecording = useCallback(() => {
226
+ const startRecording = useCallback(async () => {
106
227
  if (stopFnRef.current)
107
228
  return; // Already recording
108
229
  if (!shouldRecord())
109
230
  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);
231
+ // Reset retry counter for new recording session
232
+ if (!sessionInitializedRef.current) {
233
+ initRetryCountRef.current = 0;
234
+ }
235
+ // Initialize session first
236
+ const initialized = await initializeSession();
237
+ if (!initialized) {
238
+ console.error("[SessionRecorder] Failed to initialize session, not starting recording");
239
+ return;
116
240
  }
241
+ eventsRef.current = [];
117
242
  const stopFn = record({
118
243
  emit(event) {
119
244
  eventsRef.current.push(event);
@@ -142,7 +267,7 @@ export function SessionRecorder({ basePath = "/api/_temps", domain, enabled = fa
142
267
  }
143
268
  // Start the flush interval
144
269
  scheduleFlush();
145
- }, [shouldRecord, sendEvents, scheduleFlush, batchSize, recordCanvas, collectFonts, maskAllInputs, maskTextSelector, blockClass, ignoreClass, maskTextClass, slimDOMOptions]);
270
+ }, [shouldRecord, initializeSession, sendEvents, scheduleFlush, batchSize, recordCanvas, collectFonts, maskAllInputs, maskTextSelector, blockClass, ignoreClass, maskTextClass, slimDOMOptions]);
146
271
  const stopRecording = useCallback(() => {
147
272
  if (stopFnRef.current) {
148
273
  stopFnRef.current();
@@ -154,6 +279,9 @@ export function SessionRecorder({ basePath = "/api/_temps", domain, enabled = fa
154
279
  }
155
280
  // Send any remaining events reliably
156
281
  sendEvents(true);
282
+ // Clear session state
283
+ sessionInitializedRef.current = false;
284
+ sessionIdRef.current = "";
157
285
  // Clear session ID from localStorage
158
286
  if (typeof localStorage !== "undefined") {
159
287
  localStorage.removeItem("currentRecordingSessionId");
@@ -187,7 +315,10 @@ export function SessionRecorder({ basePath = "/api/_temps", domain, enabled = fa
187
315
  return;
188
316
  }
189
317
  const currentPath = window.location.pathname;
190
- const isExcluded = excludedPaths.some(path => currentPath.startsWith(path));
318
+ const isExcluded = excludedPaths.some(path => {
319
+ const regex = new RegExp(`^${path.replace(/\*/g, '.*')}$`);
320
+ return regex.test(currentPath);
321
+ });
191
322
  if (isExcluded && stopFnRef.current) {
192
323
  stopRecording();
193
324
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@temps-sdk/react-analytics",
3
- "version": "0.0.1-beta.16",
3
+ "version": "0.0.1-beta.18",
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
  },