@sentry/replay 7.49.0 → 7.50.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.
package/cjs/index.js CHANGED
@@ -13,11 +13,14 @@ const REPLAY_SESSION_KEY = 'sentryReplaySession';
13
13
  const REPLAY_EVENT_NAME = 'replay_event';
14
14
  const UNABLE_TO_SEND_REPLAY = 'Unable to send Replay';
15
15
 
16
- // The idle limit for a session
17
- const SESSION_IDLE_DURATION = 300000; // 5 minutes in ms
16
+ // The idle limit for a session after which recording is paused.
17
+ const SESSION_IDLE_PAUSE_DURATION = 300000; // 5 minutes in ms
18
+
19
+ // The idle limit for a session after which the session expires.
20
+ const SESSION_IDLE_EXPIRE_DURATION = 900000; // 15 minutes in ms
18
21
 
19
22
  // The maximum length of a session
20
- const MAX_SESSION_LIFE = 3600000; // 60 minutes
23
+ const MAX_SESSION_LIFE = 3600000; // 60 minutes in ms
21
24
 
22
25
  /** Default flush delays */
23
26
  const DEFAULT_FLUSH_MIN_DELAY = 5000;
@@ -26,7 +29,7 @@ const DEFAULT_FLUSH_MIN_DELAY = 5000;
26
29
  const DEFAULT_FLUSH_MAX_DELAY = 5500;
27
30
 
28
31
  /* How long to wait for error checkouts */
29
- const ERROR_CHECKOUT_TIME = 60000;
32
+ const BUFFER_CHECKOUT_TIME = 60000;
30
33
 
31
34
  const RETRY_BASE_INTERVAL = 5000;
32
35
  const RETRY_MAX_COUNT = 3;
@@ -34,6 +37,9 @@ const RETRY_MAX_COUNT = 3;
34
37
  /* The max (uncompressed) size in bytes of a network body. Any body larger than this will be truncated. */
35
38
  const NETWORK_BODY_MAX_SIZE = 150000;
36
39
 
40
+ /* The max size of a single console arg that is captured. Any arg larger than this will be truncated. */
41
+ const CONSOLE_ARG_MAX_SIZE = 5000;
42
+
37
43
  var NodeType$1;
38
44
  (function (NodeType) {
39
45
  NodeType[NodeType["Document"] = 0] = "Document";
@@ -3698,6 +3704,31 @@ function createEventBuffer({ useCompression }) {
3698
3704
  return new EventBufferArray();
3699
3705
  }
3700
3706
 
3707
+ /**
3708
+ * Removes the session from Session Storage and unsets session in replay instance
3709
+ */
3710
+ function clearSession(replay) {
3711
+ deleteSession();
3712
+ replay.session = undefined;
3713
+ }
3714
+
3715
+ /**
3716
+ * Deletes a session from storage
3717
+ */
3718
+ function deleteSession() {
3719
+ const hasSessionStorage = 'sessionStorage' in WINDOW;
3720
+
3721
+ if (!hasSessionStorage) {
3722
+ return;
3723
+ }
3724
+
3725
+ try {
3726
+ WINDOW.sessionStorage.removeItem(REPLAY_SESSION_KEY);
3727
+ } catch (e) {
3728
+ // Ignore potential SecurityError exceptions
3729
+ }
3730
+ }
3731
+
3701
3732
  /**
3702
3733
  * Given an initial timestamp and an expiry duration, checks to see if current
3703
3734
  * time should be considered as expired.
@@ -3728,11 +3759,26 @@ function isSessionExpired(session, timeouts, targetTime = +new Date()) {
3728
3759
  // First, check that maximum session length has not been exceeded
3729
3760
  isExpired(session.started, timeouts.maxSessionLife, targetTime) ||
3730
3761
  // check that the idle timeout has not been exceeded (i.e. user has
3731
- // performed an action within the last `idleTimeout` ms)
3732
- isExpired(session.lastActivity, timeouts.sessionIdle, targetTime)
3762
+ // performed an action within the last `sessionIdleExpire` ms)
3763
+ isExpired(session.lastActivity, timeouts.sessionIdleExpire, targetTime)
3733
3764
  );
3734
3765
  }
3735
3766
 
3767
+ /**
3768
+ * Given a sample rate, returns true if replay should be sampled.
3769
+ *
3770
+ * 1.0 = 100% sampling
3771
+ * 0.0 = 0% sampling
3772
+ */
3773
+ function isSampled(sampleRate) {
3774
+ if (sampleRate === undefined) {
3775
+ return false;
3776
+ }
3777
+
3778
+ // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)
3779
+ return Math.random() < sampleRate;
3780
+ }
3781
+
3736
3782
  /**
3737
3783
  * Save a session to session storage.
3738
3784
  */
@@ -3749,21 +3795,6 @@ function saveSession(session) {
3749
3795
  }
3750
3796
  }
3751
3797
 
3752
- /**
3753
- * Given a sample rate, returns true if replay should be sampled.
3754
- *
3755
- * 1.0 = 100% sampling
3756
- * 0.0 = 0% sampling
3757
- */
3758
- function isSampled(sampleRate) {
3759
- if (sampleRate === undefined) {
3760
- return false;
3761
- }
3762
-
3763
- // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)
3764
- return Math.random() < sampleRate;
3765
- }
3766
-
3767
3798
  /**
3768
3799
  * Get a session with defaults & applied sampling.
3769
3800
  */
@@ -3782,14 +3813,15 @@ function makeSession(session) {
3782
3813
  lastActivity,
3783
3814
  segmentId,
3784
3815
  sampled,
3816
+ shouldRefresh: true,
3785
3817
  };
3786
3818
  }
3787
3819
 
3788
3820
  /**
3789
3821
  * Get the sampled status for a session based on sample rates & current sampled status.
3790
3822
  */
