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