@sentry/replay 0.6.10-0 → 0.6.11-0

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.es.js CHANGED
@@ -1,4 +1,4 @@
1
- import { getCurrentHub, addBreadcrumb, captureException, addGlobalEventProcessor, setContext, getEnvelopeEndpointWithUrlEncodedAuth } from '@sentry/core';
1
+ import { getCurrentHub, captureException, addBreadcrumb, addGlobalEventProcessor, setContext, getEnvelopeEndpointWithUrlEncodedAuth } from '@sentry/core';
2
2
  import { htmlTreeAsString, logger as logger$1, uuid4, browserPerformanceTimeOrigin, addInstrumentationHandler, createEnvelope, serializeEnvelope } from '@sentry/utils';
3
3
  import debounce from 'lodash.debounce';
4
4
  import { record, EventType } from 'rrweb';
@@ -252,6 +252,11 @@ var SESSION_IDLE_DURATION = 300000; // 5 minutes in ms
252
252
  var VISIBILITY_CHANGE_TIMEOUT = SESSION_IDLE_DURATION;
253
253
  // The maximum length of a session
254
254
  var MAX_SESSION_LIFE = 1800000; // 30 minutes
255
+ /**
256
+ * Defaults for sampling rates
257
+ */
258
+ var DEFAULT_SESSION_SAMPLE_RATE = 0.1;
259
+ var DEFAULT_ERROR_SAMPLE_RATE = 1.0;
255
260
 
256
261
  /**
257
262
  * Deletes a session from storage
@@ -330,6 +335,9 @@ function saveSession(session) {
330
335
  * 0.0 = 0% sampling
331
336
  */
332
337
  function isSampled(sampleRate) {
338
+ if (sampleRate === undefined) {
339
+ return false;
340
+ }
333
341
  // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)
334
342
  return Math.random() < sampleRate;
335
343
  }
