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