@sentry/replay 0.4.1 → 0.4.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.
package/dist/index.js CHANGED
@@ -565,7 +565,7 @@ function handleScope(scope) {
565
565
  var newBreadcrumb = scope._breadcrumbs[scope._breadcrumbs.length - 1];
566
566
  // Listener can be called when breadcrumbs have not changed, so we store the
567
567
  // reference to the last crumb and only return a crumb if it has changed
568
- if (_LAST_BREADCRUMB === newBreadcrumb) {
568
+ if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {
569
569
  return null;
570
570
  }
571
571
  _LAST_BREADCRUMB = newBreadcrumb;
@@ -596,14 +596,22 @@ function handleXhr(handlerData) {
596
596
  };
597
597
  }
598
598
 
599
- function captureReplay(session) {
599
+ function captureReplay(session, initialState) {
600
600
  var hub = core.getCurrentHub();
601
601
  hub.captureEvent({
602
602
  message: ROOT_REPLAY_NAME,
603
- tags: { sequenceId: session.sequenceId },
603
+ tags: { sequenceId: session.sequenceId, url: initialState.url },
604
+ timestamp: initialState.timestamp,
604
605
  }, { event_id: session.id });
605
606
  }
606
607
 
608
+ /**
609
+ * Determine if there is browser support for `navigator.sendBeacon`
610
+ */
611
+ function supportsSendBeacon() {
612
+ return 'navigator' in window && 'sendBeacon' in window.navigator;
613
+ }
614
+
607
615
  var BASE_RETRY_INTERVAL = 5000;
608
616
  var MAX_RETRY_COUNT = 5;
609
617
  var SentryReplay = /** @class */ (function () {
@@ -612,7 +620,7 @@ var SentryReplay = /** @class */ (function () {
612
620
  var _this = this;
613
621
  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
614
622
  _f = _a.useCompression, // TBD: Making this opt-in for now
615
- useCompression = _f === void 0 ? true : _f, _g = _a.rrwebConfig, _h = _g === void 0 ? {} : _g, _j = _h.maskAllInputs, maskAllInputs = _j === void 0 ? true : _j, _k = _h.blockClass, blockClass = _k === void 0 ? 'sr-block' : _k, _l = _h.ignoreClass, ignoreClass = _l === void 0 ? 'sr-ignore' : _l, _m = _h.maskTextClass, maskTextClass = _m === void 0 ? 'sr-mask' : _m, rrwebRecordOptions = __rest(_h, ["maskAllInputs", "blockClass", "ignoreClass", "maskTextClass"]);
623
+ useCompression = _f === void 0 ? true : _f, _g = _a.captureOnlyOnError, captureOnlyOnError = _g === void 0 ? false : _g, _h = _a.recordingConfig, _j = _h === void 0 ? {} : _h, _k = _j.maskAllInputs, maskAllInputs = _k === void 0 ? true : _k, _l = _j.blockClass, blockClass = _l === void 0 ? 'sr-block' : _l, _m = _j.ignoreClass, ignoreClass = _m === void 0 ? 'sr-ignore' : _m, _o = _j.maskTextClass, maskTextClass = _o === void 0 ? 'sr-mask' : _o, recordingOptions = __rest(_j, ["maskAllInputs", "blockClass", "ignoreClass", "maskTextClass"]);
616
624
  /**
617
625
  * @inheritDoc
618
626
  */
@@ -645,6 +653,65 @@ var SentryReplay = /** @class */ (function () {
645
653
  * immediately before sending recording)
646
654
  */
647
655
  this.needsCaptureReplay = false;
656
+ /**
657
+ * Core Sentry SDK global event handler. Attaches `replayId` to all [non-replay]
658
+ * events as a tag. Also handles the case where we only want to capture a reply
659
+ * when an error occurs.
660
+ **/
661
+ this.handleGlobalEvent = function (event) {
662
+ var _a;
663
+ // Do not apply replayId to the root event
664
+ if (event.message === ROOT_REPLAY_NAME ||
665
+ ((_a = event.message) === null || _a === void 0 ? void 0 : _a.startsWith(REPLAY_EVENT_NAME))) {
666
+ return event;
667
+ }
668
+ event.tags = __assign(__assign({}, event.tags), { replayId: _this.session.id });
669
+ // Need to be very careful that this does not cause an infinite loop
670
+ if (_this.options.captureOnlyOnError && event.exception) {
671
+ // TODO: Do we continue to record after?
672
+ // TODO: What happens if another error happens? Do we record in the same session?
673
+ setTimeout(function () { return _this.flushUpdate(); });
674
+ }
675
+ return event;
676
+ };
677
+ /**
678
+ * Handler for recording events.
679
+ *
680
+ * Adds to event buffer, and has varying flushing behaviors if the event was a checkout.
681
+ */
682
+ this.handleRecordingEmit = function (event, isCheckout) {
683
+ // If this is false, it means session is expired, create and a new session and wait for checkout
684
+ if (!_this.checkAndHandleExpiredSession()) {
685
+ logger.error(new Error('Received replay event after session expired.'));
686
+ return;
687
+ }
688
+ _this.addUpdate(function () {
689
+ // We need to clear existing events on a checkout, otherwise they are
690
+ // incremental event updates and should be appended
691
+ _this.eventBuffer.addEvent(event, isCheckout);
692
+ // Different behavior for full snapshots (type=2), ignore other event types
693
+ // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16
694
+ if (event.type !== 2) {
695
+ return false;
696
+ }
697
+ // If there is a previousSessionId after a full snapshot occurs, then
698
+ // the replay session was started due to session expiration. The new session
699
+ // is started before triggering a new checkout and contains the id
700
+ // of the previous session. Do not immediately flush in this case
701
+ // to avoid capturing only the checkout and instead the replay will
702
+ // be captured if they perform any follow-up actions.
703
+ if (_this.session.previousSessionId) {
704
+ return true;
705
+ }
706
+ // If the full snapshot is due to an initial load, we will not have
707
+ // a previous session ID. In this case, we want to buffer events
708
+ // for a set amount of time before flushing. This can help avoid
709
+ // capturing replays of users that immediately close the window.
710
+ var now = new Date().getTime();
711
+ setTimeout(function () { return _this.conditionalFlush(now); }, _this.options.initialFlushDelay);
712
+ return true;
713
+ });
714
+ };
648
715
  /**
649
716
  * Handle when visibility of the page content changes. Opening a new tab will
650
717
  * cause the state to change to hidden because of content of current page will
@@ -677,11 +744,20 @@ var SentryReplay = /** @class */ (function () {
677
744
  });
678
745
  _this.doChangeToForegroundTasks(breadcrumb);
679
746
  };
747
+ /**
748
+ * Handle when page is closed
749
+ */
680
750
  this.handleWindowUnload = function () {
681
751
  _this.createCustomBreadcrumb(createBreadcrumb({
682
752
  category: 'ui.exit',
683
753
  }));
684
754
  };
755
+ /**
756
+ * Handler for Sentry Core SDK events.
757
+ *
758
+ * Transforms core SDK events into replay events.
759
+ *
760
+ */
685
761
  this.handleCoreListener = function (type) { return function (handlerData) {
686
762
  var handlerMap = {
687
763
  scope: [handleScope, 'breadcrumb'],
@@ -722,13 +798,19 @@ var SentryReplay = /** @class */ (function () {
722
798
  ) {
723
799
  _this.performanceEvents = __spreadArray(__spreadArray([], _this.performanceEvents, true), list.getEntries(), true);
724
800
  };
725
- this.rrwebRecordOptions = __assign({ maskAllInputs: maskAllInputs, blockClass: blockClass, ignoreClass: ignoreClass, maskTextClass: maskTextClass }, rrwebRecordOptions);
801
+ this.recordingOptions = __assign({ maskAllInputs: maskAllInputs, blockClass: blockClass, ignoreClass: ignoreClass, maskTextClass: maskTextClass }, recordingOptions);
726
802
  this.options = {
727
803
  flushMinDelay: flushMinDelay,
728
804
  flushMaxDelay: flushMaxDelay,
729
805
  stickySession: stickySession,
730
806
  initialFlushDelay: initialFlushDelay,
807
+ captureOnlyOnError: captureOnlyOnError,
731
808
  };
809
+ // 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.
810
+ if (this.options.captureOnlyOnError) {
811
+ // Checkout every minute, meaning we only get up-to one minute of events before the error happens
812
+ this.recordingOptions.checkoutEveryNms = 60000;
813
+ }
732
814
  this.eventBuffer = createEventBuffer({ useCompression: useCompression });
733
815
  }
734
816
  SentryReplay.attachmentUrlFromDsn = function (dsn, eventId) {
@@ -749,8 +831,12 @@ var SentryReplay = /** @class */ (function () {
749
831
  */
750
832
  window.setTimeout(function () { return _this.setup(); });
751
833
  };
834
+ /**
835
+ * Initializes the plugin.
836
+ *
837
+ * Creates or loads a session, attaches listeners to varying events (DOM, PerformanceObserver, Recording, Sentry SDK, etc)
838
+ */
752
839
  SentryReplay.prototype.setup = function () {
753
- var _this = this;
754
840
  this.loadSession({ expiry: SESSION_IDLE_DURATION });
755
841
  // If there is no session, then something bad has happened - can't continue
756
842
  if (!this.session) {
@@ -759,46 +845,14 @@ var SentryReplay = /** @class */ (function () {
759
845
  this.addListeners();
760
846
  // Tag all (non replay) events that get sent to Sentry with the current
761
847
  // replay ID so that we can reference them later in the UI
762
- core.addGlobalEventProcessor(function (event) {
763
- // Do not apply replayId to the root event
764
- if (event.message === ROOT_REPLAY_NAME) {
765
- return event;
766
- }
767
- event.tags = __assign(__assign({}, event.tags), { replayId: _this.session.id });
768
- return event;
769
- });
770
- rrweb.record(__assign(__assign({}, this.rrwebRecordOptions), { emit: function (event, isCheckout) {
771
- // If this is false, it means session is expired, create and a new session and wait for checkout
772
- if (!_this.checkAndHandleExpiredSession()) {
773
- logger.error(new Error('Received replay event after session expired.'));
774
- return;
775
- }
776
- _this.addUpdate(function () {
777
- // We need to clear existing events on a checkout, otherwise they are
778
- // incremental event updates and should be appended
779
- _this.eventBuffer.addEvent(event, isCheckout);
780
- // This event type is a fullsnapshot
781
- // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16
782
- if (event.type === 2) {
783
- // If the full snapshot is due to an initial load, we will not have
784
- // a previous session ID. In this case, we want to buffer events
785
- // for a set amount of time before flushing. This can help avoid
786
- // capturing replays of users that immediately close the window.
787
- if (!_this.session.previousSessionId) {
788
- var now_1 = new Date().getTime();
789
- setTimeout(function () { return _this.flushUpdate(now_1); }, _this.options.initialFlushDelay);
790
- return true;
791
- }
792
- // The other case where a full snapshot occurs is when a new replay
793
- // needs to be started due to session expiration. The new session
794
- // is started before triggering a new checkout and contains the id
795
- // of the previous session. Do not immediately flush in this case
796
- // to avoid capturing only the checkout and instead the replay will
797
- // be captured if they perform any follow-up actions.
798
- return true;
799
- }
800
- });
801
- } }));
848
+ core.addGlobalEventProcessor(this.handleGlobalEvent);
849
+ rrweb.record(__assign(__assign({}, this.recordingOptions), { emit: this.handleRecordingEmit }));
850
+ // Otherwise, these will be captured after the first flush, which means the
851
+ // URL and timestamps could be incorrect
852
+ this.initialState = {
853
+ timestamp: new Date().getTime(),
854
+ url: "".concat(window.location.origin).concat(window.location.pathname),
855
+ };
802
856
  };
803
857
  /**
804
858
  * We want to batch uploads of replay events. Save events only if
@@ -813,16 +867,24 @@ var SentryReplay = /** @class */ (function () {
813
867
  var now = new Date().getTime();
814
868
  // Timestamp of the first replay event since the last flush, this gets
815
869
  // reset when we finish the replay event
816
- if (!this.initialEventTimestampSinceFlush) {
870
+ if (!this.initialEventTimestampSinceFlush &&
871
+ !this.options.captureOnlyOnError) {
817
872
  this.initialEventTimestampSinceFlush = now;
818
873
  }
819
874
  // Do not finish the replay event if we receive a new replay event
820
875
  if (this.timeout) {
821
876
  window.clearTimeout(this.timeout);
822
877
  }
878
+ // We need to always run `cb` (e.g. in the case of captureOnlyOnError == true)
879
+ var cbResult = cb === null || cb === void 0 ? void 0 : cb();
880
+ // If this option is turned on then we will only want to call `flushUpdate`
881
+ // explicitly
882
+ if (this.options.captureOnlyOnError) {
883
+ return;
884
+ }
823
885
  // If callback is true, we do not want to continue with flushing -- the
824
886
  // caller will need to handle it.
825
- if ((cb === null || cb === void 0 ? void 0 : cb()) === true) {
887
+ if (cbResult === true) {
826
888
  return;
827
889
  }
828
890
  var flushMaxDelayExceeded = isExpired(this.initialEventTimestampSinceFlush, this.options.flushMaxDelay, now);
@@ -873,6 +935,9 @@ var SentryReplay = /** @class */ (function () {
873
935
  }
874
936
  this.session = session;
875
937
  };
938
+ /**
939
+ * Adds listeners to record events for the replay
940
+ */
876
941
  SentryReplay.prototype.addListeners = function () {
877
942
  var _this = this;
878
943
  document.addEventListener('visibilitychange', this.handleVisibilityChange);
@@ -906,6 +971,9 @@ var SentryReplay = /** @class */ (function () {
906
971
  });
907
972
  });
908
973
  };
974
+ /**
975
+ * Cleans up listeners that were created in `addListeners`
976
+ */
909
977
  SentryReplay.prototype.removeListeners = function () {
910
978
  document.removeEventListener('visibilitychange', this.handleVisibilityChange);
911
979
  document.removeEventListener('beforeunload', this.handleWindowUnload);
@@ -929,7 +997,7 @@ var SentryReplay = /** @class */ (function () {
929
997
  // Send replay when the page/tab becomes hidden. There is no reason to send
930
998
  // replay if it becomes visible, since no actions we care about were done
931
999
  // while it was hidden
932
- this.flushUpdate();
1000
+ this.conditionalFlush();
933
1001
  };
934
1002
  /**
935
1003
  * Tasks to run when we consider a page to be visible (via focus and/or visibility)
@@ -964,10 +1032,16 @@ var SentryReplay = /** @class */ (function () {
964
1032
  logger.log('Taking full rrweb snapshot');
965
1033
  rrweb.record.takeFullSnapshot(true);
966
1034
  };
1035
+ /**
1036
+ * Updates the session's last activity timestamp
1037
+ */
967
1038
  SentryReplay.prototype.updateLastActivity = function (lastActivity) {
968
1039
  if (lastActivity === void 0) { lastActivity = new Date().getTime(); }
969
1040
  this.session.lastActivity = lastActivity;
970
1041
  };
1042
+ /**
1043
+ * Helper to create (and buffer) a replay breadcrumb from a core SDK breadcrumb
1044
+ */
971
1045
  SentryReplay.prototype.createCustomBreadcrumb = function (breadcrumb) {
972
1046
  var _this = this;
973
1047
  this.addUpdate(function () {
@@ -1045,9 +1119,24 @@ var SentryReplay = /** @class */ (function () {
1045
1119
  this.triggerFullSnapshot();
1046
1120
  return false;
1047
1121
  };
1122
+ /**
1123
+ * Only flush if `captureOnlyOnError` is false.
1124
+ */
1125
+ SentryReplay.prototype.conditionalFlush = function (lastActivity) {
1126
+ if (this.options.captureOnlyOnError) {
1127
+ return;
1128
+ }
1129
+ return this.flushUpdate(lastActivity);
1130
+ };
1131
+ /**
1132
+ * Flushes replay event buffer to Sentry.
1133
+ *
1134
+ * Performance events are only added right before flushing - this is probably
1135
+ * due to the buffered performance observer events.
1136
+ */
1048
1137
  SentryReplay.prototype.flushUpdate = function (lastActivity) {
1049
1138
  return __awaiter(this, void 0, void 0, function () {
1050
- var recordingData, err_1;
1139
+ var timestamp, recordingData, err_1;
1051
1140
  return __generator(this, function (_a) {
1052
1141
  switch (_a.label) {
1053
1142
  case 0:
@@ -1066,7 +1155,7 @@ var SentryReplay = /** @class */ (function () {
1066
1155
  // Only want to create replay event if session is new
1067
1156
  if (this.needsCaptureReplay) {
1068
1157
  // This event needs to exist before calling `sendReplay`
1069
- captureReplay(this.session);
1158
+ captureReplay(this.session, this.initialState);
1070
1159
  this.needsCaptureReplay = false;
1071
1160
  }
1072
1161
  // Reset this to null regardless of `sendReplay` result so that future
@@ -1075,6 +1164,7 @@ var SentryReplay = /** @class */ (function () {
1075
1164
  _a.label = 1;
1076
1165
  case 1:
1077
1166
  _a.trys.push([1, 4, , 5]);
1167
+ timestamp = lastActivity !== null && lastActivity !== void 0 ? lastActivity : new Date().getTime();
1078
1168
  return [4 /*yield*/, this.eventBuffer.finish()];
1079
1169
  case 2:
1080
1170
  recordingData = _a.sent();
@@ -1083,8 +1173,12 @@ var SentryReplay = /** @class */ (function () {
1083
1173
  _a.sent();
1084
1174
  // The below will only happen after successfully sending replay //
1085
1175
  // TBD: Alternatively we could update this after every rrweb event
1086
- this.updateLastActivity(lastActivity);
1176
+ // `timestamp` should reflect when the event happens. e.g. the timestamp
1177
+ // of the event is passed as an argument in the case where a timeout
1178
+ // occurs.
1179
+ this.updateLastActivity(timestamp);
1087
1180
  core.captureEvent({
1181
+ timestamp: timestamp,
1088
1182
  message: "".concat(REPLAY_EVENT_NAME, "-").concat(utils.uuid4().substring(16)),
1089
1183
  tags: {
1090
1184
  replayId: this.session.id,
@@ -1101,12 +1195,6 @@ var SentryReplay = /** @class */ (function () {
1101
1195
  });
1102
1196
  });
1103
1197
  };
1104
- /**
1105
- * Determine if there is browser support for `navigator.sendBeacon`
1106
- */
1107
- SentryReplay.prototype.hasSendBeacon = function () {
1108
- return 'navigator' in window && 'sendBeacon' in window.navigator;
1109
- };
1110
1198
  /**
1111
1199
  * Send replay attachment using either `sendBeacon()` or `fetch()`
1112
1200
  */
@@ -1124,7 +1212,7 @@ var SentryReplay = /** @class */ (function () {
1124
1212
  logger.log('blob size in bytes: ', payloadBlob.size);
1125
1213
  formData.append('rrweb', payloadBlob, "rrweb-".concat(new Date().getTime(), ".json"));
1126
1214
  // If sendBeacon is supported and payload is smol enough...
1127
- if (this.hasSendBeacon() && payloadBlob.size <= 65535) {
1215
+ if (supportsSendBeacon() && payloadBlob.size <= 65535) {
1128
1216
  logger.log("uploading attachment via sendBeacon()");
1129
1217
  window.navigator.sendBeacon(endpoint, formData);
1130
1218
  return [2 /*return*/];