@sentry/replay 7.30.0 → 7.31.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.
Files changed (120) hide show
  1. package/cjs/constants.js +5 -0
  2. package/cjs/constants.js.map +1 -1
  3. package/cjs/coreHandlers/breadcrumbHandler.js.map +1 -1
  4. package/cjs/coreHandlers/handleDom.js.map +1 -1
  5. package/cjs/coreHandlers/handleGlobalEvent.js.map +1 -1
  6. package/cjs/coreHandlers/handleScope.js.map +1 -1
  7. package/cjs/eventBuffer.js +44 -10
  8. package/cjs/eventBuffer.js.map +1 -1
  9. package/cjs/integration.js +19 -19
  10. package/cjs/integration.js.map +1 -1
  11. package/cjs/replay.js +202 -357
  12. package/cjs/replay.js.map +1 -1
  13. package/cjs/util/addEvent.js +9 -5
  14. package/cjs/util/addEvent.js.map +1 -1
  15. package/cjs/util/addMemoryEntry.js +8 -5
  16. package/cjs/util/addMemoryEntry.js.map +1 -1
  17. package/cjs/{createPerformanceEntry.js → util/createPerformanceEntries.js} +14 -8
  18. package/cjs/util/createPerformanceEntries.js.map +1 -0
  19. package/cjs/util/createPerformanceSpans.js +5 -2
  20. package/cjs/util/createPerformanceSpans.js.map +1 -1
  21. package/cjs/util/createReplayEnvelope.js +5 -1
  22. package/cjs/util/createReplayEnvelope.js.map +1 -1
  23. package/cjs/util/isRrwebError.js.map +1 -1
  24. package/cjs/util/monkeyPatchRecordDroppedEvent.js.map +1 -1
  25. package/cjs/util/{createRecordingData.js → prepareRecordingData.js} +9 -9
  26. package/cjs/util/prepareRecordingData.js.map +1 -0
  27. package/cjs/util/prepareReplayEvent.js +1 -1
  28. package/cjs/util/prepareReplayEvent.js.map +1 -1
  29. package/cjs/util/sendReplay.js +64 -0
  30. package/cjs/util/sendReplay.js.map +1 -0
  31. package/cjs/util/sendReplayRequest.js +161 -0
  32. package/cjs/util/sendReplayRequest.js.map +1 -0
  33. package/cjs/worker/worker.js +1 -1
  34. package/cjs/worker/worker.js.map +1 -1
  35. package/esm/constants.js +4 -1
  36. package/esm/constants.js.map +1 -1
  37. package/esm/coreHandlers/breadcrumbHandler.js.map +1 -1
  38. package/esm/coreHandlers/handleDom.js.map +1 -1
  39. package/esm/coreHandlers/handleGlobalEvent.js.map +1 -1
  40. package/esm/coreHandlers/handleScope.js.map +1 -1
  41. package/esm/eventBuffer.js +44 -10
  42. package/esm/eventBuffer.js.map +1 -1
  43. package/esm/integration.js +19 -19
  44. package/esm/integration.js.map +1 -1
  45. package/esm/replay.js +205 -360
  46. package/esm/replay.js.map +1 -1
  47. package/esm/util/addEvent.js +9 -5
  48. package/esm/util/addEvent.js.map +1 -1
  49. package/esm/util/addMemoryEntry.js +8 -5
  50. package/esm/util/addMemoryEntry.js.map +1 -1
  51. package/esm/{createPerformanceEntry.js → util/createPerformanceEntries.js} +14 -8
  52. package/esm/util/createPerformanceEntries.js.map +1 -0
  53. package/esm/util/createPerformanceSpans.js +5 -2
  54. package/esm/util/createPerformanceSpans.js.map +1 -1
  55. package/esm/util/createReplayEnvelope.js +5 -1
  56. package/esm/util/createReplayEnvelope.js.map +1 -1
  57. package/esm/util/isRrwebError.js.map +1 -1
  58. package/esm/util/monkeyPatchRecordDroppedEvent.js.map +1 -1
  59. package/esm/util/{createRecordingData.js → prepareRecordingData.js} +9 -9
  60. package/esm/util/prepareRecordingData.js.map +1 -0
  61. package/esm/util/prepareReplayEvent.js +1 -1
  62. package/esm/util/prepareReplayEvent.js.map +1 -1
  63. package/esm/util/sendReplay.js +62 -0
  64. package/esm/util/sendReplay.js.map +1 -0
  65. package/esm/util/sendReplayRequest.js +154 -0
  66. package/esm/util/sendReplayRequest.js.map +1 -0
  67. package/esm/worker/worker.js +1 -1
  68. package/esm/worker/worker.js.map +1 -1
  69. package/package.json +4 -7
  70. package/types/constants.d.ts +2 -0
  71. package/types/constants.d.ts.map +1 -1
  72. package/types/coreHandlers/breadcrumbHandler.d.ts +1 -1
  73. package/types/coreHandlers/breadcrumbHandler.d.ts.map +1 -1
  74. package/types/coreHandlers/handleDom.d.ts +1 -1
  75. package/types/coreHandlers/handleDom.d.ts.map +1 -1
  76. package/types/coreHandlers/handleGlobalEvent.d.ts +1 -1
  77. package/types/coreHandlers/handleGlobalEvent.d.ts.map +1 -1
  78. package/types/coreHandlers/handleScope.d.ts +1 -1
  79. package/types/coreHandlers/handleScope.d.ts.map +1 -1
  80. package/types/eventBuffer.d.ts +18 -6
  81. package/types/eventBuffer.d.ts.map +1 -1
  82. package/types/integration.d.ts +5 -5
  83. package/types/integration.d.ts.map +1 -1
  84. package/types/replay.d.ts +53 -69
  85. package/types/replay.d.ts.map +1 -1
  86. package/types/types.d.ts +27 -6
  87. package/types/types.d.ts.map +1 -1
  88. package/types/util/addEvent.d.ts +2 -2
  89. package/types/util/addEvent.d.ts.map +1 -1
  90. package/types/util/addMemoryEntry.d.ts +2 -2
  91. package/types/util/addMemoryEntry.d.ts.map +1 -1
  92. package/types/{createPerformanceEntry.d.ts → util/createPerformanceEntries.d.ts} +2 -2
  93. package/types/util/createPerformanceEntries.d.ts.map +1 -0
  94. package/types/util/createPerformanceSpans.d.ts +2 -2
  95. package/types/util/createPerformanceSpans.d.ts.map +1 -1
  96. package/types/util/createReplayEnvelope.d.ts +1 -1
  97. package/types/util/createReplayEnvelope.d.ts.map +1 -1
  98. package/types/util/isRrwebError.d.ts +1 -1
  99. package/types/util/isRrwebError.d.ts.map +1 -1
  100. package/types/util/prepareRecordingData.d.ts +9 -0
  101. package/types/util/prepareRecordingData.d.ts.map +1 -0
  102. package/types/util/prepareReplayEvent.d.ts +2 -2
  103. package/types/util/prepareReplayEvent.d.ts.map +1 -1
  104. package/types/util/sendReplay.d.ts +9 -0
  105. package/types/util/sendReplay.d.ts.map +1 -0
  106. package/types/util/sendReplayRequest.d.ts +21 -0
  107. package/types/util/sendReplayRequest.d.ts.map +1 -0
  108. package/cjs/createPerformanceEntry.js.map +0 -1
  109. package/cjs/session/deleteSession.js +0 -23
  110. package/cjs/session/deleteSession.js.map +0 -1
  111. package/cjs/util/createRecordingData.js.map +0 -1
  112. package/esm/createPerformanceEntry.js.map +0 -1
  113. package/esm/session/deleteSession.js +0 -21
  114. package/esm/session/deleteSession.js.map +0 -1
  115. package/esm/util/createRecordingData.js.map +0 -1
  116. package/types/createPerformanceEntry.d.ts.map +0 -1
  117. package/types/session/deleteSession.d.ts +0 -5
  118. package/types/session/deleteSession.d.ts.map +0 -1
  119. package/types/util/createRecordingData.d.ts +0 -10
  120. package/types/util/createRecordingData.d.ts.map +0 -1
