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