@sentry/replay 7.49.0 → 7.51.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 (40) hide show
  1. package/README.md +19 -6
  2. package/cjs/index.js +541 -209
  3. package/cjs/index.js.map +1 -1
  4. package/esm/index.js +542 -210
  5. package/esm/index.js.map +1 -1
  6. package/package.json +5 -5
  7. package/types/constants.d.ts +4 -2
  8. package/types/constants.d.ts.map +1 -1
  9. package/types/coreHandlers/handleAfterSendEvent.d.ts.map +1 -1
  10. package/types/coreHandlers/handleNetworkBreadcrumbs.d.ts.map +1 -1
  11. package/types/coreHandlers/handleScope.d.ts +2 -0
  12. package/types/coreHandlers/handleScope.d.ts.map +1 -1
  13. package/types/coreHandlers/util/fetchUtils.d.ts.map +1 -1
  14. package/types/coreHandlers/util/networkUtils.d.ts +4 -0
  15. package/types/coreHandlers/util/networkUtils.d.ts.map +1 -1
  16. package/types/coreHandlers/util/xhrUtils.d.ts.map +1 -1
  17. package/types/eventBuffer/EventBufferArray.d.ts +5 -1
  18. package/types/eventBuffer/EventBufferArray.d.ts.map +1 -1
  19. package/types/eventBuffer/EventBufferCompressionWorker.d.ts +8 -5
  20. package/types/eventBuffer/EventBufferCompressionWorker.d.ts.map +1 -1
  21. package/types/eventBuffer/EventBufferProxy.d.ts +5 -1
  22. package/types/eventBuffer/EventBufferProxy.d.ts.map +1 -1
  23. package/types/integration.d.ts +21 -14
  24. package/types/integration.d.ts.map +1 -1
  25. package/types/replay.d.ts +35 -12
  26. package/types/replay.d.ts.map +1 -1
  27. package/types/session/Session.d.ts +0 -4
  28. package/types/session/Session.d.ts.map +1 -1
  29. package/types/session/clearSession.d.ts +6 -0
  30. package/types/session/clearSession.d.ts.map +1 -0
  31. package/types/session/createSession.d.ts +6 -2
  32. package/types/session/createSession.d.ts.map +1 -1
  33. package/types/session/getSession.d.ts +1 -1
  34. package/types/session/getSession.d.ts.map +1 -1
  35. package/types/types.d.ts +68 -45
  36. package/types/types.d.ts.map +1 -1
  37. package/types/util/addEvent.d.ts.map +1 -1
  38. package/types/util/addGlobalListeners.d.ts.map +1 -1
  39. package/types/util/timestampToMs.d.ts +5 -0
  40. package/types/util/timestampToMs.d.ts.map +1 -0
package/esm/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { getCurrentHub, addBreadcrumb, addGlobalEventProcessor, prepareEvent, setContext, captureException } from '@sentry/core';
2
- import { GLOBAL_OBJ, logger, uuid4, normalize, htmlTreeAsString, SENTRY_XHR_DATA_KEY, dropUndefinedKeys, addInstrumentationHandler, browserPerformanceTimeOrigin, createEnvelope, createEventEnvelopeHeaders, getSdkMetadataForEnvelopeHeader, isNodeEnv } from '@sentry/utils';
2
+ import { GLOBAL_OBJ, logger, uuid4, normalize, htmlTreeAsString, SENTRY_XHR_DATA_KEY, dropUndefinedKeys, stringMatchesSomePattern, addInstrumentationHandler, browserPerformanceTimeOrigin, createEnvelope, createEventEnvelopeHeaders, getSdkMetadataForEnvelopeHeader, isNodeEnv } from '@sentry/utils';
3
3
 
4
4
  // exporting a separate copy of `WINDOW` rather than exporting the one from `@sentry/browser`
5
5
  // prevents the browser package from being bundled in the CDN bundle, and avoids a
@@ -11,11 +11,14 @@ const REPLAY_SESSION_KEY = 'sentryReplaySession';
11
11
  const REPLAY_EVENT_NAME = 'replay_event';
12
12
  const UNABLE_TO_SEND_REPLAY = 'Unable to send Replay';
13
13
 
14
- // The idle limit for a session
15
- const SESSION_IDLE_DURATION = 300000; // 5 minutes in ms
14
+ // The idle limit for a session after which recording is paused.
15
+ const SESSION_IDLE_PAUSE_DURATION = 300000; // 5 minutes in ms
16
+
17
+ // The idle limit for a session after which the session expires.
18
+ const SESSION_IDLE_EXPIRE_DURATION = 900000; // 15 minutes in ms
16
19
 
17
20
  // The maximum length of a session
18
- const MAX_SESSION_LIFE = 3600000; // 60 minutes
21
+ const MAX_SESSION_LIFE = 3600000; // 60 minutes in ms
19
22
 
20
23
  /** Default flush delays */
21
24
  const DEFAULT_FLUSH_MIN_DELAY = 5000;
@@ -24,7 +27,7 @@ const DEFAULT_FLUSH_MIN_DELAY = 5000;
24
27
  const DEFAULT_FLUSH_MAX_DELAY = 5500;
25
28
 
26
29
  /* How long to wait for error checkouts */
27
- const ERROR_CHECKOUT_TIME = 60000;
30
+ const BUFFER_CHECKOUT_TIME = 60000;
28
31
 
29
32
  const RETRY_BASE_INTERVAL = 5000;
30
33
  const RETRY_MAX_COUNT = 3;
@@ -32,6 +35,9 @@ const RETRY_MAX_COUNT = 3;
32
35
  /* The max (uncompressed) size in bytes of a network body. Any body larger than this will be truncated. */
33
36
  const NETWORK_BODY_MAX_SIZE = 150000;
34
37
 
38
+ /* The max size of a single console arg that is captured. Any arg larger than this will be truncated. */
39
+ const CONSOLE_ARG_MAX_SIZE = 5000;
40
+
35
41
  var NodeType$1;