package/esm/replay.js CHANGED
@@ -1,42 +1,33 @@
1
1
  import { _optionalChain } from '@sentry/utils/esm/buildPolyfills';
2
- import { captureException, getCurrentHub, addGlobalEventProcessor, setContext } from '@sentry/core';
3
- import { logger, addInstrumentationHandler } from '@sentry/utils';
2
+ import { captureException, getCurrentHub, addGlobalEventProcessor } from '@sentry/core';
3
+ import { logger, addInstrumentationHandler, disabledUntil } from '@sentry/utils';
4
4
  import './node_modules/rrweb/es/rrweb/packages/rrweb/src/entries/all.js';
5
- import { SESSION_IDLE_DURATION, WINDOW, VISIBILITY_CHANGE_TIMEOUT, MAX_SESSION_LIFE, REPLAY_EVENT_NAME, UNABLE_TO_SEND_REPLAY } from './constants.js';
5
+ import { SESSION_IDLE_DURATION, WINDOW, VISIBILITY_CHANGE_TIMEOUT, MAX_SESSION_LIFE } from './constants.js';
6
6
  import { breadcrumbHandler } from './coreHandlers/breadcrumbHandler.js';
7
7
  import { handleFetchSpanListener } from './coreHandlers/handleFetch.js';
8
8
  import { handleGlobalEventListener } from './coreHandlers/handleGlobalEvent.js';
9
9
  import { handleHistorySpanListener } from './coreHandlers/handleHistory.js';
10
10
  import { handleXhrSpanListener } from './coreHandlers/handleXhr.js';
11
11
  import { setupPerformanceObserver } from './coreHandlers/performanceObserver.js';
12
- import { createPerformanceEntries } from './createPerformanceEntry.js';
13
12
  import { createEventBuffer } from './eventBuffer.js';
14
- import { deleteSession } from './session/deleteSession.js';
15
13
  import { getSession } from './session/getSession.js';
16
14
  import { saveSession } from './session/saveSession.js';
17
15
  import { addEvent } from './util/addEvent.js';
18
16
  import { addMemoryEntry } from './util/addMemoryEntry.js';
19
17
  import { createBreadcrumb } from './util/createBreadcrumb.js';
18
+ import { createPerformanceEntries } from './util/createPerformanceEntries.js';
20
19
  import { createPerformanceSpans } from './util/createPerformanceSpans.js';
21
- import { createRecordingData } from './util/createRecordingData.js';
22
- import { createReplayEnvelope } from './util/createReplayEnvelope.js';
23
20
  import { debounce } from './util/debounce.js';
24
21
  import { isExpired } from './util/isExpired.js';
25
22
  import { isSessionExpired } from './util/isSessionExpired.js';
26
23
  import { overwriteRecordDroppedEvent, restoreRecordDroppedEvent } from './util/monkeyPatchRecordDroppedEvent.js';
27
- import { prepareReplayEvent } from './util/prepareReplayEvent.js';
24
+ import { sendReplay } from './util/sendReplay.js';
25
+ import { RateLimitError } from './util/sendReplayRequest.js';
28
26
  import record from './node_modules/rrweb/es/rrweb/packages/rrweb/src/record/index.js';
29
27
  import { EventType } from './node_modules/rrweb/es/rrweb/packages/rrweb/src/types.js';
30
28
 
31
29
  /* eslint-disable max-lines */ // TODO: We might want to split this file up
32
30
 
33
- /**
34
- * Returns true to return control to calling function, otherwise continue with normal batching
35
- */
36
-
37
- const BASE_RETRY_INTERVAL = 5000;
38
- const MAX_RETRY_COUNT = 3;
39
-
40
31
  /**
41
32
  * The main replay container class, which holds all the state and methods for recording and sending replays.
42
33
  */
