@sentry/replay 0.5.9 → 0.5.12

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/README.md CHANGED
@@ -36,7 +36,7 @@ Sentry.init({
36
36
  dsn: '__DSN__',
37
37
  integrations: [
38
38
  new SentryReplay({
39
- stickySession: true, // Default is false
39
+ stickySession: false, // Default is true
40
40
  recordingConfig: {
41
41
  maskAllInputs: false, // Default is true
42
42
  },
@@ -46,6 +46,18 @@ Sentry.init({
46
46
  });
47
47
  ```
48
48
 
49
+ ### Stopping Replays
50
+
51
+ To stop replays you can call the `destroy()` method on the integration instance. It's possible to resume recording by calling `setup()`.
52
+
53
+ ```javascript
54
+
55
+ const replay = new SentryReplay(); // This will begin recording replays
56
+
57
+ replay.destroy(); // Stop recording
58
+
59
+ replay.setup(); // Start recording again
60
+ ```
49
61
 
50
62
  ## Configuration
51
63
 
@@ -54,7 +66,7 @@ Sentry.init({
54
66
  | `flushMinDelay` | `number` | `5000` | The minimum time to wait (in ms) before sending the recording payload. The payload is sent if `flushMinDelay` ms have elapsed between two events. |
55
67
  | `flushMaxDelay` | `number` | `15000` | The maximum time to wait (in ms) when sending the recording payload. The payload is sent if events occur at an interval less than `flushMinDelay` and `flushMaxDelay` ms have elapsed since the last time a payload was sent. |
56
68
  | `initialFlushDelay` | `number` | `5000` | The amount of time to wait (in ms) before sending the initial recording payload. This helps drop recordings where users visit and close the page quickly. |
57
- | `stickySession` | `boolean` | `false` | Keep track of the user across page loads. Note a single user using multiple tabs will result in multiple sessions. Closing a tab will result in the session being closed as well. |
69
+ | `stickySession` | `boolean` | `true` | Keep track of the user across page loads. Note a single user using multiple tabs will result in multiple sessions. Closing a tab will result in the session being closed as well. |
58
70
  | `useCompression` | `boolean` | `true` | Uses `WebWorkers` (if available) to compress the recording payload before uploading to Sentry. |
59
71
  | `captureOnlyOnError` | `boolean` | `false` | Only capture the recording when an error happens. |
60
72
  | `replaysSamplingRate` | `number` | `1.0` | The rate at which to sample replays. (1.0 will collect all replays, 0 will collect no replays). |
@@ -0,0 +1,15 @@
1
+ import { InitialState } from '@/types';
2
+ export interface CaptureReplayEventParams {
3
+ initialState: InitialState;
4
+ includeReplayStartTimestamp: boolean;
5
+ errorIds: string[];
6
+ replayId: string;
7
+ segmentId: number;
8
+ /**
9
+ * Timestamp of the event in milliseconds
10
+ */
11
+ timestamp: number;
12
+ traceIds: string[];
13
+ urls: string[];
14
+ }
15
+ export declare function captureReplayEvent({ initialState, includeReplayStartTimestamp, errorIds, replayId: replay_id, segmentId: segment_id, timestamp, traceIds, urls, }: CaptureReplayEventParams): void;
@@ -18,11 +18,7 @@ export declare class SentryReplay implements Integration {
18
18
  * @inheritDoc
19
19
  */
20
20
  name: string;
21
- eventBuffer: IEventBuffer;
22
- /**
23
- * Buffer of breadcrumbs to be uploaded
24
- */
25
- breadcrumbs: Breadcrumb[];
21
+ eventBuffer: IEventBuffer | null;
26
22
  /**
27
23
  * List of PerformanceEntry from PerformanceObserver
28
24
  */
@@ -52,14 +48,26 @@ export declare class SentryReplay implements Integration {
52
48
  * immediately before sending recording)
53
49
  */
54
50
  private needsCaptureReplay;
51
+ /**
52
+ * Is the integration currently active?
53
+ */
54
+ private isEnabled;
55
+ /**
56
+ * Have we attached listeners to the core SDK?
57
+ * Note we have to track this as there is no way to remove instrumentation handlers.
58
+ */
59
+ private hasInitializedCoreListeners;
60
+ /**
61
+ * Function to stop recording
62
+ */
63
+ private stopRecording;
55
64
  /**
56
65
  * Captured state when integration is first initialized
57
66
  */
58
67
  private initialState;
59
68
  private context;
60
69
  session: Session | undefined;
61
- constructor({ flushMinDelay, flushMaxDelay, initialFlushDelay, stickySession, // TBD: Making this opt-in for now
62
- useCompression, captureOnlyOnError, replaysSamplingRate, recordingConfig: { maskAllInputs, blockClass, ignoreClass, maskTextClass, ...recordingOptions }, }?: SentryReplayConfiguration);
70
+ constructor({ flushMinDelay, flushMaxDelay, initialFlushDelay, stickySession, useCompression, captureOnlyOnError, replaysSamplingRate, recordingConfig: { maskAllInputs, blockClass, ignoreClass, maskTextClass, ...recordingOptions }, }?: SentryReplayConfiguration);
63
71
  /**
64
72
  * Because we create a transaction in `setupOnce`, we can potentially create a
65
73
  * transaction before some native SDK integrations have run and applied their
@@ -203,7 +211,7 @@ export declare class SentryReplay implements Integration {
203
211
  /**
204
212
  * Only flush if `captureOnlyOnError` is false.
205
213
  */
206
- conditionalFlush(lastActivity?: number): Promise<void> | undefined;
214
+ conditionalFlush(): Promise<void> | undefined;
207
215
  /**
208
216
  * Return and clear context
209
217
  */
@@ -216,7 +224,7 @@ export declare class SentryReplay implements Integration {
216
224
  * Performance events are only added right before flushing - this is probably
217
225
  * due to the buffered performance observer events.
218
226
  */
219
- flushUpdate(lastActivity?: number): Promise<void>;
227
+ flushUpdate(): Promise<void>;
220
228
  /**
221
229
  * Send replay attachment using `fetch()`
222
230
  */
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Deletes a session from storage
3
+ */
4
+ export declare function deleteSession(): void;
package/dist/index.es.js CHANGED
@@ -263,6 +263,22 @@ function getSpanHandler(type) {
263
263
  return handleHistory;
264
264
  }
265
265
 
266
+ /**
267
+ * Deletes a session from storage
268
+ */
269
+ function deleteSession() {
270
+ var hasSessionStorage = 'sessionStorage' in window;
271
+ if (!hasSessionStorage) {
272
+ return;
273
+ }
274
+ try {
275
+ window.sessionStorage.removeItem(REPLAY_SESSION_KEY);
276
+ }
277
+ catch (_a) {
278
+ // Ignore potential SecurityError exceptions
279
+ }
280
+ }
281
+
266
282
  /**
267
283
  * Given an initial timestamp and an expiry duration, checks to see if current
268
284
  * time should be considered as expired.
@@ -451,7 +467,8 @@ function fetchSession() {
451
467
  */
452
468
  function getSession(_a) {
453
469
  var expiry = _a.expiry, currentSession = _a.currentSession, stickySession = _a.stickySession, samplingRate = _a.samplingRate;
454
- var session = stickySession ? fetchSession() : currentSession;
470
+ // If session exists and is passed, use it instead of always hitting session storage
471
+ var session = currentSession || (stickySession && fetchSession());
455
472
  if (session) {
456
473
  // If there is a session, check if it is valid (e.g. "last activity" time should be within the "session idle time")
457
474
  // TODO: We should probably set a max age on this as well
@@ -787,17 +804,11 @@ var SentryReplay = /** @class */ (function () {
787
804
  function SentryReplay(_a) {
788
805
  if (_a === void 0) { _a = {}; }
789
806
  var _this = this;
790
- var _b = _a.flushMinDelay, flushMinDelay = _b === void 0 ? 5000 : _b, _c = _a.flushMaxDelay, flushMaxDelay = _c === void 0 ? 15000 : _c, _d = _a.initialFlushDelay, initialFlushDelay = _d === void 0 ? 5000 : _d, _e = _a.stickySession, stickySession = _e === void 0 ? false : _e, // TBD: Making this opt-in for now
791
- _f = _a.useCompression, // TBD: Making this opt-in for now
792
- useCompression = _f === void 0 ? true : _f, _g = _a.captureOnlyOnError, captureOnlyOnError = _g === void 0 ? false : _g, _h = _a.replaysSamplingRate, replaysSamplingRate = _h === void 0 ? 1.0 : _h, _j = _a.recordingConfig, _k = _j === void 0 ? {} : _j, _l = _k.maskAllInputs, maskAllInputs = _l === void 0 ? true : _l, _m = _k.blockClass, blockClass = _m === void 0 ? 'sr-block' : _m, _o = _k.ignoreClass, ignoreClass = _o === void 0 ? 'sr-ignore' : _o, _p = _k.maskTextClass, maskTextClass = _p === void 0 ? 'sr-mask' : _p, recordingOptions = __rest(_k, ["maskAllInputs", "blockClass", "ignoreClass", "maskTextClass"]);
807
+ var _b = _a.flushMinDelay, flushMinDelay = _b === void 0 ? 5000 : _b, _c = _a.flushMaxDelay, flushMaxDelay = _c === void 0 ? 15000 : _c, _d = _a.initialFlushDelay, initialFlushDelay = _d === void 0 ? 5000 : _d, _e = _a.stickySession, stickySession = _e === void 0 ? true : _e, _f = _a.useCompression, useCompression = _f === void 0 ? true : _f, _g = _a.captureOnlyOnError, captureOnlyOnError = _g === void 0 ? false : _g, _h = _a.replaysSamplingRate, replaysSamplingRate = _h === void 0 ? 1.0 : _h, _j = _a.recordingConfig, _k = _j === void 0 ? {} : _j, _l = _k.maskAllInputs, maskAllInputs = _l === void 0 ? true : _l, _m = _k.blockClass, blockClass = _m === void 0 ? 'sr-block' : _m, _o = _k.ignoreClass, ignoreClass = _o === void 0 ? 'sr-ignore' : _o, _p = _k.maskTextClass, maskTextClass = _p === void 0 ? 'sr-mask' : _p, recordingOptions = __rest(_k, ["maskAllInputs", "blockClass", "ignoreClass", "maskTextClass"]);
793
808
  /**
794
809
  * @inheritDoc
795
810
  */
796
811
  this.name = SentryReplay.id;
797
- /**
798
- * Buffer of breadcrumbs to be uploaded
799
- */
800
- this.breadcrumbs = [];
801
812
  /**
802
813
  * List of PerformanceEntry from PerformanceObserver
803
814
  */
@@ -818,6 +829,19 @@ var SentryReplay = /** @class */ (function () {
818
829
  * immediately before sending recording)
819
830
  */
820
831
  this.needsCaptureReplay = false;
832
+ /**
833
+ * Is the integration currently active?
834
+ */
835
+ this.isEnabled = false;
836
+ /**
837
+ * Have we attached listeners to the core SDK?
838
+ * Note we have to track this as there is no way to remove instrumentation handlers.
839
+ */
840
+ this.hasInitializedCoreListeners = false;
841
+ /**
842
+ * Function to stop recording
843
+ */
844
+ this.stopRecording = null;
821
845
  this.context = {
822
846
  errorIds: new Set(),
823
847
  traceIds: new Set(),
@@ -893,8 +917,7 @@ var SentryReplay = /** @class */ (function () {
893
917
  // a previous session ID. In this case, we want to buffer events
894
918
  // for a set amount of time before flushing. This can help avoid
895
919
  // capturing replays of users that immediately close the window.
896
- var now = new Date().getTime();
897
- setTimeout(function () { return _this.conditionalFlush(now); }, _this.options.initialFlushDelay);
920
+ setTimeout(function () { return _this.conditionalFlush(); }, _this.options.initialFlushDelay);
898
921
  return true;
899
922
  });
900
923
  };
@@ -937,6 +960,9 @@ var SentryReplay = /** @class */ (function () {
937
960
  *
938
961
  */
939
962
  this.handleCoreSpanListener = function (type) { return function (handlerData) {
963
+ if (!_this.isEnabled) {
964
+ return;
965
+ }
940
966
  var handler = getSpanHandler(type);
941
967
  var result = handler(handlerData);
942
968
  if (result === null) {
@@ -960,6 +986,9 @@ var SentryReplay = /** @class */ (function () {
960
986
  * These events will create breadcrumb-like objects in the recording.
961
987
  */
962
988
  this.handleCoreBreadcrumbListener = function (type) { return function (handlerData) {
989
+ if (!_this.isEnabled) {
990
+ return;
991
+ }
963
992
  var handler = getBreadcrumbHandler(type);
964
993
  var result = handler(handlerData);
965
994
  if (result === null) {
@@ -1042,7 +1071,8 @@ var SentryReplay = /** @class */ (function () {
1042
1071
  // Tag all (non replay) events that get sent to Sentry with the current
1043
1072
  // replay ID so that we can reference them later in the UI
1044
1073
  addGlobalEventProcessor(this.handleGlobalEvent);
1045
- record(__assign(__assign({}, this.recordingOptions), { emit: this.handleRecordingEmit }));
1074
+ this.stopRecording = record(__assign(__assign({}, this.recordingOptions), { emit: this.handleRecordingEmit }));
1075
+ this.isEnabled = true;
1046
1076
  };
1047
1077
  /**
1048
1078
  * We want to batch uploads of replay events. Save events only if
@@ -1090,17 +1120,23 @@ var SentryReplay = /** @class */ (function () {
1090
1120
  // elapses.
1091
1121
  this.timeout = window.setTimeout(function () {
1092
1122
  logger.log('replay timeout exceeded, finishing replay event');
1093
- _this.flushUpdate(now);
1123
+ _this.flushUpdate();
1094
1124
  }, this.options.flushMinDelay);
1095
1125
  };
1096
1126
  /**
1097
1127
  * Currently, this needs to be manually called (e.g. for tests). Sentry SDK does not support a teardown
1098
1128
  */
1099
1129
  SentryReplay.prototype.destroy = function () {
1130
+ var _a, _b;
1100
1131
  logger.log('Destroying instance');
1132
+ this.isEnabled = false;
1101
1133
  this.removeListeners();
1134
+ (_a = this.stopRecording) === null || _a === void 0 ? void 0 : _a.call(this);
1135
+ (_b = this.eventBuffer) === null || _b === void 0 ? void 0 : _b.destroy();
1136
+ this.eventBuffer = null;
1102
1137
  };
1103
1138
  SentryReplay.prototype.clearSession = function () {
1139
+ deleteSession();
1104
1140
  this.session = undefined;
1105
1141
  };
1106
1142
  /**
@@ -1135,6 +1171,7 @@ var SentryReplay = /** @class */ (function () {
1135
1171
  SentryReplay.prototype.setInitialState = function () {
1136
1172
  var urlPath = "".concat(window.location.pathname).concat(window.location.hash).concat(window.location.search);
1137
1173
  var url = "".concat(window.location.origin).concat(urlPath);
1174
+ this.performanceEvents = [];
1138
1175
  // Reset context as well
1139
1176
  this.popEventContext();
1140
1177
  this.initialState = {
@@ -1151,13 +1188,17 @@ var SentryReplay = /** @class */ (function () {
1151
1188
  document.addEventListener('visibilitychange', this.handleVisibilityChange);
1152
1189
  window.addEventListener('blur', this.handleWindowBlur);
1153
1190
  window.addEventListener('focus', this.handleWindowFocus);
1154
- // Listeners from core SDK //
1155
- var scope = getCurrentHub().getScope();
1156
- scope === null || scope === void 0 ? void 0 : scope.addScopeListener(this.handleCoreBreadcrumbListener('scope'));
1157
- addInstrumentationHandler('dom', this.handleCoreBreadcrumbListener('dom'));
1158
- addInstrumentationHandler('fetch', this.handleCoreSpanListener('fetch'));
1159
- addInstrumentationHandler('xhr', this.handleCoreSpanListener('xhr'));
1160
- addInstrumentationHandler('history', this.handleCoreSpanListener('history'));
1191
+ // There is no way to remove these listeners, so ensure they are only added once
1192
+ if (!this.hasInitializedCoreListeners) {
1193
+ // Listeners from core SDK //
1194
+ var scope = getCurrentHub().getScope();
1195
+ scope === null || scope === void 0 ? void 0 : scope.addScopeListener(this.handleCoreBreadcrumbListener('scope'));
1196
+ addInstrumentationHandler('dom', this.handleCoreBreadcrumbListener('dom'));
1197
+ addInstrumentationHandler('fetch', this.handleCoreSpanListener('fetch'));
1198
+ addInstrumentationHandler('xhr', this.handleCoreSpanListener('xhr'));
1199
+ addInstrumentationHandler('history', this.handleCoreSpanListener('history'));
1200
+ this.hasInitializedCoreListeners = true;
1201
+ }
1161
1202
  // PerformanceObserver //
1162
1203
  if (!('PerformanceObserver' in window)) {
1163
1204
  return;
@@ -1176,10 +1217,16 @@ var SentryReplay = /** @class */ (function () {
1176
1217
  'resource',
1177
1218
  ].forEach(function (type) {
1178
1219
  var _a;
1179
- return (_a = _this.performanceObserver) === null || _a === void 0 ? void 0 : _a.observe({
1180
- type: type,
1181
- buffered: true,
1182
- });
1220
+ try {
1221
+ (_a = _this.performanceObserver) === null || _a === void 0 ? void 0 : _a.observe({
1222
+ type: type,
1223
+ buffered: true,
1224
+ });
1225
+ }
1226
+ catch (_b) {
1227
+ // This can throw if an entry type is not supported in the browser.
1228
+ // Ignore these errors.
1229
+ }
1183
1230
  });
1184
1231
  };
1185
1232
  /**
@@ -1248,7 +1295,14 @@ var SentryReplay = /** @class */ (function () {
1248
1295
  * Add an event to the event buffer
1249
1296
  */
1250
1297
  SentryReplay.prototype.addEvent = function (event, isCheckout) {
1251
- var timestampInMs = event.timestamp * 1000;
1298
+ if (!this.eventBuffer) {
1299
+ // This implies that `isEnabled` is false
1300
+ return;
1301
+ }
1302
+ // TODO: sadness -- we will want to normalize timestamps to be in ms -
1303
+ // requires coordination with frontend
1304
+ var isMs = event.timestamp > 9999999999;
1305
+ var timestampInMs = isMs ? event.timestamp : event.timestamp * 1000;
1252
1306
  if (!this.context.earliestEvent ||
1253
1307
  timestampInMs < this.context.earliestEvent) {
1254
1308
  this.context.earliestEvent = timestampInMs;
@@ -1355,11 +1409,11 @@ var SentryReplay = /** @class */ (function () {
1355
1409
  /**
1356
1410
  * Only flush if `captureOnlyOnError` is false.
1357
1411
  */
1358
- SentryReplay.prototype.conditionalFlush = function (lastActivity) {
1412
+ SentryReplay.prototype.conditionalFlush = function () {
1359
1413
  if (this.options.captureOnlyOnError) {
1360
1414
  return;
1361
1415
  }
1362
- return this.flushUpdate(lastActivity);
1416
+ return this.flushUpdate();
1363
1417
  };
1364
1418
  /**
1365
1419
  * Return and clear context
@@ -1393,13 +1447,18 @@ var SentryReplay = /** @class */ (function () {
1393
1447
  * Performance events are only added right before flushing - this is probably
1394
1448
  * due to the buffered performance observer events.
1395
1449
  */
1396
- SentryReplay.prototype.flushUpdate = function (lastActivity) {
1397
- var _a;
1450
+ SentryReplay.prototype.flushUpdate = function () {
1451
+ var _a, _b;
1398
1452
  return __awaiter(this, void 0, void 0, function () {
1399
1453
  var timestamp, recordingData, err_1;
1400
- return __generator(this, function (_b) {
1401
- switch (_b.label) {
1454
+ return __generator(this, function (_c) {
1455
+ switch (_c.label) {
1402
1456
  case 0:
1457
+ if (!this.isEnabled) {
1458
+ // This is just a precaution, there should be no listeners that would
1459
+ // cause a flush.
1460
+ return [2 /*return*/];
1461
+ }
1403
1462
  if (!this.checkAndHandleExpiredSession()) {
1404
1463
  logger.error(new Error('Attempting to finish replay event after session expired.'));
1405
1464
  return [2 /*return*/];
@@ -1412,16 +1471,16 @@ var SentryReplay = /** @class */ (function () {
1412
1471
  clearTimeout(this.timeout);
1413
1472
  return [4 /*yield*/, this.addPerformanceEntries()];
1414
1473
  case 1:
1415
- _b.sent();
1416
- if (!this.eventBuffer.length) {
1474
+ _c.sent();
1475
+ if (!((_b = this.eventBuffer) === null || _b === void 0 ? void 0 : _b.length)) {
1417
1476
  return [2 /*return*/];
1418
1477
  }
1419
1478
  // Only attach memory event if eventBuffer is not empty
1420
1479
  return [4 /*yield*/, this.addMemoryEntry()];
1421
1480
  case 2:
1422
1481
  // Only attach memory event if eventBuffer is not empty
1423
- _b.sent();
1424
- timestamp = lastActivity !== null && lastActivity !== void 0 ? lastActivity : new Date().getTime();
1482
+ _c.sent();
1483
+ timestamp = new Date().getTime();
1425
1484
  // Only want to create replay event if session is new
1426
1485
  if (this.needsCaptureReplay) {
1427
1486
  // This event needs to exist before calling `sendReplay`
@@ -1431,15 +1490,15 @@ var SentryReplay = /** @class */ (function () {
1431
1490
  // Reset this to null regardless of `sendReplay` result so that future
1432
1491
  // events will get flushed properly
1433
1492
  this.initialEventTimestampSinceFlush = null;
1434
- _b.label = 3;
1493
+ _c.label = 3;
1435
1494
  case 3:
1436
- _b.trys.push([3, 6, , 7]);
1495
+ _c.trys.push([3, 6, , 7]);
1437
1496
  return [4 /*yield*/, this.eventBuffer.finish()];
1438
1497
  case 4:
1439
- recordingData = _b.sent();
1498
+ recordingData = _c.sent();
1440
1499
  return [4 /*yield*/, this.sendReplay(this.session.id, recordingData)];
1441
1500
  case 5:
1442
- _b.sent();
1501
+ _c.sent();
1443
1502
  // The below will only happen after successfully sending replay //
1444
1503
  // TBD: Alternatively we could update this after every rrweb event
1445
1504
  // `timestamp` should reflect when the event happens. e.g. the timestamp
@@ -1449,7 +1508,7 @@ var SentryReplay = /** @class */ (function () {
1449
1508
  captureReplayUpdate(this.popEventContext({ timestamp: timestamp }));
1450
1509
  return [3 /*break*/, 7];
1451
1510
  case 6:
1452
- err_1 = _b.sent();
1511
+ err_1 = _c.sent();
1453
1512
  captureException(err_1);
1454
1513
  console.error(err_1);
1455
1514
  return [3 /*break*/, 7];