@sentry/replay 0.6.9 → 0.6.10

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/index.js CHANGED
@@ -444,6 +444,16 @@ function createSession(_a) {
444
444
  return session;
445
445
  }
446
446
 
447
+ /**
448
+ * Captures exceptions to Sentry only when it occurs on sentry.io
449
+ */
450
+ function captureInternalException(err) {
451
+ if (!isInternal()) {
452
+ return;
453
+ }
454
+ core.captureException(err);
455
+ }
456
+
447
457
  /**
448
458
  * Fetches a session from storage
449
459
  */
@@ -452,10 +462,17 @@ function fetchSession() {
452
462
  if (!hasSessionStorage) {
453
463
  return null;
454
464
  }
465
+ var sessionStringFromStorage = window.sessionStorage.getItem(REPLAY_SESSION_KEY);
466
+ if (!sessionStringFromStorage) {
467
+ return null;
468
+ }
455
469
  try {
456
- return new Session(
457
- // @ts-expect-error: Type 'null' is not assignable to type 'string'.ts(2345)
458
- JSON.parse(window.sessionStorage.getItem(REPLAY_SESSION_KEY)),
470
+ var sessionObj = JSON.parse(sessionStringFromStorage);
471
+ // NOTE: This shouldn't happen
472
+ if (sessionObj.segmentId === 0) {
473
+ captureInternalException(new Error('Session storage object with segmentId = 0'));
474
+ }
475
+ return new Session(sessionObj,
459
476
  // We are assuming that if there is a saved item, then the session is sticky,
460
477
  // however this could break down if we used a different storage mechanism (e.g. localstorage)
461
478
  { stickySession: true });
@@ -473,8 +490,9 @@ function getSession(_a) {
473
490
  // If session exists and is passed, use it instead of always hitting session storage
474
491
  var session = currentSession || (stickySession && fetchSession());
475
492
  if (session) {
476
- // If there is a session, check if it is valid (e.g. "last activity" time should be within the "session idle time")
477
- // TODO: We should probably set a max age on this as well
493
+ // If there is a session, check if it is valid (e.g. "last activity" time
494
+ // should be within the "session idle time", and "session started" time is
495
+ // within "max session time").
478
496
  var isExpired = isSessionExpired(session, expiry);
479
497
  if (!isExpired) {
480
498
  return { type: 'saved', session: session };
@@ -499,16 +517,6 @@ function addInternalBreadcrumb(arg) {
499
517
  core.addBreadcrumb(__assign({ category: category || 'console', level: level || 'debug', message: "[debug]: ".concat(message) }, rest));
500
518
  }
501
519
 
502
- /**
503
- * Captures exceptions to Sentry only when it occurs on sentry.io
504
- */
505
- function captureInternalException(err) {
506
- if (!isInternal()) {
507
- return;
508
- }
509
- core.captureException(err);
510
- }
511
-
512
520
  function createPayload(_a) {
513
521
  var events = _a.events, headers = _a.headers;
514
522
  var payloadWithSequence;
@@ -921,16 +929,22 @@ var Replay = /** @class */ (function () {
921
929
  this.performanceObserver = null;
922
930
  this.retryCount = 0;
923
931
  this.retryInterval = BASE_RETRY_INTERVAL;
932
+ this.flushLock = null;
924
933
  /**
925
- * Flag when a new session has been created. Captured replay events behave
926
- * slightly differently in this case: `replay_start_timestamp` is included.
934
+ * Timestamp of the last user activity. This lives across sessions.
927
935
  */
928
- this.newSessionCreated = false;
929
- this.flushLock = null;
936
+ this.lastActivity = new Date().getTime();
930
937
  /**
931
938
  * Is the integration currently active?
932
939
  */
933
940
  this.isEnabled = false;
941
+ /**
942
+ *
943
+ * Paused is a state where:
944
+ * - DOM Recording is not listening at all
945
+ * - Nothing will be added to event buffer (e.g. core SDK events)
946
+ */
947
+ this.isPaused = false;
934
948
  /**
935
949
  * Have we attached listeners to the core SDK?
936
950
  * Note we have to track this as there is no way to remove instrumentation handlers.
@@ -1086,7 +1100,8 @@ var Replay = /** @class */ (function () {
1086
1100
  if (type === 'history') {
1087
1101
  // Need to collect visited URLs
1088
1102
  _this.context.urls.push(result.name);
1089
- _this.updateLastActivity();
1103
+ _this.updateUserActivity();
1104
+ _this.triggerUserActivity();
1090
1105
  }
1091
1106
  _this.addUpdate(function () {
1092
1107
  _this.createPerformanceSpans([result]);
@@ -1114,7 +1129,10 @@ var Replay = /** @class */ (function () {
1114
1129
  return;
1115
1130
  }
1116
1131
  if (result.category === 'ui.click') {
1117
- _this.updateLastActivity();
1132
+ _this.triggerUserActivity();
1133
+ }
1134
+ else {
1135
+ _this.checkAndHandleExpiredSession();
1118
1136
  }
1119
1137
  _this.addUpdate(function () {
1120
1138
  _this.addEvent({
@@ -1267,7 +1285,7 @@ var Replay = /** @class */ (function () {
1267
1285
  }
1268
1286
  // setup() is generally called on page load or manually - in both cases we
1269
1287
  // should treat it as an activity
1270
- this.updateLastActivity();
1288
+ this.updateSessionActivity();
1271
1289
  this.eventBuffer = createEventBuffer({
1272
1290
  useCompression: Boolean(this.options.useCompression),
1273
1291
  });
@@ -1275,33 +1293,16 @@ var Replay = /** @class */ (function () {
1275
1293
  // Tag all (non replay) events that get sent to Sentry with the current
1276
1294
  // replay ID so that we can reference them later in the UI
1277
1295
  core.addGlobalEventProcessor(this.handleGlobalEvent);
1278
- this.stopRecording = rrweb.record(__assign(__assign({}, this.recordingOptions), { emit: this.handleRecordingEmit }));
1296
+ this.startRecording();
1279
1297
  this.isEnabled = true;
1280
1298
  };
1281
1299
  /**
1282
- * We want to batch uploads of replay events. Save events only if
1283
- * `<flushMinDelay>` milliseconds have elapsed since the last event
1284
- * *OR* if `<flushMaxDelay>` milliseconds have elapsed.
1300
+ * Start recording.
1285
1301
  *
1286
- * Accepts a callback to perform side-effects and returns true to stop batch
1287
- * processing and hand back control to caller.
1302
+ * Note that this will cause a new DOM checkout
1288
1303
  */
1289
- Replay.prototype.addUpdate = function (cb) {
1290
- // We need to always run `cb` (e.g. in the case of captureOnlyOnError == true)
1291
- var cbResult = cb === null || cb === void 0 ? void 0 : cb();
1292
- // If this option is turned on then we will only want to call `flush`
1293
- // explicitly
1294
- if (this.options.captureOnlyOnError) {
1295
- return;
1296
- }
1297
- // If callback is true, we do not want to continue with flushing -- the
1298
- // caller will need to handle it.
1299
- if (cbResult === true) {
1300
- return;
1301
- }
1302
- // addUpdate is called quite frequently - use debouncedFlush so that it
1303
- // respects the flush delays and does not flush immediately
1304
- this.debouncedFlush();
1304
+ Replay.prototype.startRecording = function () {
1305
+ this.stopRecording = rrweb.record(__assign(__assign({}, this.recordingOptions), { emit: this.handleRecordingEmit }));
1305
1306
  };
1306
1307
  /**
1307
1308
  * Currently, this needs to be manually called (e.g. for tests). Sentry SDK does not support a teardown
@@ -1318,6 +1319,27 @@ var Replay = /** @class */ (function () {
1318
1319
  (_b = this.eventBuffer) === null || _b === void 0 ? void 0 : _b.destroy();
1319
1320
  this.eventBuffer = null;
1320
1321
  };
1322
+ /**
1323
+ * Pause some replay functionality. See comments for `isPaused`.
1324
+ * This differs from stop as this only stops DOM recording, it is
1325
+ * not as thorough of a shutdown as `stop()`. */
1326
+ Replay.prototype.pause = function () {
1327
+ this.isPaused = true;
1328
+ if (this.stopRecording) {
1329
+ this.stopRecording();
1330
+ this.stopRecording = undefined;
1331
+ }
1332
+ };
1333
+ /**
1334
+ * Resumes recording, see notes for `pause().
1335
+ *
1336
+ * Note that calling `startRecording()` here will cause a
1337
+ * new DOM checkout.`
1338
+ */
1339
+ Replay.prototype.resume = function () {
1340
+ this.isPaused = false;
1341
+ this.startRecording();
1342
+ };
1321
1343
  Replay.prototype.clearSession = function () {
1322
1344
  deleteSession();
1323
1345
  this.session = undefined;
@@ -1338,7 +1360,6 @@ var Replay = /** @class */ (function () {
1338
1360
  // If session was newly created (i.e. was not loaded from storage), then
1339
1361
  // enable flag to create the root replay
1340
1362
  if (type === 'new') {
1341
- this.newSessionCreated = true;
1342
1363
  this.setInitialState();
1343
1364
  }
1344
1365
  if (session.id !== ((_b = this.session) === null || _b === void 0 ? void 0 : _b.id)) {
@@ -1424,6 +1445,31 @@ var Replay = /** @class */ (function () {
1424
1445
  this.performanceObserver = null;
1425
1446
  }
1426
1447
  };
1448
+ /**
1449
+ * We want to batch uploads of replay events. Save events only if
1450
+ * `<flushMinDelay>` milliseconds have elapsed since the last event
1451
+ * *OR* if `<flushMaxDelay>` milliseconds have elapsed.
1452
+ *
1453
+ * Accepts a callback to perform side-effects and returns true to stop batch
1454
+ * processing and hand back control to caller.
1455
+ */
1456
+ Replay.prototype.addUpdate = function (cb) {
1457
+ // We need to always run `cb` (e.g. in the case of captureOnlyOnError == true)
1458
+ var cbResult = cb === null || cb === void 0 ? void 0 : cb();
1459
+ // If this option is turned on then we will only want to call `flush`
1460
+ // explicitly
1461
+ if (this.options.captureOnlyOnError) {
1462
+ return;
1463
+ }
1464
+ // If callback is true, we do not want to continue with flushing -- the
1465
+ // caller will need to handle it.
1466
+ if (cbResult === true) {
1467
+ return;
1468
+ }
1469
+ // addUpdate is called quite frequently - use debouncedFlush so that it
1470
+ // respects the flush delays and does not flush immediately
1471
+ this.debouncedFlush();
1472
+ };
1427
1473
  /**
1428
1474
  * Tasks to run when we consider a page to be hidden (via blurring and/or visibility)
1429
1475
  */
@@ -1431,8 +1477,8 @@ var Replay = /** @class */ (function () {
1431
1477
  if (!this.session) {
1432
1478
  return;
1433
1479
  }
1434
- var isExpired = isSessionExpired(this.session, VISIBILITY_CHANGE_TIMEOUT);
1435
- if (breadcrumb && !isExpired) {
1480
+ var expired = isSessionExpired(this.session, VISIBILITY_CHANGE_TIMEOUT);
1481
+ if (breadcrumb && !expired) {
1436
1482
  this.createCustomBreadcrumb(breadcrumb);
1437
1483
  }
1438
1484
  // Send replay when the page/tab becomes hidden. There is no reason to send
@@ -1447,24 +1493,19 @@ var Replay = /** @class */ (function () {
1447
1493
  if (!this.session) {
1448
1494
  return;
1449
1495
  }
1450
- var isExpired = isSessionExpired(this.session, VISIBILITY_CHANGE_TIMEOUT);
1451
- if (isExpired) {
1496
+ var isSessionActive = this.checkAndHandleExpiredSession({
1497
+ expiry: VISIBILITY_CHANGE_TIMEOUT,
1498
+ });
1499
+ if (!isSessionActive) {
1452
1500
  // If the user has come back to the page within VISIBILITY_CHANGE_TIMEOUT
1453
1501
  // ms, we will re-use the existing session, otherwise create a new
1454
1502
  // session
1455
1503
  logger.log('Document has become active, but session has expired');
1456
- this.loadSession({ expiry: VISIBILITY_CHANGE_TIMEOUT });
1457
- this.triggerFullSnapshot();
1458
1504
  return;
1459
1505
  }
1460
1506
  if (breadcrumb) {
1461
1507
  this.createCustomBreadcrumb(breadcrumb);
1462
1508
  }
1463
- // Otherwise if session is not expired...
1464
- // Update with current timestamp as the last session activity
1465
- // Only updating session on visibility change to be conservative about
1466
- // writing to session storage. This could be changed in the future.
1467
- this.updateLastActivity();
1468
1509
  };
1469
1510
  /**
1470
1511
  * Trigger rrweb to take a full snapshot which will cause this plugin to
@@ -1478,10 +1519,15 @@ var Replay = /** @class */ (function () {
1478
1519
  * Add an event to the event buffer
1479
1520
  */
1480
1521
  Replay.prototype.addEvent = function (event, isCheckout) {
1522
+ var _a;
1481
1523
  if (!this.eventBuffer) {
1482
1524
  // This implies that `isEnabled` is false
1483
1525
  return;
1484
1526
  }
1527
+ if (this.isPaused) {
1528
+ // Do not add to event buffer when recording is paused
1529
+ return;
1530
+ }
1485
1531
  // TODO: sadness -- we will want to normalize timestamps to be in ms -
1486
1532
  // requires coordination with frontend
1487
1533
  var isMs = event.timestamp > 9999999999;
@@ -1495,22 +1541,53 @@ var Replay = /** @class */ (function () {
1495
1541
  }
1496
1542
  // Only record earliest event if a new session was created, otherwise it
1497
1543
  // shouldn't be relevant
1498
- if (this.newSessionCreated &&
1544
+ if (((_a = this.session) === null || _a === void 0 ? void 0 : _a.segmentId) === 0 &&
1499
1545
  (!this.context.earliestEvent ||
1500
1546
  timestampInMs < this.context.earliestEvent)) {
1501
1547
  this.context.earliestEvent = timestampInMs;
1502
1548
  }
1503
1549
  this.eventBuffer.addEvent(event, isCheckout);
1504
1550
  };
1551
+ /**
1552
+ * Update user activity (across session lifespans)
1553
+ */
1554
+ Replay.prototype.updateUserActivity = function (lastActivity) {
1555
+ if (lastActivity === void 0) { lastActivity = new Date().getTime(); }
1556
+ this.lastActivity = lastActivity;
1557
+ };
1505
1558
  /**
1506
1559
  * Updates the session's last activity timestamp
1507
1560
  */
1508
- Replay.prototype.updateLastActivity = function (lastActivity) {
1561
+ Replay.prototype.updateSessionActivity = function (lastActivity) {
1509
1562
  if (lastActivity === void 0) { lastActivity = new Date().getTime(); }
1510
1563
  if (this.session) {
1511
1564
  this.session.lastActivity = lastActivity;
1512
1565
  }
1513
1566
  };
1567
+ /**
1568
+ * Updates the user activity timestamp and resumes recording. This should be called in an event handler for a user action that we consider as the user being "active" (e.g. a mouse click).
1569
+ *
1570
+ */
1571
+ Replay.prototype.triggerUserActivity = function () {
1572
+ return __awaiter(this, void 0, void 0, function () {
1573
+ return __generator(this, function (_a) {
1574
+ this.updateUserActivity();
1575
+ // This case means that recording was once stopped due to inactivity.
1576
+ // Ensure that recording is resumed.
1577
+ if (!this.stopRecording) {
1578
+ // Create a new session, otherwise when the user action is flushed, it will get rejected due to an expired session.
1579
+ this.loadSession({ expiry: SESSION_IDLE_DURATION });
1580
+ // Note: This will cause a new DOM checkout
1581
+ this.resume();
1582
+ return [2 /*return*/];
1583
+ }
1584
+ // Otherwise... recording was never suspended, continue as normalish
1585
+ this.checkAndHandleExpiredSession();
1586
+ this.updateSessionActivity();
1587
+ return [2 /*return*/];
1588
+ });
1589
+ });
1590
+ };
1514
1591
  /**
1515
1592
  * Helper to create (and buffer) a replay breadcrumb from a core SDK breadcrumb
1516
1593
  */
@@ -1576,19 +1653,31 @@ var Replay = /** @class */ (function () {
1576
1653
  ]);
1577
1654
  };
1578
1655
  /**
1579
- *
1656
+ * Checks if recording should be stopped due to user inactivity. Otherwise
1657
+ * check if session is expired and create a new session if so. Triggers a new
1658
+ * full snapshot on new session.
1580
1659
  *
1581
1660
  * Returns true if session is not expired, false otherwise.
1582
1661
  */
1583
- Replay.prototype.checkAndHandleExpiredSession = function (expiry) {
1584
- var _a, _b;
1585
- if (expiry === void 0) { expiry = SESSION_IDLE_DURATION; }
1586
- var oldSessionId = (_a = this.session) === null || _a === void 0 ? void 0 : _a.id;
1662
+ Replay.prototype.checkAndHandleExpiredSession = function (_a) {
1663
+ var _b, _c;
1664
+ var _d = _a === void 0 ? {} : _a, _e = _d.expiry, expiry = _e === void 0 ? SESSION_IDLE_DURATION : _e;
1665
+ var oldSessionId = (_b = this.session) === null || _b === void 0 ? void 0 : _b.id;
1666
+ // Prevent starting a new session if the last user activity is older than
1667
+ // MAX_SESSION_LIFE. Otherwise non-user activity can trigger a new
1668
+ // session+recording. This creates noisy replays that do not have much
1669
+ // content in them.
1670
+ if (this.lastActivity && isExpired(this.lastActivity, MAX_SESSION_LIFE)) {
1671
+ // Pause recording
1672
+ this.pause();
1673
+ return;
1674
+ }
1675
+ // --- There is recent user activity --- //
1587
1676
  // This will create a new session if expired, based on expiry length
1588
1677
  this.loadSession({ expiry: expiry });
1589
1678
  // Session was expired if session ids do not match
1590
- var isExpired = oldSessionId !== ((_b = this.session) === null || _b === void 0 ? void 0 : _b.id);
1591
- if (!isExpired) {
1679
+ var expired = oldSessionId !== ((_c = this.session) === null || _c === void 0 ? void 0 : _c.id);
1680
+ if (!expired) {
1592
1681
  return true;
1593
1682
  }
1594
1683
  // TODO: We could potentially figure out a way to save the last session,
@@ -1647,7 +1736,7 @@ var Replay = /** @class */ (function () {
1647
1736
  Replay.prototype.runFlush = function () {
1648
1737
  var _a;
1649
1738
  return __awaiter(this, void 0, void 0, function () {
1650
- var replayId, newSessionCreated, segmentId, recordingData, err_2;
1739
+ var replayId, segmentId, recordingData, err_2;
1651
1740
  return __generator(this, function (_b) {
1652
1741
  switch (_b.label) {
1653
1742
  case 0:
@@ -1667,7 +1756,6 @@ var Replay = /** @class */ (function () {
1667
1756
  // Only attach memory event if eventBuffer is not empty
1668
1757
  _b.sent();
1669
1758
  replayId = this.session.id;
1670
- newSessionCreated = this.newSessionCreated;
1671
1759
  segmentId = this.session.segmentId++;
1672
1760
  _b.label = 3;
1673
1761
  case 3:
@@ -1679,11 +1767,10 @@ var Replay = /** @class */ (function () {
1679
1767
  replayId: replayId,
1680
1768
  events: recordingData,
1681
1769
  segmentId: segmentId,
1682
- includeReplayStartTimestamp: newSessionCreated,
1770
+ includeReplayStartTimestamp: segmentId === 0,
1683
1771
  })];
1684
1772
  case 5:
1685
1773
  _b.sent();
1686
- this.newSessionCreated = false;
1687
1774
  return [3 /*break*/, 7];
1688
1775
  case 6:
1689
1776
  err_2 = _b.sent();
@@ -1728,7 +1815,7 @@ var Replay = /** @class */ (function () {
1728
1815
  timestamp = new Date().getTime();
1729
1816
  sdkInfo = {
1730
1817
  name: 'sentry.javascript.integration.replay',
1731
- version: "0.6.9",
1818
+ version: "0.6.10",
1732
1819
  };
1733
1820
  return [4 /*yield*/, new Promise(function (resolve) {
1734
1821
  var _a;