3791
- function getSessionSampleType(sessionSampleRate, errorSampleRate) {
3792
- return isSampled(sessionSampleRate) ? 'session' : isSampled(errorSampleRate) ? 'error' : false;
3823
+ function getSessionSampleType(sessionSampleRate, allowBuffering) {
3824
+ return isSampled(sessionSampleRate) ? 'session' : allowBuffering ? 'buffer' : false;
3793
3825
  }
3794
3826
 
3795
3827
  /**
@@ -3797,8 +3829,8 @@ function getSessionSampleType(sessionSampleRate, errorSampleRate) {
3797
3829
  * that all replays will be saved to as attachments. Currently, we only expect
3798
3830
  * one of these Sentry events per "replay session".
3799
3831
  */
3800
- function createSession({ sessionSampleRate, errorSampleRate, stickySession = false }) {
3801
- const sampled = getSessionSampleType(sessionSampleRate, errorSampleRate);
3832
+ function createSession({ sessionSampleRate, allowBuffering, stickySession = false }) {
3833
+ const sampled = getSessionSampleType(sessionSampleRate, allowBuffering);
3802
3834
  const session = makeSession({
3803
3835
  sampled,
3804
3836
  });
@@ -3846,7 +3878,7 @@ function getSession({
3846
3878
  currentSession,
3847
3879
  stickySession,
3848
3880
  sessionSampleRate,
3849
- errorSampleRate,
3881
+ allowBuffering,
3850
3882
  }) {
3851
3883
  // If session exists and is passed, use it instead of always hitting session storage
3852
3884
  const session = currentSession || (stickySession && fetchSession());
@@ -3859,8 +3891,9 @@ function getSession({
3859
3891
 
3860
3892
  if (!isExpired) {
3861
3893
  return { type: 'saved', session };
3862
- } else if (session.sampled === 'error') {
3863
- // Error samples should not be re-created when expired, but instead we stop when the replay is done
3894
+ } else if (!session.shouldRefresh) {
3895
+ // In this case, stop
3896
+ // This is the case if we have an error session that is completed (=triggered an error)
3864
3897
  const discardedSession = makeSession({ sampled: false });
3865
3898
  return { type: 'new', session: discardedSession };
3866
3899
  } else {
@@ -3872,7 +3905,7 @@ function getSession({
3872
3905
  const newSession = createSession({
3873
3906
  stickySession,
3874
3907
  sessionSampleRate,
3875
- errorSampleRate,
3908
+ allowBuffering,
3876
3909
  });
3877
3910
 
3878
3911
  return { type: 'new', session: newSession };
@@ -3906,7 +3939,7 @@ async function addEvent(
3906
3939
  // page has been left open and idle for a long period of time and user
3907
3940
  // comes back to trigger a new session. The performance entries rely on
3908
3941
  // `performance.timeOrigin`, which is when the page first opened.
3909
- if (timestampInMs + replay.timeouts.sessionIdle < Date.now()) {
3942
+ if (timestampInMs + replay.timeouts.sessionIdlePause < Date.now()) {
3910
3943
  return null;
3911
3944
  }
3912
3945
 
@@ -3921,7 +3954,7 @@ async function addEvent(
3921
3954
  return await replay.eventBuffer.addEvent(event, isCheckout);
3922
3955
  } catch (error) {
3923
3956
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error(error);
3924
- replay.stop('addEvent');
3957
+ await replay.stop('addEvent');
3925
3958
 
3926
3959
  const client = core.getCurrentHub().getClient();
3927
3960
 
@@ -3988,23 +4021,17 @@ function handleAfterSendEvent(replay) {
3988
4021
  // Trigger error recording
3989
4022
  // Need to be very careful that this does not cause an infinite loop
3990
4023
  if (
3991
- replay.recordingMode === 'error' &&
4024
+ replay.recordingMode === 'buffer' &&
3992
4025
  event.exception &&
3993
4026
  event.message !== UNABLE_TO_SEND_REPLAY // ignore this error because otherwise we could loop indefinitely with trying to capture replay and failing
3994
4027
  ) {
3995
- setTimeout(async () => {
3996
- // Allow flush to complete before resuming as a session recording, otherwise
3997
- // the checkout from `startRecording` may be included in the payload.
3998
- // Prefer to keep the error replay as a separate (and smaller) segment
3999
- // than the session replay.
4000
- await replay.flushImmediate();
4001
-
4002
- if (replay.stopRecording()) {
4003
- // Reset all "capture on error" configuration before
4004
- // starting a new recording
4005
- replay.recordingMode = 'session';
4006
- replay.startRecording();
4007
- }
4028
+ if (!isSampled(replay.getOptions().errorSampleRate)) {
4029
+ return;
4030
+ }
4031
+
4032
+ setTimeout(() => {
4033
+ // Capture current event buffer as new replay
4034
+ void replay.sendBufferedReplayOrFlush();
4008
4035
  });
4009
4036
  }
4010
4037
  };
@@ -4959,6 +4986,17 @@ function makeNetworkReplayBreadcrumb(
4959
4986
  return result;
4960
4987
  }
4961
4988
 
4989
+ /** Build the request or response part of a replay network breadcrumb that was skipped. */
4990
+ function buildSkippedNetworkRequestOrResponse(bodySize) {
4991
+ return {
4992
+ headers: {},
4993
+ size: bodySize,
4994
+ _meta: {
4995
+ warnings: ['URL_SKIPPED'],
4996
+ },
4997
+ };
4998
+ }
4999
+
4962
5000
  /** Build the request or response part of a replay network breadcrumb. */
4963
5001
  function buildNetworkRequestOrResponse(
4964
5002
  headers,
@@ -5039,8 +5077,8 @@ function normalizeNetworkBody(body)
5039
5077
  };
5040
5078
  } catch (e3) {
5041
5079
  return {
5042
- body,
5043
- warnings: ['INVALID_JSON'],
5080
+ body: exceedsSizeLimit ? `${body.slice(0, NETWORK_BODY_MAX_SIZE)}…` : body,
5081
+ warnings: exceedsSizeLimit ? ['INVALID_JSON', 'TEXT_TRUNCATED'] : ['INVALID_JSON'],
5044
5082
  };
5045
5083
  }
5046
5084
  }
@@ -5059,6 +5097,11 @@ function _strIsProbablyJson(str) {
5059
5097
  return (first === '[' && last === ']') || (first === '{' && last === '}');
5060
5098
  }
5061
5099
 
5100
+ /** Match an URL against a list of strings/Regex. */
5101
+ function urlMatches(url, urls) {
5102
+ return utils.stringMatchesSomePattern(url, urls);
5103
+ }
5104
+
5062
5105
  /**
5063
5106
  * Capture a fetch breadcrumb to a replay.
5064
5107
  * This adds additional data (where approriate).
@@ -5118,33 +5161,37 @@ async function _prepareFetchData(
5118
5161
  const {
5119
5162
  url,
5120
5163
  method,
5121
- status_code: statusCode,
5164
+ status_code: statusCode = 0,
5122
5165
  request_body_size: requestBodySize,
5123
5166
  response_body_size: responseBodySize,
5124
5167
  } = breadcrumb.data;
5125
5168
 
5126
- const request = _getRequestInfo(options, hint.input, requestBodySize);
5127
- const response = await _getResponseInfo(options, hint.response, responseBodySize);
5169
+ const captureDetails = urlMatches(url, options.networkDetailAllowUrls);
5170
+
5171
+ const request = captureDetails
5172
+ ? _getRequestInfo(options, hint.input, requestBodySize)
5173
+ : buildSkippedNetworkRequestOrResponse(requestBodySize);
5174
+ const response = await _getResponseInfo(captureDetails, options, hint.response, responseBodySize);
5128
5175
 
5129
5176
  return {
5130
5177
  startTimestamp,
5131
5178
  endTimestamp,
5132
5179
  url,
5133
5180
  method,
5134
- statusCode: statusCode || 0,
5181
+ statusCode,
5135
5182
  request,
5136
5183
  response,
5137
5184
  };
5138
5185
  }
5139
5186
 
5140
5187
  function _getRequestInfo(
5141
- { captureBodies, requestHeaders },
5188
+ { networkCaptureBodies, networkRequestHeaders },
5142
5189
  input,
5143
5190
  requestBodySize,
5144
5191
  ) {
5145
- const headers = getRequestHeaders(input, requestHeaders);
5192
+ const headers = getRequestHeaders(input, networkRequestHeaders);
5146
5193
 
5147
- if (!captureBodies) {
5194
+ if (!networkCaptureBodies) {
5148
5195
  return buildNetworkRequestOrResponse(headers, requestBodySize, undefined);
5149
5196
  }
5150
5197
 
@@ -5155,19 +5202,24 @@ function _getRequestInfo(
5155
5202
  }
5156
5203
 
5157
5204
  async function _getResponseInfo(
5205
+ captureDetails,
5158
5206
  {
5159
- captureBodies,
5207
+ networkCaptureBodies,
5160
5208
  textEncoder,
5161
- responseHeaders,
5209
+ networkResponseHeaders,
5162
5210
  }
5163
5211
 
5164
5212
  ,
5165
5213
  response,
5166
5214
  responseBodySize,
5167
5215
  ) {
5168
- const headers = getAllHeaders(response.headers, responseHeaders);
5216
+ if (!captureDetails && responseBodySize !== undefined) {
5217
+ return buildSkippedNetworkRequestOrResponse(responseBodySize);
5218
+ }
5219
+
5220
+ const headers = getAllHeaders(response.headers, networkResponseHeaders);
5169
5221
 
5170
- if (!captureBodies && responseBodySize !== undefined) {
5222
+ if (!networkCaptureBodies && responseBodySize !== undefined) {
5171
5223
  return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);
5172
5224
  }
5173
5225
 
@@ -5182,7 +5234,11 @@ async function _getResponseInfo(
5182
5234
  ? getBodySize(bodyText, textEncoder)
5183
5235
  : responseBodySize;
5184
5236
 
5185
- if (captureBodies) {
5237
+ if (!captureDetails) {
5238
+ return buildSkippedNetworkRequestOrResponse(size);
5239
+ }
5240
+
5241
+ if (networkCaptureBodies) {
5186
5242
  return buildNetworkRequestOrResponse(headers, size, bodyText);
5187
5243
  }
5188
5244
 
@@ -5315,28 +5371,44 @@ function _prepareXhrData(
5315
5371
  const {
5316
5372
  url,
5317
5373
  method,
5318
- status_code: statusCode,
5374
+ status_code: statusCode = 0,
5319
5375
  request_body_size: requestBodySize,
5320
5376
  response_body_size: responseBodySize,
5321
5377
  } = breadcrumb.data;
5322
5378
 
5323
- const xhrInfo = xhr[utils.SENTRY_XHR_DATA_KEY];
5324
- const requestHeaders = xhrInfo ? getAllowedHeaders(xhrInfo.request_headers, options.requestHeaders) : {};
5325
- const responseHeaders = getAllowedHeaders(getResponseHeaders(xhr), options.responseHeaders);
5326
-
5327
5379
  if (!url) {
5328
5380
  return null;
5329
5381
  }
5330
5382
 
5383
+ if (!urlMatches(url, options.networkDetailAllowUrls)) {
5384
+ const request = buildSkippedNetworkRequestOrResponse(requestBodySize);
5385
+ const response = buildSkippedNetworkRequestOrResponse(responseBodySize);
5386
+ return {
5387
+ startTimestamp,
5388
+ endTimestamp,
5389
+ url,
5390
+ method,
5391
+ statusCode,
5392
+ request,
5393
+ response,
5394
+ };
5395
+ }
5396
+
5397
+ const xhrInfo = xhr[utils.SENTRY_XHR_DATA_KEY];
5398
+ const networkRequestHeaders = xhrInfo
5399
+ ? getAllowedHeaders(xhrInfo.request_headers, options.networkRequestHeaders)
5400
+ : {};
5401
+ const networkResponseHeaders = getAllowedHeaders(getResponseHeaders(xhr), options.networkResponseHeaders);
5402
+
5331
5403
  const request = buildNetworkRequestOrResponse(
5332
- requestHeaders,
5404
+ networkRequestHeaders,
5333
5405
  requestBodySize,
5334
- options.captureBodies ? getBodyString(input) : undefined,
5406
+ options.networkCaptureBodies ? getBodyString(input) : undefined,
5335
5407
  );
5336
5408
  const response = buildNetworkRequestOrResponse(
5337
- responseHeaders,
5409
+ networkResponseHeaders,
5338
5410
  responseBodySize,
5339
- options.captureBodies ? hint.xhr.responseText : undefined,
5411
+ options.networkCaptureBodies ? hint.xhr.responseText : undefined,
5340
5412
  );
5341
5413
 
5342
5414
  return {
@@ -5344,7 +5416,7 @@ function _prepareXhrData(
5344
5416
  endTimestamp,
5345
5417
  url,
5346
5418
  method,
5347
- statusCode: statusCode || 0,
5419
+ statusCode,
5348
5420
  request,
5349
5421
  response,
5350
5422
  };
@@ -5376,10 +5448,16 @@ function handleNetworkBreadcrumbs(replay) {
5376
5448
  try {
5377
5449
  const textEncoder = new TextEncoder();
5378
5450
 
5451
+ const { networkDetailAllowUrls, networkCaptureBodies, networkRequestHeaders, networkResponseHeaders } =
5452
+ replay.getOptions();
5453
+
5379
5454
  const options = {
5380
5455
  replay,
5381
5456
  textEncoder,
5382
- ...replay.getExperimentalOptions().network,
5457
+ networkDetailAllowUrls,
5458
+ networkCaptureBodies,
5459
+ networkRequestHeaders,
5460
+ networkResponseHeaders,
5383
5461
  };
5384
5462
 
5385
5463
  if (client && client.on) {
@@ -5487,9 +5565,66 @@ function handleScope(scope) {
5487
5565
  return null;
5488
5566
  }
5489
5567
 
5568
+ if (newBreadcrumb.category === 'console') {
5569
+ return normalizeConsoleBreadcrumb(newBreadcrumb);
5570
+ }
5571
+
5490
5572
  return createBreadcrumb(newBreadcrumb);
5491
5573
  }
5492
5574
 
5575
+ /** exported for tests only */
5576
+ function normalizeConsoleBreadcrumb(breadcrumb) {
5577
+ const args = breadcrumb.data && breadcrumb.data.arguments;
5578
+
5579
+ if (!Array.isArray(args) || args.length === 0) {
5580
+ return createBreadcrumb(breadcrumb);
5581
+ }
5582
+
5583
+ let isTruncated = false;
5584
+
5585
+ // Avoid giant args captures
5586
+ const normalizedArgs = args.map(arg => {
5587
+ if (!arg) {
5588
+ return arg;
5589
+ }
5590
+ if (typeof arg === 'string') {
5591
+ if (arg.length > CONSOLE_ARG_MAX_SIZE) {
5592
+ isTruncated = true;
5593
+ return `${arg.slice(0, CONSOLE_ARG_MAX_SIZE)}…`;
5594
+ }
5595
+
5596
+ return arg;
5597
+ }
5598
+ if (typeof arg === 'object') {
5599
+ try {
5600
+ const normalizedArg = utils.normalize(arg, 7);
5601
+ const stringified = JSON.stringify(normalizedArg);
5602
+ if (stringified.length > CONSOLE_ARG_MAX_SIZE) {
5603
+ const fixedJson = fixJson(stringified.slice(0, CONSOLE_ARG_MAX_SIZE));
5604
+ const json = JSON.parse(fixedJson);
5605
+ // We only set this after JSON.parse() was successfull, so we know we didn't run into `catch`
5606
+ isTruncated = true;
5607
+ return json;
5608
+ }
5609
+ return normalizedArg;
5610
+ } catch (e) {
5611
+ // fall back to default
5612
+ }
5613
+ }
5614
+
5615
+ return arg;
5616
+ });
5617
+
5618
+ return createBreadcrumb({
5619
+ ...breadcrumb,
5620
+ data: {
5621
+ ...breadcrumb.data,
5622
+ arguments: normalizedArgs,
5623
+ ...(isTruncated ? { _meta: { warnings: ['CONSOLE_ARG_TRUNCATED'] } } : {}),
5624
+ },
5625
+ });
5626
+ }
5627
+
5493
5628
  /**
5494
5629
  * Add global listeners that cannot be removed.
5495
5630
  */
@@ -5514,7 +5649,7 @@ function addGlobalListeners(replay) {
5514
5649
  client.on('afterSendEvent', handleAfterSendEvent(replay));
5515
5650
  client.on('createDsc', (dsc) => {
5516
5651
  const replayId = replay.getSessionId();
5517
- if (replayId) {
5652
+ if (replayId && replay.isEnabled()) {
5518
5653
  dsc.replay_id = replayId;
5519
5654
  }
5520
5655
  });
@@ -5822,7 +5957,7 @@ function getHandleRecordingEmit(replay) {
5822
5957
  // when an error occurs. Clear any state that happens before this current
5823
5958
  // checkout. This needs to happen before `addEvent()` which updates state
5824
5959
  // dependent on this reset.
5825
- if (replay.recordingMode === 'error' && isCheckout) {
5960
+ if (replay.recordingMode === 'buffer' && isCheckout) {
5826
5961
  replay.setInitialState();
5827
5962
  }
5828
5963
 
@@ -5848,7 +5983,7 @@ function getHandleRecordingEmit(replay) {
5848
5983
 
5849
5984
  // See note above re: session start needs to reflect the most recent
5850
5985
  // checkout.
5851
- if (replay.recordingMode === 'error' && replay.session) {
5986
+ if (replay.recordingMode === 'buffer' && replay.session) {
5852
5987
  const { earliestEvent } = replay.getContext();
5853
5988
  if (earliestEvent) {
5854
5989
  replay.session.started = earliestEvent;
@@ -6197,9 +6332,11 @@ class ReplayContainer {
6197
6332
  __init2() {this.performanceEvents = [];}
6198
6333
 
6199
6334
  /**
6200
- * Recording can happen in one of two modes:
6201
- * * session: Record the whole session, sending it continuously
6202
- * * error: Always keep the last 60s of recording, and when an error occurs, send it immediately
6335
+ * Recording can happen in one of three modes:
6336
+ * - session: Record the whole session, sending it continuously
6337
+ * - buffer: Always keep the last 60s of recording, requires:
6338
+ * - having replaysOnErrorSampleRate > 0 to capture replay when an error occurs
6339
+ * - or calling `flush()` to send the replay
6203
6340
  */
6204
6341
  __init3() {this.recordingMode = 'session';}
6205
6342
 
@@ -6208,7 +6345,8 @@ class ReplayContainer {
6208
6345
  * @hidden
6209
6346
  */
6210
6347
  __init4() {this.timeouts = {
6211
- sessionIdle: SESSION_IDLE_DURATION,
6348
+ sessionIdlePause: SESSION_IDLE_PAUSE_DURATION,
6349
+ sessionIdleExpire: SESSION_IDLE_EXPIRE_DURATION,
6212
6350
  maxSessionLife: MAX_SESSION_LIFE,
6213
6351
  }; }
6214
6352
 
@@ -6269,8 +6407,6 @@ class ReplayContainer {
6269
6407
  this._debouncedFlush = debounce(() => this._flush(), this._options.flushMinDelay, {
6270
6408
  maxWait: this._options.flushMaxDelay,
6271
6409
  });
6272
-
6273
- this._experimentalOptions = _getExperimentalOptions(options);
6274
6410
  }
6275
6411
 
6276
6412
  /** Get the event context. */
@@ -6294,58 +6430,102 @@ class ReplayContainer {
6294
6430
  }
6295
6431
 
6296
6432
  /**
6297
- * Get the experimental options.
6298
- * THIS IS INTERNAL AND SUBJECT TO CHANGE!
6299
- * @hidden
6433
+ * Initializes the plugin based on sampling configuration. Should not be
6434
+ * called outside of constructor.
6300
6435
  */
6301
- getExperimentalOptions() {
6302
- return this._experimentalOptions;
6436
+ initializeSampling() {
6437
+ const { errorSampleRate, sessionSampleRate } = this._options;
6438
+
6439
+ // If neither sample rate is > 0, then do nothing - user will need to call one of
6440
+ // `start()` or `startBuffering` themselves.
6441
+ if (errorSampleRate <= 0 && sessionSampleRate <= 0) {
6442
+ return;
6443
+ }
6444
+
6445
+ // Otherwise if there is _any_ sample rate set, try to load an existing
6446
+ // session, or create a new one.
6447
+ const isSessionSampled = this._loadAndCheckSession();
6448
+
6449
+ if (!isSessionSampled) {
6450
+ // This should only occur if `errorSampleRate` is 0 and was unsampled for
6451
+ // session-based replay. In this case there is nothing to do.
6452
+ return;
6453
+ }
6454
+
6455
+ if (!this.session) {
6456
+ // This should not happen, something wrong has occurred
6457
+ this._handleException(new Error('Unable to initialize and create session'));
6458
+ return;
6459
+ }
6460
+
6461
+ if (this.session.sampled && this.session.sampled !== 'session') {
6462
+ // If not sampled as session-based, then recording mode will be `buffer`
6463
+ // Note that we don't explicitly check if `sampled === 'buffer'` because we
6464
+ // could have sessions from Session storage that are still `error` from
6465
+ // prior SDK version.
6466
+ this.recordingMode = 'buffer';
6467
+ }
6468
+
6469
+ this._initializeRecording();
6303
6470
  }
6304
6471
 
6305
6472
  /**
6306
- * Initializes the plugin.
6473
+ * Start a replay regardless of sampling rate. Calling this will always
6474
+ * create a new session. Will throw an error if replay is already in progress.
6307
6475
  *
6308
6476
  * Creates or loads a session, attaches listeners to varying events (DOM,
6309
6477
  * _performanceObserver, Recording, Sentry SDK, etc)
6310
6478
  */
6311
6479
  start() {
6312
- this.setInitialState();
6313
-
6314
- if (!this._loadAndCheckSession()) {
6315
- return;
6480
+ if (this._isEnabled && this.recordingMode === 'session') {
6481
+ throw new Error('Replay recording is already in progress');
6316
6482
  }
6317
6483
 
6318
- // If there is no session, then something bad has happened - can't continue
6319
- if (!this.session) {
6320
- this._handleException(new Error('No session found'));
6321
- return;
6484
+ if (this._isEnabled && this.recordingMode === 'buffer') {
6485
+ throw new Error('Replay buffering is in progress, call `flush()` to save the replay');
6322
6486
  }
6323
6487
 
6324
- if (!this.session.sampled) {
6325
- // If session was not sampled, then we do not initialize the integration at all.
6326
- return;
6327
- }
6488
+ const previousSessionId = this.session && this.session.id;
6489
+
6490
+ const { session } = getSession({
6491
+ timeouts: this.timeouts,
6492
+ stickySession: Boolean(this._options.stickySession),
6493
+ currentSession: this.session,
6494
+ // This is intentional: create a new session-based replay when calling `start()`
6495
+ sessionSampleRate: 1,
6496
+ allowBuffering: false,
6497
+ });
6498
+
6499
+ session.previousSessionId = previousSessionId;
6500
+ this.session = session;
6501
+
6502
+ this._initializeRecording();
6503
+ }
6328
6504
 
6329
- // If session is sampled for errors, then we need to set the recordingMode
6330
- // to 'error', which will configure recording with different options.
6331
- if (this.session.sampled === 'error') {
6332
- this.recordingMode = 'error';
6505
+ /**
6506
+ * Start replay buffering. Buffers until `flush()` is called or, if
6507
+ * `replaysOnErrorSampleRate` > 0, an error occurs.
6508
+ */
6509
+ startBuffering() {
6510
+ if (this._isEnabled) {
6511
+ throw new Error('Replay recording is already in progress');
6333
6512
  }
6334
6513
 
6335
- // setup() is generally called on page load or manually - in both cases we
6336
- // should treat it as an activity
6337
- this._updateSessionActivity();
6514
+ const previousSessionId = this.session && this.session.id;
6338
6515
 
6339
- this.eventBuffer = createEventBuffer({
6340
- useCompression: this._options.useCompression,
6516
+ const { session } = getSession({
6517
+ timeouts: this.timeouts,
6518
+ stickySession: Boolean(this._options.stickySession),
6519
+ currentSession: this.session,
6520
+ sessionSampleRate: 0,
6521
+ allowBuffering: true,
6341
6522
  });
6342
6523
 
6343
- this._addListeners();
6344
-
6345
- // Need to set as enabled before we start recording, as `record()` can trigger a flush with a new checkout
6346
- this._isEnabled = true;
6524
+ session.previousSessionId = previousSessionId;
6525
+ this.session = session;
6347
6526
 
6348
- this.startRecording();
6527
+ this.recordingMode = 'buffer';
6528
+ this._initializeRecording();
6349
6529
  }
6350
6530
 
6351
6531
  /**
@@ -6360,7 +6540,7 @@ class ReplayContainer {
6360
6540
  // When running in error sampling mode, we need to overwrite `checkoutEveryNms`
6361
6541
  // Without this, it would record forever, until an error happens, which we don't want
6362
6542
  // instead, we'll always keep the last 60 seconds of replay before an error happened
6363
- ...(this.recordingMode === 'error' && { checkoutEveryNms: ERROR_CHECKOUT_TIME }),
6543
+ ...(this.recordingMode === 'buffer' && { checkoutEveryNms: BUFFER_CHECKOUT_TIME }),
6364
6544
  emit: getHandleRecordingEmit(this),
6365
6545
  onMutation: this._onMutationHandler,
6366
6546
  });
@@ -6371,17 +6551,18 @@ class ReplayContainer {
6371
6551
 
6372
6552
  /**
6373
6553
  * Stops the recording, if it was running.
6374
- * Returns true if it was stopped, else false.
6554
+ *
6555
+ * Returns true if it was previously stopped, or is now stopped,
6556
+ * otherwise false.
6375
6557
  */
6376
6558
  stopRecording() {
6377
6559
  try {
6378
6560
  if (this._stopRecording) {
6379
6561
  this._stopRecording();
6380
6562
  this._stopRecording = undefined;
6381
- return true;
6382
6563
  }
6383
6564
 
6384
- return false;
6565
+ return true;
6385
6566
  } catch (err) {
6386
6567
  this._handleException(err);
6387
6568
  return false;
@@ -6392,7 +6573,7 @@ class ReplayContainer {
6392
6573
  * Currently, this needs to be manually called (e.g. for tests). Sentry SDK
6393
6574
  * does not support a teardown
6394
6575
  */
6395
- stop(reason) {
6576
+ async stop(reason) {
6396
6577
  if (!this._isEnabled) {
6397
6578
  return;
6398
6579
  }
@@ -6408,12 +6589,24 @@ class ReplayContainer {
6408
6589
  log(msg);
6409
6590
  }
6410
6591
 
6592
+ // We can't move `_isEnabled` after awaiting a flush, otherwise we can
6593
+ // enter into an infinite loop when `stop()` is called while flushing.
6411
6594
  this._isEnabled = false;
6412
6595
  this._removeListeners();
6413
6596
  this.stopRecording();
6597
+
6598
+ this._debouncedFlush.cancel();
6599
+ // See comment above re: `_isEnabled`, we "force" a flush, ignoring the
6600
+ // `_isEnabled` state of the plugin since it was disabled above.
6601
+ await this._flush({ force: true });
6602
+
6603
+ // After flush, destroy event buffer
6414
6604
  this.eventBuffer && this.eventBuffer.destroy();
6415
6605
  this.eventBuffer = null;
6416
- this._debouncedFlush.cancel();
6606
+
6607
+ // Clear session from session storage, note this means if a new session
6608
+ // is started after, it will not have `previousSessionId`
6609
+ clearSession(this);
6417
6610
  } catch (err) {
6418
6611
  this._handleException(err);
6419
6612
  }
@@ -6444,6 +6637,45 @@ class ReplayContainer {
6444
6637
  this.startRecording();
6445
6638
  }
6446
6639
 
6640
+ /**
6641
+ * If not in "session" recording mode, flush event buffer which will create a new replay.
6642
+ * Unless `continueRecording` is false, the replay will continue to record and
6643
+ * behave as a "session"-based replay.
6644
+ *
6645
+ * Otherwise, queue up a flush.
6646
+ */
6647
+ async sendBufferedReplayOrFlush({ continueRecording = true } = {}) {
6648
+ if (this.recordingMode === 'session') {
6649
+ return this.flushImmediate();
6650
+ }
6651
+
6652
+ // Allow flush to complete before resuming as a session recording, otherwise
6653
+ // the checkout from `startRecording` may be included in the payload.
6654
+ // Prefer to keep the error replay as a separate (and smaller) segment
6655
+ // than the session replay.
6656
+ await this.flushImmediate();
6657
+
6658
+ const hasStoppedRecording = this.stopRecording();
6659
+
6660
+ if (!continueRecording || !hasStoppedRecording) {
6661
+ return;
6662
+ }
6663
+
6664
+ // Re-start recording, but in "session" recording mode
6665
+
6666
+ // Reset all "capture on error" configuration before
6667
+ // starting a new recording
6668
+ this.recordingMode = 'session';
6669
+
6670
+ // Once this session ends, we do not want to refresh it
6671
+ if (this.session) {
6672
+ this.session.shouldRefresh = false;
6673
+ this._maybeSaveSession();
6674
+ }
6675
+
6676
+ this.startRecording();
6677
+ }
6678
+
6447
6679
  /**
6448
6680
  * We want to batch uploads of replay events. Save events only if
6449
6681
  * `<flushMinDelay>` milliseconds have elapsed since the last event
@@ -6453,12 +6685,12 @@ class ReplayContainer {
6453
6685
  * processing and hand back control to caller.
6454
6686
  */
6455
6687
  addUpdate(cb) {
6456
- // We need to always run `cb` (e.g. in the case of `this.recordingMode == 'error'`)
6688
+ // We need to always run `cb` (e.g. in the case of `this.recordingMode == 'buffer'`)
6457
6689
  const cbResult = cb();
6458
6690
 
6459
6691
  // If this option is turned on then we will only want to call `flush`
6460
6692
  // explicitly
6461
- if (this.recordingMode === 'error') {
6693
+ if (this.recordingMode === 'buffer') {
6462
6694
  return;
6463
6695
  }
6464
6696
 
@@ -6530,12 +6762,12 @@ class ReplayContainer {
6530
6762
  const oldSessionId = this.getSessionId();
6531
6763
 
6532
6764
  // Prevent starting a new session if the last user activity is older than
6533
- // SESSION_IDLE_DURATION. Otherwise non-user activity can trigger a new
6765
+ // SESSION_IDLE_PAUSE_DURATION. Otherwise non-user activity can trigger a new
6534
6766
  // session+recording. This creates noisy replays that do not have much
6535
6767
  // content in them.
6536
6768
  if (
6537
6769
  this._lastActivity &&
6538
- isExpired(this._lastActivity, this.timeouts.sessionIdle) &&
6770
+ isExpired(this._lastActivity, this.timeouts.sessionIdlePause) &&
6539
6771
  this.session &&
6540
6772
  this.session.sampled === 'session'
6541
6773
  ) {
@@ -6585,6 +6817,30 @@ class ReplayContainer {
6585
6817
  this._context.urls.push(url);
6586
6818
  }
6587
6819
 
6820
+ /**
6821
+ * Initialize and start all listeners to varying events (DOM,
6822
+ * Performance Observer, Recording, Sentry SDK, etc)
6823
+ */
6824
+ _initializeRecording() {
6825
+ this.setInitialState();
6826
+
6827
+ // this method is generally called on page load or manually - in both cases
6828
+ // we should treat it as an activity
6829
+ this._updateSessionActivity();
6830
+
6831
+ this.eventBuffer = createEventBuffer({
6832
+ useCompression: this._options.useCompression,
6833
+ });
6834
+
6835
+ this._removeListeners();
6836
+ this._addListeners();
6837
+
6838
+ // Need to set as enabled before we start recording, as `record()` can trigger a flush with a new checkout
6839
+ this._isEnabled = true;
6840
+
6841
+ this.startRecording();
6842
+ }
6843
+
6588
6844
  /** A wrapper to conditionally capture exceptions. */
6589
6845
  _handleException(error) {
6590
6846
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error('[Replay]', error);
@@ -6604,7 +6860,7 @@ class ReplayContainer {
6604
6860
  stickySession: Boolean(this._options.stickySession),
6605
6861
  currentSession: this.session,
6606
6862
  sessionSampleRate: this._options.sessionSampleRate,
6607
- errorSampleRate: this._options.errorSampleRate,
6863
+ allowBuffering: this._options.errorSampleRate > 0,
6608
6864
  });
6609
6865
 
6610
6866
  // If session was newly created (i.e. was not loaded from storage), then
@@ -6621,7 +6877,7 @@ class ReplayContainer {
6621
6877
  this.session = session;
6622
6878
 
6623
6879
  if (!this.session.sampled) {
6624
- this.stop('session unsampled');
6880
+ void this.stop('session unsampled');
6625
6881
  return false;
6626
6882
  }
6627
6883
 
@@ -6745,7 +7001,7 @@ class ReplayContainer {
6745
7001
  const isSessionActive = this.checkAndHandleExpiredSession();
6746
7002
 
6747
7003
  if (!isSessionActive) {
6748
- // If the user has come back to the page within SESSION_IDLE_DURATION
7004
+ // If the user has come back to the page within SESSION_IDLE_PAUSE_DURATION
6749
7005
  // ms, we will re-use the existing session, otherwise create a new
6750
7006
  // session
6751
7007
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('[Replay] Document has become active, but session has expired');
@@ -6819,7 +7075,7 @@ class ReplayContainer {
6819
7075
  * Only flush if `this.recordingMode === 'session'`
6820
7076
  */
6821
7077
  _conditionalFlush() {
6822
- if (this.recordingMode === 'error') {
7078
+ if (this.recordingMode === 'buffer') {
6823
7079
  return;
6824
7080
  }
6825
7081
 
@@ -6914,7 +7170,7 @@ class ReplayContainer {
6914
7170
  // This means we retried 3 times and all of them failed,
6915
7171
  // or we ran into a problem we don't want to retry, like rate limiting.
6916
7172
  // In this case, we want to completely stop the replay - otherwise, we may get inconsistent segments
6917
- this.stop('sendReplay');
7173
+ void this.stop('sendReplay');
6918
7174
 
6919
7175
  const client = core.getCurrentHub().getClient();
6920
7176
 
@@ -6928,8 +7184,12 @@ class ReplayContainer {
6928
7184
  * Flush recording data to Sentry. Creates a lock so that only a single flush
6929
7185
  * can be active at a time. Do not call this directly.
6930
7186
  */
6931
- __init16() {this._flush = async () => {
6932
- if (!this._isEnabled) {
7187
+ __init16() {this._flush = async ({
7188
+ force = false,
7189
+ }
7190
+
7191
+ = {}) => {
7192
+ if (!this._isEnabled && !force) {
6933
7193
  // This can happen if e.g. the replay was stopped because of exceeding the retry limit
6934
7194
  return;
6935
7195
  }
@@ -7010,23 +7270,6 @@ class ReplayContainer {
7010
7270
  };}
7011
7271
  }
7012
7272
 
7013
- function _getExperimentalOptions(options) {
7014
- const requestHeaders = options._experiments.captureRequestHeaders || [];
7015
- const responseHeaders = options._experiments.captureResponseHeaders || [];
7016
- const captureBodies = options._experiments.captureNetworkBodies || false;
7017
-
7018
- // Add defaults
7019
- const defaultHeaders = ['content-length', 'content-type', 'accept'];
7020
-
7021
- return {
7022
- network: {
7023
- captureBodies,
7024
- requestHeaders: [...defaultHeaders, ...requestHeaders.map(header => header.toLowerCase())],
7025
- responseHeaders: [...defaultHeaders, ...responseHeaders.map(header => header.toLowerCase())],
7026
- },
7027
- };
7028
- }
7029
-
7030
7273
  function getOption(
7031
7274
  selectors,
7032
7275
  defaultSelectors,
@@ -7130,6 +7373,8 @@ function isElectronNodeRenderer() {
7130
7373
  const MEDIA_SELECTORS =
7131
7374
  'img,image,svg,video,object,picture,embed,map,audio,link[rel="icon"],link[rel="apple-touch-icon"]';
7132
7375
 
7376
+ const DEFAULT_NETWORK_HEADERS = ['content-length', 'content-type', 'accept'];
7377
+
7133
7378
  let _initialized = false;
7134
7379
 
7135
7380
  /**
@@ -7170,6 +7415,11 @@ class Replay {
7170
7415
  maskAllInputs = true,
7171
7416
  blockAllMedia = true,
7172
7417
 
7418
+ networkDetailAllowUrls = [],
7419
+ networkCaptureBodies = true,
7420
+ networkRequestHeaders = [],
7421
+ networkResponseHeaders = [],
7422
+
7173
7423
  mask = [],
7174
7424
  unmask = [],
7175
7425
  block = [],
@@ -7228,6 +7478,11 @@ class Replay {
7228
7478
  errorSampleRate,
7229
7479
  useCompression,
7230
7480
  blockAllMedia,
7481
+ networkDetailAllowUrls,
7482
+ networkCaptureBodies,
7483
+ networkRequestHeaders: _getMergedNetworkHeaders(networkRequestHeaders),
7484
+ networkResponseHeaders: _getMergedNetworkHeaders(networkResponseHeaders),
7485
+
7231
7486
  _experiments,
7232
7487
  };
7233
7488
 
@@ -7281,14 +7536,7 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
7281
7536
  }
7282
7537
 
7283
7538
  /**
7284
- * We previously used to create a transaction in `setupOnce` and it would
7285
- * potentially create a transaction before some native SDK integrations have run
7286
- * and applied their own global event processor. An example is:
7287
- * https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts
7288
- *
7289
- * So we call `replay.setup` in next event loop as a workaround to wait for other
7290
- * global event processors to finish. This is no longer needed, but keeping it
7291
- * here to avoid any future issues.
7539
+ * Setup and initialize replay container
7292
7540
  */
7293
7541
  setupOnce() {
7294
7542
  if (!isBrowser()) {
@@ -7297,12 +7545,20 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
7297
7545
 
7298
7546
  this._setup();
7299
7547
 
7300
- // XXX: See method comments above
7301
- setTimeout(() => this.start());
7548
+ // Once upon a time, we tried to create a transaction in `setupOnce` and it would
7549
+ // potentially create a transaction before some native SDK integrations have run
7550
+ // and applied their own global event processor. An example is:
7551
+ // https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts
7552
+ //
7553
+ // So we call `this._initialize()` in next event loop as a workaround to wait for other
7554
+ // global event processors to finish. This is no longer needed, but keeping it
7555
+ // here to avoid any future issues.
7556
+ setTimeout(() => this._initialize());
7302
7557
  }
7303
7558
 
7304
7559
  /**
7305
- * Initializes the plugin.
7560
+ * Start a replay regardless of sampling rate. Calling this will always
7561
+ * create a new session. Will throw an error if replay is already in progress.
7306
7562
  *
7307
7563
  * Creates or loads a session, attaches listeners to varying events (DOM,
7308
7564
  * PerformanceObserver, Recording, Sentry SDK, etc)
@@ -7315,27 +7571,43 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
7315
7571
  this._replay.start();
7316
7572
  }
7317
7573
 
7574
+ /**
7575
+ * Start replay buffering. Buffers until `flush()` is called or, if
7576
+ * `replaysOnErrorSampleRate` > 0, until an error occurs.
7577
+ */
7578
+ startBuffering() {
7579
+ if (!this._replay) {
7580
+ return;
7581
+ }
7582
+
7583
+ this._replay.startBuffering();
7584
+ }
7585
+
7318
7586
  /**
7319
7587
  * Currently, this needs to be manually called (e.g. for tests). Sentry SDK
7320
7588
  * does not support a teardown
7321
7589
  */
7322
7590
  stop() {
7323
7591
  if (!this._replay) {
7324
- return;
7592
+ return Promise.resolve();
7325
7593
  }
7326
7594
 
7327
- this._replay.stop();
7595
+ return this._replay.stop();
7328
7596
  }
7329
7597
 
7330
7598
  /**
7331
- * Immediately send all pending events.
7599
+ * If not in "session" recording mode, flush event buffer which will create a new replay.
7600
+ * Unless `continueRecording` is false, the replay will continue to record and
7601
+ * behave as a "session"-based replay.
7602
+ *
7603
+ * Otherwise, queue up a flush.
7332
7604
  */
7333
- flush() {
7605
+ flush(options) {
7334
7606
  if (!this._replay || !this._replay.isEnabled()) {
7335
- return;
7607
+ return Promise.resolve();
7336
7608
  }
7337
7609
 
7338
- return this._replay.flushImmediate();
7610
+ return this._replay.sendBufferedReplayOrFlush(options);
7339
7611
  }
7340
7612
 
7341
7613
  /**
@@ -7348,6 +7620,16 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
7348
7620
 
7349
7621
  return this._replay.getSessionId();
7350
7622
  }
7623
+ /**
7624
+ * Initializes replay.
7625
+ */
7626
+ _initialize() {
7627
+ if (!this._replay) {
7628
+ return;
7629
+ }
7630
+
7631
+ this._replay.initializeSampling();
7632
+ }
7351
7633
 
7352
7634
  /** Setup the integration. */
7353
7635
  _setup() {
@@ -7397,5 +7679,9 @@ function loadReplayOptionsFromClient(initialOptions) {
7397
7679
  return finalOptions;
7398
7680
  }
7399
7681
 
7682
+ function _getMergedNetworkHeaders(headers) {
7683
+ return [...DEFAULT_NETWORK_HEADERS, ...headers.map(header => header.toLowerCase())];
7684
+ }
7685
+
7400
7686
  exports.Replay = Replay;
7401
7687
  //# sourceMappingURL=index.js.map