36
42
  (function (NodeType) {
37
43
  NodeType[NodeType["Document"] = 0] = "Document";
@@ -3369,6 +3375,14 @@ function t(t){let e=t.length;for(;--e>=0;)t[e]=0}const e=new Uint8Array([0,0,0,0
3369
3375
 
3370
3376
  function e(){const e=new Blob([r]);return URL.createObjectURL(e)}
3371
3377
 
3378
+ /**
3379
+ * Converts a timestamp to ms, if it was in s, or keeps it as ms.
3380
+ */
3381
+ function timestampToMs(timestamp) {
3382
+ const isMs = timestamp > 9999999999;
3383
+ return isMs ? timestamp : timestamp * 1000;
3384
+ }
3385
+
3372
3386
  /**
3373
3387
  * A basic event buffer that does not do any compression.
3374
3388
  * Used as fallback if the compression worker cannot be loaded or is disabled.
@@ -3391,14 +3405,8 @@ class EventBufferArray {
3391
3405
  }
3392
3406
 
3393
3407
  /** @inheritdoc */
3394
- async addEvent(event, isCheckout) {
3395
- if (isCheckout) {
3396
- this.events = [event];
3397
- return;
3398
- }
3399
-
3408
+ async addEvent(event) {
3400
3409
  this.events.push(event);
3401
- return;
3402
3410
  }
3403
3411
 
3404
3412
  /** @inheritdoc */
@@ -3412,6 +3420,22 @@ class EventBufferArray {
3412
3420
  resolve(JSON.stringify(eventsRet));
3413
3421
  });
3414
3422
  }
3423
+
3424
+ /** @inheritdoc */
3425
+ clear() {
3426
+ this.events = [];
3427
+ }
3428
+
3429
+ /** @inheritdoc */
3430
+ getEarliestTimestamp() {
3431
+ const timestamp = this.events.map(event => event.timestamp).sort()[0];
3432
+
3433
+ if (!timestamp) {
3434
+ return null;
3435
+ }
3436
+
3437
+ return timestampToMs(timestamp);
3438
+ }
3415
3439
  }
3416
3440
 
3417
3441
  /**
@@ -3519,11 +3543,15 @@ class WorkerHandler {
3519
3543
  * Exported only for testing.
3520
3544
  */
3521
3545
  class EventBufferCompressionWorker {
3522
- /** @inheritdoc */
3523
3546
 
3524
3547
  constructor(worker) {
3525
3548
  this._worker = new WorkerHandler(worker);
3526
- this.hasEvents = false;
3549
+ this._earliestTimestamp = null;
3550
+ }
3551
+
3552
+ /** @inheritdoc */
3553
+ get hasEvents() {
3554
+ return !!this._earliestTimestamp;
3527
3555
  }
3528
3556
 
3529
3557
  /**
@@ -3546,13 +3574,10 @@ class EventBufferCompressionWorker {
3546
3574
  *
3547
3575
  * Returns true if event was successfuly received and processed by worker.
3548
3576
  */
3549
- async addEvent(event, isCheckout) {
3550
- this.hasEvents = true;
3551
-
3552
- if (isCheckout) {
3553
- // This event is a checkout, make sure worker buffer is cleared before
3554
- // proceeding.
3555
- await this._clear();
3577
+ addEvent(event) {
3578
+ const timestamp = timestampToMs(event.timestamp);
3579
+ if (!this._earliestTimestamp || timestamp < this._earliestTimestamp) {
3580
+ this._earliestTimestamp = timestamp;
3556
3581
  }
3557
3582
 
3558
3583
  return this._sendEventToWorker(event);
@@ -3565,6 +3590,18 @@ class EventBufferCompressionWorker {
3565
3590
  return this._finishRequest();
3566
3591
  }
3567
3592
 
3593
+ /** @inheritdoc */
3594
+ clear() {
3595
+ this._earliestTimestamp = null;
3596
+ // We do not wait on this, as we assume the order of messages is consistent for the worker
3597
+ void this._worker.postMessage('clear');
3598
+ }
3599
+
3600
+ /** @inheritdoc */
3601
+ getEarliestTimestamp() {
3602
+ return this._earliestTimestamp;
3603
+ }
3604
+
3568
3605
  /**
3569
3606
  * Send the event to the worker.
3570
3607
  */
@@ -3578,15 +3615,10 @@ class EventBufferCompressionWorker {
3578
3615
  async _finishRequest() {
3579
3616
  const response = await this._worker.postMessage('finish');
3580
3617
 
3581
- this.hasEvents = false;
3618
+ this._earliestTimestamp = null;
3582
3619
 
3583
3620
  return response;
3584
3621
  }
3585
-
3586
- /** Clear any pending events from the worker. */
3587
- _clear() {
3588
- return this._worker.postMessage('clear');
3589
- }
3590
3622
  }
3591
3623
 
3592
3624
  /**
@@ -3615,13 +3647,23 @@ class EventBufferProxy {
3615
3647
  this._compression.destroy();
3616
3648
  }
3617
3649
 
3650
+ /** @inheritdoc */
3651
+ clear() {
3652
+ return this._used.clear();
3653
+ }
3654
+
3655
+ /** @inheritdoc */
3656
+ getEarliestTimestamp() {
3657
+ return this._used.getEarliestTimestamp();
3658
+ }
3659
+
3618
3660
  /**
3619
3661
  * Add an event to the event buffer.
3620
3662
  *
3621
3663
  * Returns true if event was successfully added.
3622
3664
  */
3623
- addEvent(event, isCheckout) {
3624
- return this._used.addEvent(event, isCheckout);
3665
+ addEvent(event) {
3666
+ return this._used.addEvent(event);
3625
3667
  }
3626
3668
 
3627
3669
  /** @inheritDoc */
@@ -3696,6 +3738,31 @@ function createEventBuffer({ useCompression }) {
3696
3738
  return new EventBufferArray();
3697
3739
  }
3698
3740
 
3741
+ /**
3742
+ * Removes the session from Session Storage and unsets session in replay instance
3743
+ */
3744
+ function clearSession(replay) {
3745
+ deleteSession();
3746
+ replay.session = undefined;
3747
+ }
3748
+
3749
+ /**
3750
+ * Deletes a session from storage
3751
+ */
3752
+ function deleteSession() {
3753
+ const hasSessionStorage = 'sessionStorage' in WINDOW;
3754
+
3755
+ if (!hasSessionStorage) {
3756
+ return;
3757
+ }
3758
+
3759
+ try {
3760
+ WINDOW.sessionStorage.removeItem(REPLAY_SESSION_KEY);
3761
+ } catch (e) {
3762
+ // Ignore potential SecurityError exceptions
3763
+ }
3764
+ }
3765
+
3699
3766
  /**
3700
3767
  * Given an initial timestamp and an expiry duration, checks to see if current
3701
3768
  * time should be considered as expired.
@@ -3726,11 +3793,26 @@ function isSessionExpired(session, timeouts, targetTime = +new Date()) {
3726
3793
  // First, check that maximum session length has not been exceeded
3727
3794
  isExpired(session.started, timeouts.maxSessionLife, targetTime) ||
3728
3795
  // check that the idle timeout has not been exceeded (i.e. user has
3729
- // performed an action within the last `idleTimeout` ms)
3730
- isExpired(session.lastActivity, timeouts.sessionIdle, targetTime)
3796
+ // performed an action within the last `sessionIdleExpire` ms)
3797
+ isExpired(session.lastActivity, timeouts.sessionIdleExpire, targetTime)
3731
3798
  );
3732
3799
  }
3733
3800
 
3801
+ /**
3802
+ * Given a sample rate, returns true if replay should be sampled.
3803
+ *
3804
+ * 1.0 = 100% sampling
3805
+ * 0.0 = 0% sampling
3806
+ */
3807
+ function isSampled(sampleRate) {
3808
+ if (sampleRate === undefined) {
3809
+ return false;
3810
+ }
3811
+
3812
+ // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)
3813
+ return Math.random() < sampleRate;
3814
+ }
3815
+
3734
3816
  /**
3735
3817
  * Save a session to session storage.
3736
3818
  */
@@ -3747,21 +3829,6 @@ function saveSession(session) {
3747
3829
  }
3748
3830
  }
3749
3831
 
3750
- /**
3751
- * Given a sample rate, returns true if replay should be sampled.
3752
- *
3753
- * 1.0 = 100% sampling
3754
- * 0.0 = 0% sampling
3755
- */
3756
- function isSampled(sampleRate) {
3757
- if (sampleRate === undefined) {
3758
- return false;
3759
- }
3760
-
3761
- // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)
3762
- return Math.random() < sampleRate;
3763
- }
3764
-
3765
3832
  /**
3766
3833
  * Get a session with defaults & applied sampling.
3767
3834
  */
@@ -3780,14 +3847,15 @@ function makeSession(session) {
3780
3847
  lastActivity,
3781
3848
  segmentId,
3782
3849
  sampled,
3850
+ shouldRefresh: true,
3783
3851
  };
3784
3852
  }
3785
3853
 
3786
3854
  /**
3787
3855
  * Get the sampled status for a session based on sample rates & current sampled status.
3788
3856
  */
3789
- function getSessionSampleType(sessionSampleRate, errorSampleRate) {
3790
- return isSampled(sessionSampleRate) ? 'session' : isSampled(errorSampleRate) ? 'error' : false;
3857
+ function getSessionSampleType(sessionSampleRate, allowBuffering) {
3858
+ return isSampled(sessionSampleRate) ? 'session' : allowBuffering ? 'buffer' : false;
3791
3859
  }
3792
3860
 
3793
3861
  /**
@@ -3795,8 +3863,8 @@ function getSessionSampleType(sessionSampleRate, errorSampleRate) {
3795
3863
  * that all replays will be saved to as attachments. Currently, we only expect
3796
3864
  * one of these Sentry events per "replay session".
3797
3865
  */
3798
- function createSession({ sessionSampleRate, errorSampleRate, stickySession = false }) {
3799
- const sampled = getSessionSampleType(sessionSampleRate, errorSampleRate);
3866
+ function createSession({ sessionSampleRate, allowBuffering, stickySession = false }) {
3867
+ const sampled = getSessionSampleType(sessionSampleRate, allowBuffering);
3800
3868
  const session = makeSession({
3801
3869
  sampled,
3802
3870
  });
@@ -3844,7 +3912,7 @@ function getSession({
3844
3912
  currentSession,
3845
3913
  stickySession,
3846
3914
  sessionSampleRate,
3847
- errorSampleRate,
3915
+ allowBuffering,
3848
3916
  }) {
3849
3917
  // If session exists and is passed, use it instead of always hitting session storage
3850
3918
  const session = currentSession || (stickySession && fetchSession());
@@ -3857,8 +3925,9 @@ function getSession({
3857
3925
 
3858
3926
  if (!isExpired) {
3859
3927
  return { type: 'saved', session };
3860
- } else if (session.sampled === 'error') {
3861
- // Error samples should not be re-created when expired, but instead we stop when the replay is done
3928
+ } else if (!session.shouldRefresh) {
3929
+ // In this case, stop
3930
+ // This is the case if we have an error session that is completed (=triggered an error)
3862
3931
  const discardedSession = makeSession({ sampled: false });
3863
3932
  return { type: 'new', session: discardedSession };
3864
3933
  } else {
@@ -3870,7 +3939,7 @@ function getSession({
3870
3939
  const newSession = createSession({
3871
3940
  stickySession,
3872
3941
  sessionSampleRate,
3873
- errorSampleRate,
3942
+ allowBuffering,
3874
3943
  });
3875
3944
 
3876
3945
  return { type: 'new', session: newSession };
@@ -3895,31 +3964,25 @@ async function addEvent(
3895
3964
  return null;
3896
3965
  }
3897
3966
 
3898
- // TODO: sadness -- we will want to normalize timestamps to be in ms -
3899
- // requires coordination with frontend
3900
- const isMs = event.timestamp > 9999999999;
3901
- const timestampInMs = isMs ? event.timestamp : event.timestamp * 1000;
3967
+ const timestampInMs = timestampToMs(event.timestamp);
3902
3968
 
3903
3969
  // Throw out events that happen more than 5 minutes ago. This can happen if
3904
3970
  // page has been left open and idle for a long period of time and user
3905
3971
  // comes back to trigger a new session. The performance entries rely on
3906
3972
  // `performance.timeOrigin`, which is when the page first opened.
3907
- if (timestampInMs + replay.timeouts.sessionIdle < Date.now()) {
3973
+ if (timestampInMs + replay.timeouts.sessionIdlePause < Date.now()) {
3908
3974
  return null;
3909
3975
  }
3910
3976
 
3911
- // Only record earliest event if a new session was created, otherwise it
3912
- // shouldn't be relevant
3913
- const earliestEvent = replay.getContext().earliestEvent;
3914
- if (replay.session && replay.session.segmentId === 0 && (!earliestEvent || timestampInMs < earliestEvent)) {
3915
- replay.getContext().earliestEvent = timestampInMs;
3916
- }
3917
-
3918
3977
  try {
3919
- return await replay.eventBuffer.addEvent(event, isCheckout);
3978
+ if (isCheckout) {
3979
+ replay.eventBuffer.clear();
3980
+ }
3981
+
3982
+ return await replay.eventBuffer.addEvent(event);
3920
3983
  } catch (error) {
3921
3984
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error(error);
3922
- replay.stop('addEvent');
3985
+ await replay.stop('addEvent');
3923
3986
 
3924
3987
  const client = getCurrentHub().getClient();
3925
3988
 
@@ -3986,23 +4049,17 @@ function handleAfterSendEvent(replay) {
3986
4049
  // Trigger error recording
3987
4050
  // Need to be very careful that this does not cause an infinite loop
3988
4051
  if (
3989
- replay.recordingMode === 'error' &&
4052
+ replay.recordingMode === 'buffer' &&
3990
4053
  event.exception &&
3991
4054
  event.message !== UNABLE_TO_SEND_REPLAY // ignore this error because otherwise we could loop indefinitely with trying to capture replay and failing
3992
4055
  ) {
3993
- setTimeout(async () => {
3994
- // Allow flush to complete before resuming as a session recording, otherwise
3995
- // the checkout from `startRecording` may be included in the payload.
3996
- // Prefer to keep the error replay as a separate (and smaller) segment
3997
- // than the session replay.
3998
- await replay.flushImmediate();
3999
-
4000
- if (replay.stopRecording()) {
4001
- // Reset all "capture on error" configuration before
4002
- // starting a new recording
4003
- replay.recordingMode = 'session';
4004
- replay.startRecording();
4005
- }
4056
+ if (!isSampled(replay.getOptions().errorSampleRate)) {
4057
+ return;
4058
+ }
4059
+
4060
+ setTimeout(() => {
4061
+ // Capture current event buffer as new replay
4062
+ void replay.sendBufferedReplayOrFlush();
4006
4063
  });
4007
4064
  }
4008
4065
  };
@@ -4957,6 +5014,17 @@ function makeNetworkReplayBreadcrumb(
4957
5014
  return result;
4958
5015
  }
4959
5016
 
5017
+ /** Build the request or response part of a replay network breadcrumb that was skipped. */
5018
+ function buildSkippedNetworkRequestOrResponse(bodySize) {
5019
+ return {
5020
+ headers: {},
5021
+ size: bodySize,
5022
+ _meta: {
5023
+ warnings: ['URL_SKIPPED'],
5024
+ },
5025
+ };
5026
+ }
5027
+
4960
5028
  /** Build the request or response part of a replay network breadcrumb. */
4961
5029
  function buildNetworkRequestOrResponse(
4962
5030
  headers,
@@ -5037,8 +5105,8 @@ function normalizeNetworkBody(body)
5037
5105
  };
5038
5106
  } catch (e3) {
5039
5107
  return {
5040
- body,
5041
- warnings: ['INVALID_JSON'],
5108
+ body: exceedsSizeLimit ? `${body.slice(0, NETWORK_BODY_MAX_SIZE)}…` : body,
5109
+ warnings: exceedsSizeLimit ? ['INVALID_JSON', 'TEXT_TRUNCATED'] : ['INVALID_JSON'],
5042
5110
  };
5043
5111
  }
5044
5112
  }
@@ -5057,6 +5125,11 @@ function _strIsProbablyJson(str) {
5057
5125
  return (first === '[' && last === ']') || (first === '{' && last === '}');
5058
5126
  }
5059
5127
 
5128
+ /** Match an URL against a list of strings/Regex. */
5129
+ function urlMatches(url, urls) {
5130
+ return stringMatchesSomePattern(url, urls);
5131
+ }
5132
+
5060
5133
  /**
5061
5134
  * Capture a fetch breadcrumb to a replay.
5062
5135
  * This adds additional data (where approriate).
@@ -5116,33 +5189,37 @@ async function _prepareFetchData(
5116
5189
  const {
5117
5190
  url,
5118
5191
  method,
5119
- status_code: statusCode,
5192
+ status_code: statusCode = 0,
5120
5193
  request_body_size: requestBodySize,
5121
5194
  response_body_size: responseBodySize,
5122
5195
  } = breadcrumb.data;
5123
5196
 
5124
- const request = _getRequestInfo(options, hint.input, requestBodySize);
5125
- const response = await _getResponseInfo(options, hint.response, responseBodySize);
5197
+ const captureDetails = urlMatches(url, options.networkDetailAllowUrls);
5198
+
5199
+ const request = captureDetails
5200
+ ? _getRequestInfo(options, hint.input, requestBodySize)
5201
+ : buildSkippedNetworkRequestOrResponse(requestBodySize);
5202
+ const response = await _getResponseInfo(captureDetails, options, hint.response, responseBodySize);
5126
5203
 
5127
5204
  return {
5128
5205
  startTimestamp,
5129
5206
  endTimestamp,
5130
5207
  url,
5131
5208
  method,
5132
- statusCode: statusCode || 0,
5209
+ statusCode,
5133
5210
  request,
5134
5211
  response,
5135
5212
  };
5136
5213
  }
5137
5214
 
5138
5215
  function _getRequestInfo(
5139
- { captureBodies, requestHeaders },
5216
+ { networkCaptureBodies, networkRequestHeaders },
5140
5217
  input,
5141
5218
  requestBodySize,
5142
5219
  ) {
5143
- const headers = getRequestHeaders(input, requestHeaders);
5220
+ const headers = getRequestHeaders(input, networkRequestHeaders);
5144
5221
 
5145
- if (!captureBodies) {
5222
+ if (!networkCaptureBodies) {
5146
5223
  return buildNetworkRequestOrResponse(headers, requestBodySize, undefined);
5147
5224
  }
5148
5225
 
@@ -5153,19 +5230,24 @@ function _getRequestInfo(
5153
5230
  }
5154
5231
 
5155
5232
  async function _getResponseInfo(
5233
+ captureDetails,
5156
5234
  {
5157
- captureBodies,
5235
+ networkCaptureBodies,
5158
5236
  textEncoder,
5159
- responseHeaders,
5237
+ networkResponseHeaders,
5160
5238
  }
5161
5239
 
5162
5240
  ,
5163
5241
  response,
5164
5242
  responseBodySize,
5165
5243
  ) {
5166
- const headers = getAllHeaders(response.headers, responseHeaders);
5244
+ if (!captureDetails && responseBodySize !== undefined) {
5245
+ return buildSkippedNetworkRequestOrResponse(responseBodySize);
5246
+ }
5247
+
5248
+ const headers = getAllHeaders(response.headers, networkResponseHeaders);
5167
5249
 
5168
- if (!captureBodies && responseBodySize !== undefined) {
5250
+ if (!networkCaptureBodies && responseBodySize !== undefined) {
5169
5251
  return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);
5170
5252
  }
5171
5253
 
@@ -5180,7 +5262,11 @@ async function _getResponseInfo(
5180
5262
  ? getBodySize(bodyText, textEncoder)
5181
5263
  : responseBodySize;
5182
5264
 
5183
- if (captureBodies) {
5265
+ if (!captureDetails) {
5266
+ return buildSkippedNetworkRequestOrResponse(size);
5267
+ }
5268
+
5269
+ if (networkCaptureBodies) {
5184
5270
  return buildNetworkRequestOrResponse(headers, size, bodyText);
5185
5271
  }
5186
5272
 
@@ -5313,28 +5399,44 @@ function _prepareXhrData(
5313
5399
  const {
5314
5400
  url,
5315
5401
  method,
5316
- status_code: statusCode,
5402
+ status_code: statusCode = 0,
5317
5403
  request_body_size: requestBodySize,
5318
5404
  response_body_size: responseBodySize,
5319
5405
  } = breadcrumb.data;
5320
5406
 
5321
- const xhrInfo = xhr[SENTRY_XHR_DATA_KEY];
5322
- const requestHeaders = xhrInfo ? getAllowedHeaders(xhrInfo.request_headers, options.requestHeaders) : {};
5323
- const responseHeaders = getAllowedHeaders(getResponseHeaders(xhr), options.responseHeaders);
5324
-
5325
5407
  if (!url) {
5326
5408
  return null;
5327
5409
  }
5328
5410
 
5411
+ if (!urlMatches(url, options.networkDetailAllowUrls)) {
5412
+ const request = buildSkippedNetworkRequestOrResponse(requestBodySize);
5413
+ const response = buildSkippedNetworkRequestOrResponse(responseBodySize);
5414
+ return {
5415
+ startTimestamp,
5416
+ endTimestamp,
5417
+ url,
5418
+ method,
5419
+ statusCode,
5420
+ request,
5421
+ response,
5422
+ };
5423
+ }
5424
+
5425
+ const xhrInfo = xhr[SENTRY_XHR_DATA_KEY];
5426
+ const networkRequestHeaders = xhrInfo
5427
+ ? getAllowedHeaders(xhrInfo.request_headers, options.networkRequestHeaders)
5428
+ : {};
5429
+ const networkResponseHeaders = getAllowedHeaders(getResponseHeaders(xhr), options.networkResponseHeaders);
5430
+
5329
5431
  const request = buildNetworkRequestOrResponse(
5330
- requestHeaders,
5432
+ networkRequestHeaders,
5331
5433
  requestBodySize,
5332
- options.captureBodies ? getBodyString(input) : undefined,
5434
+ options.networkCaptureBodies ? getBodyString(input) : undefined,
5333
5435
  );
5334
5436
  const response = buildNetworkRequestOrResponse(
5335
- responseHeaders,
5437
+ networkResponseHeaders,
5336
5438
  responseBodySize,
5337
- options.captureBodies ? hint.xhr.responseText : undefined,
5439
+ options.networkCaptureBodies ? hint.xhr.responseText : undefined,
5338
5440
  );
5339
5441
 
5340
5442
  return {
@@ -5342,7 +5444,7 @@ function _prepareXhrData(
5342
5444
  endTimestamp,
5343
5445
  url,
5344
5446
  method,
5345
- statusCode: statusCode || 0,
5447
+ statusCode,
5346
5448
  request,
5347
5449
  response,
5348
5450
  };
@@ -5374,10 +5476,16 @@ function handleNetworkBreadcrumbs(replay) {
5374
5476
  try {
5375
5477
  const textEncoder = new TextEncoder();
5376
5478
 
5479
+ const { networkDetailAllowUrls, networkCaptureBodies, networkRequestHeaders, networkResponseHeaders } =
5480
+ replay.getOptions();
5481
+
5377
5482
  const options = {
5378
5483
  replay,
5379
5484
  textEncoder,
5380
- ...replay.getExperimentalOptions().network,
5485
+ networkDetailAllowUrls,
5486
+ networkCaptureBodies,
5487
+ networkRequestHeaders,
5488
+ networkResponseHeaders,
5381
5489
  };
5382
5490
 
5383
5491
  if (client && client.on) {
@@ -5485,9 +5593,66 @@ function handleScope(scope) {
5485
5593
  return null;
5486
5594
  }
5487
5595
 
5596
+ if (newBreadcrumb.category === 'console') {
5597
+ return normalizeConsoleBreadcrumb(newBreadcrumb);
5598
+ }
5599
+
5488
5600
  return createBreadcrumb(newBreadcrumb);
5489
5601
  }
5490
5602
 
5603
+ /** exported for tests only */
5604
+ function normalizeConsoleBreadcrumb(breadcrumb) {
5605
+ const args = breadcrumb.data && breadcrumb.data.arguments;
5606
+
5607
+ if (!Array.isArray(args) || args.length === 0) {
5608
+ return createBreadcrumb(breadcrumb);
5609
+ }
5610
+
5611
+ let isTruncated = false;
5612
+
5613
+ // Avoid giant args captures
5614
+ const normalizedArgs = args.map(arg => {
5615
+ if (!arg) {
5616
+ return arg;
5617
+ }
5618
+ if (typeof arg === 'string') {
5619
+ if (arg.length > CONSOLE_ARG_MAX_SIZE) {
5620
+ isTruncated = true;
5621
+ return `${arg.slice(0, CONSOLE_ARG_MAX_SIZE)}…`;
5622
+ }
5623
+
5624
+ return arg;
5625
+ }
5626
+ if (typeof arg === 'object') {
5627
+ try {
5628
+ const normalizedArg = normalize(arg, 7);
5629
+ const stringified = JSON.stringify(normalizedArg);
5630
+ if (stringified.length > CONSOLE_ARG_MAX_SIZE) {
5631
+ const fixedJson = fixJson(stringified.slice(0, CONSOLE_ARG_MAX_SIZE));
5632
+ const json = JSON.parse(fixedJson);
5633
+ // We only set this after JSON.parse() was successfull, so we know we didn't run into `catch`
5634
+ isTruncated = true;
5635
+ return json;
5636
+ }
5637
+ return normalizedArg;
5638
+ } catch (e) {
5639
+ // fall back to default
5640
+ }
5641
+ }
5642
+
5643
+ return arg;
5644
+ });
5645
+
5646
+ return createBreadcrumb({
5647
+ ...breadcrumb,
5648
+ data: {
5649
+ ...breadcrumb.data,
5650
+ arguments: normalizedArgs,
5651
+ ...(isTruncated ? { _meta: { warnings: ['CONSOLE_ARG_TRUNCATED'] } } : {}),
5652
+ },
5653
+ });
5654
+ }
5655
+
5491
5656
  /**
5492
5657
  * Add global listeners that cannot be removed.
5493
5658
  */
@@ -5512,7 +5677,8 @@ function addGlobalListeners(replay) {
5512
5677
  client.on('afterSendEvent', handleAfterSendEvent(replay));
5513
5678
  client.on('createDsc', (dsc) => {
5514
5679
  const replayId = replay.getSessionId();
5515
- if (replayId) {
5680
+ // We do not want to set the DSC when in buffer mode, as that means the replay has not been sent (yet)
5681
+ if (replayId && replay.isEnabled() && replay.recordingMode === 'session') {
5516
5682
  dsc.replay_id = replayId;
5517
5683
  }
5518
5684
  });
@@ -5820,7 +5986,7 @@ function getHandleRecordingEmit(replay) {
5820
5986
  // when an error occurs. Clear any state that happens before this current
5821
5987
  // checkout. This needs to happen before `addEvent()` which updates state
5822
5988
  // dependent on this reset.
5823
- if (replay.recordingMode === 'error' && isCheckout) {
5989
+ if (replay.recordingMode === 'buffer' && isCheckout) {
5824
5990
  replay.setInitialState();
5825
5991
  }
5826
5992
 
@@ -5844,10 +6010,10 @@ function getHandleRecordingEmit(replay) {
5844
6010
  return true;
5845
6011
  }
5846
6012
 
5847
- // See note above re: session start needs to reflect the most recent
5848
- // checkout.
5849
- if (replay.recordingMode === 'error' && replay.session) {
5850
- const { earliestEvent } = replay.getContext();
6013
+ // When in buffer mode, make sure we adjust the session started date to the current earliest event of the buffer
6014
+ // this should usually be the timestamp of the checkout event, but to be safe...
6015
+ if (replay.recordingMode === 'buffer' && replay.session && replay.eventBuffer) {
6016
+ const earliestEvent = replay.eventBuffer.getEarliestTimestamp();
5851
6017
  if (earliestEvent) {
5852
6018
  replay.session.started = earliestEvent;
5853
6019
 
@@ -6195,9 +6361,11 @@ class ReplayContainer {
6195
6361
  __init2() {this.performanceEvents = [];}
6196
6362
 
6197
6363
  /**
6198
- * Recording can happen in one of two modes:
6199
- * * session: Record the whole session, sending it continuously
6200
- * * error: Always keep the last 60s of recording, and when an error occurs, send it immediately
6364
+ * Recording can happen in one of three modes:
6365
+ * - session: Record the whole session, sending it continuously
6366
+ * - buffer: Always keep the last 60s of recording, requires:
6367
+ * - having replaysOnErrorSampleRate > 0 to capture replay when an error occurs
6368
+ * - or calling `flush()` to send the replay
6201
6369
  */
6202
6370
  __init3() {this.recordingMode = 'session';}
6203
6371
 
@@ -6206,7 +6374,8 @@ class ReplayContainer {
6206
6374
  * @hidden
6207
6375
  */
6208
6376
  __init4() {this.timeouts = {
6209
- sessionIdle: SESSION_IDLE_DURATION,
6377
+ sessionIdlePause: SESSION_IDLE_PAUSE_DURATION,
6378
+ sessionIdleExpire: SESSION_IDLE_EXPIRE_DURATION,
6210
6379
  maxSessionLife: MAX_SESSION_LIFE,
6211
6380
  }; }
6212
6381
 
@@ -6250,7 +6419,6 @@ class ReplayContainer {
6250
6419
  errorIds: new Set(),
6251
6420
  traceIds: new Set(),
6252
6421
  urls: [],
6253
- earliestEvent: null,
6254
6422
  initialTimestamp: Date.now(),
6255
6423
  initialUrl: '',
6256
6424
  };}
@@ -6267,8 +6435,6 @@ class ReplayContainer {
6267
6435
  this._debouncedFlush = debounce(() => this._flush(), this._options.flushMinDelay, {
6268
6436
  maxWait: this._options.flushMaxDelay,
6269
6437
  });
6270
-
6271
- this._experimentalOptions = _getExperimentalOptions(options);
6272
6438
  }
6273
6439
 
6274
6440
  /** Get the event context. */
@@ -6292,58 +6458,102 @@ class ReplayContainer {
6292
6458
  }
6293
6459
 
6294
6460
  /**
6295
- * Get the experimental options.
6296
- * THIS IS INTERNAL AND SUBJECT TO CHANGE!
6297
- * @hidden
6461
+ * Initializes the plugin based on sampling configuration. Should not be
6462
+ * called outside of constructor.
6298
6463
  */
6299
- getExperimentalOptions() {
6300
- return this._experimentalOptions;
6464
+ initializeSampling() {
6465
+ const { errorSampleRate, sessionSampleRate } = this._options;
6466
+
6467
+ // If neither sample rate is > 0, then do nothing - user will need to call one of
6468
+ // `start()` or `startBuffering` themselves.
6469
+ if (errorSampleRate <= 0 && sessionSampleRate <= 0) {
6470
+ return;
6471
+ }
6472
+
6473
+ // Otherwise if there is _any_ sample rate set, try to load an existing
6474
+ // session, or create a new one.
6475
+ const isSessionSampled = this._loadAndCheckSession();
6476
+
6477
+ if (!isSessionSampled) {
6478
+ // This should only occur if `errorSampleRate` is 0 and was unsampled for
6479
+ // session-based replay. In this case there is nothing to do.
6480
+ return;
6481
+ }
6482
+
6483
+ if (!this.session) {
6484
+ // This should not happen, something wrong has occurred
6485
+ this._handleException(new Error('Unable to initialize and create session'));
6486
+ return;
6487
+ }
6488
+
6489
+ if (this.session.sampled && this.session.sampled !== 'session') {
6490
+ // If not sampled as session-based, then recording mode will be `buffer`
6491
+ // Note that we don't explicitly check if `sampled === 'buffer'` because we
6492
+ // could have sessions from Session storage that are still `error` from
6493
+ // prior SDK version.
6494
+ this.recordingMode = 'buffer';
6495
+ }
6496
+
6497
+ this._initializeRecording();
6301
6498
  }
6302
6499
 
6303
6500
  /**
6304
- * Initializes the plugin.
6501
+ * Start a replay regardless of sampling rate. Calling this will always
6502
+ * create a new session. Will throw an error if replay is already in progress.
6305
6503
  *
6306
6504
  * Creates or loads a session, attaches listeners to varying events (DOM,
6307
6505
  * _performanceObserver, Recording, Sentry SDK, etc)
6308
6506
  */
6309
6507
  start() {
6310
- this.setInitialState();
6311
-
6312
- if (!this._loadAndCheckSession()) {
6313
- return;
6508
+ if (this._isEnabled && this.recordingMode === 'session') {
6509
+ throw new Error('Replay recording is already in progress');
6314
6510
  }
6315
6511
 
6316
- // If there is no session, then something bad has happened - can't continue
6317
- if (!this.session) {
6318
- this._handleException(new Error('No session found'));
6319
- return;
6512
+ if (this._isEnabled && this.recordingMode === 'buffer') {
6513
+ throw new Error('Replay buffering is in progress, call `flush()` to save the replay');
6320
6514
  }
6321
6515
 
6322
- if (!this.session.sampled) {
6323
- // If session was not sampled, then we do not initialize the integration at all.
6324
- return;
6325
- }
6516
+ const previousSessionId = this.session && this.session.id;
6326
6517
 
6327
- // If session is sampled for errors, then we need to set the recordingMode
6328
- // to 'error', which will configure recording with different options.
6329
- if (this.session.sampled === 'error') {
6330
- this.recordingMode = 'error';
6518
+ const { session } = getSession({
6519
+ timeouts: this.timeouts,
6520
+ stickySession: Boolean(this._options.stickySession),
6521
+ currentSession: this.session,
6522
+ // This is intentional: create a new session-based replay when calling `start()`
6523
+ sessionSampleRate: 1,
6524
+ allowBuffering: false,
6525
+ });
6526
+
6527
+ session.previousSessionId = previousSessionId;
6528
+ this.session = session;
6529
+
6530
+ this._initializeRecording();
6531
+ }
6532
+
6533
+ /**
6534
+ * Start replay buffering. Buffers until `flush()` is called or, if
6535
+ * `replaysOnErrorSampleRate` > 0, an error occurs.
6536
+ */
6537
+ startBuffering() {
6538
+ if (this._isEnabled) {
6539
+ throw new Error('Replay recording is already in progress');
6331
6540
  }
6332
6541
 
6333
- // setup() is generally called on page load or manually - in both cases we
6334
- // should treat it as an activity
6335
- this._updateSessionActivity();
6542
+ const previousSessionId = this.session && this.session.id;
6336
6543
 
6337
- this.eventBuffer = createEventBuffer({
6338
- useCompression: this._options.useCompression,
6544
+ const { session } = getSession({
6545
+ timeouts: this.timeouts,
6546
+ stickySession: Boolean(this._options.stickySession),
6547
+ currentSession: this.session,
6548
+ sessionSampleRate: 0,
6549
+ allowBuffering: true,
6339
6550
  });
6340
6551
 
6341
- this._addListeners();
6342
-
6343
- // Need to set as enabled before we start recording, as `record()` can trigger a flush with a new checkout
6344
- this._isEnabled = true;
6552
+ session.previousSessionId = previousSessionId;
6553
+ this.session = session;
6345
6554
 
6346
- this.startRecording();
6555
+ this.recordingMode = 'buffer';
6556
+ this._initializeRecording();
6347
6557
  }
6348
6558
 
6349
6559
  /**
@@ -6358,7 +6568,7 @@ class ReplayContainer {
6358
6568
  // When running in error sampling mode, we need to overwrite `checkoutEveryNms`
6359
6569
  // Without this, it would record forever, until an error happens, which we don't want
6360
6570
  // instead, we'll always keep the last 60 seconds of replay before an error happened
6361
- ...(this.recordingMode === 'error' && { checkoutEveryNms: ERROR_CHECKOUT_TIME }),
6571
+ ...(this.recordingMode === 'buffer' && { checkoutEveryNms: BUFFER_CHECKOUT_TIME }),
6362
6572
  emit: getHandleRecordingEmit(this),
6363
6573
  onMutation: this._onMutationHandler,
6364
6574
  });
@@ -6369,17 +6579,18 @@ class ReplayContainer {
6369
6579
 
6370
6580
  /**
6371
6581
  * Stops the recording, if it was running.
6372
- * Returns true if it was stopped, else false.
6582
+ *
6583
+ * Returns true if it was previously stopped, or is now stopped,
6584
+ * otherwise false.
6373
6585
  */
6374
6586
  stopRecording() {
6375
6587
  try {
6376
6588
  if (this._stopRecording) {
6377
6589
  this._stopRecording();
6378
6590
  this._stopRecording = undefined;
6379
- return true;
6380
6591
  }
6381
6592
 
6382
- return false;
6593
+ return true;
6383
6594
  } catch (err) {
6384
6595
  this._handleException(err);
6385
6596
  return false;
@@ -6390,7 +6601,7 @@ class ReplayContainer {
6390
6601
  * Currently, this needs to be manually called (e.g. for tests). Sentry SDK
6391
6602
  * does not support a teardown
6392
6603
  */
6393
- stop(reason) {
6604
+ async stop(reason) {
6394
6605
  if (!this._isEnabled) {
6395
6606
  return;
6396
6607
  }
@@ -6406,12 +6617,24 @@ class ReplayContainer {
6406
6617
  log(msg);
6407
6618
  }
6408
6619
 
6620
+ // We can't move `_isEnabled` after awaiting a flush, otherwise we can
6621
+ // enter into an infinite loop when `stop()` is called while flushing.
6409
6622
  this._isEnabled = false;
6410
6623
  this._removeListeners();
6411
6624
  this.stopRecording();
6625
+
6626
+ this._debouncedFlush.cancel();
6627
+ // See comment above re: `_isEnabled`, we "force" a flush, ignoring the
6628
+ // `_isEnabled` state of the plugin since it was disabled above.
6629
+ await this._flush({ force: true });
6630
+
6631
+ // After flush, destroy event buffer
6412
6632
  this.eventBuffer && this.eventBuffer.destroy();
6413
6633
  this.eventBuffer = null;
6414
- this._debouncedFlush.cancel();
6634
+
6635
+ // Clear session from session storage, note this means if a new session
6636
+ // is started after, it will not have `previousSessionId`
6637
+ clearSession(this);
6415
6638
  } catch (err) {
6416
6639
  this._handleException(err);
6417
6640
  }
@@ -6442,6 +6665,45 @@ class ReplayContainer {
6442
6665
  this.startRecording();
6443
6666
  }
6444
6667
 
6668
+ /**
6669
+ * If not in "session" recording mode, flush event buffer which will create a new replay.
6670
+ * Unless `continueRecording` is false, the replay will continue to record and
6671
+ * behave as a "session"-based replay.
6672
+ *
6673
+ * Otherwise, queue up a flush.
6674
+ */
6675
+ async sendBufferedReplayOrFlush({ continueRecording = true } = {}) {
6676
+ if (this.recordingMode === 'session') {
6677
+ return this.flushImmediate();
6678
+ }
6679
+
6680
+ // Allow flush to complete before resuming as a session recording, otherwise
6681
+ // the checkout from `startRecording` may be included in the payload.
6682
+ // Prefer to keep the error replay as a separate (and smaller) segment
6683
+ // than the session replay.
6684
+ await this.flushImmediate();
6685
+
6686
+ const hasStoppedRecording = this.stopRecording();
6687
+
6688
+ if (!continueRecording || !hasStoppedRecording) {
6689
+ return;
6690
+ }
6691
+
6692
+ // Re-start recording, but in "session" recording mode
6693
+
6694
+ // Reset all "capture on error" configuration before
6695
+ // starting a new recording
6696
+ this.recordingMode = 'session';
6697
+
6698
+ // Once this session ends, we do not want to refresh it
6699
+ if (this.session) {
6700
+ this.session.shouldRefresh = false;
6701
+ this._maybeSaveSession();
6702
+ }
6703
+
6704
+ this.startRecording();
6705
+ }
6706
+
6445
6707
  /**
6446
6708
  * We want to batch uploads of replay events. Save events only if
6447
6709
  * `<flushMinDelay>` milliseconds have elapsed since the last event
@@ -6451,12 +6713,12 @@ class ReplayContainer {
6451
6713
  * processing and hand back control to caller.
6452
6714
  */
6453
6715
  addUpdate(cb) {
6454
- // We need to always run `cb` (e.g. in the case of `this.recordingMode == 'error'`)
6716
+ // We need to always run `cb` (e.g. in the case of `this.recordingMode == 'buffer'`)
6455
6717
  const cbResult = cb();
6456
6718
 
6457
6719
  // If this option is turned on then we will only want to call `flush`
6458
6720
  // explicitly
6459
- if (this.recordingMode === 'error') {
6721
+ if (this.recordingMode === 'buffer') {
6460
6722
  return;
6461
6723
  }
6462
6724
 
@@ -6528,12 +6790,12 @@ class ReplayContainer {
6528
6790
  const oldSessionId = this.getSessionId();
6529
6791
 
6530
6792
  // Prevent starting a new session if the last user activity is older than
6531
- // SESSION_IDLE_DURATION. Otherwise non-user activity can trigger a new
6793
+ // SESSION_IDLE_PAUSE_DURATION. Otherwise non-user activity can trigger a new
6532
6794
  // session+recording. This creates noisy replays that do not have much
6533
6795
  // content in them.
6534
6796
  if (
6535
6797
  this._lastActivity &&
6536
- isExpired(this._lastActivity, this.timeouts.sessionIdle) &&
6798
+ isExpired(this._lastActivity, this.timeouts.sessionIdlePause) &&
6537
6799
  this.session &&
6538
6800
  this.session.sampled === 'session'
6539
6801
  ) {
@@ -6583,6 +6845,30 @@ class ReplayContainer {
6583
6845
  this._context.urls.push(url);
6584
6846
  }
6585
6847
 
6848
+ /**
6849
+ * Initialize and start all listeners to varying events (DOM,
6850
+ * Performance Observer, Recording, Sentry SDK, etc)
6851
+ */
6852
+ _initializeRecording() {
6853
+ this.setInitialState();
6854
+
6855
+ // this method is generally called on page load or manually - in both cases
6856
+ // we should treat it as an activity
6857
+ this._updateSessionActivity();
6858
+
6859
+ this.eventBuffer = createEventBuffer({
6860
+ useCompression: this._options.useCompression,
6861
+ });
6862
+
6863
+ this._removeListeners();
6864
+ this._addListeners();
6865
+
6866
+ // Need to set as enabled before we start recording, as `record()` can trigger a flush with a new checkout
6867
+ this._isEnabled = true;
6868
+
6869
+ this.startRecording();
6870
+ }
6871
+
6586
6872
  /** A wrapper to conditionally capture exceptions. */
6587
6873
  _handleException(error) {
6588
6874
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay]', error);
@@ -6602,7 +6888,7 @@ class ReplayContainer {
6602
6888
  stickySession: Boolean(this._options.stickySession),
6603
6889
  currentSession: this.session,
6604
6890
  sessionSampleRate: this._options.sessionSampleRate,
6605
- errorSampleRate: this._options.errorSampleRate,
6891
+ allowBuffering: this._options.errorSampleRate > 0,
6606
6892
  });
6607
6893
 
6608
6894
  // If session was newly created (i.e. was not loaded from storage), then
@@ -6619,7 +6905,7 @@ class ReplayContainer {
6619
6905
  this.session = session;
6620
6906
 
6621
6907
  if (!this.session.sampled) {
6622
- this.stop('session unsampled');
6908
+ void this.stop('session unsampled');
6623
6909
  return false;
6624
6910
  }
6625
6911
 
@@ -6743,7 +7029,7 @@ class ReplayContainer {
6743
7029
  const isSessionActive = this.checkAndHandleExpiredSession();
6744
7030
 
6745
7031
  if (!isSessionActive) {
6746
- // If the user has come back to the page within SESSION_IDLE_DURATION
7032
+ // If the user has come back to the page within SESSION_IDLE_PAUSE_DURATION
6747
7033
  // ms, we will re-use the existing session, otherwise create a new
6748
7034
  // session
6749
7035
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Document has become active, but session has expired');
@@ -6817,7 +7103,7 @@ class ReplayContainer {
6817
7103
  * Only flush if `this.recordingMode === 'session'`
6818
7104
  */
6819
7105
  _conditionalFlush() {
6820
- if (this.recordingMode === 'error') {
7106
+ if (this.recordingMode === 'buffer') {
6821
7107
  return;
6822
7108
  }
6823
7109
 
@@ -6832,22 +7118,35 @@ class ReplayContainer {
6832
7118
  this._context.errorIds.clear();
6833
7119
  this._context.traceIds.clear();
6834
7120
  this._context.urls = [];
6835
- this._context.earliestEvent = null;
7121
+ }
7122
+
7123
+ /** Update the initial timestamp based on the buffer content. */
7124
+ _updateInitialTimestampFromEventBuffer() {
7125
+ const { session, eventBuffer } = this;
7126
+ if (!session || !eventBuffer) {
7127
+ return;
7128
+ }
7129
+
7130
+ // we only ever update this on the initial segment
7131
+ if (session.segmentId) {
7132
+ return;
7133
+ }
7134
+
7135
+ const earliestEvent = eventBuffer.getEarliestTimestamp();
7136
+ if (earliestEvent && earliestEvent < this._context.initialTimestamp) {
7137
+ this._context.initialTimestamp = earliestEvent;
7138
+ }
6836
7139
  }
6837
7140
 
6838
7141
  /**
6839
7142
  * Return and clear _context
6840
7143
  */
6841
7144
  _popEventContext() {
6842
- if (this._context.earliestEvent && this._context.earliestEvent < this._context.initialTimestamp) {
6843
- this._context.initialTimestamp = this._context.earliestEvent;
6844
- }
6845
-
6846
7145
  const _context = {
6847
7146
  initialTimestamp: this._context.initialTimestamp,
6848
7147
  initialUrl: this._context.initialUrl,
6849
- errorIds: Array.from(this._context.errorIds).filter(Boolean),
6850
- traceIds: Array.from(this._context.traceIds).filter(Boolean),
7148
+ errorIds: Array.from(this._context.errorIds),
7149
+ traceIds: Array.from(this._context.traceIds),
6851
7150
  urls: this._context.urls,
6852
7151
  };
6853
7152
 
@@ -6886,6 +7185,9 @@ class ReplayContainer {
6886
7185
  }
6887
7186
 
6888
7187
  try {
7188
+ // This uses the data from the eventBuffer, so we need to call this before `finish()
7189
+ this._updateInitialTimestampFromEventBuffer();
7190
+
6889
7191
  // Note this empties the event buffer regardless of outcome of sending replay
6890
7192
  const recordingData = await this.eventBuffer.finish();
6891
7193
 
@@ -6912,7 +7214,7 @@ class ReplayContainer {
6912
7214
  // This means we retried 3 times and all of them failed,
6913
7215
  // or we ran into a problem we don't want to retry, like rate limiting.
6914
7216
  // In this case, we want to completely stop the replay - otherwise, we may get inconsistent segments
6915
- this.stop('sendReplay');
7217
+ void this.stop('sendReplay');
6916
7218
 
6917
7219
  const client = getCurrentHub().getClient();
6918
7220
 
@@ -6926,8 +7228,12 @@ class ReplayContainer {
6926
7228
  * Flush recording data to Sentry. Creates a lock so that only a single flush
6927
7229
  * can be active at a time. Do not call this directly.
6928
7230
  */
6929
- __init16() {this._flush = async () => {
6930
- if (!this._isEnabled) {
7231
+ __init16() {this._flush = async ({
7232
+ force = false,
7233
+ }
7234
+
7235
+ = {}) => {
7236
+ if (!this._isEnabled && !force) {
6931
7237
  // This can happen if e.g. the replay was stopped because of exceeding the retry limit
6932
7238
  return;
6933
7239
  }
@@ -7008,23 +7314,6 @@ class ReplayContainer {
7008
7314
  };}
7009
7315
  }
7010
7316
 
7011
- function _getExperimentalOptions(options) {
7012
- const requestHeaders = options._experiments.captureRequestHeaders || [];
7013
- const responseHeaders = options._experiments.captureResponseHeaders || [];
7014
- const captureBodies = options._experiments.captureNetworkBodies || false;
7015
-
7016
- // Add defaults
7017
- const defaultHeaders = ['content-length', 'content-type', 'accept'];
7018
-
7019
- return {
7020
- network: {
7021
- captureBodies,
7022
- requestHeaders: [...defaultHeaders, ...requestHeaders.map(header => header.toLowerCase())],
7023
- responseHeaders: [...defaultHeaders, ...responseHeaders.map(header => header.toLowerCase())],
7024
- },
7025
- };
7026
- }
7027
-
7028
7317
  function getOption(
7029
7318
  selectors,
7030
7319
  defaultSelectors,
@@ -7128,6 +7417,8 @@ function isElectronNodeRenderer() {
7128
7417
  const MEDIA_SELECTORS =
7129
7418
  'img,image,svg,video,object,picture,embed,map,audio,link[rel="icon"],link[rel="apple-touch-icon"]';
7130
7419
 
7420
+ const DEFAULT_NETWORK_HEADERS = ['content-length', 'content-type', 'accept'];
7421
+
7131
7422
  let _initialized = false;
7132
7423
 
7133
7424
  /**
@@ -7168,6 +7459,11 @@ class Replay {
7168
7459
  maskAllInputs = true,
7169
7460
  blockAllMedia = true,
7170
7461
 
7462
+ networkDetailAllowUrls = [],
7463
+ networkCaptureBodies = true,
7464
+ networkRequestHeaders = [],
7465
+ networkResponseHeaders = [],
7466
+
7171
7467
  mask = [],
7172
7468
  unmask = [],
7173
7469
  block = [],
@@ -7226,6 +7522,11 @@ class Replay {
7226
7522
  errorSampleRate,
7227
7523
  useCompression,
7228
7524
  blockAllMedia,
7525
+ networkDetailAllowUrls,
7526
+ networkCaptureBodies,
7527
+ networkRequestHeaders: _getMergedNetworkHeaders(networkRequestHeaders),
7528
+ networkResponseHeaders: _getMergedNetworkHeaders(networkResponseHeaders),
7529
+
7229
7530
  _experiments,
7230
7531
  };
7231
7532
 
@@ -7279,14 +7580,7 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
7279
7580
  }
7280
7581
 
7281
7582
  /**
7282
- * We previously used to create a transaction in `setupOnce` and it would
7283
- * potentially create a transaction before some native SDK integrations have run
7284
- * and applied their own global event processor. An example is:
7285
- * https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts
7286
- *
7287
- * So we call `replay.setup` in next event loop as a workaround to wait for other
7288
- * global event processors to finish. This is no longer needed, but keeping it
7289
- * here to avoid any future issues.
7583
+ * Setup and initialize replay container
7290
7584
  */
7291
7585
  setupOnce() {
7292
7586
  if (!isBrowser()) {
@@ -7295,12 +7589,20 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
7295
7589
 
7296
7590
  this._setup();
7297
7591
 
7298
- // XXX: See method comments above
7299
- setTimeout(() => this.start());
7592
+ // Once upon a time, we tried to create a transaction in `setupOnce` and it would
7593
+ // potentially create a transaction before some native SDK integrations have run
7594
+ // and applied their own global event processor. An example is:
7595
+ // https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts
7596
+ //
7597
+ // So we call `this._initialize()` in next event loop as a workaround to wait for other
7598
+ // global event processors to finish. This is no longer needed, but keeping it
7599
+ // here to avoid any future issues.
7600
+ setTimeout(() => this._initialize());
7300
7601
  }
7301
7602
 
7302
7603
  /**
7303
- * Initializes the plugin.
7604
+ * Start a replay regardless of sampling rate. Calling this will always
7605
+ * create a new session. Will throw an error if replay is already in progress.
7304
7606
  *
7305
7607
  * Creates or loads a session, attaches listeners to varying events (DOM,
7306
7608
  * PerformanceObserver, Recording, Sentry SDK, etc)
@@ -7313,27 +7615,43 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
7313
7615
  this._replay.start();
7314
7616
  }
7315
7617
 
7618
+ /**
7619
+ * Start replay buffering. Buffers until `flush()` is called or, if
7620
+ * `replaysOnErrorSampleRate` > 0, until an error occurs.
7621
+ */
7622
+ startBuffering() {
7623
+ if (!this._replay) {
7624
+ return;
7625
+ }
7626
+
7627
+ this._replay.startBuffering();
7628
+ }
7629
+
7316
7630
  /**
7317
7631
  * Currently, this needs to be manually called (e.g. for tests). Sentry SDK
7318
7632
  * does not support a teardown
7319
7633
  */
7320
7634
  stop() {
7321
7635
  if (!this._replay) {
7322
- return;
7636
+ return Promise.resolve();
7323
7637
  }
7324
7638
 
7325
- this._replay.stop();
7639
+ return this._replay.stop();
7326
7640
  }
7327
7641
 
7328
7642
  /**
7329
- * Immediately send all pending events.
7643
+ * If not in "session" recording mode, flush event buffer which will create a new replay.
7644
+ * Unless `continueRecording` is false, the replay will continue to record and
7645
+ * behave as a "session"-based replay.
7646
+ *
7647
+ * Otherwise, queue up a flush.
7330
7648
  */
7331
- flush() {
7649
+ flush(options) {
7332
7650
  if (!this._replay || !this._replay.isEnabled()) {
7333
- return;
7651
+ return Promise.resolve();
7334
7652
  }
7335
7653
 
7336
- return this._replay.flushImmediate();
7654
+ return this._replay.sendBufferedReplayOrFlush(options);
7337
7655
  }
7338
7656
 
7339
7657
  /**
@@ -7346,6 +7664,16 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
7346
7664
 
7347
7665
  return this._replay.getSessionId();
7348
7666
  }
7667
+ /**
7668
+ * Initializes replay.
7669
+ */
7670
+ _initialize() {
7671
+ if (!this._replay) {
7672
+ return;
7673
+ }
7674
+
7675
+ this._replay.initializeSampling();
7676
+ }
7349
7677
 
7350
7678
  /** Setup the integration. */
7351
7679
  _setup() {
@@ -7395,5 +7723,9 @@ function loadReplayOptionsFromClient(initialOptions) {
7395
7723
  return finalOptions;
7396
7724
  }
7397
7725
 
7726
+ function _getMergedNetworkHeaders(headers) {
7727
+ return [...DEFAULT_NETWORK_HEADERS, ...headers.map(header => header.toLowerCase())];
7728
+ }
7729
+
7398
7730
  export { Replay };
7399
7731
  //# sourceMappingURL=index.js.map