@sentry/replay 0.5.15 → 0.5.16

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.
@@ -1,15 +1,37 @@
1
1
  import { InitialState } from '@/types';
2
2
  export interface CaptureReplayEventParams {
3
+ /**
4
+ * Initial state of the replay
5
+ */
3
6
  initialState: InitialState;
7
+ /**
8
+ * Include a timestamp that should be deemed as the "starting" timestamp of the
9
+ * replay. This usually comes from a `window.performance` entry.
10
+ */
4
11
  includeReplayStartTimestamp: boolean;
12
+ /**
13
+ * List of error ids contained in current recording segment
14
+ */
5
15
  errorIds: string[];
16
+ /**
17
+ * The current replay id
18
+ */
6
19
  replayId: string;
20
+ /**
21
+ * The current recording segment id
22
+ */
7
23
  segmentId: number;
8
24
  /**
9
25
  * Timestamp of the event in milliseconds
10
26
  */
11
27
  timestamp: number;
28
+ /**
29
+ * List of trace ids contained in current recording segment
30
+ */
12
31
  traceIds: string[];
32
+ /**
33
+ * List of URLs visisted in current recording segment
34
+ */
13
35
  urls: string[];
14
36
  }
15
37
  export declare function captureReplayEvent({ initialState, includeReplayStartTimestamp, errorIds, replayId: replay_id, segmentId: segment_id, timestamp, traceIds, urls, }: CaptureReplayEventParams): void;
