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