@sentry/replay 7.48.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.
Files changed (39) hide show
  1. package/README.md +19 -6
  2. package/cjs/index.js +888 -200
  3. package/cjs/index.js.map +1 -1
  4. package/esm/index.js +889 -201
  5. package/esm/index.js.map +1 -1
  6. package/package.json +5 -5
  7. package/types/constants.d.ts +5 -3
  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/addBreadcrumbEvent.d.ts.map +1 -1
  14. package/types/coreHandlers/util/fetchUtils.d.ts.map +1 -1
  15. package/types/coreHandlers/util/networkUtils.d.ts +5 -1
  16. package/types/coreHandlers/util/networkUtils.d.ts.map +1 -1
  17. package/types/coreHandlers/util/xhrUtils.d.ts.map +1 -1
  18. package/types/integration.d.ts +21 -14
  19. package/types/integration.d.ts.map +1 -1
  20. package/types/replay.d.ts +33 -12
  21. package/types/replay.d.ts.map +1 -1
  22. package/types/session/Session.d.ts +0 -4
  23. package/types/session/Session.d.ts.map +1 -1
  24. package/types/session/clearSession.d.ts +6 -0
  25. package/types/session/clearSession.d.ts.map +1 -0
  26. package/types/session/createSession.d.ts +6 -2
  27. package/types/session/createSession.d.ts.map +1 -1
  28. package/types/session/getSession.d.ts +1 -1
  29. package/types/session/getSession.d.ts.map +1 -1
  30. package/types/types.d.ts +60 -38
  31. package/types/types.d.ts.map +1 -1
  32. package/types/util/truncateJson/completeJson.d.ts +9 -0
  33. package/types/util/truncateJson/completeJson.d.ts.map +1 -0
  34. package/types/util/truncateJson/constants.d.ts +12 -0
  35. package/types/util/truncateJson/constants.d.ts.map +1 -0
  36. package/types/util/truncateJson/evaluateJson.d.ts +6 -0
  37. package/types/util/truncateJson/evaluateJson.d.ts.map +1 -0
  38. package/types/util/truncateJson/fixJson.d.ts +6 -0
  39. package/types/util/truncateJson/fixJson.d.ts.map +1 -0
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,13 +29,16 @@ 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;
33
36
 
34
- /* The max (uncompressed) size in bytes of a network body. Any body larger than this will be dropped. */
35
- const NETWORK_BODY_MAX_SIZE = 300000;
37
+ /* The max (uncompressed) size in bytes of a network body. Any body larger than this will be truncated. */
38
+ const NETWORK_BODY_MAX_SIZE = 150000;
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;
36
42
 
37
43
  var NodeType$1;
38
44
  (function (NodeType) {
@@ -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
  };
@@ -4071,7 +4098,8 @@ function addBreadcrumbEvent(replay, breadcrumb) {
4071
4098
  timestamp: (breadcrumb.timestamp || 0) * 1000,
4072
4099
  data: {
4073
4100
  tag: 'breadcrumb',
4074
- payload: utils.normalize(breadcrumb),
4101
+ // normalize to max. 10 depth and 1_000 properties per object
4102
+ payload: utils.normalize(breadcrumb, 10, 1000),
4075
4103
  },
4076
4104
  });
4077
4105
 
@@ -4478,6 +4506,393 @@ function handleXhrSpanListener(replay) {
4478
4506
  };
4479
4507
  }
4480
4508
 