@@ -337,14 +345,15 @@ function isSampled(sampleRate) {
337
345
  var Session = /** @class */ (function () {
338
346
  function Session(session, _a) {
339
347
  if (session === void 0) { session = {}; }
340
- var _b = _a === void 0 ? {} : _a, _c = _b.stickySession, stickySession = _c === void 0 ? false : _c, _d = _b.samplingRate, samplingRate = _d === void 0 ? 1.0 : _d;
341
- var _e, _f, _g, _h;
348
+ var stickySession = _a.stickySession, sessionSampleRate = _a.sessionSampleRate, errorSampleRate = _a.errorSampleRate;
349
+ var _b, _c, _d, _e;
342
350
  var now = new Date().getTime();
343
351
  this._id = session.id || uuid4();
344
- this._started = (_e = session.started) !== null && _e !== void 0 ? _e : now;
345
- this._lastActivity = (_f = session.lastActivity) !== null && _f !== void 0 ? _f : now;
346
- this._segmentId = (_g = session.segmentId) !== null && _g !== void 0 ? _g : 0;
347
- this._sampled = (_h = session.sampled) !== null && _h !== void 0 ? _h : isSampled(samplingRate);
352
+ this._started = (_b = session.started) !== null && _b !== void 0 ? _b : now;
353
+ this._lastActivity = (_c = session.lastActivity) !== null && _c !== void 0 ? _c : now;
354
+ this._segmentId = (_d = session.segmentId) !== null && _d !== void 0 ? _d : 0;
355
+ this._sampled =
356
+ (_e = session.sampled) !== null && _e !== void 0 ? _e : (isSampled(sessionSampleRate) || isSampled(errorSampleRate));
348
357
  this.options = {
349
358
  stickySession: stickySession,
350
359
  };
@@ -427,8 +436,12 @@ var Session = /** @class */ (function () {
427
436
  * one of these Sentry events per "replay session".
428
437
  */
429
438
  function createSession(_a) {
430
- var _b = _a.stickySession, stickySession = _b === void 0 ? false : _b, _c = _a.samplingRate, samplingRate = _c === void 0 ? 1.0 : _c;
431
- var session = new Session(undefined, { stickySession: stickySession, samplingRate: samplingRate });
439
+ var sessionSampleRate = _a.sessionSampleRate, errorSampleRate = _a.errorSampleRate, _b = _a.stickySession, stickySession = _b === void 0 ? false : _b;
440
+ var session = new Session(undefined, {
441
+ stickySession: stickySession,
442
+ errorSampleRate: errorSampleRate,
443
+ sessionSampleRate: sessionSampleRate,
444
+ });
432
445
  logger.log("Creating new session: ".concat(session.id));
433
446
  if (stickySession) {
434
447
  saveSession(session);
@@ -436,23 +449,41 @@ function createSession(_a) {
436
449
  return session;
437
450
  }
438
451
 
452
+ /**
453
+ * Captures exceptions to Sentry only when it occurs on sentry.io
454
+ */
455
+ function captureInternalException(err) {
456
+ if (!isInternal()) {
457
+ return;
458
+ }
459
+ captureException(err);
460
+ }
461
+
439
462
  /**
440
463
  * Fetches a session from storage
441
464
  */
442
- function fetchSession() {
465
+ function fetchSession(_a) {
466
+ var sessionSampleRate = _a.sessionSampleRate, errorSampleRate = _a.errorSampleRate;
443
467
  var hasSessionStorage = 'sessionStorage' in window;
444
468
  if (!hasSessionStorage) {
445
469
  return null;
446
470
  }
471
+ var sessionStringFromStorage = window.sessionStorage.getItem(REPLAY_SESSION_KEY);
472
+ if (!sessionStringFromStorage) {
473
+ return null;
474
+ }
447
475
  try {
448
- return new Session(
449
- // @ts-expect-error: Type 'null' is not assignable to type 'string'.ts(2345)
450
- JSON.parse(window.sessionStorage.getItem(REPLAY_SESSION_KEY)),
476
+ var sessionObj = JSON.parse(sessionStringFromStorage);
477
+ // NOTE: This shouldn't happen
478
+ if (sessionObj.segmentId === 0) {
479
+ captureInternalException(new Error('Session storage object with segmentId = 0'));
480
+ }
481
+ return new Session(sessionObj,
451
482
  // We are assuming that if there is a saved item, then the session is sticky,
452
483
  // however this could break down if we used a different storage mechanism (e.g. localstorage)
453
- { stickySession: true });
484
+ { stickySession: true, sessionSampleRate: sessionSampleRate, errorSampleRate: errorSampleRate });
454
485
  }
455
- catch (_a) {
486
+ catch (_b) {
456
487
  return null;
457
488
  }
458
489
  }
@@ -461,9 +492,10 @@ function fetchSession() {
461
492
  * Get or create a session
462
493
  */
463
494
  function getSession(_a) {
464
- var expiry = _a.expiry, currentSession = _a.currentSession, stickySession = _a.stickySession, samplingRate = _a.samplingRate;
495
+ var expiry = _a.expiry, currentSession = _a.currentSession, stickySession = _a.stickySession, sessionSampleRate = _a.sessionSampleRate, errorSampleRate = _a.errorSampleRate;
465
496
  // If session exists and is passed, use it instead of always hitting session storage
466
- var session = currentSession || (stickySession && fetchSession());
497
+ var session = currentSession ||
498
+ (stickySession && fetchSession({ sessionSampleRate: sessionSampleRate, errorSampleRate: errorSampleRate }));
467
499
  if (session) {
468
500
  // If there is a session, check if it is valid (e.g. "last activity" time
469
501
  // should be within the "session idle time", and "session started" time is
@@ -477,7 +509,11 @@ function getSession(_a) {
477
509
  }
478
510
  // Otherwise continue to create a new session
479
511
  }
480
- var newSession = createSession({ stickySession: stickySession, samplingRate: samplingRate });
512
+ var newSession = createSession({
513
+ stickySession: stickySession,
514
+ sessionSampleRate: sessionSampleRate,
515
+ errorSampleRate: errorSampleRate,
516
+ });
481
517
  return { type: 'new', session: newSession };
482
518
  }
483
519
 
@@ -492,16 +528,6 @@ function addInternalBreadcrumb(arg) {
492
528
  addBreadcrumb(__assign({ category: category || 'console', level: level || 'debug', message: "[debug]: ".concat(message) }, rest));
493
529
  }
494
530
 
495
- /**
496
- * Captures exceptions to Sentry only when it occurs on sentry.io
497
- */
498
- function captureInternalException(err) {
499
- if (!isInternal()) {
500
- return;
501
- }
502
- captureException(err);
503
- }
504
-
505
531
  function createPayload(_a) {
506
532
  var events = _a.events, headers = _a.headers;
507
533
  var payloadWithSequence;
@@ -902,7 +928,7 @@ var Replay = /** @class */ (function () {
902
928
  function Replay(_a) {
903
929
  if (_a === void 0) { _a = {}; }
904
930
  var _this = this;
905
- 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.maskAllText, maskAllText = _j === void 0 ? true : _j, _k = _a.maskAllInputs, maskAllInputs = _k === void 0 ? true : _k, _l = _a.blockAllMedia, blockAllMedia = _l === void 0 ? true : _l, _m = _a.blockClass, blockClass = _m === void 0 ? 'sentry-block' : _m, _o = _a.ignoreClass, ignoreClass = _o === void 0 ? 'sentry-ignore' : _o, _p = _a.maskTextClass, maskTextClass = _p === void 0 ? 'sentry-mask' : _p, _q = _a.blockSelector, blockSelector = _q === void 0 ? '[data-sentry-block]' : _q, recordingOptions = __rest(_a, ["flushMinDelay", "flushMaxDelay", "initialFlushDelay", "stickySession", "useCompression", "captureOnlyOnError", "replaysSamplingRate", "maskAllText", "maskAllInputs", "blockAllMedia", "blockClass", "ignoreClass", "maskTextClass", "blockSelector"]);
931
+ 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.sessionSampleRate, sessionSampleRate = _g === void 0 ? DEFAULT_SESSION_SAMPLE_RATE : _g, _h = _a.errorSampleRate, errorSampleRate = _h === void 0 ? DEFAULT_ERROR_SAMPLE_RATE : _h, _j = _a.maskAllText, maskAllText = _j === void 0 ? true : _j, _k = _a.maskAllInputs, maskAllInputs = _k === void 0 ? true : _k, _l = _a.blockAllMedia, blockAllMedia = _l === void 0 ? true : _l, _m = _a.blockClass, blockClass = _m === void 0 ? 'sentry-block' : _m, _o = _a.ignoreClass, ignoreClass = _o === void 0 ? 'sentry-ignore' : _o, _p = _a.maskTextClass, maskTextClass = _p === void 0 ? 'sentry-mask' : _p, _q = _a.blockSelector, blockSelector = _q === void 0 ? '[data-sentry-block]' : _q, replaysSamplingRate = _a.replaysSamplingRate, captureOnlyOnError = _a.captureOnlyOnError, recordingOptions = __rest(_a, ["flushMinDelay", "flushMaxDelay", "initialFlushDelay", "stickySession", "useCompression", "sessionSampleRate", "errorSampleRate", "maskAllText", "maskAllInputs", "blockAllMedia", "blockClass", "ignoreClass", "maskTextClass", "blockSelector", "replaysSamplingRate", "captureOnlyOnError"]);
906
932
  /**
907
933
  * @inheritDoc
908
934
  */
@@ -914,11 +940,6 @@ var Replay = /** @class */ (function () {
914
940
  this.performanceObserver = null;
915
941
  this.retryCount = 0;
916
942
  this.retryInterval = BASE_RETRY_INTERVAL;
917
- /**
918
- * Flag when a new session has been created. Captured replay events behave
919
- * slightly differently in this case: `replay_start_timestamp` is included.
920
- */
921
- this.newSessionCreated = false;
922
943
  this.flushLock = null;
923
944
  /**
924
945
  * Timestamp of the last user activity. This lives across sessions.
@@ -929,12 +950,16 @@ var Replay = /** @class */ (function () {
929
950
  */
930
951
  this.isEnabled = false;
931
952
  /**
932
- *
933
953
  * Paused is a state where:
934
954
  * - DOM Recording is not listening at all
935
955
  * - Nothing will be added to event buffer (e.g. core SDK events)
936
956
  */
937
957
  this.isPaused = false;
958
+ /**
959
+ * Integration will wait until an error occurs before creating and sending a
960
+ * replay.
961
+ */
962
+ this.waitForError = false;
938
963
  /**
939
964
  * Have we attached listeners to the core SDK?
940
965
  * Note we have to track this as there is no way to remove instrumentation handlers.
@@ -979,13 +1004,28 @@ var Replay = /** @class */ (function () {
979
1004
  message: "Tagging event (".concat(event.event_id, ") - ").concat(event.message, " - ").concat((exc === null || exc === void 0 ? void 0 : exc.type) || 'Unknown', ": ").concat((exc === null || exc === void 0 ? void 0 : exc.value) || 'n/a'),
980
1005
  });
981
1006
  // Need to be very careful that this does not cause an infinite loop
982
- if (_this.options.captureOnlyOnError &&
1007
+ if (_this.waitForError &&
983
1008
  event.exception &&
984
- event.message !== UNABLE_TO_SEND_REPLAY // ignore this error because other we could loop indefinitely with trying to capture replay and failing
1009
+ event.message !== UNABLE_TO_SEND_REPLAY // ignore this error because otherwise we could loop indefinitely with trying to capture replay and failing
985
1010
  ) {
986
- // TODO: Do we continue to record after?
987
- // TODO: What happens if another error happens? Do we record in the same session?
988
- setTimeout(function () { return _this.flushImmediate(); });
1011
+ setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
1012
+ return __generator(this, function (_a) {
1013
+ switch (_a.label) {
1014
+ case 0: return [4 /*yield*/, this.flushImmediate()];
1015
+ case 1:
1016
+ _a.sent();
1017
+ if (this.stopRecording) {
1018
+ this.stopRecording();
1019
+ // Reset all "capture on error" configuration before
1020
+ // starting a new recording
1021
+ delete this.recordingOptions.checkoutEveryNms;
1022
+ this.waitForError = false;
1023
+ this.startRecording();
1024
+ }
1025
+ return [2 /*return*/];
1026
+ }
1027
+ });
1028
+ }); });
989
1029
  }
990
1030
  return event;
991
1031
  };
@@ -1198,21 +1238,37 @@ var Replay = /** @class */ (function () {
1198
1238
  });
1199
1239
  }); };
1200
1240
  this.recordingOptions = __assign({ maskAllInputs: maskAllInputs, blockClass: blockClass, ignoreClass: ignoreClass, maskTextClass: maskTextClass, blockSelector: blockSelector }, recordingOptions);
1241
+ var usingDeprecatedReplaysSamplingRate = replaysSamplingRate !== undefined;
1242
+ var usingDeprecatedCaptureOnlyOnError = captureOnlyOnError !== undefined;
1201
1243
  this.options = {
1202
1244
  flushMinDelay: flushMinDelay,
1203
1245
  flushMaxDelay: flushMaxDelay,
1204
1246
  stickySession: stickySession,
1205
1247
  initialFlushDelay: initialFlushDelay,
1206
- captureOnlyOnError: captureOnlyOnError,
1207
- replaysSamplingRate: replaysSamplingRate,
1248
+ sessionSampleRate: usingDeprecatedReplaysSamplingRate
1249
+ ? replaysSamplingRate
1250
+ : sessionSampleRate,
1251
+ errorSampleRate: usingDeprecatedCaptureOnlyOnError
1252
+ ? 1.0
1253
+ : errorSampleRate,
1208
1254
  useCompression: useCompression,
1209
1255
  maskAllText: maskAllText,
1210
1256
  blockAllMedia: blockAllMedia,
1211
1257
  };
1212
- // Modify rrweb options to checkoutEveryNthSecond if this is defined, as we don't know when an error occurs, so we want to try to minimize the number of events captured.
1213
- if (this.options.captureOnlyOnError) {
1258
+ // Modify recording options to checkoutEveryNthSecond if this is defined, as we
1259
+ // don't know when an error will occur, so we need to keep a buffer of replay events.
1260
+ if (this.options.errorSampleRate > 0 &&
1261
+ this.options.sessionSampleRate < 1.0) {
1214
1262
  // Checkout every minute, meaning we only get up-to one minute of events before the error happens
1215
1263
  this.recordingOptions.checkoutEveryNms = 60000;
1264
+ this.waitForError = true;
1265
+ }
1266
+ // TODO(deprecated): Maintain backwards compatibility for alpha users
1267
+ if (usingDeprecatedCaptureOnlyOnError) {
1268
+ console.warn('[@sentry/replay]: The `captureOnlyOnError` option is deprecated! Please configure `errorSampleRate` instead.');
1269
+ }
1270
+ if (usingDeprecatedReplaysSamplingRate) {
1271
+ console.warn('[@sentry/replay]: The `replaysSamplingRate` option is deprecated! Please configure `sessionSampleRate` instead.');
1216
1272
  }
1217
1273
  if (this.options.maskAllText) {
1218
1274
  // `maskAllText` is a more user friendly option to configure
@@ -1345,12 +1401,12 @@ var Replay = /** @class */ (function () {
1345
1401
  expiry: expiry,
1346
1402
  stickySession: Boolean(this.options.stickySession),
1347
1403
  currentSession: this.session,
1348
- samplingRate: this.options.replaysSamplingRate,
1404
+ sessionSampleRate: this.options.sessionSampleRate,
1405
+ errorSampleRate: this.options.errorSampleRate,
1349
1406
  }), type = _d.type, session = _d.session;
1350
1407
  // If session was newly created (i.e. was not loaded from storage), then
1351
1408
  // enable flag to create the root replay
1352
1409
  if (type === 'new') {
1353
- this.newSessionCreated = true;
1354
1410
  this.setInitialState();
1355
1411
  }
1356
1412
  if (session.id !== ((_b = this.session) === null || _b === void 0 ? void 0 : _b.id)) {
@@ -1445,11 +1501,11 @@ var Replay = /** @class */ (function () {
1445
1501
  * processing and hand back control to caller.
1446
1502
  */
1447
1503
  Replay.prototype.addUpdate = function (cb) {
1448
- // We need to always run `cb` (e.g. in the case of captureOnlyOnError == true)
1504
+ // We need to always run `cb` (e.g. in the case of `this.waitForError == true`)
1449
1505
  var cbResult = cb === null || cb === void 0 ? void 0 : cb();
1450
1506
  // If this option is turned on then we will only want to call `flush`
1451
1507
  // explicitly
1452
- if (this.options.captureOnlyOnError) {
1508
+ if (this.waitForError) {
1453
1509
  return;
1454
1510
  }
1455
1511
  // If callback is true, we do not want to continue with flushing -- the
@@ -1510,6 +1566,7 @@ var Replay = /** @class */ (function () {
1510
1566
  * Add an event to the event buffer
1511
1567
  */
1512
1568
  Replay.prototype.addEvent = function (event, isCheckout) {
1569
+ var _a;
1513
1570
  if (!this.eventBuffer) {
1514
1571
  // This implies that `isEnabled` is false
1515
1572
  return;
@@ -1531,7 +1588,7 @@ var Replay = /** @class */ (function () {
1531
1588
  }
1532
1589
  // Only record earliest event if a new session was created, otherwise it
1533
1590
  // shouldn't be relevant
1534
- if (this.newSessionCreated &&
1591
+ if (((_a = this.session) === null || _a === void 0 ? void 0 : _a.segmentId) === 0 &&
1535
1592
  (!this.context.earliestEvent ||
1536
1593
  timestampInMs < this.context.earliestEvent)) {
1537
1594
  this.context.earliestEvent = timestampInMs;
@@ -1679,10 +1736,10 @@ var Replay = /** @class */ (function () {
1679
1736
  return false;
1680
1737
  };
1681
1738
  /**
1682
- * Only flush if `captureOnlyOnError` is false.
1739
+ * Only flush if `this.waitForError` is false.
1683
1740
  */
1684
1741
  Replay.prototype.conditionalFlush = function () {
1685
- if (this.options.captureOnlyOnError) {
1742
+ if (this.waitForError) {
1686
1743
  return;
1687
1744
  }
1688
1745
  this.flushImmediate();
@@ -1726,7 +1783,7 @@ var Replay = /** @class */ (function () {
1726
1783
  Replay.prototype.runFlush = function () {
1727
1784
  var _a;
1728
1785
  return __awaiter(this, void 0, void 0, function () {
1729
- var replayId, newSessionCreated, segmentId, recordingData, err_2;
1786
+ var replayId, segmentId, recordingData, err_2;
1730
1787
  return __generator(this, function (_b) {
1731
1788
  switch (_b.label) {
1732
1789
  case 0:
@@ -1746,7 +1803,6 @@ var Replay = /** @class */ (function () {
1746
1803
  // Only attach memory event if eventBuffer is not empty
1747
1804
  _b.sent();
1748
1805
  replayId = this.session.id;
1749
- newSessionCreated = this.newSessionCreated;
1750
1806
  segmentId = this.session.segmentId++;
1751
1807
  _b.label = 3;
1752
1808
  case 3:
@@ -1758,11 +1814,10 @@ var Replay = /** @class */ (function () {
1758
1814
  replayId: replayId,
1759
1815
  events: recordingData,
1760
1816
  segmentId: segmentId,
1761
- includeReplayStartTimestamp: newSessionCreated,
1817
+ includeReplayStartTimestamp: segmentId === 0,
1762
1818
  })];
1763
1819
  case 5:
1764
1820
  _b.sent();
1765
- this.newSessionCreated = false;
1766
1821
  return [3 /*break*/, 7];
1767
1822
  case 6:
1768
1823
  err_2 = _b.sent();
@@ -1783,7 +1838,7 @@ var Replay = /** @class */ (function () {
1783
1838
  Replay.prototype.flushImmediate = function () {
1784
1839
  this.debouncedFlush();
1785
1840
  // `.flush` is provided by lodash.debounce
1786
- this.debouncedFlush.flush();
1841
+ return this.debouncedFlush.flush();
1787
1842
  };
1788
1843
  /**
1789
1844
  * Send replay attachment using `fetch()`
@@ -1807,7 +1862,7 @@ var Replay = /** @class */ (function () {
1807
1862
  timestamp = new Date().getTime();
1808
1863
  sdkInfo = {
1809
1864
  name: 'sentry.javascript.integration.replay',
1810
- version: "0.6.10-0",
1865
+ version: "0.6.11-0",
1811
1866
  };
1812
1867
  return [4 /*yield*/, new Promise(function (resolve) {
1813
1868
  var _a;