@@ -61,40 +52,37 @@ class ReplayContainer {
61
52
 
62
53
  __init4() {this._performanceObserver = null;}
63
54
 
64
- __init5() {this._retryCount = 0;}
65
- __init6() {this._retryInterval = BASE_RETRY_INTERVAL;}
66
-
67
- __init7() {this._flushLock = null;}
55
+ __init5() {this._flushLock = null;}
68
56
 
69
57
  /**
70
58
  * Timestamp of the last user activity. This lives across sessions.
71
59
  */
72
- __init8() {this._lastActivity = new Date().getTime();}
60
+ __init6() {this._lastActivity = new Date().getTime();}
73
61
 
74
62
  /**
75
63
  * Is the integration currently active?
76
64
  */
77
- __init9() {this._isEnabled = false;}
65
+ __init7() {this._isEnabled = false;}
78
66
 
79
67
  /**
80
68
  * Paused is a state where:
81
69
  * - DOM Recording is not listening at all
82
70
  * - Nothing will be added to event buffer (e.g. core SDK events)
83
71
  */
84
- __init10() {this._isPaused = false;}
72
+ __init8() {this._isPaused = false;}
85
73
 
86
74
  /**
87
75
  * Have we attached listeners to the core SDK?
88
76
  * Note we have to track this as there is no way to remove instrumentation handlers.
89
77
  */
90
- __init11() {this._hasInitializedCoreListeners = false;}
78
+ __init9() {this._hasInitializedCoreListeners = false;}
91
79
 
92
80
  /**
93
81
  * Function to stop recording
94
82
  */
95
- __init12() {this._stopRecording = null;}
83
+ __init10() {this._stopRecording = null;}
96
84
 
97
- __init13() {this._context = {
85
+ __init11() {this._context = {
98
86
  errorIds: new Set(),
99
87
  traceIds: new Set(),
100
88
  urls: [],
@@ -103,11 +91,16 @@ class ReplayContainer {
103
91
  initialUrl: '',
104
92
  };}
105
93
 
106
- constructor({ options, recordingOptions }) {;ReplayContainer.prototype.__init.call(this);ReplayContainer.prototype.__init2.call(this);ReplayContainer.prototype.__init3.call(this);ReplayContainer.prototype.__init4.call(this);ReplayContainer.prototype.__init5.call(this);ReplayContainer.prototype.__init6.call(this);ReplayContainer.prototype.__init7.call(this);ReplayContainer.prototype.__init8.call(this);ReplayContainer.prototype.__init9.call(this);ReplayContainer.prototype.__init10.call(this);ReplayContainer.prototype.__init11.call(this);ReplayContainer.prototype.__init12.call(this);ReplayContainer.prototype.__init13.call(this);ReplayContainer.prototype.__init14.call(this);ReplayContainer.prototype.__init15.call(this);ReplayContainer.prototype.__init16.call(this);ReplayContainer.prototype.__init17.call(this);ReplayContainer.prototype.__init18.call(this);ReplayContainer.prototype.__init19.call(this);
94
+ constructor({
95
+ options,
96
+ recordingOptions,
97
+ }
98
+
99
+ ) {;ReplayContainer.prototype.__init.call(this);ReplayContainer.prototype.__init2.call(this);ReplayContainer.prototype.__init3.call(this);ReplayContainer.prototype.__init4.call(this);ReplayContainer.prototype.__init5.call(this);ReplayContainer.prototype.__init6.call(this);ReplayContainer.prototype.__init7.call(this);ReplayContainer.prototype.__init8.call(this);ReplayContainer.prototype.__init9.call(this);ReplayContainer.prototype.__init10.call(this);ReplayContainer.prototype.__init11.call(this);ReplayContainer.prototype.__init12.call(this);ReplayContainer.prototype.__init13.call(this);ReplayContainer.prototype.__init14.call(this);ReplayContainer.prototype.__init15.call(this);ReplayContainer.prototype.__init16.call(this);ReplayContainer.prototype.__init17.call(this);
107
100
  this._recordingOptions = recordingOptions;
108
101
  this._options = options;
109
102
 
110
- this._debouncedFlush = debounce(() => this.flush(), this._options.flushMinDelay, {
103
+ this._debouncedFlush = debounce(() => this._flush(), this._options.flushMinDelay, {
111
104
  maxWait: this._options.flushMaxDelay,
112
105
  });
113
106
  }
@@ -138,14 +131,14 @@ class ReplayContainer {
138
131
  * Creates or loads a session, attaches listeners to varying events (DOM,
139
132
  * _performanceObserver, Recording, Sentry SDK, etc)
140
133
  */
141
- start() {
142
- this.setInitialState();
134
+ start() {
135
+ this._setInitialState();
143
136
 
144
- this.loadSession({ expiry: SESSION_IDLE_DURATION });
137
+ this._loadSession({ expiry: SESSION_IDLE_DURATION });
145
138
 
146
139
  // If there is no session, then something bad has happened - can't continue
147
140
  if (!this.session) {
148
- this.handleException(new Error('No session found'));
141
+ this._handleException(new Error('No session found'));
149
142
  return;
150
143
  }
151
144
 
@@ -154,23 +147,21 @@ class ReplayContainer {
154
147
  return;
155
148
  }
156
149
 
157
- // Modify recording options to checkoutEveryNthSecond if
158
- // sampling for error replay. This is because we don't know
159
- // when an error will occur, so we need to keep a buffer of
160
- // replay events.
150
+ // If session is sampled for errors, then we need to set the recordingMode
151
+ // to 'error', which will configure recording with different options.
161
152
  if (this.session.sampled === 'error') {
162
153
  this.recordingMode = 'error';
163
154
  }
164
155
 
165
156
  // setup() is generally called on page load or manually - in both cases we
166
157
  // should treat it as an activity
167
- this.updateSessionActivity();
158
+ this._updateSessionActivity();
168
159
 
169
160
  this.eventBuffer = createEventBuffer({
170
161
  useCompression: Boolean(this._options.useCompression),
171
162
  });
172
163
 
173
- this.addListeners();
164
+ this._addListeners();
174
165
 
175
166
  // Need to set as enabled before we start recording, as `record()` can trigger a flush with a new checkout
176
167
  this._isEnabled = true;
@@ -183,18 +174,18 @@ class ReplayContainer {
183
174
  *
184
175
  * Note that this will cause a new DOM checkout
185
176
  */
186
- startRecording() {
177
+ startRecording() {
187
178
  try {
188
179
  this._stopRecording = record({
189
180
  ...this._recordingOptions,
190
- // When running in error sampling mode, we need to overwrite `checkoutEveryNth`
181
+ // When running in error sampling mode, we need to overwrite `checkoutEveryNms`
191
182
  // Without this, it would record forever, until an error happens, which we don't want
192
183
  // instead, we'll always keep the last 60 seconds of replay before an error happened
193
- ...(this.recordingMode === 'error' && { checkoutEveryNth: 60000 }),
194
- emit: this.handleRecordingEmit,
184
+ ...(this.recordingMode === 'error' && { checkoutEveryNms: 60000 }),
185
+ emit: this._handleRecordingEmit,
195
186
  });
196
187
  } catch (err) {
197
- this.handleException(err);
188
+ this._handleException(err);
198
189
  }
199
190
  }
200
191
 
@@ -215,16 +206,17 @@ class ReplayContainer {
215
206
  * Currently, this needs to be manually called (e.g. for tests). Sentry SDK
216
207
  * does not support a teardown
217
208
  */
218
- stop() {
209
+ stop() {
219
210
  try {
220
211
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Stopping Replays');
221
212
  this._isEnabled = false;
222
- this.removeListeners();
213
+ this._removeListeners();
223
214
  _optionalChain([this, 'access', _8 => _8._stopRecording, 'optionalCall', _9 => _9()]);
224
215
  _optionalChain([this, 'access', _10 => _10.eventBuffer, 'optionalAccess', _11 => _11.destroy, 'call', _12 => _12()]);
225
216
  this.eventBuffer = null;
217
+ this._debouncedFlush.cancel();
226
218
  } catch (err) {
227
- this.handleException(err);
219
+ this._handleException(err);
228
220
  }
229
221
  }
230
222
 
@@ -233,7 +225,7 @@ class ReplayContainer {
233
225
  * This differs from stop as this only stops DOM recording, it is
234
226
  * not as thorough of a shutdown as `stop()`.
235
227
  */
236
- pause() {
228
+ pause() {
237
229
  this._isPaused = true;
238
230
  try {
239
231
  if (this._stopRecording) {
@@ -241,7 +233,7 @@ class ReplayContainer {
241
233
  this._stopRecording = undefined;
242
234
  }
243
235
  } catch (err) {
244
- this.handleException(err);
236
+ this._handleException(err);
245
237
  }
246
238
  }
247
239
 
@@ -251,13 +243,80 @@ class ReplayContainer {
251
243
  * Note that calling `startRecording()` here will cause a
252
244
  * new DOM checkout.`
253
245
  */
254
- resume() {
246
+ resume() {
255
247
  this._isPaused = false;
256
248
  this.startRecording();
257
249
  }
258
250
 
251
+ /**
252
+ * We want to batch uploads of replay events. Save events only if
253
+ * `<flushMinDelay>` milliseconds have elapsed since the last event
254
+ * *OR* if `<flushMaxDelay>` milliseconds have elapsed.
255
+ *
256
+ * Accepts a callback to perform side-effects and returns true to stop batch
257
+ * processing and hand back control to caller.
258
+ */
259
+ addUpdate(cb) {
260
+ // We need to always run `cb` (e.g. in the case of `this.recordingMode == 'error'`)
261
+ const cbResult = _optionalChain([cb, 'optionalCall', _13 => _13()]);
262
+
263
+ // If this option is turned on then we will only want to call `flush`
264
+ // explicitly
265
+ if (this.recordingMode === 'error') {
266
+ return;
267
+ }
268
+
269
+ // If callback is true, we do not want to continue with flushing -- the
270
+ // caller will need to handle it.
271
+ if (cbResult === true) {
272
+ return;
273
+ }
274
+
275
+ // addUpdate is called quite frequently - use _debouncedFlush so that it
276
+ // respects the flush delays and does not flush immediately
277
+ this._debouncedFlush();
278
+ }
279
+
280
+ /**
281
+ * Updates the user activity timestamp and resumes recording. This should be
282
+ * called in an event handler for a user action that we consider as the user
283
+ * being "active" (e.g. a mouse click).
284
+ */
285
+ triggerUserActivity() {
286
+ this._updateUserActivity();
287
+
288
+ // This case means that recording was once stopped due to inactivity.
289
+ // Ensure that recording is resumed.
290
+ if (!this._stopRecording) {
291
+ // Create a new session, otherwise when the user action is flushed, it
292
+ // will get rejected due to an expired session.
293
+ this._loadSession({ expiry: SESSION_IDLE_DURATION });
294
+
295
+ // Note: This will cause a new DOM checkout
296
+ this.resume();
297
+ return;
298
+ }
299
+
300
+ // Otherwise... recording was never suspended, continue as normalish
301
+ this._checkAndHandleExpiredSession();
302
+
303
+ this._updateSessionActivity();
304
+ }
305
+
306
+ /**
307
+ *
308
+ * Always flush via `_debouncedFlush` so that we do not have flushes triggered
309
+ * from calling both `flush` and `_debouncedFlush`. Otherwise, there could be
310
+ * cases of mulitple flushes happening closely together.
311
+ */
312
+ flushImmediate() {
313
+ this._debouncedFlush();
314
+ // `.flush` is provided by the debounced function, analogously to lodash.debounce
315
+ return this._debouncedFlush.flush() ;
316
+ }
317
+
259
318
  /** A wrapper to conditionally capture exceptions. */
260
- handleException(error) {
319
+ _handleException(error) {
261
320
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay]', error);
262
321
 
263
322
  if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && this._options._experiments && this._options._experiments.captureExceptions) {
@@ -265,21 +324,11 @@ class ReplayContainer {
265
324
  }
266
325
  }
267
326
 
268
- /** for tests only */
269
- clearSession() {
270
- try {
271
- deleteSession();
272
- this.session = undefined;
273
- } catch (err) {
274
- this.handleException(err);
275
- }
276
- }
277
-
278
327
  /**
279
328
  * Loads a session from storage, or creates a new one if it does not exist or
280
329
  * is expired.
281
330
  */
282
- loadSession({ expiry }) {
331
+ _loadSession({ expiry }) {
283
332
  const { type, session } = getSession({
284
333
  expiry,
285
334
  stickySession: Boolean(this._options.stickySession),
@@ -291,11 +340,11 @@ class ReplayContainer {
291
340
  // If session was newly created (i.e. was not loaded from storage), then
292
341
  // enable flag to create the root replay
293
342
  if (type === 'new') {
294
- this.setInitialState();
343
+ this._setInitialState();
295
344
  }
296
345
 
297
- if (session.id !== _optionalChain([this, 'access', _13 => _13.session, 'optionalAccess', _14 => _14.id])) {
298
- session.previousSessionId = _optionalChain([this, 'access', _15 => _15.session, 'optionalAccess', _16 => _16.id]);
346
+ if (session.id !== _optionalChain([this, 'access', _14 => _14.session, 'optionalAccess', _15 => _15.id])) {
347
+ session.previousSessionId = _optionalChain([this, 'access', _16 => _16.session, 'optionalAccess', _17 => _17.id]);
299
348
  }
300
349
 
301
350
  this.session = session;
@@ -306,14 +355,14 @@ class ReplayContainer {
306
355
  * replay. This is required because otherwise they would be captured at the
307
356
  * first flush.
308
357
  */
309
- setInitialState() {
358
+ _setInitialState() {
310
359
  const urlPath = `${WINDOW.location.pathname}${WINDOW.location.hash}${WINDOW.location.search}`;
311
360
  const url = `${WINDOW.location.origin}${urlPath}`;
312
361
 
313
362
  this.performanceEvents = [];
314
363
 
315
364
  // Reset _context as well
316
- this.clearContext();
365
+ this._clearContext();
317
366
 
318
367
  this._context.initialUrl = url;
319
368
  this._context.initialTimestamp = new Date().getTime();
@@ -323,11 +372,11 @@ class ReplayContainer {
323
372
  /**
324
373
  * Adds listeners to record events for the replay
325
374
  */
326
- addListeners() {
375
+ _addListeners() {
327
376
  try {
328
- WINDOW.document.addEventListener('visibilitychange', this.handleVisibilityChange);
329
- WINDOW.addEventListener('blur', this.handleWindowBlur);
330
- WINDOW.addEventListener('focus', this.handleWindowFocus);
377
+ WINDOW.document.addEventListener('visibilitychange', this._handleVisibilityChange);
378
+ WINDOW.addEventListener('blur', this._handleWindowBlur);
379
+ WINDOW.addEventListener('focus', this._handleWindowFocus);
331
380
 
332
381
  // We need to filter out dropped events captured by `addGlobalEventProcessor(this.handleGlobalEvent)` below
333
382
  overwriteRecordDroppedEvent(this._context.errorIds);
@@ -336,8 +385,8 @@ class ReplayContainer {
336
385
  if (!this._hasInitializedCoreListeners) {
337
386
  // Listeners from core SDK //
338
387
  const scope = getCurrentHub().getScope();
339
- _optionalChain([scope, 'optionalAccess', _17 => _17.addScopeListener, 'call', _18 => _18(this.handleCoreBreadcrumbListener('scope'))]);
340
- addInstrumentationHandler('dom', this.handleCoreBreadcrumbListener('dom'));
388
+ _optionalChain([scope, 'optionalAccess', _18 => _18.addScopeListener, 'call', _19 => _19(this._handleCoreBreadcrumbListener('scope'))]);
389
+ addInstrumentationHandler('dom', this._handleCoreBreadcrumbListener('dom'));
341
390
  addInstrumentationHandler('fetch', handleFetchSpanListener(this));
342
391
  addInstrumentationHandler('xhr', handleXhrSpanListener(this));
343
392
  addInstrumentationHandler('history', handleHistorySpanListener(this));
@@ -349,7 +398,7 @@ class ReplayContainer {
349
398
  this._hasInitializedCoreListeners = true;
350
399
  }
351
400
  } catch (err) {
352
- this.handleException(err);
401
+ this._handleException(err);
353
402
  }
354
403
 
355
404
  // _performanceObserver //
@@ -361,14 +410,14 @@ class ReplayContainer {
361
410
  }
362
411
 
363
412
  /**
364
- * Cleans up listeners that were created in `addListeners`
413
+ * Cleans up listeners that were created in `_addListeners`
365
414
  */
366
- removeListeners() {
415
+ _removeListeners() {
367
416
  try {
368
- WINDOW.document.removeEventListener('visibilitychange', this.handleVisibilityChange);
417
+ WINDOW.document.removeEventListener('visibilitychange', this._handleVisibilityChange);
369
418
 
370
- WINDOW.removeEventListener('blur', this.handleWindowBlur);
371
- WINDOW.removeEventListener('focus', this.handleWindowFocus);
419
+ WINDOW.removeEventListener('blur', this._handleWindowBlur);
420
+ WINDOW.removeEventListener('focus', this._handleWindowFocus);
372
421
 
373
422
  restoreRecordDroppedEvent();
374
423
 
@@ -377,50 +426,21 @@ class ReplayContainer {
377
426
  this._performanceObserver = null;
378
427
  }
379
428
  } catch (err) {
380
- this.handleException(err);
429
+ this._handleException(err);
381
430
  }
382
431
  }
383
432
 
384
- /**
385
- * We want to batch uploads of replay events. Save events only if
386
- * `<flushMinDelay>` milliseconds have elapsed since the last event
387
- * *OR* if `<flushMaxDelay>` milliseconds have elapsed.
388
- *
389
- * Accepts a callback to perform side-effects and returns true to stop batch
390
- * processing and hand back control to caller.
391
- */
392
- addUpdate(cb) {
393
- // We need to always run `cb` (e.g. in the case of `this.recordingMode == 'error'`)
394
- const cbResult = _optionalChain([cb, 'optionalCall', _19 => _19()]);
395
-
396
- // If this option is turned on then we will only want to call `flush`
397
- // explicitly
398
- if (this.recordingMode === 'error') {
399
- return;
400
- }
401
-
402
- // If callback is true, we do not want to continue with flushing -- the
403
- // caller will need to handle it.
404
- if (cbResult === true) {
405
- return;
406
- }
407
-
408
- // addUpdate is called quite frequently - use _debouncedFlush so that it
409
- // respects the flush delays and does not flush immediately
410
- this._debouncedFlush();
411
- }
412
-
413
433
  /**
414
434
  * Handler for recording events.
415
435
  *
416
436
  * Adds to event buffer, and has varying flushing behaviors if the event was a checkout.
417
437
  */
418
- __init14() {this.handleRecordingEmit = (
438
+ __init12() {this._handleRecordingEmit = (
419
439
  event,
420
440
  isCheckout,
421
441
  ) => {
422
442
  // If this is false, it means session is expired, create and a new session and wait for checkout
423
- if (!this.checkAndHandleExpiredSession()) {
443
+ if (!this._checkAndHandleExpiredSession()) {
424
444
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay] Received replay event after session expired.');
425
445
 
426
446
  return;
@@ -433,12 +453,12 @@ class ReplayContainer {
433
453
  // checkout. This needs to happen before `addEvent()` which updates state
434
454
  // dependent on this reset.
435
455
  if (this.recordingMode === 'error' && event.type === 2) {
436
- this.setInitialState();
456
+ this._setInitialState();
437
457
  }
438
458
 
439
459
  // We need to clear existing events on a checkout, otherwise they are
440
460
  // incremental event updates and should be appended
441
- addEvent(this, event, isCheckout);
461
+ void addEvent(this, event, isCheckout);
442
462
 
443
463
  // Different behavior for full snapshots (type=2), ignore other event types
444
464
  // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16
@@ -481,38 +501,38 @@ class ReplayContainer {
481
501
  * be hidden. Likewise, moving a different window to cover the contents of the
482
502
  * page will also trigger a change to a hidden state.
483
503
  */
484
- __init15() {this.handleVisibilityChange = () => {
504
+ __init13() {this._handleVisibilityChange = () => {
485
505
  if (WINDOW.document.visibilityState === 'visible') {
486
- this.doChangeToForegroundTasks();
506
+ this._doChangeToForegroundTasks();
487
507
  } else {
488
- this.doChangeToBackgroundTasks();
508
+ this._doChangeToBackgroundTasks();
489
509
  }
490
510
  };}
491
511
 
492
512
  /**
493
513
  * Handle when page is blurred
494
514
  */
495
- __init16() {this.handleWindowBlur = () => {
515
+ __init14() {this._handleWindowBlur = () => {
496
516
  const breadcrumb = createBreadcrumb({
497
517
  category: 'ui.blur',
498
518
  });
499
519
 
500
520
  // Do not count blur as a user action -- it's part of the process of them
501
521
  // leaving the page
502
- this.doChangeToBackgroundTasks(breadcrumb);
522
+ this._doChangeToBackgroundTasks(breadcrumb);
503
523
  };}
504
524
 
505
525
  /**
506
526
  * Handle when page is focused
507
527
  */
508
- __init17() {this.handleWindowFocus = () => {
528
+ __init15() {this._handleWindowFocus = () => {
509
529
  const breadcrumb = createBreadcrumb({
510
530
  category: 'ui.focus',
511
531
  });
512
532
 
513
533
  // Do not count focus as a user action -- instead wait until they focus and
514
534
  // interactive with page
515
- this.doChangeToForegroundTasks(breadcrumb);
535
+ this._doChangeToForegroundTasks(breadcrumb);
516
536
  };}
517
537
 
518
538
  /**
@@ -520,7 +540,7 @@ class ReplayContainer {
520
540
  *
521
541
  * These events will create breadcrumb-like objects in the recording.
522
542
  */
523
- __init18() {this.handleCoreBreadcrumbListener =
543
+ __init16() {this._handleCoreBreadcrumbListener =
524
544
  (type) =>
525
545
  (handlerData) => {
526
546
  if (!this._isEnabled) {
@@ -540,11 +560,11 @@ class ReplayContainer {
540
560
  if (result.category === 'ui.click') {
541
561
  this.triggerUserActivity();
542
562
  } else {
543
- this.checkAndHandleExpiredSession();
563
+ this._checkAndHandleExpiredSession();
544
564
  }
545
565
 
546
566
  this.addUpdate(() => {
547
- addEvent(this, {
567
+ void addEvent(this, {
548
568
  type: EventType.Custom,
549
569
  // TODO: We were converting from ms to seconds for breadcrumbs, spans,
550
570
  // but maybe we should just keep them as milliseconds
@@ -563,7 +583,7 @@ class ReplayContainer {
563
583
  /**
564
584
  * Tasks to run when we consider a page to be hidden (via blurring and/or visibility)
565
585
  */
566
- doChangeToBackgroundTasks(breadcrumb) {
586
+ _doChangeToBackgroundTasks(breadcrumb) {
567
587
  if (!this.session) {
568
588
  return;
569
589
  }
@@ -571,24 +591,24 @@ class ReplayContainer {
571
591
  const expired = isSessionExpired(this.session, VISIBILITY_CHANGE_TIMEOUT);
572
592
 
573
593
  if (breadcrumb && !expired) {
574
- this.createCustomBreadcrumb(breadcrumb);
594
+ this._createCustomBreadcrumb(breadcrumb);
575
595
  }
576
596
 
577
597
  // Send replay when the page/tab becomes hidden. There is no reason to send
578
598
  // replay if it becomes visible, since no actions we care about were done
579
599
  // while it was hidden
580
- this.conditionalFlush();
600
+ this._conditionalFlush();
581
601
  }
582
602
 
583
603
  /**
584
604
  * Tasks to run when we consider a page to be visible (via focus and/or visibility)
585
605
  */
586
- doChangeToForegroundTasks(breadcrumb) {
606
+ _doChangeToForegroundTasks(breadcrumb) {
587
607
  if (!this.session) {
588
608
  return;
589
609
  }
590
610
 
591
- const isSessionActive = this.checkAndHandleExpiredSession({
611
+ const isSessionActive = this._checkAndHandleExpiredSession({
592
612
  expiry: VISIBILITY_CHANGE_TIMEOUT,
593
613
  });
594
614
 
@@ -601,7 +621,7 @@ class ReplayContainer {
601
621
  }
602
622
 
603
623
  if (breadcrumb) {
604
- this.createCustomBreadcrumb(breadcrumb);
624
+ this._createCustomBreadcrumb(breadcrumb);
605
625
  }
606
626
  }
607
627
 
@@ -609,7 +629,7 @@ class ReplayContainer {
609
629
  * Trigger rrweb to take a full snapshot which will cause this plugin to
610
630
  * create a new Replay event.
611
631
  */
612
- triggerFullSnapshot() {
632
+ _triggerFullSnapshot() {
613
633
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Taking full rrweb snapshot');
614
634
  record.takeFullSnapshot(true);
615
635
  }
@@ -617,52 +637,26 @@ class ReplayContainer {
617
637
  /**
618
638
  * Update user activity (across session lifespans)
619
639
  */
620
- updateUserActivity(_lastActivity = new Date().getTime()) {
640
+ _updateUserActivity(_lastActivity = new Date().getTime()) {
621
641
  this._lastActivity = _lastActivity;
622
642
  }
623
643
 
624
644
  /**
625
645
  * Updates the session's last activity timestamp
626
646
  */
627
- updateSessionActivity(_lastActivity = new Date().getTime()) {
647
+ _updateSessionActivity(_lastActivity = new Date().getTime()) {
628
648
  if (this.session) {
629
649
  this.session.lastActivity = _lastActivity;
630
650
  this._maybeSaveSession();
631
651
  }
632
652
  }
633
653
 
634
- /**
635
- * Updates the user activity timestamp and resumes recording. This should be
636
- * called in an event handler for a user action that we consider as the user
637
- * being "active" (e.g. a mouse click).
638
- */
639
- triggerUserActivity() {
640
- this.updateUserActivity();
641
-
642
- // This case means that recording was once stopped due to inactivity.
643
- // Ensure that recording is resumed.
644
- if (!this._stopRecording) {
645
- // Create a new session, otherwise when the user action is flushed, it
646
- // will get rejected due to an expired session.
647
- this.loadSession({ expiry: SESSION_IDLE_DURATION });
648
-
649
- // Note: This will cause a new DOM checkout
650
- this.resume();
651
- return;
652
- }
653
-
654
- // Otherwise... recording was never suspended, continue as normalish
655
- this.checkAndHandleExpiredSession();
656
-
657
- this.updateSessionActivity();
658
- }
659
-
660
654
  /**
661
655
  * Helper to create (and buffer) a replay breadcrumb from a core SDK breadcrumb
662
656
  */
663
- createCustomBreadcrumb(breadcrumb) {
657
+ _createCustomBreadcrumb(breadcrumb) {
664
658
  this.addUpdate(() => {
665
- addEvent(this, {
659
+ void addEvent(this, {
666
660
  type: EventType.Custom,
667
661
  timestamp: breadcrumb.timestamp || 0,
668
662
  data: {
@@ -677,12 +671,12 @@ class ReplayContainer {
677
671
  * Observed performance events are added to `this.performanceEvents`. These
678
672
  * are included in the replay event before it is finished and sent to Sentry.
679
673
  */
680
- addPerformanceEntries() {
674
+ _addPerformanceEntries() {
681
675
  // Copy and reset entries before processing
682
676
  const entries = [...this.performanceEvents];
683
677
  this.performanceEvents = [];
684
678
 
685
- createPerformanceSpans(this, createPerformanceEntries(entries));
679
+ return Promise.all(createPerformanceSpans(this, createPerformanceEntries(entries)));
686
680
  }
687
681
 
688
682
  /**
@@ -692,7 +686,7 @@ class ReplayContainer {
692
686
  *
693
687
  * Returns true if session is not expired, false otherwise.
694
688
  */
695
- checkAndHandleExpiredSession({ expiry = SESSION_IDLE_DURATION } = {}) {
689
+ _checkAndHandleExpiredSession({ expiry = SESSION_IDLE_DURATION } = {}) {
696
690
  const oldSessionId = _optionalChain([this, 'access', _22 => _22.session, 'optionalAccess', _23 => _23.id]);
697
691
 
698
692
  // Prevent starting a new session if the last user activity is older than
@@ -707,7 +701,7 @@ class ReplayContainer {
707
701
 
708
702
  // --- There is recent user activity --- //
709
703
  // This will create a new session if expired, based on expiry length
710
- this.loadSession({ expiry });
704
+ this._loadSession({ expiry });
711
705
 
712
706
  // Session was expired if session ids do not match
713
707
  const expired = oldSessionId !== _optionalChain([this, 'access', _24 => _24.session, 'optionalAccess', _25 => _25.id]);
@@ -717,7 +711,7 @@ class ReplayContainer {
717
711
  }
718
712
 
719
713
  // Session is expired, trigger a full snapshot (which will create a new session)
720
- this.triggerFullSnapshot();
714
+ this._triggerFullSnapshot();
721
715
 
722
716
  return false;
723
717
  }
@@ -725,7 +719,7 @@ class ReplayContainer {
725
719
  /**
726
720
  * Only flush if `this.recordingMode === 'session'`
727
721
  */
728
- conditionalFlush() {
722
+ _conditionalFlush() {
729
723
  if (this.recordingMode === 'error') {
730
724
  return;
731
725
  }
@@ -736,7 +730,7 @@ class ReplayContainer {
736
730
  /**
737
731
  * Clear _context
738
732
  */
739
- clearContext() {
733
+ _clearContext() {
740
734
  // XXX: `initialTimestamp` and `initialUrl` do not get cleared
741
735
  this._context.errorIds.clear();
742
736
  this._context.traceIds.clear();
@@ -747,7 +741,7 @@ class ReplayContainer {
747
741
  /**
748
742
  * Return and clear _context
749
743
  */
750
- popEventContext() {
744
+ _popEventContext() {
751
745
  if (this._context.earliestEvent && this._context.earliestEvent < this._context.initialTimestamp) {
752
746
  this._context.initialTimestamp = this._context.earliestEvent;
753
747
  }
@@ -760,7 +754,7 @@ class ReplayContainer {
760
754
  urls: this._context.urls,
761
755
  };
762
756
 
763
- this.clearContext();
757
+ this._clearContext();
764
758
 
765
759
  return _context;
766
760
  }
@@ -773,15 +767,15 @@ class ReplayContainer {
773
767
  *
774
768
  * Should never be called directly, only by `flush`
775
769
  */
776
- async runFlush() {
770
+ async _runFlush() {
777
771
  if (!this.session) {
778
772
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay] No session found to flush.');
779
773
  return;
780
774
  }
781
775
 
782
- await this.addPerformanceEntries();
776
+ await this._addPerformanceEntries();
783
777
 
784
- if (!_optionalChain([this, 'access', _26 => _26.eventBuffer, 'optionalAccess', _27 => _27.length])) {
778
+ if (!_optionalChain([this, 'access', _26 => _26.eventBuffer, 'optionalAccess', _27 => _27.pendingLength])) {
785
779
  return;
786
780
  }
787
781
 
@@ -795,20 +789,32 @@ class ReplayContainer {
795
789
  // NOTE: Copy values from instance members, as it's possible they could
796
790
  // change before the flush finishes.
797
791
  const replayId = this.session.id;
798
- const eventContext = this.popEventContext();
792
+ const eventContext = this._popEventContext();
799
793
  // Always increment segmentId regardless of outcome of sending replay
800
794
  const segmentId = this.session.segmentId++;
801
795
  this._maybeSaveSession();
802
796
 
803
- await this.sendReplay({
797
+ await sendReplay({
804
798
  replayId,
805
- events: recordingData,
799
+ recordingData,
806
800
  segmentId,
807
801
  includeReplayStartTimestamp: segmentId === 0,
808
802
  eventContext,
803
+ session: this.session,
804
+ options: this.getOptions(),
805
+ timestamp: new Date().getTime(),
809
806
  });
810
807
  } catch (err) {
811
- this.handleException(err);
808
+ this._handleException(err);
809
+
810
+ if (err instanceof RateLimitError) {
811
+ this._handleRateLimit(err.rateLimits);
812
+ return;
813
+ }
814
+
815
+ // This means we retried 3 times, and all of them failed
816
+ // In this case, we want to completely stop the replay - otherwise, we may get inconsistent segments
817
+ this.stop();
812
818
  }
813
819
  }
814
820
 
@@ -816,14 +822,13 @@ class ReplayContainer {
816
822
  * Flush recording data to Sentry. Creates a lock so that only a single flush
817
823
  * can be active at a time. Do not call this directly.
818
824
  */
819
- __init19() {this.flush = async () => {
825
+ __init17() {this._flush = async () => {
820
826
  if (!this._isEnabled) {
821
- // This is just a precaution, there should be no listeners that would
822
- // cause a flush.
827
+ // This can happen if e.g. the replay was stopped because of exceeding the retry limit
823
828
  return;
824
829
  }
825
830
 
826
- if (!this.checkAndHandleExpiredSession()) {
831
+ if (!this._checkAndHandleExpiredSession()) {
827
832
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay] Attempting to finish replay event after session expired.');
828
833
  return;
829
834
  }
@@ -836,16 +841,16 @@ class ReplayContainer {
836
841
  // A flush is about to happen, cancel any queued flushes
837
842
  _optionalChain([this, 'access', _30 => _30._debouncedFlush, 'optionalAccess', _31 => _31.cancel, 'call', _32 => _32()]);
838
843
 
839
- // this._flushLock acts as a lock so that future calls to `flush()`
844
+ // this._flushLock acts as a lock so that future calls to `_flush()`
840
845
  // will be blocked until this promise resolves
841
846
  if (!this._flushLock) {
842
- this._flushLock = this.runFlush();
847
+ this._flushLock = this._runFlush();
843
848
  await this._flushLock;
844
849
  this._flushLock = null;
845
850
  return;
846
851
  }
847
852
 
848
- // Wait for previous flush to finish, then call the debounced `flush()`.
853
+ // Wait for previous flush to finish, then call the debounced `_flush()`.
849
854
  // It's possible there are other flush requests queued and waiting for it
850
855
  // to resolve. We want to reduce all outstanding requests (as well as any
851
856
  // new flush requests that occur within a second of the locked flush
@@ -860,195 +865,35 @@ class ReplayContainer {
860
865
  }
861
866
  };}
862
867
 
863
- /**
864
- *
865
- * Always flush via `_debouncedFlush` so that we do not have flushes triggered
866
- * from calling both `flush` and `_debouncedFlush`. Otherwise, there could be
867
- * cases of mulitple flushes happening closely together.
868
- */
869
- flushImmediate() {
870
- this._debouncedFlush();
871
- // `.flush` is provided by the debounced function, analogously to lodash.debounce
872
- return this._debouncedFlush.flush() ;
873
- }
874
-
875
- /**
876
- * Send replay attachment using `fetch()`
877
- */
878
- async sendReplayRequest({
879
- events,
880
- replayId,
881
- segmentId: segment_id,
882
- includeReplayStartTimestamp,
883
- eventContext,
884
- }) {
885
- const recordingData = createRecordingData({
886
- events,
887
- headers: {
888
- segment_id,
889
- },
890
- });
891
-
892
- const { urls, errorIds, traceIds, initialTimestamp } = eventContext;
893
-
894
- const currentTimestamp = new Date().getTime();
895
-
896
- const hub = getCurrentHub();
897
- const client = hub.getClient();
898
- const scope = hub.getScope();
899
- const transport = client && client.getTransport();
900
- const dsn = _optionalChain([client, 'optionalAccess', _33 => _33.getDsn, 'call', _34 => _34()]);
901
-
902
- if (!client || !scope || !transport || !dsn || !this.session || !this.session.sampled) {
903
- return;
904
- }
905
-
906
- const baseEvent = {
907
- // @ts-ignore private api
908
- type: REPLAY_EVENT_NAME,
909
- ...(includeReplayStartTimestamp ? { replay_start_timestamp: initialTimestamp / 1000 } : {}),
910
- timestamp: currentTimestamp / 1000,
911
- error_ids: errorIds,
912
- trace_ids: traceIds,
913
- urls,
914
- replay_id: replayId,
915
- segment_id,
916
- replay_type: this.session.sampled,
917
- };
918
-
919
- const replayEvent = await prepareReplayEvent({ scope, client, replayId, event: baseEvent });
920
-
921
- if (!replayEvent) {
922
- // Taken from baseclient's `_processEvent` method, where this is handled for errors/transactions
923
- client.recordDroppedEvent('event_processor', 'replay_event', baseEvent);
924
- (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('An event processor returned `null`, will not send event.');
925
- return;
926
- }
927
-
928
- replayEvent.tags = {
929
- ...replayEvent.tags,
930
- sessionSampleRate: this._options.sessionSampleRate,
931
- errorSampleRate: this._options.errorSampleRate,
932
- };
933
-
934
- /*
935
- For reference, the fully built event looks something like this:
936
- {
937
- "type": "replay_event",
938
- "timestamp": 1670837008.634,
939
- "error_ids": [
940
- "errorId"
941
- ],
942
- "trace_ids": [
943
- "traceId"
944
- ],
945
- "urls": [
946
- "https://example.com"
947
- ],
948
- "replay_id": "eventId",
949
- "segment_id": 3,
950
- "replay_type": "error",
951
- "platform": "javascript",
952
- "event_id": "eventId",
953
- "environment": "production",
954
- "sdk": {
955
- "integrations": [
956
- "BrowserTracing",
957
- "Replay"
958
- ],
959
- "name": "sentry.javascript.browser",
960
- "version": "7.25.0"
961
- },
962
- "sdkProcessingMetadata": {},
963
- "tags": {
964
- "sessionSampleRate": 1,
965
- "errorSampleRate": 0,
966
- }
967
- }
968
- */
969
-
970
- const envelope = createReplayEnvelope(replayEvent, recordingData, dsn, client.getOptions().tunnel);
971
-
972
- try {
973
- return await transport.send(envelope);
974
- } catch (e) {
975
- throw new Error(UNABLE_TO_SEND_REPLAY);
868
+ /** Save the session, if it is sticky */
869
+ _maybeSaveSession() {
870
+ if (this.session && this._options.stickySession) {
871
+ saveSession(this.session);
976
872
  }
977
873
  }
978
874
 
979
875
  /**
980
- * Reset the counter of retries for sending replays.
981
- */
982
- resetRetries() {
983
- this._retryCount = 0;
984
- this._retryInterval = BASE_RETRY_INTERVAL;
985
- }
986
-
987
- /**
988
- * Finalize and send the current replay event to Sentry
876
+ * Pauses the replay and resumes it after the rate-limit duration is over.
989
877
  */
990
- async sendReplay({
991
- replayId,
992
- events,
993
- segmentId,
994
- includeReplayStartTimestamp,
995
- eventContext,
996
- }) {
997
- // short circuit if there's no events to upload (this shouldn't happen as runFlush makes this check)
998
- if (!events.length) {
878
+ _handleRateLimit(rateLimits) {
879
+ // in case recording is already paused, we don't need to do anything, as we might have already paused because of a
880
+ // rate limit
881
+ if (this.isPaused()) {
999
882
  return;
1000
883
  }
1001
884
 
1002
- try {
1003
- await this.sendReplayRequest({
1004
- events,
1005
- replayId,
1006
- segmentId,
1007
- includeReplayStartTimestamp,
1008
- eventContext,
1009
- });
1010
- this.resetRetries();
1011
- return true;
1012
- } catch (err) {
1013
- // Capture error for every failed replay
1014
- setContext('Replays', {
1015
- _retryCount: this._retryCount,
1016
- });
1017
- this.handleException(err);
1018
-
1019
- // If an error happened here, it's likely that uploading the attachment
1020
- // failed, we'll can retry with the same events payload
1021
- if (this._retryCount >= MAX_RETRY_COUNT) {
1022
- throw new Error(`${UNABLE_TO_SEND_REPLAY} - max retries exceeded`);
1023
- }
885
+ const rateLimitEnd = disabledUntil(rateLimits, 'replay');
886
+ const rateLimitDuration = rateLimitEnd - Date.now();
1024
887
 
1025
- this._retryCount = this._retryCount + 1;
1026
- // will retry in intervals of 5, 10, 30
1027
- this._retryInterval = this._retryCount * this._retryInterval;
1028
-
1029
- return await new Promise((resolve, reject) => {
1030
- setTimeout(async () => {
1031
- try {
1032
- await this.sendReplay({
1033
- replayId,
1034
- events,
1035
- segmentId,
1036
- includeReplayStartTimestamp,
1037
- eventContext,
1038
- });
1039
- resolve(true);
1040
- } catch (err) {
1041
- reject(err);
1042
- }
1043
- }, this._retryInterval);
1044
- });
1045
- }
1046
- }
888
+ if (rateLimitDuration > 0) {
889
+ (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('[Replay]', `Rate limit hit, pausing replay for ${rateLimitDuration}ms`);
890
+ this.pause();
891
+ this._debouncedFlush.cancel();
1047
892
 
1048
- /** Save the session, if it is sticky */
1049
- _maybeSaveSession() {
1050
- if (this.session && this._options.stickySession) {
1051
- saveSession(this.session);
893
+ setTimeout(() => {
894
+ (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.info('[Replay]', 'Resuming replay after rate limit');
895
+ this.resume();
896
+ }, rateLimitDuration);
1052
897
  }
1053
898
  }
1054
899
  }