4509
+ const OBJ = 10;
4510
+ const OBJ_KEY = 11;
4511
+ const OBJ_KEY_STR = 12;
4512
+ const OBJ_VAL = 13;
4513
+ const OBJ_VAL_STR = 14;
4514
+ const OBJ_VAL_COMPLETED = 15;
4515
+
4516
+ const ARR = 20;
4517
+ const ARR_VAL = 21;
4518
+ const ARR_VAL_STR = 22;
4519
+ const ARR_VAL_COMPLETED = 23;
4520
+
4521
+ const ALLOWED_PRIMITIVES = ['true', 'false', 'null'];
4522
+
4523
+ /**
4524
+ * Complete an incomplete JSON string.
4525
+ * This will ensure that the last element always has a `"~~"` to indicate it was truncated.
4526
+ * For example, `[1,2,` will be completed to `[1,2,"~~"]`
4527
+ * and `{"aa":"b` will be completed to `{"aa":"b~~"}`
4528
+ */
4529
+ function completeJson(incompleteJson, stack) {
4530
+ if (!stack.length) {
4531
+ return incompleteJson;
4532
+ }
4533
+
4534
+ let json = incompleteJson;
4535
+
4536
+ // Most checks are only needed for the last step in the stack
4537
+ const lastPos = stack.length - 1;
4538
+ const lastStep = stack[lastPos];
4539
+
4540
+ json = _fixLastStep(json, lastStep);
4541
+
4542
+ // Complete remaining steps - just add closing brackets
4543
+ for (let i = lastPos; i >= 0; i--) {
4544
+ const step = stack[i];
4545
+
4546
+ switch (step) {
4547
+ case OBJ:
4548
+ json = `${json}}`;
4549
+ break;
4550
+ case ARR:
4551
+ json = `${json}]`;
4552
+ break;
4553
+ }
4554
+ }
4555
+
4556
+ return json;
4557
+ }
4558
+
4559
+ function _fixLastStep(json, lastStep) {
4560
+ switch (lastStep) {
4561
+ // Object cases
4562
+ case OBJ:
4563
+ return `${json}"~~":"~~"`;
4564
+ case OBJ_KEY:
4565
+ return `${json}:"~~"`;
4566
+ case OBJ_KEY_STR:
4567
+ return `${json}~~":"~~"`;
4568
+ case OBJ_VAL:
4569
+ return _maybeFixIncompleteObjValue(json);
4570
+ case OBJ_VAL_STR:
4571
+ return `${json}~~"`;
4572
+ case OBJ_VAL_COMPLETED:
4573
+ return `${json},"~~":"~~"`;
4574
+
4575
+ // Array cases
4576
+ case ARR:
4577
+ return `${json}"~~"`;
4578
+ case ARR_VAL:
4579
+ return _maybeFixIncompleteArrValue(json);
4580
+ case ARR_VAL_STR:
4581
+ return `${json}~~"`;
4582
+ case ARR_VAL_COMPLETED:
4583
+ return `${json},"~~"`;
4584
+ }
4585
+
4586
+ return json;
4587
+ }
4588
+
4589
+ function _maybeFixIncompleteArrValue(json) {
4590
+ const pos = _findLastArrayDelimiter(json);
4591
+
4592
+ if (pos > -1) {
4593
+ const part = json.slice(pos + 1);
4594
+
4595
+ if (ALLOWED_PRIMITIVES.includes(part.trim())) {
4596
+ return `${json},"~~"`;
4597
+ }
4598
+
4599
+ // Everything else is replaced with `"~~"`
4600
+ return `${json.slice(0, pos + 1)}"~~"`;
4601
+ }
4602
+
4603
+ // fallback, this shouldn't happen, to be save
4604
+ return json;
4605
+ }
4606
+
4607
+ function _findLastArrayDelimiter(json) {
4608
+ for (let i = json.length - 1; i >= 0; i--) {
4609
+ const char = json[i];
4610
+
4611
+ if (char === ',' || char === '[') {
4612
+ return i;
4613
+ }
4614
+ }
4615
+
4616
+ return -1;
4617
+ }
4618
+
4619
+ function _maybeFixIncompleteObjValue(json) {
4620
+ const startPos = json.lastIndexOf(':');
4621
+
4622
+ const part = json.slice(startPos + 1);
4623
+
4624
+ if (ALLOWED_PRIMITIVES.includes(part.trim())) {
4625
+ return `${json},"~~":"~~"`;
4626
+ }
4627
+
4628
+ // Everything else is replaced with `"~~"`
4629
+ // This also means we do not have incomplete numbers, e.g `[1` is replaced with `["~~"]`
4630
+ return `${json.slice(0, startPos + 1)}"~~"`;
4631
+ }
4632
+
4633
+ /**
4634
+ * Evaluate an (incomplete) JSON string.
4635
+ */
4636
+ function evaluateJson(json) {
4637
+ const stack = [];
4638
+
4639
+ for (let pos = 0; pos < json.length; pos++) {
4640
+ _evaluateJsonPos(stack, json, pos);
4641
+ }
4642
+
4643
+ return stack;
4644
+ }
4645
+
4646
+ function _evaluateJsonPos(stack, json, pos) {
4647
+ const curStep = stack[stack.length - 1];
4648
+
4649
+ const char = json[pos];
4650
+
4651
+ const whitespaceRegex = /\s/;
4652
+
4653
+ if (whitespaceRegex.test(char)) {
4654
+ return;
4655
+ }
4656
+
4657
+ if (char === '"' && !_isEscaped(json, pos)) {
4658
+ _handleQuote(stack, curStep);
4659
+ return;
4660
+ }
4661
+
4662
+ switch (char) {
4663
+ case '{':
4664
+ _handleObj(stack, curStep);
4665
+ break;
4666
+ case '[':
4667
+ _handleArr(stack, curStep);
4668
+ break;
4669
+ case ':':
4670
+ _handleColon(stack, curStep);
4671
+ break;
4672
+ case ',':
4673
+ _handleComma(stack, curStep);
4674
+ break;
4675
+ case '}':
4676
+ _handleObjClose(stack, curStep);
4677
+ break;
4678
+ case ']':
4679
+ _handleArrClose(stack, curStep);
4680
+ break;
4681
+ }
4682
+ }
4683
+
4684
+ function _handleQuote(stack, curStep) {
4685
+ // End of obj value
4686
+ if (curStep === OBJ_VAL_STR) {
4687
+ stack.pop();
4688
+ stack.push(OBJ_VAL_COMPLETED);
4689
+ return;
4690
+ }
4691
+
4692
+ // End of arr value
4693
+ if (curStep === ARR_VAL_STR) {
4694
+ stack.pop();
4695
+ stack.push(ARR_VAL_COMPLETED);
4696
+ return;
4697
+ }
4698
+
4699
+ // Start of obj value
4700
+ if (curStep === OBJ_VAL) {
4701
+ stack.push(OBJ_VAL_STR);
4702
+ return;
4703
+ }
4704
+
4705
+ // Start of arr value
4706
+ if (curStep === ARR_VAL) {
4707
+ stack.push(ARR_VAL_STR);
4708
+ return;
4709
+ }
4710
+
4711
+ // Start of obj key
4712
+ if (curStep === OBJ) {
4713
+ stack.push(OBJ_KEY_STR);
4714
+ return;
4715
+ }
4716
+
4717
+ // End of obj key
4718
+ if (curStep === OBJ_KEY_STR) {
4719
+ stack.pop();
4720
+ stack.push(OBJ_KEY);
4721
+ return;
4722
+ }
4723
+ }
4724
+
4725
+ function _handleObj(stack, curStep) {
4726
+ // Initial object
4727
+ if (!curStep) {
4728
+ stack.push(OBJ);
4729
+ return;
4730
+ }
4731
+
4732
+ // New object as obj value
4733
+ if (curStep === OBJ_VAL) {
4734
+ stack.push(OBJ);
4735
+ return;
4736
+ }
4737
+
4738
+ // New object as array element
4739
+ if (curStep === ARR_VAL) {
4740
+ stack.push(OBJ);
4741
+ }
4742
+
4743
+ // New object as first array element
4744
+ if (curStep === ARR) {
4745
+ stack.push(OBJ);
4746
+ return;
4747
+ }
4748
+ }
4749
+
4750
+ function _handleArr(stack, curStep) {
4751
+ // Initial array
4752
+ if (!curStep) {
4753
+ stack.push(ARR);
4754
+ stack.push(ARR_VAL);
4755
+ return;
4756
+ }
4757
+
4758
+ // New array as obj value
4759
+ if (curStep === OBJ_VAL) {
4760
+ stack.push(ARR);
4761
+ stack.push(ARR_VAL);
4762
+ return;
4763
+ }
4764
+
4765
+ // New array as array element
4766
+ if (curStep === ARR_VAL) {
4767
+ stack.push(ARR);
4768
+ stack.push(ARR_VAL);
4769
+ }
4770
+
4771
+ // New array as first array element
4772
+ if (curStep === ARR) {
4773
+ stack.push(ARR);
4774
+ stack.push(ARR_VAL);
4775
+ return;
4776
+ }
4777
+ }
4778
+
4779
+ function _handleColon(stack, curStep) {
4780
+ if (curStep === OBJ_KEY) {
4781
+ stack.pop();
4782
+ stack.push(OBJ_VAL);
4783
+ }
4784
+ }
4785
+
4786
+ function _handleComma(stack, curStep) {
4787
+ // Comma after obj value
4788
+ if (curStep === OBJ_VAL) {
4789
+ stack.pop();
4790
+ return;
4791
+ }
4792
+ if (curStep === OBJ_VAL_COMPLETED) {
4793
+ // Pop OBJ_VAL_COMPLETED & OBJ_VAL
4794
+ stack.pop();
4795
+ stack.pop();
4796
+ return;
4797
+ }
4798
+
4799
+ // Comma after arr value
4800
+ if (curStep === ARR_VAL) {
4801
+ // do nothing - basically we'd pop ARR_VAL but add it right back
4802
+ return;
4803
+ }
4804
+
4805
+ if (curStep === ARR_VAL_COMPLETED) {
4806
+ // Pop ARR_VAL_COMPLETED
4807
+ stack.pop();
4808
+
4809
+ // basically we'd pop ARR_VAL but add it right back
4810
+ return;
4811
+ }
4812
+ }
4813
+
4814
+ function _handleObjClose(stack, curStep) {
4815
+ // Empty object {}
4816
+ if (curStep === OBJ) {
4817
+ stack.pop();
4818
+ }
4819
+
4820
+ // Object with element
4821
+ if (curStep === OBJ_VAL) {
4822
+ // Pop OBJ_VAL, OBJ
4823
+ stack.pop();
4824
+ stack.pop();
4825
+ }
4826
+
4827
+ // Obj with element
4828
+ if (curStep === OBJ_VAL_COMPLETED) {
4829
+ // Pop OBJ_VAL_COMPLETED, OBJ_VAL, OBJ
4830
+ stack.pop();
4831
+ stack.pop();
4832
+ stack.pop();
4833
+ }
4834
+
4835
+ // if was obj value, complete it
4836
+ if (stack[stack.length - 1] === OBJ_VAL) {
4837
+ stack.push(OBJ_VAL_COMPLETED);
4838
+ }
4839
+
4840
+ // if was arr value, complete it
4841
+ if (stack[stack.length - 1] === ARR_VAL) {
4842
+ stack.push(ARR_VAL_COMPLETED);
4843
+ }
4844
+ }
4845
+
4846
+ function _handleArrClose(stack, curStep) {
4847
+ // Empty array []
4848
+ if (curStep === ARR) {
4849
+ stack.pop();
4850
+ }
4851
+
4852
+ // Array with element
4853
+ if (curStep === ARR_VAL) {
4854
+ // Pop ARR_VAL, ARR
4855
+ stack.pop();
4856
+ stack.pop();
4857
+ }
4858
+
4859
+ // Array with element
4860
+ if (curStep === ARR_VAL_COMPLETED) {
4861
+ // Pop ARR_VAL_COMPLETED, ARR_VAL, ARR
4862
+ stack.pop();
4863
+ stack.pop();
4864
+ stack.pop();
4865
+ }
4866
+
4867
+ // if was obj value, complete it
4868
+ if (stack[stack.length - 1] === OBJ_VAL) {
4869
+ stack.push(OBJ_VAL_COMPLETED);
4870
+ }
4871
+
4872
+ // if was arr value, complete it
4873
+ if (stack[stack.length - 1] === ARR_VAL) {
4874
+ stack.push(ARR_VAL_COMPLETED);
4875
+ }
4876
+ }
4877
+
4878
+ function _isEscaped(str, pos) {
4879
+ const previousChar = str[pos - 1];
4880
+
4881
+ return previousChar === '\\' && !_isEscaped(str, pos - 1);
4882
+ }
4883
+
4884
+ /* eslint-disable max-lines */
4885
+
4886
+ /**
4887
+ * Takes an incomplete JSON string, and returns a hopefully valid JSON string.
4888
+ * Note that this _can_ fail, so you should check the return value is valid JSON.
4889
+ */
4890
+ function fixJson(incompleteJson) {
4891
+ const stack = evaluateJson(incompleteJson);
4892
+
4893
+ return completeJson(incompleteJson, stack);
4894
+ }
4895
+
4481
4896
  /** Get the size of a body. */