@@ -1,3 +1,4 @@
1
+ import { AllPerformanceEntry } from './types';
1
2
  export interface ReplayPerformanceEntry {
2
3
  /**
3
4
  * One of these types https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry/entryType
@@ -25,7 +26,7 @@ interface MemoryInfo {
25
26
  totalJSHeapSize: number;
26
27
  usedJSHeapSize: number;
27
28
  }
28
- export declare function createPerformanceEntries(entries: PerformanceEntry[]): ReplayPerformanceEntry[];
29
+ export declare function createPerformanceEntries(entries: AllPerformanceEntry[]): ReplayPerformanceEntry[];
29
30
  export declare function createMemoryEntry(memoryEntry: MemoryInfo): {
30
31
  type: string;
31
32
  name: string;
@@ -1,9 +1,10 @@
1
+ /// <reference types="lodash" />
1
2
  import { Breadcrumb, Event, Integration } from '@sentry/types';
2
3
  import { CaptureReplayEventParams } from './api/captureReplayEvent';
3
4
  import { Session } from './session/Session';
4
5
  import { ReplayPerformanceEntry } from './createPerformanceEntry';
5
6
  import { IEventBuffer } from './eventBuffer';
6
- import type { InstrumentationTypeBreadcrumb, InstrumentationTypeSpan, RecordedEvents, RecordingConfig, RecordingEvent, ReplayRequest, SentryReplayConfiguration, SentryReplayPluginOptions } from './types';
7
+ import type { AllPerformanceEntry, InstrumentationTypeBreadcrumb, InstrumentationTypeSpan, RecordedEvents, RecordingConfig, RecordingEvent, ReplayRequest, SentryReplayConfiguration, SentryReplayPluginOptions } from './types';
7
8
  /**
8
9
  * Returns true to return control to calling function, otherwise continue with normal batching
9
10
  */
@@ -21,7 +22,7 @@ export declare class SentryReplay implements Integration {
21
22
  /**
22
23
  * List of PerformanceEntry from PerformanceObserver
23
24
  */
24
- performanceEvents: PerformanceEntry[];
25
+ performanceEvents: AllPerformanceEntry[];
25
26
  /**
26
27
  * Options to pass to `rrweb.record()`
27
28
  */
@@ -45,6 +46,7 @@ export declare class SentryReplay implements Integration {
45
46
  * slightly differently in this case: `replay_start_timestamp` is included.
46
47
  */
47
48
  private newSessionCreated;
49
+ private flushLock;
48
50
  /**
49
51
  * Is the integration currently active?
50
52
  */
@@ -209,19 +211,25 @@ export declare class SentryReplay implements Integration {
209
211
  * Only flush if `captureOnlyOnError` is false.
210
212
  */
211
213
  conditionalFlush(): Promise<void> | undefined;
214
+ /**
215
+ * Clear context
216
+ */
217
+ clearContext(): void;
212
218
  /**
213
219
  * Return and clear context
214
220
  */
215
- popEventContext({ timestamp, }?: {
216
- timestamp?: number;
217
- }): CaptureReplayEventParams;
221
+ popEventContext({ timestamp, }: {
222
+ timestamp: number;
223
+ }): Omit<CaptureReplayEventParams, 'includeReplayStartTimestamp' | 'segmentId' | 'replayId'>;
224
+ runFlush(): Promise<void>;
218
225
  /**
219
226
  * Flushes replay event buffer to Sentry.
220
227
  *
221
228
  * Performance events are only added right before flushing - this is probably
222
229
  * due to the buffered performance observer events.
223
230
  */
224
- flushUpdate(): Promise<void>;
231
+ flushUpdate: () => Promise<void>;
232
+ throttledFlushUpdate: import("lodash").DebouncedFunc<() => Promise<void>>;
225
233
  /**
226
234
  * Send replay attachment using `fetch()`
227
235
  */
@@ -0,0 +1 @@
1
+ export {};
@@ -3,6 +3,7 @@ import type { eventWithTime } from 'rrweb/typings/types';
3
3
  export declare type RecordingEvent = eventWithTime;
4
4
  export declare type RecordingConfig = Parameters<typeof record>[0];
5
5
  export declare type RecordedEvents = Uint8Array | string;
6
+ export declare type AllPerformanceEntry = PerformancePaintTiming | PerformanceResourceTiming | PerformanceNavigationTiming;
6
7
  export interface ReplayRequest {
7
8
  endpoint: string;
8
9
  events: RecordedEvents;
package/dist/index.es.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { captureEvent, getCurrentHub, captureException, addGlobalEventProcessor, setContext, getEnvelopeEndpointWithUrlEncodedAuth } from '@sentry/core';
2
2
  import { htmlTreeAsString, logger as logger$1, uuid4, addInstrumentationHandler, createEnvelope, serializeEnvelope } from '@sentry/utils';
3
+ import throttle from 'lodash.throttle';
3
4
  import { record, EventType } from 'rrweb';
4
5
 
5
6
  /******************************************************************************
@@ -97,11 +98,11 @@ var VISIBILITY_CHANGE_TIMEOUT = SESSION_IDLE_DURATION;
97
98
 
98
99
  function captureReplayEvent(_a) {
99
100
  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;
100
- captureEvent(__assign(__assign(__assign({
101
+ captureEvent(__assign(__assign({
101
102
  // @ts-expect-error replay_event is a new event type
102
103
  type: REPLAY_EVENT_NAME }, (includeReplayStartTimestamp
103
104
  ? { replay_start_timestamp: initialState.timestamp / 1000 }
104
- : {})), (timestamp ? { timestamp: timestamp / 1000 } : {})), { error_ids: errorIds, trace_ids: traceIds, urls: urls, replay_id: replay_id, segment_id: segment_id }), { event_id: replay_id });
105
+ : {})), { timestamp: timestamp / 1000, error_ids: errorIds, trace_ids: traceIds, urls: urls, replay_id: replay_id, segment_id: segment_id }), { event_id: replay_id });
105
106
  }
106
107
 
107
108
  function createBreadcrumb(breadcrumb) {
@@ -814,6 +815,7 @@ var SentryReplay = /** @class */ (function () {
814
815
  * slightly differently in this case: `replay_start_timestamp` is included.
815
816
  */
816
817
  this.newSessionCreated = false;
818
+ this.flushLock = null;
817
819
  /**
818
820
  * Is the integration currently active?
819
821
  */
@@ -927,6 +929,8 @@ var SentryReplay = /** @class */ (function () {
927
929
  var breadcrumb = createBreadcrumb({
928
930
  category: 'ui.blur',
929
931
  });
932
+ // Do not count blur as a user action -- it's part of the process of them
933
+ // leaving the page
930
934
  _this.doChangeToBackgroundTasks(breadcrumb);
931
935
  };
932
936
  /**
@@ -936,6 +940,8 @@ var SentryReplay = /** @class */ (function () {
936
940
  var breadcrumb = createBreadcrumb({
937
941
  category: 'ui.focus',
938
942
  });
943
+ // Do not count focus as a user action -- instead wait until they focus and
944
+ // interactive with page
939
945
  _this.doChangeToForegroundTasks(breadcrumb);
940
946
  };
941
947
  /**
@@ -956,6 +962,7 @@ var SentryReplay = /** @class */ (function () {
956
962
  if (type === 'history') {
957
963
  // Need to collect visited URLs
958
964
  _this.context.urls.push(result.name);
965
+ _this.updateLastActivity();
959
966
  }
960
967
  _this.addUpdate(function () {
961
968
  _this.createPerformanceSpans([result]);
@@ -982,6 +989,9 @@ var SentryReplay = /** @class */ (function () {
982
989
  if (result.category === 'sentry.transaction') {
983
990
  return;
984
991
  }
992
+ if (result.category === 'ui.click') {
993
+ _this.updateLastActivity();
994
+ }
985
995
  _this.addUpdate(function () {
986
996
  _this.addEvent({
987
997
  type: EventType.Custom,
@@ -1004,6 +1014,63 @@ var SentryReplay = /** @class */ (function () {
1004
1014
  var newEntries = new Set(list.getEntries());
1005
1015
  _this.performanceEvents = __spreadArray(__spreadArray([], _this.performanceEvents, true), Array.from(newEntries), true);
1006
1016
  };
1017
+ /**
1018
+ * Flushes replay event buffer to Sentry.
1019
+ *
1020
+ * Performance events are only added right before flushing - this is probably
1021
+ * due to the buffered performance observer events.
1022
+ */
1023
+ this.flushUpdate = function () { return __awaiter(_this, void 0, void 0, function () {
1024
+ var err_1;
1025
+ var _a;
1026
+ return __generator(this, function (_b) {
1027
+ switch (_b.label) {
1028
+ case 0:
1029
+ if (!this.isEnabled) {
1030
+ // This is just a precaution, there should be no listeners that would
1031
+ // cause a flush.
1032
+ return [2 /*return*/];
1033
+ }
1034
+ if (!this.checkAndHandleExpiredSession()) {
1035
+ logger.error(new Error('Attempting to finish replay event after session expired.'));
1036
+ return [2 /*return*/];
1037
+ }
1038
+ if (!((_a = this.session) === null || _a === void 0 ? void 0 : _a.id)) {
1039
+ console.error(new Error('[Sentry]: No transaction, no replay'));
1040
+ return [2 /*return*/];
1041
+ }
1042
+ // Since flushing, ensure other queued flushes are cancelled
1043
+ // We do this regardless of having a queued flush since the event updates
1044
+ // will be handled by queued flush
1045
+ clearTimeout(this.timeout);
1046
+ if (!!this.flushLock) return [3 /*break*/, 2];
1047
+ this.flushLock = this.runFlush();
1048
+ return [4 /*yield*/, this.flushLock];
1049
+ case 1:
1050
+ _b.sent();
1051
+ this.flushLock = null;
1052
+ return [2 /*return*/];
1053
+ case 2:
1054
+ _b.trys.push([2, 4, 5, 6]);
1055
+ return [4 /*yield*/, this.flushLock];
1056
+ case 3:
1057
+ _b.sent();
1058
+ return [3 /*break*/, 6];
1059
+ case 4:
1060
+ err_1 = _b.sent();
1061
+ console.error(err_1);
1062
+ return [3 /*break*/, 6];
1063
+ case 5:
1064
+ this.throttledFlushUpdate();
1065
+ return [7 /*endfinally*/];
1066
+ case 6: return [2 /*return*/];
1067
+ }
1068
+ });
1069
+ }); };
1070
+ this.throttledFlushUpdate = throttle(this.flushUpdate, 1000, {
1071
+ leading: false,
1072
+ trailing: true,
1073
+ });
1007
1074
  this.recordingOptions = __assign({ maskAllInputs: maskAllInputs, blockClass: blockClass, ignoreClass: ignoreClass, maskTextClass: maskTextClass }, recordingOptions);
1008
1075
  this.options = {
1009
1076
  flushMinDelay: flushMinDelay,
@@ -1049,6 +1116,9 @@ var SentryReplay = /** @class */ (function () {
1049
1116
  // If session was not sampled, then we do not initialize the integration at all.
1050
1117
  return;
1051
1118
  }
1119
+ // setup() is generally called on page load or manually - in both cases we
1120
+ // should treat it as an activity
1121
+ this.updateLastActivity();
1052
1122
  this.eventBuffer = createEventBuffer({
1053
1123
  useCompression: Boolean(this.options.useCompression),
1054
1124
  });
@@ -1159,7 +1229,7 @@ var SentryReplay = /** @class */ (function () {
1159
1229
  this.performanceEvents = [];
1160
1230
  this.initialEventTimestampSinceFlush = null;
1161
1231
  // Reset context as well
1162
- this.popEventContext();
1232
+ this.clearContext();
1163
1233
  this.initialState = {
1164
1234
  timestamp: new Date().getTime(),
1165
1235
  url: url,
@@ -1404,11 +1474,20 @@ var SentryReplay = /** @class */ (function () {
1404
1474
  }
1405
1475
  return this.flushUpdate();
1406
1476
  };
1477
+ /**
1478
+ * Clear context
1479
+ */
1480
+ SentryReplay.prototype.clearContext = function () {
1481
+ this.context.errorIds.clear();
1482
+ this.context.traceIds.clear();
1483
+ this.context.urls = [];
1484
+ this.context.earliestEvent = null;
1485
+ };
1407
1486
  /**
1408
1487
  * Return and clear context
1409
1488
  */
1410
1489
  SentryReplay.prototype.popEventContext = function (_a) {
1411
- var _b = _a === void 0 ? {} : _a, timestamp = _b.timestamp;
1490
+ var timestamp = _a.timestamp;
1412
1491
  var initialState = this.initialState;
1413
1492
  if (this.initialState &&
1414
1493
  this.context.earliestEvent &&
@@ -1422,52 +1501,31 @@ var SentryReplay = /** @class */ (function () {
1422
1501
  traceIds: Array.from(this.context.traceIds).filter(Boolean),
1423
1502
  urls: this.context.urls,
1424
1503
  };
1425
- this.context.errorIds.clear();
1426
- this.context.traceIds.clear();
1427
- this.context.urls = [];
1428
- this.context.earliestEvent = null;
1429
- // @ts-expect-error: Type 'undefined' is not assignable to type 'Session'.ts(2322)
1504
+ this.clearContext();
1430
1505
  return context;
1431
1506
  };
1432
- /**
1433
- * Flushes replay event buffer to Sentry.
1434
- *
1435
- * Performance events are only added right before flushing - this is probably
1436
- * due to the buffered performance observer events.
1437
- */
1438
- SentryReplay.prototype.flushUpdate = function () {
1439
- var _a, _b;
1507
+ SentryReplay.prototype.runFlush = function () {
1508
+ var _a;
1440
1509
  return __awaiter(this, void 0, void 0, function () {
1441
- var timestamp, replayId, newSessionCreated, segmentId, recordingData, err_1;
1442
- return __generator(this, function (_c) {
1443
- switch (_c.label) {
1510
+ var timestamp, replayId, newSessionCreated, segmentId, recordingData, err_2;
1511
+ return __generator(this, function (_b) {
1512
+ switch (_b.label) {
1444
1513
  case 0:
1445
- if (!this.isEnabled) {
1446
- // This is just a precaution, there should be no listeners that would
1447
- // cause a flush.
1448
- return [2 /*return*/];
1449
- }
1450
- if (!this.checkAndHandleExpiredSession()) {
1451
- logger.error(new Error('Attempting to finish replay event after session expired.'));
1452
- return [2 /*return*/];
1453
- }
1454
- if (!((_a = this.session) === null || _a === void 0 ? void 0 : _a.id)) {
1514
+ if (!this.session) {
1455
1515
  console.error(new Error('[Sentry]: No transaction, no replay'));
1456
1516
  return [2 /*return*/];
1457
1517
  }
1458
- // Since already flushing, ensure other queued flushes are cancelled
1459
- clearTimeout(this.timeout);
1460
1518
  return [4 /*yield*/, this.addPerformanceEntries()];
1461
1519
  case 1:
1462
- _c.sent();
1463
- if (!((_b = this.eventBuffer) === null || _b === void 0 ? void 0 : _b.length)) {
1520
+ _b.sent();
1521
+ if (!((_a = this.eventBuffer) === null || _a === void 0 ? void 0 : _a.length)) {
1464
1522
  return [2 /*return*/];
1465
1523
  }
1466
1524
  // Only attach memory event if eventBuffer is not empty
1467
1525
  return [4 /*yield*/, this.addMemoryEntry()];
1468
1526
  case 2:
1469
1527
  // Only attach memory event if eventBuffer is not empty
1470
- _c.sent();
1528
+ _b.sent();
1471
1529
  timestamp = new Date().getTime();
1472
1530
  replayId = this.session.id;
1473
1531
  newSessionCreated = this.newSessionCreated;
@@ -1475,28 +1533,23 @@ var SentryReplay = /** @class */ (function () {
1475
1533
  // Reset this to null regardless of `sendReplay` result so that future
1476
1534
  // events will get flushed properly
1477
1535
  this.initialEventTimestampSinceFlush = null;
1478
- _c.label = 3;
1536
+ _b.label = 3;
1479
1537
  case 3:
1480
- _c.trys.push([3, 6, , 7]);
1538
+ _b.trys.push([3, 6, , 7]);
1481
1539
  return [4 /*yield*/, this.eventBuffer.finish()];
1482
1540
  case 4:
1483
- recordingData = _c.sent();
1541
+ recordingData = _b.sent();
1484
1542
  return [4 /*yield*/, this.sendReplay(replayId, recordingData, segmentId)];
1485
1543
  case 5:
1486
- _c.sent();
1544
+ _b.sent();
1487
1545
  // The below will only happen after successfully sending replay //
1488
- // TBD: Alternatively we could update this after every rrweb event
1489
- // `timestamp` should reflect when the event happens. e.g. the timestamp
1490
- // of the event is passed as an argument in the case where a timeout
1491
- // occurs.
1492
- this.updateLastActivity(timestamp);
1493
1546
  captureReplayEvent(__assign(__assign({}, this.popEventContext({ timestamp: timestamp })), { replayId: replayId, segmentId: segmentId, includeReplayStartTimestamp: newSessionCreated }));
1494
1547
  this.newSessionCreated = false;
1495
1548
  return [3 /*break*/, 7];
1496
1549
  case 6:
1497
- err_1 = _c.sent();
1498
- captureException(err_1);
1499
- console.error(err_1);
1550
+ err_2 = _b.sent();
1551
+ captureException(err_2);
1552
+ console.error(err_2);
1500
1553
  return [3 /*break*/, 7];
1501
1554
  case 7: return [2 /*return*/];
1502
1555
  }
package/dist/index.js CHANGED
@@ -4,8 +4,13 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var core = require('@sentry/core');
6
6
  var utils = require('@sentry/utils');
7
+ var throttle = require('lodash.throttle');
7
8
  var rrweb = require('rrweb');
8
9
 
10
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
11
+
12
+ var throttle__default = /*#__PURE__*/_interopDefaultLegacy(throttle);
13
+
9
14
  /******************************************************************************
10
15
  Copyright (c) Microsoft Corporation.
11
16
 
@@ -101,11 +106,11 @@ var VISIBILITY_CHANGE_TIMEOUT = SESSION_IDLE_DURATION;
101
106
 
102
107
  function captureReplayEvent(_a) {
103
108
  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({
109
+ core.captureEvent(__assign(__assign({
105
110
  // @ts-expect-error replay_event is a new event type
106
111
  type: REPLAY_EVENT_NAME }, (includeReplayStartTimestamp
107
112
  ? { 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 });
113
+ : {})), { timestamp: timestamp / 1000, error_ids: errorIds, trace_ids: traceIds, urls: urls, replay_id: replay_id, segment_id: segment_id }), { event_id: replay_id });
109
114
  }
110
115
 
111
116
  function createBreadcrumb(breadcrumb) {
@@ -818,6 +823,7 @@ var SentryReplay = /** @class */ (function () {
818
823
  * slightly differently in this case: `replay_start_timestamp` is included.
819
824
  */
820
825
  this.newSessionCreated = false;
826
+ this.flushLock = null;
821
827
  /**
822
828
  * Is the integration currently active?
823
829
  */
@@ -931,6 +937,8 @@ var SentryReplay = /** @class */ (function () {
931
937
  var breadcrumb = createBreadcrumb({
932
938
  category: 'ui.blur',
933
939
  });
940
+ // Do not count blur as a user action -- it's part of the process of them
941
+ // leaving the page
934
942
  _this.doChangeToBackgroundTasks(breadcrumb);
935
943
  };
936
944
  /**
@@ -940,6 +948,8 @@ var SentryReplay = /** @class */ (function () {
940
948
  var breadcrumb = createBreadcrumb({
941
949
  category: 'ui.focus',
942
950
  });
951
+ // Do not count focus as a user action -- instead wait until they focus and
952
+ // interactive with page
943
953
  _this.doChangeToForegroundTasks(breadcrumb);
944
954
  };
945
955
  /**
@@ -960,6 +970,7 @@ var SentryReplay = /** @class */ (function () {
960
970
  if (type === 'history') {
961
971
  // Need to collect visited URLs
962
972
  _this.context.urls.push(result.name);
973
+ _this.updateLastActivity();
963
974
  }
964
975
  _this.addUpdate(function () {
965
976
  _this.createPerformanceSpans([result]);
@@ -986,6 +997,9 @@ var SentryReplay = /** @class */ (function () {
986
997
  if (result.category === 'sentry.transaction') {
987
998
  return;
988
999
  }
1000
+ if (result.category === 'ui.click') {
1001
+ _this.updateLastActivity();
1002
+ }
989
1003
  _this.addUpdate(function () {
990
1004
  _this.addEvent({
991
1005
  type: rrweb.EventType.Custom,
@@ -1008,6 +1022,63 @@ var SentryReplay = /** @class */ (function () {
1008
1022
  var newEntries = new Set(list.getEntries());
1009
1023
  _this.performanceEvents = __spreadArray(__spreadArray([], _this.performanceEvents, true), Array.from(newEntries), true);
1010
1024
  };
1025
+ /**
1026
+ * Flushes replay event buffer to Sentry.
1027
+ *
1028
+ * Performance events are only added right before flushing - this is probably
1029
+ * due to the buffered performance observer events.
1030
+ */
1031
+ this.flushUpdate = function () { return __awaiter(_this, void 0, void 0, function () {
1032
+ var err_1;
1033
+ var _a;
1034
+ return __generator(this, function (_b) {
1035
+ switch (_b.label) {
1036
+ case 0:
1037
+ if (!this.isEnabled) {
1038
+ // This is just a precaution, there should be no listeners that would
1039
+ // cause a flush.
1040
+ return [2 /*return*/];
1041
+ }
1042
+ if (!this.checkAndHandleExpiredSession()) {
1043
+ logger.error(new Error('Attempting to finish replay event after session expired.'));
1044
+ return [2 /*return*/];
1045
+ }
1046
+ if (!((_a = this.session) === null || _a === void 0 ? void 0 : _a.id)) {
1047
+ console.error(new Error('[Sentry]: No transaction, no replay'));
1048
+ return [2 /*return*/];
1049
+ }
1050
+ // Since flushing, ensure other queued flushes are cancelled
1051
+ // We do this regardless of having a queued flush since the event updates
1052
+ // will be handled by queued flush
1053
+ clearTimeout(this.timeout);
1054
+ if (!!this.flushLock) return [3 /*break*/, 2];
1055
+ this.flushLock = this.runFlush();
1056
+ return [4 /*yield*/, this.flushLock];
1057
+ case 1:
1058
+ _b.sent();
1059
+ this.flushLock = null;
1060
+ return [2 /*return*/];
1061
+ case 2:
1062
+ _b.trys.push([2, 4, 5, 6]);
1063
+ return [4 /*yield*/, this.flushLock];
1064
+ case 3:
1065
+ _b.sent();
1066
+ return [3 /*break*/, 6];
1067
+ case 4:
1068
+ err_1 = _b.sent();
1069
+ console.error(err_1);
1070
+ return [3 /*break*/, 6];
1071
+ case 5:
1072
+ this.throttledFlushUpdate();
1073
+ return [7 /*endfinally*/];
1074
+ case 6: return [2 /*return*/];
1075
+ }
1076
+ });
1077
+ }); };
1078
+ this.throttledFlushUpdate = throttle__default["default"](this.flushUpdate, 1000, {
1079
+ leading: false,
1080
+ trailing: true,
1081
+ });
1011
1082
  this.recordingOptions = __assign({ maskAllInputs: maskAllInputs, blockClass: blockClass, ignoreClass: ignoreClass, maskTextClass: maskTextClass }, recordingOptions);
1012
1083
  this.options = {
1013
1084
  flushMinDelay: flushMinDelay,
@@ -1053,6 +1124,9 @@ var SentryReplay = /** @class */ (function () {
1053
1124
  // If session was not sampled, then we do not initialize the integration at all.
1054
1125
  return;
1055
1126
  }
1127
+ // setup() is generally called on page load or manually - in both cases we
1128
+ // should treat it as an activity
1129
+ this.updateLastActivity();
1056
1130
  this.eventBuffer = createEventBuffer({
1057
1131
  useCompression: Boolean(this.options.useCompression),
1058
1132
  });
@@ -1163,7 +1237,7 @@ var SentryReplay = /** @class */ (function () {
1163
1237
  this.performanceEvents = [];
1164
1238
  this.initialEventTimestampSinceFlush = null;
1165
1239
  // Reset context as well
1166
- this.popEventContext();
1240
+ this.clearContext();
1167
1241
  this.initialState = {
1168
1242
  timestamp: new Date().getTime(),
1169
1243
  url: url,
@@ -1408,11 +1482,20 @@ var SentryReplay = /** @class */ (function () {
1408
1482
  }
1409
1483
  return this.flushUpdate();
1410
1484
  };
1485
+ /**
1486
+ * Clear context
1487
+ */
1488
+ SentryReplay.prototype.clearContext = function () {
1489
+ this.context.errorIds.clear();
1490
+ this.context.traceIds.clear();
1491
+ this.context.urls = [];
1492
+ this.context.earliestEvent = null;
1493
+ };
1411
1494
  /**
1412
1495
  * Return and clear context
1413
1496
  */
1414
1497
  SentryReplay.prototype.popEventContext = function (_a) {
1415
- var _b = _a === void 0 ? {} : _a, timestamp = _b.timestamp;
1498
+ var timestamp = _a.timestamp;
1416
1499
  var initialState = this.initialState;
1417
1500
  if (this.initialState &&
1418
1501
  this.context.earliestEvent &&
@@ -1426,52 +1509,31 @@ var SentryReplay = /** @class */ (function () {
1426
1509
  traceIds: Array.from(this.context.traceIds).filter(Boolean),
1427
1510
  urls: this.context.urls,
1428
1511
  };
1429
- this.context.errorIds.clear();
1430
- this.context.traceIds.clear();
1431
- this.context.urls = [];
1432
- this.context.earliestEvent = null;
1433
- // @ts-expect-error: Type 'undefined' is not assignable to type 'Session'.ts(2322)
1512
+ this.clearContext();
1434
1513
  return context;
1435
1514
  };
1436
- /**
1437
- * Flushes replay event buffer to Sentry.
1438
- *
1439
- * Performance events are only added right before flushing - this is probably
1440
- * due to the buffered performance observer events.
1441
- */
1442
- SentryReplay.prototype.flushUpdate = function () {
1443
- var _a, _b;
1515
+ SentryReplay.prototype.runFlush = function () {
1516
+ var _a;
1444
1517
  return __awaiter(this, void 0, void 0, function () {
1445
- var timestamp, replayId, newSessionCreated, segmentId, recordingData, err_1;
1446
- return __generator(this, function (_c) {
1447
- switch (_c.label) {
1518
+ var timestamp, replayId, newSessionCreated, segmentId, recordingData, err_2;
1519
+ return __generator(this, function (_b) {
1520
+ switch (_b.label) {
1448
1521
  case 0:
1449
- if (!this.isEnabled) {
1450
- // This is just a precaution, there should be no listeners that would
1451
- // cause a flush.
1452
- return [2 /*return*/];
1453
- }
1454
- if (!this.checkAndHandleExpiredSession()) {
1455
- logger.error(new Error('Attempting to finish replay event after session expired.'));
1456
- return [2 /*return*/];
1457
- }
1458
- if (!((_a = this.session) === null || _a === void 0 ? void 0 : _a.id)) {
1522
+ if (!this.session) {
1459
1523
  console.error(new Error('[Sentry]: No transaction, no replay'));
1460
1524
  return [2 /*return*/];
1461
1525
  }
1462
- // Since already flushing, ensure other queued flushes are cancelled
1463
- clearTimeout(this.timeout);
1464
1526
  return [4 /*yield*/, this.addPerformanceEntries()];
1465
1527
  case 1:
1466
- _c.sent();
1467
- if (!((_b = this.eventBuffer) === null || _b === void 0 ? void 0 : _b.length)) {
1528
+ _b.sent();
1529
+ if (!((_a = this.eventBuffer) === null || _a === void 0 ? void 0 : _a.length)) {
1468
1530
  return [2 /*return*/];
1469
1531
  }
1470
1532
  // Only attach memory event if eventBuffer is not empty
1471
1533
  return [4 /*yield*/, this.addMemoryEntry()];
1472
1534
  case 2:
1473
1535
  // Only attach memory event if eventBuffer is not empty
1474
- _c.sent();
1536
+ _b.sent();
1475
1537
  timestamp = new Date().getTime();
1476
1538
  replayId = this.session.id;
1477
1539
  newSessionCreated = this.newSessionCreated;
@@ -1479,28 +1541,23 @@ var SentryReplay = /** @class */ (function () {
1479
1541
  // Reset this to null regardless of `sendReplay` result so that future
1480
1542
  // events will get flushed properly
1481
1543
  this.initialEventTimestampSinceFlush = null;
1482
- _c.label = 3;
1544
+ _b.label = 3;
1483
1545
  case 3:
1484
- _c.trys.push([3, 6, , 7]);
1546
+ _b.trys.push([3, 6, , 7]);
1485
1547
  return [4 /*yield*/, this.eventBuffer.finish()];
1486
1548
  case 4:
1487
- recordingData = _c.sent();
1549
+ recordingData = _b.sent();
1488
1550
  return [4 /*yield*/, this.sendReplay(replayId, recordingData, segmentId)];
1489
1551
  case 5:
1490
- _c.sent();
1552
+ _b.sent();
1491
1553
  // The below will only happen after successfully sending replay //
1492
- // TBD: Alternatively we could update this after every rrweb event
1493
- // `timestamp` should reflect when the event happens. e.g. the timestamp
1494
- // of the event is passed as an argument in the case where a timeout
1495
- // occurs.
1496
- this.updateLastActivity(timestamp);
1497
1554
  captureReplayEvent(__assign(__assign({}, this.popEventContext({ timestamp: timestamp })), { replayId: replayId, segmentId: segmentId, includeReplayStartTimestamp: newSessionCreated }));
1498
1555
  this.newSessionCreated = false;
1499
1556
  return [3 /*break*/, 7];
1500
1557
  case 6:
1501
- err_1 = _c.sent();
1502
- core.captureException(err_1);
1503
- console.error(err_1);
1558
+ err_2 = _b.sent();
1559
+ core.captureException(err_2);
1560
+ console.error(err_2);
1504
1561
  return [3 /*break*/, 7];
1505
1562
  case 7: return [2 /*return*/];
1506
1563
  }