@sentry/replay 0.5.10 → 0.5.13

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
@@ -99,32 +99,13 @@ var SESSION_IDLE_DURATION = 900000; // 15 minutes
99
99
  // Grace period to keep a session when a user changes tabs or hides window
100
100
  var VISIBILITY_CHANGE_TIMEOUT = SESSION_IDLE_DURATION;
101
101
 
102
- function captureReplay(_a) {
103
- var session = _a.session, initialState = _a.initialState, errorIds = _a.errorIds, traceIds = _a.traceIds, urls = _a.urls;
104
- core.captureEvent({
102
+ function captureReplayEvent(_a) {
103
+ var initialState = _a.initialState, includeReplayStartTimestamp = _a.includeReplayStartTimestamp, errorIds = _a.errorIds, replay_id = _a.replayId, segment_id = _a.segmentId, timestamp = _a.timestamp, traceIds = _a.traceIds, urls = _a.urls;
104
+ core.captureEvent(__assign(__assign(__assign({
105
105
  // @ts-expect-error replay_event is a new event type
106
- type: REPLAY_EVENT_NAME,
107
- replay_start_timestamp: initialState.timestamp / 1000,
108
- error_ids: errorIds,
109
- trace_ids: traceIds,
110
- urls: urls,
111
- replay_id: session.id,
112
- segment_id: session.segmentId, // TODO: Should this increment?
113
- }, { event_id: session.id });
114
- }
115
-
116
- function captureReplayUpdate(_a) {
117
- var session = _a.session, timestamp = _a.timestamp, errorIds = _a.errorIds, traceIds = _a.traceIds, urls = _a.urls;
118
- core.captureEvent({
119
- // @ts-expect-error replay_event is a new event type
120
- type: REPLAY_EVENT_NAME,
121
- timestamp: timestamp / 1000,
122
- error_ids: errorIds,
123
- trace_ids: traceIds,
124
- urls: urls,
125
- replay_id: session.id,
126
- segment_id: ++session.segmentId,
127
- });
106
+ type: REPLAY_EVENT_NAME }, (includeReplayStartTimestamp
107
+ ? { replay_start_timestamp: initialState.timestamp / 1000 }
108
+ : {})), (timestamp ? { timestamp: timestamp / 1000 } : {})), { error_ids: errorIds, trace_ids: traceIds, urls: urls, replay_id: replay_id, segment_id: segment_id }), { event_id: replay_id });
128
109
  }
129
110
 
130
111
  function createBreadcrumb(breadcrumb) {
@@ -471,7 +452,8 @@ function fetchSession() {
471
452
  */
472
453
  function getSession(_a) {
473
454
  var expiry = _a.expiry, currentSession = _a.currentSession, stickySession = _a.stickySession, samplingRate = _a.samplingRate;
474
- var session = stickySession ? fetchSession() : currentSession;
455
+ // If session exists and is passed, use it instead of always hitting session storage
456
+ var session = currentSession || (stickySession && fetchSession());
475
457
  if (session) {
476
458
  // If there is a session, check if it is valid (e.g. "last activity" time should be within the "session idle time")
477
459
  // TODO: We should probably set a max age on this as well
@@ -801,7 +783,7 @@ var EventBufferCompressionWorker = /** @class */ (function () {
801
783
  }());
802
784
 
803
785
  var BASE_RETRY_INTERVAL = 5000;
804
- var MAX_RETRY_COUNT = 5;
786
+ var MAX_RETRY_COUNT = 3;
805
787
  var UNABLE_TO_SEND_REPLAY = 'Unable to send replay';
806
788
  var SentryReplay = /** @class */ (function () {
807
789
  function SentryReplay(_a) {
@@ -812,10 +794,6 @@ var SentryReplay = /** @class */ (function () {
812
794
  * @inheritDoc
813
795
  */
814
796
  this.name = SentryReplay.id;
815
- /**
816
- * Buffer of breadcrumbs to be uploaded
817
- */
818
- this.breadcrumbs = [];
819
797
  /**
820
798
  * List of PerformanceEntry from PerformanceObserver
821
799
  */
@@ -830,12 +808,23 @@ var SentryReplay = /** @class */ (function () {
830
808
  this.retryCount = 0;
831
809
  this.retryInterval = BASE_RETRY_INTERVAL;
832
810
  /**
833
- * Flag to make sure we only create a replay event when
834
- * necessary (i.e. we only want to have a single replay
835
- * event per session and it should only be created
836
- * immediately before sending recording)
811
+ * Flag when a new session has been created. Captured replay events behave
812
+ * slightly differently in this case: `replay_start_timestamp` is included.
813
+ */
814
+ this.newSessionCreated = false;
815
+ /**
816
+ * Is the integration currently active?
837
817
  */
838
- this.needsCaptureReplay = false;
818
+ this.isEnabled = false;
819
+ /**
820
+ * Have we attached listeners to the core SDK?
821
+ * Note we have to track this as there is no way to remove instrumentation handlers.
822
+ */
823
+ this.hasInitializedCoreListeners = false;
824
+ /**
825
+ * Function to stop recording
826
+ */
827
+ this.stopRecording = null;
839
828
  this.context = {
840
829
  errorIds: new Set(),
841
830
  traceIds: new Set(),
@@ -954,6 +943,9 @@ var SentryReplay = /** @class */ (function () {
954
943
  *
955
944
  */
956
945
  this.handleCoreSpanListener = function (type) { return function (handlerData) {
946
+ if (!_this.isEnabled) {
947
+ return;
948
+ }
957
949
  var handler = getSpanHandler(type);
958
950
  var result = handler(handlerData);
959
951
  if (result === null) {
@@ -977,6 +969,9 @@ var SentryReplay = /** @class */ (function () {
977
969
  * These events will create breadcrumb-like objects in the recording.
978
970
  */
979
971
  this.handleCoreBreadcrumbListener = function (type) { return function (handlerData) {
972
+ if (!_this.isEnabled) {
973
+ return;
974
+ }
980
975
  var handler = getBreadcrumbHandler(type);
981
976
  var result = handler(handlerData);
982
977
  if (result === null) {
@@ -1005,6 +1000,7 @@ var SentryReplay = /** @class */ (function () {
1005
1000
  // For whatever reason the observer was returning duplicate navigation
1006
1001
  // entries (the other entry types were not duplicated).
1007
1002
  var newEntries = new Set(list.getEntries());
1003
+ console.log(list.getEntries());
1008
1004
  _this.performanceEvents = __spreadArray(__spreadArray([], _this.performanceEvents, true), Array.from(newEntries), true);
1009
1005
  };
1010
1006
  this.recordingOptions = __assign({ maskAllInputs: maskAllInputs, blockClass: blockClass, ignoreClass: ignoreClass, maskTextClass: maskTextClass }, recordingOptions);
@@ -1059,7 +1055,8 @@ var SentryReplay = /** @class */ (function () {
1059
1055
  // Tag all (non replay) events that get sent to Sentry with the current
1060
1056
  // replay ID so that we can reference them later in the UI
1061
1057
  core.addGlobalEventProcessor(this.handleGlobalEvent);
1062
- rrweb.record(__assign(__assign({}, this.recordingOptions), { emit: this.handleRecordingEmit }));
1058
+ this.stopRecording = rrweb.record(__assign(__assign({}, this.recordingOptions), { emit: this.handleRecordingEmit }));
1059
+ this.isEnabled = true;
1063
1060
  };
1064
1061
  /**
1065
1062
  * We want to batch uploads of replay events. Save events only if
@@ -1114,8 +1111,13 @@ var SentryReplay = /** @class */ (function () {
1114
1111
  * Currently, this needs to be manually called (e.g. for tests). Sentry SDK does not support a teardown
1115
1112
  */
1116
1113
  SentryReplay.prototype.destroy = function () {
1114
+ var _a, _b;
1117
1115
  logger.log('Destroying instance');
1116
+ this.isEnabled = false;
1118
1117
  this.removeListeners();
1118
+ (_a = this.stopRecording) === null || _a === void 0 ? void 0 : _a.call(this);
1119
+ (_b = this.eventBuffer) === null || _b === void 0 ? void 0 : _b.destroy();
1120
+ this.eventBuffer = null;
1119
1121
  };
1120
1122
  SentryReplay.prototype.clearSession = function () {
1121
1123
  deleteSession();
@@ -1137,7 +1139,7 @@ var SentryReplay = /** @class */ (function () {
1137
1139
  // If session was newly created (i.e. was not loaded from storage), then
1138
1140
  // enable flag to create the root replay
1139
1141
  if (type === 'new') {
1140
- this.needsCaptureReplay = true;
1142
+ this.newSessionCreated = true;
1141
1143
  this.setInitialState();
1142
1144
  }
1143
1145
  if (session.id !== ((_b = this.session) === null || _b === void 0 ? void 0 : _b.id)) {
@@ -1153,6 +1155,7 @@ var SentryReplay = /** @class */ (function () {
1153
1155
  SentryReplay.prototype.setInitialState = function () {
1154
1156
  var urlPath = "".concat(window.location.pathname).concat(window.location.hash).concat(window.location.search);
1155
1157
  var url = "".concat(window.location.origin).concat(urlPath);
1158
+ this.performanceEvents = [];
1156
1159
  // Reset context as well
1157
1160
  this.popEventContext();
1158
1161
  this.initialState = {
@@ -1169,13 +1172,17 @@ var SentryReplay = /** @class */ (function () {
1169
1172
  document.addEventListener('visibilitychange', this.handleVisibilityChange);
1170
1173
  window.addEventListener('blur', this.handleWindowBlur);
1171
1174
  window.addEventListener('focus', this.handleWindowFocus);
1172
- // Listeners from core SDK //
1173
- var scope = core.getCurrentHub().getScope();
1174
- scope === null || scope === void 0 ? void 0 : scope.addScopeListener(this.handleCoreBreadcrumbListener('scope'));
1175
- utils.addInstrumentationHandler('dom', this.handleCoreBreadcrumbListener('dom'));
1176
- utils.addInstrumentationHandler('fetch', this.handleCoreSpanListener('fetch'));
1177
- utils.addInstrumentationHandler('xhr', this.handleCoreSpanListener('xhr'));
1178
- utils.addInstrumentationHandler('history', this.handleCoreSpanListener('history'));
1175
+ // There is no way to remove these listeners, so ensure they are only added once
1176
+ if (!this.hasInitializedCoreListeners) {
1177
+ // Listeners from core SDK //
1178
+ var scope = core.getCurrentHub().getScope();
1179
+ scope === null || scope === void 0 ? void 0 : scope.addScopeListener(this.handleCoreBreadcrumbListener('scope'));
1180
+ utils.addInstrumentationHandler('dom', this.handleCoreBreadcrumbListener('dom'));
1181
+ utils.addInstrumentationHandler('fetch', this.handleCoreSpanListener('fetch'));
1182
+ utils.addInstrumentationHandler('xhr', this.handleCoreSpanListener('xhr'));
1183
+ utils.addInstrumentationHandler('history', this.handleCoreSpanListener('history'));
1184
+ this.hasInitializedCoreListeners = true;
1185
+ }
1179
1186
  // PerformanceObserver //
1180
1187
  if (!('PerformanceObserver' in window)) {
1181
1188
  return;
@@ -1272,7 +1279,14 @@ var SentryReplay = /** @class */ (function () {
1272
1279
  * Add an event to the event buffer
1273
1280
  */
1274
1281
  SentryReplay.prototype.addEvent = function (event, isCheckout) {
1275
- var timestampInMs = event.timestamp * 1000;
1282
+ if (!this.eventBuffer) {
1283
+ // This implies that `isEnabled` is false
1284
+ return;
1285
+ }
1286
+ // TODO: sadness -- we will want to normalize timestamps to be in ms -
1287
+ // requires coordination with frontend
1288
+ var isMs = event.timestamp > 9999999999;
1289
+ var timestampInMs = isMs ? event.timestamp : event.timestamp * 1000;
1276
1290
  if (!this.context.earliestEvent ||
1277
1291
  timestampInMs < this.context.earliestEvent) {
1278
1292
  this.context.earliestEvent = timestampInMs;
@@ -1397,7 +1411,6 @@ var SentryReplay = /** @class */ (function () {
1397
1411
  initialState.timestamp = this.context.earliestEvent;
1398
1412
  }
1399
1413
  var context = {
1400
- session: this.session,
1401
1414
  initialState: initialState,
1402
1415
  timestamp: timestamp,
1403
1416
  errorIds: Array.from(this.context.errorIds).filter(Boolean),
@@ -1418,12 +1431,17 @@ var SentryReplay = /** @class */ (function () {
1418
1431
  * due to the buffered performance observer events.
1419
1432
  */
1420
1433
  SentryReplay.prototype.flushUpdate = function () {
1421
- var _a;
1434
+ var _a, _b;
1422
1435
  return __awaiter(this, void 0, void 0, function () {
1423
- var timestamp, recordingData, err_1;
1424
- return __generator(this, function (_b) {
1425
- switch (_b.label) {
1436
+ var timestamp, replayId, newSessionCreated, segmentId, recordingData, err_1;
1437
+ return __generator(this, function (_c) {
1438
+ switch (_c.label) {
1426
1439
  case 0:
1440
+ if (!this.isEnabled) {
1441
+ // This is just a precaution, there should be no listeners that would
1442
+ // cause a flush.
1443
+ return [2 /*return*/];
1444
+ }
1427
1445
  if (!this.checkAndHandleExpiredSession()) {
1428
1446
  logger.error(new Error('Attempting to finish replay event after session expired.'));
1429
1447
  return [2 /*return*/];
@@ -1436,44 +1454,42 @@ var SentryReplay = /** @class */ (function () {
1436
1454
  clearTimeout(this.timeout);
1437
1455
  return [4 /*yield*/, this.addPerformanceEntries()];
1438
1456
  case 1:
1439
- _b.sent();
1440
- if (!this.eventBuffer.length) {
1457
+ _c.sent();
1458
+ if (!((_b = this.eventBuffer) === null || _b === void 0 ? void 0 : _b.length)) {
1441
1459
  return [2 /*return*/];
1442
1460
  }
1443
1461
  // Only attach memory event if eventBuffer is not empty
1444
1462
  return [4 /*yield*/, this.addMemoryEntry()];
1445
1463
  case 2:
1446
1464
  // Only attach memory event if eventBuffer is not empty
1447
- _b.sent();
1465
+ _c.sent();
1448
1466
  timestamp = new Date().getTime();
1449
- // Only want to create replay event if session is new
1450
- if (this.needsCaptureReplay) {
1451
- // This event needs to exist before calling `sendReplay`
1452
- captureReplay(this.popEventContext({ timestamp: timestamp }));
1453
- this.needsCaptureReplay = false;
1454
- }
1467
+ replayId = this.session.id;
1468
+ newSessionCreated = this.newSessionCreated;
1469
+ segmentId = this.session.segmentId++;
1455
1470
  // Reset this to null regardless of `sendReplay` result so that future
1456
1471
  // events will get flushed properly
1457
1472
  this.initialEventTimestampSinceFlush = null;
1458
- _b.label = 3;
1473
+ _c.label = 3;
1459
1474
  case 3:
1460
- _b.trys.push([3, 6, , 7]);
1475
+ _c.trys.push([3, 6, , 7]);
1461
1476
  return [4 /*yield*/, this.eventBuffer.finish()];
1462
1477
  case 4:
1463
- recordingData = _b.sent();
1464
- return [4 /*yield*/, this.sendReplay(this.session.id, recordingData)];
1478
+ recordingData = _c.sent();
1479
+ return [4 /*yield*/, this.sendReplay(replayId, recordingData, segmentId)];
1465
1480
  case 5:
1466
- _b.sent();
1481
+ _c.sent();
1467
1482
  // The below will only happen after successfully sending replay //
1468
1483
  // TBD: Alternatively we could update this after every rrweb event
1469
1484
  // `timestamp` should reflect when the event happens. e.g. the timestamp
1470
1485
  // of the event is passed as an argument in the case where a timeout
1471
1486
  // occurs.
1472
1487
  this.updateLastActivity(timestamp);
1473
- captureReplayUpdate(this.popEventContext({ timestamp: timestamp }));
1488
+ captureReplayEvent(__assign(__assign({}, this.popEventContext({ timestamp: timestamp })), { replayId: replayId, segmentId: segmentId, includeReplayStartTimestamp: newSessionCreated }));
1489
+ this.newSessionCreated = false;
1474
1490
  return [3 /*break*/, 7];
1475
1491
  case 6:
1476
- err_1 = _b.sent();
1492
+ err_1 = _c.sent();
1477
1493
  core.captureException(err_1);
1478
1494
  console.error(err_1);
1479
1495
  return [3 /*break*/, 7];
@@ -1486,22 +1502,21 @@ var SentryReplay = /** @class */ (function () {
1486
1502
  * Send replay attachment using `fetch()`
1487
1503
  */
1488
1504
  SentryReplay.prototype.sendReplayRequest = function (_a) {
1489
- var _b, _c;
1490
- var endpoint = _a.endpoint, events = _a.events;
1505
+ var endpoint = _a.endpoint, events = _a.events, event_id = _a.replayId, segment_id = _a.segmentId;
1491
1506
  return __awaiter(this, void 0, void 0, function () {
1492
- var payloadWithSequence, envelope, response, _d, _e;
1493
- var _f;
1494
- return __generator(this, function (_g) {
1495
- switch (_g.label) {
1507
+ var payloadWithSequence, envelope, response, _b, _c;
1508
+ var _d;
1509
+ return __generator(this, function (_e) {
1510
+ switch (_e.label) {
1496
1511
  case 0:
1497
1512
  payloadWithSequence = createPayload({
1498
1513
  events: events,
1499
1514
  headers: {
1500
- segment_id: (_b = this.session) === null || _b === void 0 ? void 0 : _b.segmentId,
1515
+ segment_id: segment_id,
1501
1516
  },
1502
1517
  });
1503
1518
  envelope = utils.createEnvelope({
1504
- event_id: (_c = this.session) === null || _c === void 0 ? void 0 : _c.id,
1519
+ event_id: event_id,
1505
1520
  sent_at: new Date().toISOString(),
1506
1521
  sdk: { name: 'sentry.javascript.integration.replay', version: '1.0.0' },
1507
1522
  }, [
@@ -1522,17 +1537,17 @@ var SentryReplay = /** @class */ (function () {
1522
1537
  body: utils.serializeEnvelope(envelope),
1523
1538
  })];
1524
1539
  case 1:
1525
- response = _g.sent();
1540
+ response = _e.sent();
1526
1541
  if (!(response.status !== 200)) return [3 /*break*/, 3];
1527
- _d = core.setContext;
1528
- _e = ['Send Replay Response'];
1529
- _f = {
1542
+ _b = core.setContext;
1543
+ _c = ['Send Replay Response'];
1544
+ _d = {
1530
1545
  status: response.status
1531
1546
  };
1532
1547
  return [4 /*yield*/, response.text()];
1533
1548
  case 2:
1534
- _d.apply(void 0, _e.concat([(_f.body = _g.sent(),
1535
- _f)]));
1549
+ _b.apply(void 0, _c.concat([(_d.body = _e.sent(),
1550
+ _d)]));
1536
1551
  throw new Error(UNABLE_TO_SEND_REPLAY);
1537
1552
  case 3: return [2 /*return*/];
1538
1553
  }
@@ -1546,7 +1561,7 @@ var SentryReplay = /** @class */ (function () {
1546
1561
  /**
1547
1562
  * Finalize and send the current replay event to Sentry
1548
1563
  */
1549
- SentryReplay.prototype.sendReplay = function (eventId, events) {
1564
+ SentryReplay.prototype.sendReplay = function (replayId, events, segmentId) {
1550
1565
  return __awaiter(this, void 0, void 0, function () {
1551
1566
  var client, endpoint, ex_1;
1552
1567
  var _this = this;
@@ -1565,6 +1580,8 @@ var SentryReplay = /** @class */ (function () {
1565
1580
  return [4 /*yield*/, this.sendReplayRequest({
1566
1581
  endpoint: endpoint,
1567
1582
  events: events,
1583
+ replayId: replayId,
1584
+ segmentId: segmentId,
1568
1585
  })];
1569
1586
  case 2:
1570
1587
  _b.sent();
@@ -1583,29 +1600,30 @@ var SentryReplay = /** @class */ (function () {
1583
1600
  // failed, we'll can retry with the same events payload
1584
1601
  if (this.retryCount >= MAX_RETRY_COUNT) {
1585
1602
  this.resetRetries();
1586
- return [2 /*return*/, false];
1603
+ throw new Error(UNABLE_TO_SEND_REPLAY);
1587
1604
  }
1588
1605
  this.retryCount = this.retryCount + 1;
1589
- // will retry in intervals of 5, 10, 15, 20, 25 seconds
1606
+ // will retry in intervals of 5, 10, 30
1590
1607
  this.retryInterval = this.retryCount * this.retryInterval;
1591
1608
  _b.label = 4;
1592
1609
  case 4:
1593
1610
  _b.trys.push([4, 6, , 7]);
1594
1611
  return [4 /*yield*/, new Promise(function (resolve, reject) {
1595
1612
  setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
1596
- var result;
1597
- return __generator(this, function (_a) {
1598
- switch (_a.label) {
1599
- case 0: return [4 /*yield*/, this.sendReplay(eventId, events)];
1613
+ return __generator(this, function (_b) {
1614
+ switch (_b.label) {
1615
+ case 0:
1616
+ _b.trys.push([0, 2, , 3]);
1617
+ return [4 /*yield*/, this.sendReplay(replayId, events, segmentId)];
1600
1618
  case 1:
1601
- result = _a.sent();
1602
- if (result) {
1603
- resolve(true);
1604
- }
1605
- else {
1606
- reject(new Error('Could not send replay'));
1607
- }
1608
- return [2 /*return*/];
1619
+ _b.sent();
1620
+ resolve(true);
1621
+ return [3 /*break*/, 3];
1622
+ case 2:
1623
+ _b.sent();
1624
+ reject(new Error(UNABLE_TO_SEND_REPLAY));
1625
+ return [3 /*break*/, 3];
1626
+ case 3: return [2 /*return*/];
1609
1627
  }
1610
1628
  });
1611
1629
  }); }, _this.retryInterval);
@@ -1615,7 +1633,7 @@ var SentryReplay = /** @class */ (function () {
1615
1633
  return [2 /*return*/, true];
1616
1634
  case 6:
1617
1635
  _b.sent();
1618
- return [2 /*return*/, false];
1636
+ throw new Error(UNABLE_TO_SEND_REPLAY);
1619
1637
  case 7: return [3 /*break*/, 8];
1620
1638
  case 8: return [2 /*return*/];
1621
1639
  }