@temps-sdk/analytics-core 0.0.2 → 0.0.6

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,22 +1,32 @@
1
+ // SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ // SPDX-License-Identifier: MIT OR Apache-2.0
1
3
  import { record } from "rrweb";
2
4
  import { pack } from "@rrweb/packer";
3
5
  import { SESSION_RECORDER_ENDPOINT, DEFAULT_BASE_PATH, DEFAULT_EXCLUDED_PATHS } from "./constants";
4
- function generateSessionId() {
6
+ import { getOrCreateVisitorId } from "./identity";
7
+ import { beaconBlob, ingestKeyHeaders, withIngestKey } from "./utils";
8
+ /** Interaction that counts as the visitor still being present. */
9
+ const ACTIVITY_EVENTS = [
10
+ "pointerdown",
11
+ "keydown",
12
+ "scroll",
13
+ "touchstart",
14
+ "wheel",
15
+ "mousemove",
16
+ ];
17
+ /** Upper bound on how often the idle check runs, regardless of `idleTimeout`. */
18
+ const IDLE_CHECK_CEILING_MS = 15000;
19
+ function randomId(prefix) {
5
20
  if (typeof crypto !== "undefined" && crypto.randomUUID) {
6
21
  return crypto.randomUUID();
7
22
  }
8
- return `session_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
23
+ return `${prefix}_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
9
24
  }
10
- function generateVisitorId() {
11
- if (typeof localStorage !== "undefined") {
12
- let visitorId = localStorage.getItem("temps_visitor_id");
13
- if (!visitorId) {
14
- visitorId = `visitor_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
15
- localStorage.setItem("temps_visitor_id", visitorId);
16
- }
17
- return visitorId;
18
- }
19
- return `visitor_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
25
+ function generateSessionId() {
26
+ return randomId("session");
27
+ }
28
+ function generateBatchId() {
29
+ return randomId("batch");
20
30
  }
21
31
  function matchesAnyPath(currentPath, paths) {
22
32
  return paths.some((path) => {
@@ -24,13 +34,37 @@ function matchesAnyPath(currentPath, paths) {
24
34
  return regex.test(currentPath);
25
35
  });
26
36
  }
37
+ /**
38
+ * Mirror the active session id into `localStorage` for the React
39
+ * `SessionRecordingProvider`. Best effort: storage may be blocked or full, and
40
+ * a failed write must not look like a failed session init (the server session
41
+ * already exists by then).
42
+ */
43
+ function rememberRecordingSessionId(sessionId) {
44
+ try {
45
+ if (typeof localStorage === "undefined")
46
+ return;
47
+ if (sessionId === null)
48
+ localStorage.removeItem("currentRecordingSessionId");
49
+ else
50
+ localStorage.setItem("currentRecordingSessionId", sessionId);
51
+ }
52
+ catch {
53
+ // Nothing reads it for correctness; see above.
54
+ }
55
+ }
27
56
  function getSessionMetadata() {
28
57
  if (typeof window === "undefined")
29
58
  return {};
30
59
  const screen = window.screen || {};
31
60
  const nav = window.navigator || {};
32
61
  return {
33
- visitorId: generateVisitorId(),
62
+ // `getOrCreateVisitorId()` returns `undefined` when `localStorage` is
63
+ // unavailable (private-browsing modes, storage-partitioned iframes). Fall
64
+ // back to an ephemeral id rather than sending no visitor identity at all
65
+ // — it won't survive a reload, but that's strictly better than a session
66
+ // recording with zero visitor attribution.
67
+ visitorId: getOrCreateVisitorId() ?? randomId("visitor"),
34
68
  userAgent: nav.userAgent,
35
69
  language: nav.language,
36
70
  timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
@@ -46,15 +80,25 @@ function getSessionMetadata() {
46
80
  /**
47
81
  * Framework-agnostic rrweb wrapper. Call `start()` to begin recording and
48
82
  * `stop()` to end. `destroy()` removes all listeners and flushes pending events.
83
+ *
84
+ * Recording pauses while the visitor is idle or the tab is hidden, and resumes
85
+ * on the next interaction with a fresh full snapshot. rrweb records DOM
86
+ * mutations rather than user actions, so without that gate a page that animates
87
+ * or mutates on a timer produces events indefinitely from a visitor who is
88
+ * doing nothing at all.
49
89
  */
50
90
  export class SessionRecorder {
51
91
  constructor(options = {}) {
92
+ /** Failure kinds already reported, so a failing endpoint warns once. */
93
+ this.reportedFailures = new Set();
52
94
  this.stopFn = null;
53
95
  this.takeSnapshot = null;
54
- this.events = [];
96
+ this.pending = [];
97
+ this.inflight = null;
55
98
  this.sessionId = "";
56
99
  this.sessionInitialized = false;
57
100
  this.flushTimer = null;
101
+ this.idleTimer = null;
58
102
  this.initRetryCount = 0;
59
103
  this.initFailed = false;
60
104
  this.maxInitRetries = 3;
@@ -62,15 +106,48 @@ export class SessionRecorder {
62
106
  this.maxSendRetries = 5;
63
107
  this.lastSendAttempt = 0;
64
108
  this.isSending = false;
109
+ this.starting = false;
110
+ /**
111
+ * Bumped by every `stopRecording`. `startRecording` captures it before
112
+ * awaiting session init and re-checks afterwards: a stop that lands while
113
+ * init is in flight cannot clean up state that does not exist yet, so the
114
+ * starter has to notice it was superseded and release the session itself.
115
+ */
116
+ this.stopGeneration = 0;
117
+ this.paused = false;
118
+ this.lastActivityAt = Date.now();
119
+ this.droppedEvents = 0;
120
+ /**
121
+ * Sampling verdict for this recorder, decided once. Re-rolling per call (the
122
+ * previous behaviour) let a recorded session flip itself off on any later
123
+ * path check or resume.
124
+ */
125
+ this.sampleDecision = null;
65
126
  this.originalPushState = null;
66
127
  this.originalReplaceState = null;
128
+ this.globalListenersAttached = false;
129
+ this.handleActivity = () => {
130
+ this.lastActivityAt = Date.now();
131
+ if (this.paused)
132
+ this.resumeRecording();
133
+ };
134
+ this.handleVisibilityChange = () => {
135
+ if (!this.pauseOnHidden)
136
+ return;
137
+ if (document.visibilityState === "hidden") {
138
+ this.pauseRecording();
139
+ }
140
+ else {
141
+ this.handleActivity();
142
+ }
143
+ };
67
144
  this.handleUnload = () => {
68
- if (this.sessionInitialized && this.events.length > 0) {
145
+ if (this.sessionInitialized && this.hasBufferedEvents()) {
69
146
  void this.sendEvents(true);
70
147
  }
71
148
  };
72
149
  this.handlePopState = () => {
73
- if (this.stopFn && this.events.length > 0)
150
+ if (this.stopFn && this.hasBufferedEvents())
74
151
  void this.sendEvents(false);
75
152
  setTimeout(() => {
76
153
  this.checkPath();
@@ -79,6 +156,7 @@ export class SessionRecorder {
79
156
  }, 100);
80
157
  };
81
158
  this.basePath = options.basePath || DEFAULT_BASE_PATH;
159
+ this.ingestKey = options.ingestKey;
82
160
  this.excludedPaths =
83
161
  options.useDefaultExcludedPaths === false
84
162
  ? options.excludedPaths || []
@@ -95,6 +173,11 @@ export class SessionRecorder {
95
173
  this.collectFonts = options.collectFonts ?? true;
96
174
  this.batchSize = options.batchSize ?? 100;
97
175
  this.flushInterval = options.flushInterval ?? 10000;
176
+ this.idleTimeout = options.idleTimeout ?? 60000;
177
+ this.pauseOnHidden = options.pauseOnHidden ?? true;
178
+ this.checkoutEveryNms = options.checkoutEveryNms ?? 30000;
179
+ this.checkoutEveryNth = options.checkoutEveryNth ?? 200;
180
+ this.maxBufferedEvents = options.maxBufferedEvents ?? 5000;
98
181
  this.slimDOMOptions = options.slimDOMOptions || {
99
182
  script: false,
100
183
  comment: true,
@@ -126,22 +209,55 @@ export class SessionRecorder {
126
209
  input: "last",
127
210
  ...(options.sampling || {}),
128
211
  };
212
+ this.debug = options.debug ?? false;
129
213
  this.enabled = options.enabled ?? false;
130
214
  if (this.enabled && typeof window !== "undefined") {
131
215
  this.start();
132
216
  }
133
217
  }
218
+ /** Sampling verdict, decided once per recorder and then cached. */
219
+ passesSampling() {
220
+ if (this.sampleDecision === null) {
221
+ this.sampleDecision = this.sessionSampleRate >= 1.0 || Math.random() <= this.sessionSampleRate;
222
+ }
223
+ return this.sampleDecision;
224
+ }
134
225
  shouldRecord() {
135
226
  if (!this.enabled || typeof window === "undefined")
136
227
  return false;
137
- const currentPath = window.location.pathname;
138
- const isExcluded = matchesAnyPath(currentPath, this.excludedPaths);
139
- if (isExcluded)
228
+ if (matchesAnyPath(window.location.pathname, this.excludedPaths)) {
229
+ this.debugLog(`not recording ${window.location.pathname}: excluded path`);
140
230
  return false;
141
- if (this.sessionSampleRate < 1.0 && Math.random() > this.sessionSampleRate)
231
+ }
232
+ if (!this.passesSampling()) {
233
+ this.debugLog(`not recording: sampled out (sessionSampleRate ${this.sessionSampleRate})`);
142
234
  return false;
235
+ }
143
236
  return true;
144
237
  }
238
+ /**
239
+ * Report a failed session-replay request. Without `debug`, each kind is
240
+ * reported once per recorder, as a warning: an unreachable endpoint must not
241
+ * print an error into every visitor's console on every retry, but a
242
+ * rejected request (a wrong ingest key, say) must not be silent either.
243
+ */
244
+ reportFailure(kind, detail) {
245
+ if (!this.debug) {
246
+ if (this.reportedFailures.has(kind))
247
+ return;
248
+ this.reportedFailures.add(kind);
249
+ }
250
+ // eslint-disable-next-line no-console
251
+ console.warn(`[SessionRecorder] session replay ${kind} failed:`, detail, ...(this.debug
252
+ ? []
253
+ : ["(reported once; set sessionRecordingConfig.debug to log every failure)"]));
254
+ }
255
+ debugLog(message, ...details) {
256
+ if (!this.debug)
257
+ return;
258
+ // eslint-disable-next-line no-console
259
+ console.debug(`[SessionRecorder] ${message}`, ...details);
260
+ }
145
261
  async initializeSession() {
146
262
  if (this.sessionInitialized)
147
263
  return true;
@@ -156,36 +272,58 @@ export class SessionRecorder {
156
272
  this.sessionId = sessionId;
157
273
  try {
158
274
  const metadata = { sessionId, ...getSessionMetadata() };
159
- const response = await fetch(`${this.basePath}/${SESSION_RECORDER_ENDPOINT}/init`, {
275
+ const initUrl = `${this.basePath}/${SESSION_RECORDER_ENDPOINT}/init`;
276
+ const response = await fetch(initUrl, {
160
277
  method: "POST",
161
- headers: { "Content-Type": "application/json" },
278
+ headers: {
279
+ "Content-Type": "application/json",
280
+ ...ingestKeyHeaders(this.ingestKey),
281
+ },
162
282
  body: JSON.stringify(metadata),
163
283
  });
164
- if (response.status === 201) {
284
+ // Any 2xx, like the events endpoint: the server answers 201, but a
285
+ // same-origin proxy may relay it as 200. Accepting only 201 made every
286
+ // retry create another server-side session while recording nothing.
287
+ if (response.ok) {
165
288
  this.sessionInitialized = true;
166
289
  this.initRetryCount = 0;
167
290
  this.initFailed = false;
168
- if (typeof localStorage !== "undefined") {
169
- localStorage.setItem("currentRecordingSessionId", sessionId);
170
- }
291
+ rememberRecordingSessionId(sessionId);
292
+ this.debugLog("session started", sessionId);
171
293
  return true;
172
294
  }
295
+ this.reportFailure("init", `HTTP ${response.status} from ${initUrl}`);
173
296
  this.sessionId = "";
174
297
  if (this.initRetryCount >= this.maxInitRetries)
175
298
  this.initFailed = true;
176
299
  return false;
177
300
  }
178
301
  catch (error) {
179
- // eslint-disable-next-line no-console
180
- console.error("[SessionRecorder] init failed:", error);
302
+ this.reportFailure("init", error);
181
303
  this.sessionId = "";
182
304
  if (this.initRetryCount >= this.maxInitRetries)
183
305
  this.initFailed = true;
184
306
  return false;
185
307
  }
186
308
  }
309
+ /**
310
+ * Claim the batch to transmit. A batch still in flight is returned unchanged
311
+ * so a retry is byte-identical to the attempt that failed; otherwise the
312
+ * pending buffer is drained into a new, immutable batch.
313
+ */
314
+ claimBatch() {
315
+ if (this.inflight)
316
+ return this.inflight;
317
+ if (this.pending.length === 0)
318
+ return null;
319
+ this.inflight = {
320
+ batchId: generateBatchId(),
321
+ events: this.pending.splice(0, this.pending.length),
322
+ };
323
+ return this.inflight;
324
+ }
187
325
  async sendEvents(isReliable = false) {
188
- if (!this.sessionInitialized || this.events.length === 0)
326
+ if (!this.sessionInitialized)
189
327
  return;
190
328
  if (this.isSending && !isReliable)
191
329
  return;
@@ -195,19 +333,31 @@ export class SessionRecorder {
195
333
  if (now - this.lastSendAttempt < backoff)
196
334
  return;
197
335
  }
336
+ const batch = this.claimBatch();
337
+ if (!batch)
338
+ return;
198
339
  this.isSending = true;
199
340
  this.lastSendAttempt = now;
200
- const eventsToSend = [...this.events];
201
341
  try {
202
- const packed = pack(eventsToSend);
342
+ const packed = pack(batch.events);
203
343
  const encodedEvents = btoa(packed);
204
- const payload = { sessionId: this.sessionId, events: encodedEvents };
344
+ const payload = {
345
+ sessionId: this.sessionId,
346
+ batchId: batch.batchId,
347
+ events: encodedEvents,
348
+ };
205
349
  const url = `${this.basePath}/${SESSION_RECORDER_ENDPOINT}/events`;
350
+ // The unload path cannot set headers (sendBeacon) and must not trigger a
351
+ // CORS preflight (keepalive fetch), so it carries the ingest key in the
352
+ // query string instead. Identical to `url` when no key is configured.
353
+ const unloadUrl = withIngestKey(url, this.ingestKey);
206
354
  if (isReliable) {
355
+ // sendBeacon reports queueing, not delivery, so there is no ack to wait
356
+ // for: release the batch and accept the small risk of loss on unload.
207
357
  if (navigator.sendBeacon) {
208
- const blob = new Blob([JSON.stringify(payload)], { type: "application/json" });
209
- if (!navigator.sendBeacon(url, blob)) {
210
- await fetch(url, {
358
+ const blob = beaconBlob(JSON.stringify(payload), this.ingestKey);
359
+ if (!navigator.sendBeacon(unloadUrl, blob)) {
360
+ await fetch(unloadUrl, {
211
361
  method: "POST",
212
362
  headers: { "Content-Type": "application/json" },
213
363
  body: JSON.stringify(payload),
@@ -216,51 +366,53 @@ export class SessionRecorder {
216
366
  }
217
367
  }
218
368
  else {
219
- await fetch(url, {
369
+ await fetch(unloadUrl, {
220
370
  method: "POST",
221
371
  headers: { "Content-Type": "application/json" },
222
372
  body: JSON.stringify(payload),
223
373
  keepalive: true,
224
374
  });
225
375
  }
226
- this.events = [];
376
+ this.inflight = null;
227
377
  this.sendRetryCount = 0;
228
378
  }
229
379
  else {
230
380
  const response = await fetch(url, {
231
381
  method: "POST",
232
- headers: { "Content-Type": "application/json" },
382
+ headers: {
383
+ "Content-Type": "application/json",
384
+ ...ingestKeyHeaders(this.ingestKey),
385
+ },
233
386
  body: JSON.stringify(payload),
234
387
  });
235
388
  if (response.status === 404) {
236
- this.sessionInitialized = false;
237
- this.sessionId = "";
238
- if (typeof localStorage !== "undefined") {
239
- localStorage.removeItem("currentRecordingSessionId");
240
- }
389
+ this.debugLog("the server no longer knows this session; recording stopped");
390
+ this.clearSession();
241
391
  this.stopRecording();
242
- this.events = [];
392
+ this.inflight = null;
393
+ this.pending = [];
243
394
  this.sendRetryCount = 0;
244
395
  }
245
396
  else if (!response.ok) {
397
+ this.reportFailure("upload", `HTTP ${response.status} from ${url}`);
246
398
  this.sendRetryCount++;
399
+ // The batch stays in flight so the next attempt resends it verbatim.
247
400
  if (this.sendRetryCount >= this.maxSendRetries) {
248
- this.events = [];
401
+ this.inflight = null;
249
402
  this.sendRetryCount = 0;
250
403
  }
251
404
  }
252
405
  else {
253
- this.events = [];
406
+ this.inflight = null;
254
407
  this.sendRetryCount = 0;
255
408
  }
256
409
  }
257
410
  }
258
411
  catch (error) {
259
- // eslint-disable-next-line no-console
260
- console.error("[SessionRecorder] send failed:", error);
412
+ this.reportFailure("upload", error);
261
413
  this.sendRetryCount++;
262
414
  if (this.sendRetryCount >= this.maxSendRetries) {
263
- this.events = [];
415
+ this.inflight = null;
264
416
  this.sendRetryCount = 0;
265
417
  }
266
418
  }
@@ -268,76 +420,165 @@ export class SessionRecorder {
268
420
  this.isSending = false;
269
421
  }
270
422
  }
271
- scheduleFlush() {
423
+ /** True while there is anything left to transmit. */
424
+ hasBufferedEvents() {
425
+ return this.pending.length > 0 || this.inflight !== null;
426
+ }
427
+ startFlushTimer() {
272
428
  if (this.flushTimer)
273
- clearTimeout(this.flushTimer);
274
- this.flushTimer = setTimeout(() => {
275
- if (this.events.length > 0)
429
+ return;
430
+ this.flushTimer = setInterval(() => {
431
+ if (this.hasBufferedEvents())
276
432
  void this.sendEvents(false);
277
- this.scheduleFlush();
278
433
  }, this.flushInterval);
279
434
  }
435
+ stopFlushTimer() {
436
+ if (!this.flushTimer)
437
+ return;
438
+ clearInterval(this.flushTimer);
439
+ this.flushTimer = null;
440
+ }
441
+ startIdleTimer() {
442
+ if (this.idleTimer || this.idleTimeout <= 0)
443
+ return;
444
+ const tick = Math.min(this.idleTimeout, IDLE_CHECK_CEILING_MS);
445
+ this.idleTimer = setInterval(() => {
446
+ if (this.paused || !this.stopFn)
447
+ return;
448
+ if (Date.now() - this.lastActivityAt >= this.idleTimeout)
449
+ this.pauseRecording();
450
+ }, tick);
451
+ }
452
+ stopIdleTimer() {
453
+ if (!this.idleTimer)
454
+ return;
455
+ clearInterval(this.idleTimer);
456
+ this.idleTimer = null;
457
+ }
280
458
  async startRecording() {
281
- if (this.stopFn || this.initFailed)
459
+ // `stopFn` is only assigned after the await below, so it cannot on its own
460
+ // keep a second caller out of this function. Without `starting`, anything
461
+ // that calls in during session init — a framework router touching
462
+ // `replaceState`, say — attaches a second rrweb recorder to the same page
463
+ // and every event is captured twice.
464
+ if (this.stopFn || this.initFailed || this.starting)
282
465
  return;
283
466
  if (!this.shouldRecord())
284
467
  return;
285
- const ok = await this.initializeSession();
286
- if (!ok)
287
- return;
288
- const stopFn = record({
289
- emit: (event) => {
290
- this.events.push(event);
291
- if (this.events.length >= this.batchSize) {
292
- void this.sendEvents(false);
293
- this.scheduleFlush();
294
- }
295
- },
296
- sampling: this.samplingConfig,
297
- blockSelector: this.blockSelector,
298
- ignoreSelector: this.ignoreSelector,
299
- recordCanvas: this.recordCanvas,
300
- collectFonts: this.collectFonts,
301
- maskAllInputs: this.maskAllInputs,
302
- maskInputOptions: this.maskInputOptions,
303
- maskTextSelector: this.maskTextSelector,
304
- blockClass: this.blockClass,
305
- ignoreClass: this.ignoreClass,
306
- maskTextClass: this.maskTextClass,
307
- slimDOMOptions: this.slimDOMOptions,
308
- checkoutEveryNms: 30000,
309
- checkoutEveryNth: 200,
310
- });
311
- if (stopFn) {
312
- this.stopFn = stopFn;
313
- const exposed = stopFn;
314
- this.takeSnapshot = exposed.takeFullSnapshot || null;
468
+ this.starting = true;
469
+ const generation = this.stopGeneration;
470
+ try {
471
+ const ok = await this.initializeSession();
472
+ if (!ok)
473
+ return;
474
+ // A stop()/destroy() during init — a StrictMode double-mount, or the
475
+ // React binding's effect cleanup — returned before this session existed,
476
+ // so it could not tear it down. Release it here instead of leaving a
477
+ // server-side session that never receives an event.
478
+ if (this.stopGeneration !== generation || this.stopFn || !this.enabled) {
479
+ this.clearSession();
480
+ return;
481
+ }
482
+ const stopFn = record({
483
+ emit: (event) => {
484
+ this.pending.push(event);
485
+ if (this.pending.length > this.maxBufferedEvents) {
486
+ const overflow = this.pending.length - this.maxBufferedEvents;
487
+ this.pending.splice(0, overflow);
488
+ this.droppedEvents += overflow;
489
+ }
490
+ if (this.pending.length >= this.batchSize)
491
+ void this.sendEvents(false);
492
+ },
493
+ sampling: this.samplingConfig,
494
+ blockSelector: this.blockSelector,
495
+ ignoreSelector: this.ignoreSelector,
496
+ recordCanvas: this.recordCanvas,
497
+ collectFonts: this.collectFonts,
498
+ maskAllInputs: this.maskAllInputs,
499
+ maskInputOptions: this.maskInputOptions,
500
+ maskTextSelector: this.maskTextSelector,
501
+ blockClass: this.blockClass,
502
+ ignoreClass: this.ignoreClass,
503
+ maskTextClass: this.maskTextClass,
504
+ slimDOMOptions: this.slimDOMOptions,
505
+ checkoutEveryNms: this.checkoutEveryNms,
506
+ checkoutEveryNth: this.checkoutEveryNth,
507
+ });
508
+ if (stopFn) {
509
+ this.stopFn = stopFn;
510
+ const exposed = stopFn;
511
+ this.takeSnapshot = exposed.takeFullSnapshot || null;
512
+ }
513
+ this.paused = false;
514
+ this.lastActivityAt = Date.now();
515
+ this.startFlushTimer();
516
+ this.startIdleTimer();
517
+ }
518
+ finally {
519
+ this.starting = false;
315
520
  }
316
- this.scheduleFlush();
317
521
  }
318
- stopRecording() {
522
+ /** Forget the server session and any client state pointing at it. */
523
+ clearSession() {
524
+ this.sessionInitialized = false;
525
+ this.sessionId = "";
526
+ rememberRecordingSessionId(null);
527
+ }
528
+ detachRecorder() {
319
529
  if (!this.stopFn)
320
530
  return;
321
531
  this.stopFn();
322
532
  this.stopFn = null;
323
- if (this.flushTimer) {
324
- clearTimeout(this.flushTimer);
325
- this.flushTimer = null;
326
- }
533
+ this.takeSnapshot = null;
534
+ }
535
+ /**
536
+ * Suspend recording without ending the session. rrweb is detached so a
537
+ * passive page emits nothing at all; `resumeRecording` reattaches and rrweb
538
+ * emits a fresh full snapshot, which is what replay needs to resync after
539
+ * the gap.
540
+ */
541
+ pauseRecording() {
542
+ if (this.paused || !this.stopFn)
543
+ return;
544
+ this.debugLog("paused (idle or hidden tab)");
545
+ this.detachRecorder();
546
+ this.paused = true;
547
+ this.stopFlushTimer();
548
+ if (this.hasBufferedEvents())
549
+ void this.sendEvents(false);
550
+ }
551
+ resumeRecording() {
552
+ if (!this.paused || !this.enabled || this.initFailed)
553
+ return;
554
+ this.debugLog("resumed");
555
+ this.paused = false;
556
+ void this.startRecording();
557
+ }
558
+ stopRecording() {
559
+ // `starting` and `sessionInitialized` are part of the condition: guarding
560
+ // on `stopFn` alone skipped cleanup entirely while init was in flight,
561
+ // stranding the session it was about to create.
562
+ if (!this.stopFn && !this.paused && !this.starting && !this.sessionInitialized)
563
+ return;
564
+ this.stopGeneration++;
565
+ this.detachRecorder();
566
+ this.stopFlushTimer();
567
+ this.stopIdleTimer();
568
+ this.paused = false;
327
569
  void this.sendEvents(true);
328
- this.sessionInitialized = false;
329
- this.sessionId = "";
330
- if (typeof localStorage !== "undefined") {
331
- localStorage.removeItem("currentRecordingSessionId");
332
- }
570
+ this.clearSession();
333
571
  this.initRetryCount = 0;
334
572
  this.initFailed = false;
335
573
  }
336
- wrapHistory() {
574
+ attachGlobalListeners() {
575
+ if (this.globalListenersAttached)
576
+ return;
577
+ this.globalListenersAttached = true;
337
578
  this.originalPushState = window.history.pushState;
338
579
  this.originalReplaceState = window.history.replaceState;
339
580
  const flushAndCheck = () => {
340
- if (this.stopFn && this.events.length > 0)
581
+ if (this.stopFn && this.hasBufferedEvents())
341
582
  void this.sendEvents(false);
342
583
  setTimeout(() => {
343
584
  this.checkPath();
@@ -356,6 +597,32 @@ export class SessionRecorder {
356
597
  window.addEventListener("popstate", this.handlePopState);
357
598
  window.addEventListener("beforeunload", this.handleUnload);
358
599
  window.addEventListener("pagehide", this.handleUnload);
600
+ document.addEventListener("visibilitychange", this.handleVisibilityChange);
601
+ // These stay attached while paused — they are how a paused recorder learns
602
+ // the visitor came back.
603
+ for (const name of ACTIVITY_EVENTS) {
604
+ window.addEventListener(name, this.handleActivity, { passive: true, capture: true });
605
+ }
606
+ }
607
+ detachGlobalListeners() {
608
+ if (!this.globalListenersAttached)
609
+ return;
610
+ this.globalListenersAttached = false;
611
+ if (this.originalPushState) {
612
+ window.history.pushState = this.originalPushState;
613
+ this.originalPushState = null;
614
+ }
615
+ if (this.originalReplaceState) {
616
+ window.history.replaceState = this.originalReplaceState;
617
+ this.originalReplaceState = null;
618
+ }
619
+ window.removeEventListener("popstate", this.handlePopState);
620
+ window.removeEventListener("beforeunload", this.handleUnload);
621
+ window.removeEventListener("pagehide", this.handleUnload);
622
+ document.removeEventListener("visibilitychange", this.handleVisibilityChange);
623
+ for (const name of ACTIVITY_EVENTS) {
624
+ window.removeEventListener(name, this.handleActivity, { capture: true });
625
+ }
359
626
  }
360
627
  checkPath() {
361
628
  if (!this.enabled || this.initFailed) {
@@ -363,13 +630,14 @@ export class SessionRecorder {
363
630
  this.stopRecording();
364
631
  return;
365
632
  }
366
- const currentPath = window.location.pathname;
367
- const isExcluded = matchesAnyPath(currentPath, this.excludedPaths);
633
+ const isExcluded = matchesAnyPath(window.location.pathname, this.excludedPaths);
368
634
  const isRecording = this.stopFn !== null;
635
+ if (isExcluded)
636
+ this.debugLog(`not recording ${window.location.pathname}: excluded path`);
369
637
  if (isExcluded && isRecording) {
370
638
  this.stopRecording();
371
639
  }
372
- else if (!isExcluded && !isRecording && !this.initFailed) {
640
+ else if (!isExcluded && !isRecording && !this.paused) {
373
641
  void this.startRecording();
374
642
  }
375
643
  }
@@ -379,8 +647,7 @@ export class SessionRecorder {
379
647
  this.enabled = true;
380
648
  if (typeof window === "undefined")
381
649
  return;
382
- if (!this.originalPushState)
383
- this.wrapHistory();
650
+ this.attachGlobalListeners();
384
651
  void this.startRecording();
385
652
  }
386
653
  stop() {
@@ -389,19 +656,18 @@ export class SessionRecorder {
389
656
  }
390
657
  destroy() {
391
658
  this.stop();
392
- if (this.originalPushState) {
393
- window.history.pushState = this.originalPushState;
394
- this.originalPushState = null;
395
- }
396
- if (this.originalReplaceState) {
397
- window.history.replaceState = this.originalReplaceState;
398
- this.originalReplaceState = null;
399
- }
400
- window.removeEventListener("popstate", this.handlePopState);
401
- window.removeEventListener("beforeunload", this.handleUnload);
402
- window.removeEventListener("pagehide", this.handleUnload);
659
+ this.stopIdleTimer();
660
+ this.detachGlobalListeners();
403
661
  }
404
662
  getSessionId() {
405
663
  return this.sessionId || null;
406
664
  }
665
+ /** Events discarded because the buffer hit `maxBufferedEvents`. */
666
+ getDroppedEventCount() {
667
+ return this.droppedEvents;
668
+ }
669
+ /** Whether recording is currently suspended for idleness or a hidden tab. */
670
+ isPaused() {
671
+ return this.paused;
672
+ }
407
673
  }