4482
4897
  function getBodySize(
4483
4898
  body,
@@ -4571,19 +4986,15 @@ function makeNetworkReplayBreadcrumb(
4571
4986
  return result;
4572
4987
  }
4573
4988
 
4574
- /** Get either a JSON network body, or a text representation. */
4575
- function getNetworkBody(bodyText) {
4576
- if (!bodyText) {
4577
- return;
4578
- }
4579
-
4580
- try {
4581
- return JSON.parse(bodyText);
4582
- } catch (e2) {
4583
- // return text
4584
- }
4585
-
4586
- return bodyText;
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
+ };
4587
4998
  }
4588
4999
 
4589
5000
  /** Build the request or response part of a replay network breadcrumb. */
@@ -4614,11 +5025,11 @@ function buildNetworkRequestOrResponse(
4614
5025
  size: bodySize,
4615
5026
  };
4616
5027
 
4617
- if (bodySize < NETWORK_BODY_MAX_SIZE) {
4618
- info.body = body;
4619
- } else {
5028
+ const { body: normalizedBody, warnings } = normalizeNetworkBody(body);
5029
+ info.body = normalizedBody;
5030
+ if (warnings.length > 0) {
4620
5031
  info._meta = {
4621
- errors: ['MAX_BODY_SIZE_EXCEEDED'],
5032
+ warnings,
4622
5033
  };
4623
5034
  }
4624
5035
 
@@ -4644,6 +5055,53 @@ function _serializeFormData(formData) {
4644
5055
  return new URLSearchParams(formData).toString();
4645
5056
  }
4646
5057
 
5058
+ function normalizeNetworkBody(body)
5059
+
5060
+ {
5061
+ if (!body || typeof body !== 'string') {
5062
+ return {
5063
+ body,
5064
+ warnings: [],
5065
+ };
5066
+ }
5067
+
5068
+ const exceedsSizeLimit = body.length > NETWORK_BODY_MAX_SIZE;
5069
+
5070
+ if (_strIsProbablyJson(body)) {
5071
+ try {
5072
+ const json = exceedsSizeLimit ? fixJson(body.slice(0, NETWORK_BODY_MAX_SIZE)) : body;
5073
+ const normalizedBody = JSON.parse(json);
5074
+ return {
5075
+ body: normalizedBody,
5076
+ warnings: exceedsSizeLimit ? ['JSON_TRUNCATED'] : [],
5077
+ };
5078
+ } catch (e3) {
5079
+ return {
5080
+ body: exceedsSizeLimit ? `${body.slice(0, NETWORK_BODY_MAX_SIZE)}…` : body,
5081
+ warnings: exceedsSizeLimit ? ['INVALID_JSON', 'TEXT_TRUNCATED'] : ['INVALID_JSON'],
5082
+ };
5083
+ }
5084
+ }
5085
+
5086
+ return {
5087
+ body: exceedsSizeLimit ? `${body.slice(0, NETWORK_BODY_MAX_SIZE)}…` : body,
5088
+ warnings: exceedsSizeLimit ? ['TEXT_TRUNCATED'] : [],
5089
+ };
5090
+ }
5091
+
5092
+ function _strIsProbablyJson(str) {
5093
+ const first = str[0];
5094
+ const last = str[str.length - 1];
5095
+
5096
+ // Simple check: If this does not start & end with {} or [], it's not JSON
5097
+ return (first === '[' && last === ']') || (first === '{' && last === '}');
5098
+ }
5099
+
5100
+ /** Match an URL against a list of strings/Regex. */
5101
+ function urlMatches(url, urls) {
5102
+ return utils.stringMatchesSomePattern(url, urls);
5103
+ }
5104
+
4647
5105
  /**
4648
5106
  * Capture a fetch breadcrumb to a replay.
4649
5107
  * This adds additional data (where approriate).
@@ -4703,56 +5161,65 @@ async function _prepareFetchData(
4703
5161
  const {
4704
5162
  url,
4705
5163
  method,
4706
- status_code: statusCode,
5164
+ status_code: statusCode = 0,
4707
5165
  request_body_size: requestBodySize,
4708
5166
  response_body_size: responseBodySize,
4709
5167
  } = breadcrumb.data;
4710
5168
 
4711
- const request = _getRequestInfo(options, hint.input, requestBodySize);
4712
- 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);
4713
5175
 
4714
5176
  return {
4715
5177
  startTimestamp,
4716
5178
  endTimestamp,
4717
5179
  url,
4718
5180
  method,
4719
- statusCode: statusCode || 0,
5181
+ statusCode,
4720
5182
  request,
4721
5183
  response,
4722
5184
  };
4723
5185
  }
4724
5186
 
4725
5187
  function _getRequestInfo(
4726
- { captureBodies, requestHeaders },
5188
+ { networkCaptureBodies, networkRequestHeaders },
4727
5189
  input,
4728
5190
  requestBodySize,
4729
5191
  ) {
4730
- const headers = getRequestHeaders(input, requestHeaders);
5192
+ const headers = getRequestHeaders(input, networkRequestHeaders);
4731
5193
 
4732
- if (!captureBodies) {
5194
+ if (!networkCaptureBodies) {
4733
5195
  return buildNetworkRequestOrResponse(headers, requestBodySize, undefined);
4734
5196
  }
4735
5197
 
4736
5198
  // We only want to transmit string or string-like bodies
4737
5199
  const requestBody = _getFetchRequestArgBody(input);
4738
- const body = getNetworkBody(getBodyString(requestBody));
4739
- return buildNetworkRequestOrResponse(headers, requestBodySize, body);
5200
+ const bodyStr = getBodyString(requestBody);
5201
+ return buildNetworkRequestOrResponse(headers, requestBodySize, bodyStr);
4740
5202
  }
4741
5203
 
4742
5204
  async function _getResponseInfo(
5205
+ captureDetails,
4743
5206
  {
4744
- captureBodies,
5207
+ networkCaptureBodies,
4745
5208
  textEncoder,
4746
- responseHeaders,
5209
+ networkResponseHeaders,
4747
5210
  }
4748
5211
 
4749
5212
  ,
4750
5213
  response,
4751
5214
  responseBodySize,
4752
5215
  ) {
4753
- const headers = getAllHeaders(response.headers, responseHeaders);
5216
+ if (!captureDetails && responseBodySize !== undefined) {
5217
+ return buildSkippedNetworkRequestOrResponse(responseBodySize);
5218
+ }
4754
5219
 
4755
- if (!captureBodies && responseBodySize !== undefined) {
5220
+ const headers = getAllHeaders(response.headers, networkResponseHeaders);
5221
+
5222
+ if (!networkCaptureBodies && responseBodySize !== undefined) {
4756
5223
  return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);
4757
5224
  }
4758
5225
 
@@ -4760,15 +5227,19 @@ async function _getResponseInfo(
4760
5227
  try {
4761
5228
  // We have to clone this, as the body can only be read once
4762
5229
  const res = response.clone();
4763
- const { body, bodyText } = await _parseFetchBody(res);
5230
+ const bodyText = await _parseFetchBody(res);
4764
5231
 
4765
5232
  const size =
4766
5233
  bodyText && bodyText.length && responseBodySize === undefined
4767
5234
  ? getBodySize(bodyText, textEncoder)
4768
5235
  : responseBodySize;
4769
5236
 
4770
- if (captureBodies) {
4771
- return buildNetworkRequestOrResponse(headers, size, body);
5237
+ if (!captureDetails) {
5238
+ return buildSkippedNetworkRequestOrResponse(size);
5239
+ }
5240
+
5241
+ if (networkCaptureBodies) {
5242
+ return buildNetworkRequestOrResponse(headers, size, bodyText);
4772
5243
  }
4773
5244
 
4774
5245
  return buildNetworkRequestOrResponse(headers, size, undefined);
@@ -4778,25 +5249,12 @@ async function _getResponseInfo(
4778
5249
  }
4779
5250
  }
4780
5251
 
4781
- async function _parseFetchBody(
4782
- response,
4783
- ) {
4784
- let bodyText;
4785
-
5252
+ async function _parseFetchBody(response) {
4786
5253
  try {
4787
- bodyText = await response.text();
5254
+ return await response.text();
4788
5255
  } catch (e2) {
4789
- return {};
4790
- }
4791
-
4792
- try {
4793
- const body = JSON.parse(bodyText);
4794
- return { body, bodyText };
4795
- } catch (e3) {
4796
- // just send bodyText
5256
+ return undefined;
4797
5257
  }
4798
-
4799
- return { bodyText, body: bodyText };
4800
5258
  }
4801
5259
 
4802
5260
  function _getFetchRequestArgBody(fetchArgs = []) {
@@ -4913,28 +5371,44 @@ function _prepareXhrData(
4913
5371
  const {
4914
5372
  url,
4915
5373
  method,
4916
- status_code: statusCode,
5374
+ status_code: statusCode = 0,
4917
5375
  request_body_size: requestBodySize,
4918
5376
  response_body_size: responseBodySize,
4919
5377
  } = breadcrumb.data;
4920
5378
 
4921
- const xhrInfo = xhr[utils.SENTRY_XHR_DATA_KEY];
4922
- const requestHeaders = xhrInfo ? getAllowedHeaders(xhrInfo.request_headers, options.requestHeaders) : {};
4923
- const responseHeaders = getAllowedHeaders(getResponseHeaders(xhr), options.responseHeaders);
4924
-
4925
5379
  if (!url) {
4926
5380
  return null;
4927
5381
  }
4928
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
+
4929
5403
  const request = buildNetworkRequestOrResponse(
4930
- requestHeaders,
5404
+ networkRequestHeaders,
4931
5405
  requestBodySize,
4932
- options.captureBodies ? getNetworkBody(getBodyString(input)) : undefined,
5406
+ options.networkCaptureBodies ? getBodyString(input) : undefined,
4933
5407
  );
4934
5408
  const response = buildNetworkRequestOrResponse(
4935
- responseHeaders,
5409
+ networkResponseHeaders,
4936
5410
  responseBodySize,
4937
- options.captureBodies ? getNetworkBody(hint.xhr.responseText) : undefined,
5411
+ options.networkCaptureBodies ? hint.xhr.responseText : undefined,
4938
5412
  );
4939
5413
 
4940
5414
  return {
@@ -4942,7 +5416,7 @@ function _prepareXhrData(
4942
5416
  endTimestamp,
4943
5417
  url,
4944
5418
  method,
4945
- statusCode: statusCode || 0,
5419
+ statusCode,
4946
5420
  request,
4947
5421
  response,
4948
5422
  };
@@ -4974,10 +5448,16 @@ function handleNetworkBreadcrumbs(replay) {
4974
5448
  try {
4975
5449
  const textEncoder = new TextEncoder();
4976
5450
 
5451
+ const { networkDetailAllowUrls, networkCaptureBodies, networkRequestHeaders, networkResponseHeaders } =
5452
+ replay.getOptions();
5453
+
4977
5454
  const options = {
4978
5455
  replay,
4979
5456
  textEncoder,
4980
- ...replay.getExperimentalOptions().network,
5457
+ networkDetailAllowUrls,
5458
+ networkCaptureBodies,
5459
+ networkRequestHeaders,
5460
+ networkResponseHeaders,
4981
5461
  };
4982
5462
 
4983
5463
  if (client && client.on) {
@@ -5085,9 +5565,66 @@ function handleScope(scope) {
5085
5565
  return null;
5086
5566
  }
5087
5567
 
5568
+ if (newBreadcrumb.category === 'console') {
5569
+ return normalizeConsoleBreadcrumb(newBreadcrumb);
5570
+ }
5571
+
5088
5572
  return createBreadcrumb(newBreadcrumb);
5089
5573
  }
5090
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
+
5091
5628
  /**
5092
5629
  * Add global listeners that cannot be removed.
5093
5630
  */
@@ -5112,7 +5649,7 @@ function addGlobalListeners(replay) {
5112
5649
  client.on('afterSendEvent', handleAfterSendEvent(replay));
5113
5650
  client.on('createDsc', (dsc) => {
5114
5651
  const replayId = replay.getSessionId();
5115
- if (replayId) {
5652
+ if (replayId && replay.isEnabled()) {
5116
5653
  dsc.replay_id = replayId;
5117
5654
  }
5118
5655
  });
@@ -5420,7 +5957,7 @@ function getHandleRecordingEmit(replay) {
5420
5957
  // when an error occurs. Clear any state that happens before this current
5421
5958
  // checkout. This needs to happen before `addEvent()` which updates state
5422
5959
  // dependent on this reset.
5423
- if (replay.recordingMode === 'error' && isCheckout) {
5960
+ if (replay.recordingMode === 'buffer' && isCheckout) {
5424
5961
  replay.setInitialState();
5425
5962
  }
5426
5963
 
@@ -5446,7 +5983,7 @@ function getHandleRecordingEmit(replay) {
5446
5983
 
5447
5984
  // See note above re: session start needs to reflect the most recent
5448
5985
  // checkout.
5449
- if (replay.recordingMode === 'error' && replay.session) {
5986
+ if (replay.recordingMode === 'buffer' && replay.session) {
5450
5987
  const { earliestEvent } = replay.getContext();
5451
5988
  if (earliestEvent) {
5452
5989
  replay.session.started = earliestEvent;
@@ -5795,9 +6332,11 @@ class ReplayContainer {
5795
6332
  __init2() {this.performanceEvents = [];}
5796
6333
 
5797
6334
  /**
5798
- * Recording can happen in one of two modes:
5799
- * * session: Record the whole session, sending it continuously
5800
- * * 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
5801
6340
  */
5802
6341
  __init3() {this.recordingMode = 'session';}
5803
6342
 
@@ -5806,7 +6345,8 @@ class ReplayContainer {
5806
6345
  * @hidden
5807
6346
  */
5808
6347
  __init4() {this.timeouts = {
5809
- sessionIdle: SESSION_IDLE_DURATION,
6348
+ sessionIdlePause: SESSION_IDLE_PAUSE_DURATION,
6349
+ sessionIdleExpire: SESSION_IDLE_EXPIRE_DURATION,
5810
6350
  maxSessionLife: MAX_SESSION_LIFE,
5811
6351
  }; }
5812
6352
 
@@ -5867,8 +6407,6 @@ class ReplayContainer {
5867
6407
  this._debouncedFlush = debounce(() => this._flush(), this._options.flushMinDelay, {
5868
6408
  maxWait: this._options.flushMaxDelay,
5869
6409
  });
5870
-
5871
- this._experimentalOptions = _getExperimentalOptions(options);
5872
6410
  }
5873
6411
 
5874
6412
  /** Get the event context. */
@@ -5892,58 +6430,102 @@ class ReplayContainer {
5892
6430
  }
5893
6431
 
5894
6432
  /**
5895
- * Get the experimental options.
5896
- * THIS IS INTERNAL AND SUBJECT TO CHANGE!
5897
- * @hidden
6433
+ * Initializes the plugin based on sampling configuration. Should not be
6434
+ * called outside of constructor.
5898
6435
  */
5899
- getExperimentalOptions() {
5900
- 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();
5901
6470
  }
5902
6471
 
5903
6472
  /**
5904
- * 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.
5905
6475
  *
5906
6476
  * Creates or loads a session, attaches listeners to varying events (DOM,
5907
6477
  * _performanceObserver, Recording, Sentry SDK, etc)
5908
6478
  */
5909
6479
  start() {
5910
- this.setInitialState();
5911
-
5912
- if (!this._loadAndCheckSession()) {
5913
- return;
6480
+ if (this._isEnabled && this.recordingMode === 'session') {
6481
+ throw new Error('Replay recording is already in progress');
5914
6482
  }
5915
6483
 
5916
- // If there is no session, then something bad has happened - can't continue
5917
- if (!this.session) {
5918
- this._handleException(new Error('No session found'));
5919
- return;
6484
+ if (this._isEnabled && this.recordingMode === 'buffer') {
6485
+ throw new Error('Replay buffering is in progress, call `flush()` to save the replay');
5920
6486
  }
5921
6487
 
5922
- if (!this.session.sampled) {
5923
- // If session was not sampled, then we do not initialize the integration at all.
5924
- return;
5925
- }
6488
+ const previousSessionId = this.session && this.session.id;
5926
6489
 
5927
- // If session is sampled for errors, then we need to set the recordingMode
5928
- // to 'error', which will configure recording with different options.
5929
- if (this.session.sampled === 'error') {
5930
- this.recordingMode = 'error';
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
+ }
6504
+
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');
5931
6512
  }
5932
6513
 
5933
- // setup() is generally called on page load or manually - in both cases we
5934
- // should treat it as an activity
5935
- this._updateSessionActivity();
6514
+ const previousSessionId = this.session && this.session.id;
5936
6515
 
5937
- this.eventBuffer = createEventBuffer({
5938
- 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,
5939
6522
  });
5940
6523
 
5941
- this._addListeners();
5942
-
5943
- // Need to set as enabled before we start recording, as `record()` can trigger a flush with a new checkout
5944
- this._isEnabled = true;
6524
+ session.previousSessionId = previousSessionId;
6525
+ this.session = session;
5945
6526
 
5946
- this.startRecording();
6527
+ this.recordingMode = 'buffer';
6528
+ this._initializeRecording();
5947
6529
  }
5948
6530
 
5949
6531
  /**
@@ -5958,7 +6540,7 @@ class ReplayContainer {
5958
6540
  // When running in error sampling mode, we need to overwrite `checkoutEveryNms`
5959
6541
  // Without this, it would record forever, until an error happens, which we don't want
5960
6542
  // instead, we'll always keep the last 60 seconds of replay before an error happened
5961
- ...(this.recordingMode === 'error' && { checkoutEveryNms: ERROR_CHECKOUT_TIME }),
6543
+ ...(this.recordingMode === 'buffer' && { checkoutEveryNms: BUFFER_CHECKOUT_TIME }),
5962
6544
  emit: getHandleRecordingEmit(this),
5963
6545
  onMutation: this._onMutationHandler,
5964
6546
  });
@@ -5969,17 +6551,18 @@ class ReplayContainer {
5969
6551
 
5970
6552
  /**
5971
6553
  * Stops the recording, if it was running.
5972
- * Returns true if it was stopped, else false.
6554
+ *
6555
+ * Returns true if it was previously stopped, or is now stopped,
6556
+ * otherwise false.
5973
6557
  */
5974
6558
  stopRecording() {
5975
6559
  try {
5976
6560
  if (this._stopRecording) {
5977
6561
  this._stopRecording();
5978
6562
  this._stopRecording = undefined;
5979
- return true;
5980
6563
  }
5981
6564
 
5982
- return false;
6565
+ return true;
5983
6566
  } catch (err) {
5984
6567
  this._handleException(err);
5985
6568
  return false;
@@ -5990,7 +6573,7 @@ class ReplayContainer {
5990
6573
  * Currently, this needs to be manually called (e.g. for tests). Sentry SDK
5991
6574
  * does not support a teardown
5992
6575
  */
5993
- stop(reason) {
6576
+ async stop(reason) {
5994
6577
  if (!this._isEnabled) {
5995
6578
  return;
5996
6579
  }
@@ -6006,12 +6589,24 @@ class ReplayContainer {
6006
6589
  log(msg);
6007
6590
  }
6008
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.
6009
6594
  this._isEnabled = false;
6010
6595
  this._removeListeners();
6011
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
6012
6604
  this.eventBuffer && this.eventBuffer.destroy();
6013
6605
  this.eventBuffer = null;
6014
- 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);
6015
6610
  } catch (err) {
6016
6611
  this._handleException(err);
6017
6612
  }
@@ -6042,6 +6637,45 @@ class ReplayContainer {
6042
6637
  this.startRecording();
6043
6638
  }
6044
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
+
6045
6679
  /**
6046
6680
  * We want to batch uploads of replay events. Save events only if
6047
6681
  * `<flushMinDelay>` milliseconds have elapsed since the last event
@@ -6051,12 +6685,12 @@ class ReplayContainer {
6051
6685
  * processing and hand back control to caller.
6052
6686
  */
6053
6687
  addUpdate(cb) {
6054
- // 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'`)
6055
6689
  const cbResult = cb();
6056
6690
 
6057
6691
  // If this option is turned on then we will only want to call `flush`
6058
6692
  // explicitly
6059
- if (this.recordingMode === 'error') {
6693
+ if (this.recordingMode === 'buffer') {
6060
6694
  return;
6061
6695
  }
6062
6696
 
@@ -6128,12 +6762,12 @@ class ReplayContainer {
6128
6762
  const oldSessionId = this.getSessionId();
6129
6763
 
6130
6764
  // Prevent starting a new session if the last user activity is older than
6131
- // SESSION_IDLE_DURATION. Otherwise non-user activity can trigger a new
6765
+ // SESSION_IDLE_PAUSE_DURATION. Otherwise non-user activity can trigger a new
6132
6766
  // session+recording. This creates noisy replays that do not have much
6133
6767
  // content in them.
6134
6768
  if (
6135
6769
  this._lastActivity &&
6136
- isExpired(this._lastActivity, this.timeouts.sessionIdle) &&
6770
+ isExpired(this._lastActivity, this.timeouts.sessionIdlePause) &&
6137
6771
  this.session &&
6138
6772
  this.session.sampled === 'session'
6139
6773
  ) {
@@ -6183,6 +6817,30 @@ class ReplayContainer {
6183
6817
  this._context.urls.push(url);
6184
6818
  }
6185
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
+
6186
6844
  /** A wrapper to conditionally capture exceptions. */
6187
6845
  _handleException(error) {
6188
6846
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.error('[Replay]', error);
@@ -6202,7 +6860,7 @@ class ReplayContainer {
6202
6860
  stickySession: Boolean(this._options.stickySession),
6203
6861
  currentSession: this.session,
6204
6862
  sessionSampleRate: this._options.sessionSampleRate,
6205
- errorSampleRate: this._options.errorSampleRate,
6863
+ allowBuffering: this._options.errorSampleRate > 0,
6206
6864
  });
6207
6865
 
6208
6866
  // If session was newly created (i.e. was not loaded from storage), then
@@ -6219,7 +6877,7 @@ class ReplayContainer {
6219
6877
  this.session = session;
6220
6878
 
6221
6879
  if (!this.session.sampled) {
6222
- this.stop('session unsampled');
6880
+ void this.stop('session unsampled');
6223
6881
  return false;
6224
6882
  }
6225
6883
 
@@ -6343,7 +7001,7 @@ class ReplayContainer {
6343
7001
  const isSessionActive = this.checkAndHandleExpiredSession();
6344
7002
 
6345
7003
  if (!isSessionActive) {
6346
- // 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
6347
7005
  // ms, we will re-use the existing session, otherwise create a new
6348
7006
  // session
6349
7007
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && utils.logger.log('[Replay] Document has become active, but session has expired');
@@ -6417,7 +7075,7 @@ class ReplayContainer {
6417
7075
  * Only flush if `this.recordingMode === 'session'`
6418
7076
  */
6419
7077
  _conditionalFlush() {
6420
- if (this.recordingMode === 'error') {
7078
+ if (this.recordingMode === 'buffer') {
6421
7079
  return;
6422
7080
  }
6423
7081
 
@@ -6512,7 +7170,7 @@ class ReplayContainer {
6512
7170
  // This means we retried 3 times and all of them failed,
6513
7171
  // or we ran into a problem we don't want to retry, like rate limiting.
6514
7172
  // In this case, we want to completely stop the replay - otherwise, we may get inconsistent segments
6515
- this.stop('sendReplay');
7173
+ void this.stop('sendReplay');
6516
7174
 
6517
7175
  const client = core.getCurrentHub().getClient();
6518
7176
 
@@ -6526,8 +7184,12 @@ class ReplayContainer {
6526
7184
  * Flush recording data to Sentry. Creates a lock so that only a single flush
6527
7185
  * can be active at a time. Do not call this directly.
6528
7186
  */
6529
- __init16() {this._flush = async () => {
6530
- if (!this._isEnabled) {
7187
+ __init16() {this._flush = async ({
7188
+ force = false,
7189
+ }
7190
+
7191
+ = {}) => {
7192
+ if (!this._isEnabled && !force) {
6531
7193
  // This can happen if e.g. the replay was stopped because of exceeding the retry limit
6532
7194
  return;
6533
7195
  }
@@ -6608,23 +7270,6 @@ class ReplayContainer {
6608
7270
  };}
6609
7271
  }
6610
7272
 
6611
- function _getExperimentalOptions(options) {
6612
- const requestHeaders = options._experiments.captureRequestHeaders || [];
6613
- const responseHeaders = options._experiments.captureResponseHeaders || [];
6614
- const captureBodies = options._experiments.captureNetworkBodies || false;
6615
-
6616
- // Add defaults
6617
- const defaultHeaders = ['content-length', 'content-type', 'accept'];
6618
-
6619
- return {
6620
- network: {
6621
- captureBodies,
6622
- requestHeaders: [...defaultHeaders, ...requestHeaders.map(header => header.toLowerCase())],
6623
- responseHeaders: [...defaultHeaders, ...responseHeaders.map(header => header.toLowerCase())],
6624
- },
6625
- };
6626
- }
6627
-
6628
7273
  function getOption(
6629
7274
  selectors,
6630
7275
  defaultSelectors,
@@ -6728,6 +7373,8 @@ function isElectronNodeRenderer() {
6728
7373
  const MEDIA_SELECTORS =
6729
7374
  'img,image,svg,video,object,picture,embed,map,audio,link[rel="icon"],link[rel="apple-touch-icon"]';
6730
7375
 
7376
+ const DEFAULT_NETWORK_HEADERS = ['content-length', 'content-type', 'accept'];
7377
+
6731
7378
  let _initialized = false;
6732
7379
 
6733
7380
  /**
@@ -6768,6 +7415,11 @@ class Replay {
6768
7415
  maskAllInputs = true,
6769
7416
  blockAllMedia = true,
6770
7417
 
7418
+ networkDetailAllowUrls = [],
7419
+ networkCaptureBodies = true,
7420
+ networkRequestHeaders = [],
7421
+ networkResponseHeaders = [],
7422
+
6771
7423
  mask = [],
6772
7424
  unmask = [],
6773
7425
  block = [],
@@ -6826,6 +7478,11 @@ class Replay {
6826
7478
  errorSampleRate,
6827
7479
  useCompression,
6828
7480
  blockAllMedia,
7481
+ networkDetailAllowUrls,
7482
+ networkCaptureBodies,
7483
+ networkRequestHeaders: _getMergedNetworkHeaders(networkRequestHeaders),
7484
+ networkResponseHeaders: _getMergedNetworkHeaders(networkResponseHeaders),
7485
+
6829
7486
  _experiments,
6830
7487
  };
6831
7488
 
@@ -6879,14 +7536,7 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
6879
7536
  }
6880
7537
 
6881
7538
  /**
6882
- * We previously used to create a transaction in `setupOnce` and it would
6883
- * potentially create a transaction before some native SDK integrations have run
6884
- * and applied their own global event processor. An example is:
6885
- * https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts
6886
- *
6887
- * So we call `replay.setup` in next event loop as a workaround to wait for other
6888
- * global event processors to finish. This is no longer needed, but keeping it
6889
- * here to avoid any future issues.
7539
+ * Setup and initialize replay container
6890
7540
  */
6891
7541
  setupOnce() {
6892
7542
  if (!isBrowser()) {
@@ -6895,12 +7545,20 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
6895
7545
 
6896
7546
  this._setup();
6897
7547
 
6898
- // XXX: See method comments above
6899
- 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());
6900
7557
  }
6901
7558
 
6902
7559
  /**
6903
- * 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.
6904
7562
  *
6905
7563
  * Creates or loads a session, attaches listeners to varying events (DOM,
6906
7564
  * PerformanceObserver, Recording, Sentry SDK, etc)
@@ -6913,27 +7571,43 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
6913
7571
  this._replay.start();
6914
7572
  }
6915
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
+
6916
7586
  /**
6917
7587
  * Currently, this needs to be manually called (e.g. for tests). Sentry SDK
6918
7588
  * does not support a teardown
6919
7589
  */
6920
7590
  stop() {
6921
7591
  if (!this._replay) {
6922
- return;
7592
+ return Promise.resolve();
6923
7593
  }
6924
7594
 
6925
- this._replay.stop();
7595
+ return this._replay.stop();
6926
7596
  }
6927
7597
 
6928
7598
  /**
6929
- * 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.
6930
7604
  */
6931
- flush() {
7605
+ flush(options) {
6932
7606
  if (!this._replay || !this._replay.isEnabled()) {
6933
- return;
7607
+ return Promise.resolve();
6934
7608
  }
6935
7609
 
6936
- return this._replay.flushImmediate();
7610
+ return this._replay.sendBufferedReplayOrFlush(options);
6937
7611
  }
6938
7612
 
6939
7613
  /**
@@ -6946,6 +7620,16 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
6946
7620
 
6947
7621
  return this._replay.getSessionId();
6948
7622
  }
7623
+ /**
7624
+ * Initializes replay.
7625
+ */
7626
+ _initialize() {
7627
+ if (!this._replay) {
7628
+ return;
7629
+ }
7630
+
7631
+ this._replay.initializeSampling();
7632
+ }
6949
7633
 
6950
7634
  /** Setup the integration. */
6951
7635
  _setup() {
@@ -6995,5 +7679,9 @@ function loadReplayOptionsFromClient(initialOptions) {
6995
7679
  return finalOptions;
6996
7680
  }
6997
7681
 
7682
+ function _getMergedNetworkHeaders(headers) {
7683
+ return [...DEFAULT_NETWORK_HEADERS, ...headers.map(header => header.toLowerCase())];
7684
+ }
7685
+
6998
7686
  exports.Replay = Replay;
6999
7687
  //# sourceMappingURL=index.js.map