@sentry/replay 7.47.0 → 7.49.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 (33) hide show
  1. package/README.md +5 -0
  2. package/cjs/index.js +607 -60
  3. package/cjs/index.js.map +1 -1
  4. package/esm/index.js +608 -61
  5. package/esm/index.js.map +1 -1
  6. package/package.json +5 -5
  7. package/types/constants.d.ts +1 -1
  8. package/types/coreHandlers/handleNetworkBreadcrumbs.d.ts +2 -3
  9. package/types/coreHandlers/handleNetworkBreadcrumbs.d.ts.map +1 -1
  10. package/types/coreHandlers/handleXhr.d.ts.map +1 -1
  11. package/types/coreHandlers/util/addBreadcrumbEvent.d.ts.map +1 -1
  12. package/types/coreHandlers/util/fetchUtils.d.ts +2 -3
  13. package/types/coreHandlers/util/fetchUtils.d.ts.map +1 -1
  14. package/types/coreHandlers/util/networkUtils.d.ts +3 -1
  15. package/types/coreHandlers/util/networkUtils.d.ts.map +1 -1
  16. package/types/coreHandlers/util/xhrUtils.d.ts +2 -3
  17. package/types/coreHandlers/util/xhrUtils.d.ts.map +1 -1
  18. package/types/integration.d.ts +4 -0
  19. package/types/integration.d.ts.map +1 -1
  20. package/types/replay.d.ts +8 -1
  21. package/types/replay.d.ts.map +1 -1
  22. package/types/types.d.ts +26 -4
  23. package/types/types.d.ts.map +1 -1
  24. package/types/util/sendReplayRequest.d.ts +1 -1
  25. package/types/util/sendReplayRequest.d.ts.map +1 -1
  26. package/types/util/truncateJson/completeJson.d.ts +9 -0
  27. package/types/util/truncateJson/completeJson.d.ts.map +1 -0
  28. package/types/util/truncateJson/constants.d.ts +12 -0
  29. package/types/util/truncateJson/constants.d.ts.map +1 -0
  30. package/types/util/truncateJson/evaluateJson.d.ts +6 -0
  31. package/types/util/truncateJson/evaluateJson.d.ts.map +1 -0
  32. package/types/util/truncateJson/fixJson.d.ts +6 -0
  33. package/types/util/truncateJson/fixJson.d.ts.map +1 -0
package/esm/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { getCurrentHub, addBreadcrumb, addGlobalEventProcessor, prepareEvent, setContext, captureException } from '@sentry/core';
2
- import { GLOBAL_OBJ, logger, uuid4, normalize, htmlTreeAsString, dropUndefinedKeys, addInstrumentationHandler, browserPerformanceTimeOrigin, createEnvelope, createEventEnvelopeHeaders, getSdkMetadataForEnvelopeHeader, isNodeEnv } from '@sentry/utils';
2
+ import { GLOBAL_OBJ, logger, uuid4, normalize, htmlTreeAsString, SENTRY_XHR_DATA_KEY, dropUndefinedKeys, addInstrumentationHandler, browserPerformanceTimeOrigin, createEnvelope, createEventEnvelopeHeaders, getSdkMetadataForEnvelopeHeader, isNodeEnv } from '@sentry/utils';
3
3
 
4
4
  // exporting a separate copy of `WINDOW` rather than exporting the one from `@sentry/browser`
5
5
  // prevents the browser package from being bundled in the CDN bundle, and avoids a
@@ -29,8 +29,8 @@ const ERROR_CHECKOUT_TIME = 60000;
29
29
  const RETRY_BASE_INTERVAL = 5000;
30
30
  const RETRY_MAX_COUNT = 3;
31
31
 
32
- /* The max (uncompressed) size in bytes of a network body. Any body larger than this will be dropped. */
33
- const NETWORK_BODY_MAX_SIZE = 300000;
32
+ /* The max (uncompressed) size in bytes of a network body. Any body larger than this will be truncated. */
33
+ const NETWORK_BODY_MAX_SIZE = 150000;
34
34
 
35
35
  var NodeType$1;
36
36
  (function (NodeType) {
@@ -4069,7 +4069,8 @@ function addBreadcrumbEvent(replay, breadcrumb) {
4069
4069
  timestamp: (breadcrumb.timestamp || 0) * 1000,
4070
4070
  data: {
4071
4071
  tag: 'breadcrumb',
4072
- payload: normalize(breadcrumb),
4072
+ // normalize to max. 10 depth and 1_000 properties per object
4073
+ payload: normalize(breadcrumb, 10, 1000),
4073
4074
  },
4074
4075
  });
4075
4076
 
@@ -4436,12 +4437,14 @@ function handleFetchSpanListener(replay) {
4436
4437
  function handleXhr(handlerData) {
4437
4438
  const { startTimestamp, endTimestamp, xhr } = handlerData;
4438
4439
 
4439
- if (!startTimestamp || !endTimestamp || !xhr.__sentry_xhr__) {
4440
+ const sentryXhrData = xhr[SENTRY_XHR_DATA_KEY];
4441
+
4442
+ if (!startTimestamp || !endTimestamp || !sentryXhrData) {
4440
4443
  return null;
4441
4444
  }
4442
4445
 
4443
4446
  // This is only used as a fallback, so we know the body sizes are never set here
4444
- const { method, url, status_code: statusCode } = xhr.__sentry_xhr__;
4447
+ const { method, url, status_code: statusCode } = sentryXhrData;
4445
4448
 
4446
4449
  if (url === undefined) {
4447
4450
  return null;
@@ -4474,6 +4477,393 @@ function handleXhrSpanListener(replay) {
4474
4477
  };
4475
4478
  }
4476
4479
 
4480
+ const OBJ = 10;
4481
+ const OBJ_KEY = 11;
4482
+ const OBJ_KEY_STR = 12;
4483
+ const OBJ_VAL = 13;
4484
+ const OBJ_VAL_STR = 14;
4485
+ const OBJ_VAL_COMPLETED = 15;
4486
+
4487
+ const ARR = 20;
4488
+ const ARR_VAL = 21;
4489
+ const ARR_VAL_STR = 22;
4490
+ const ARR_VAL_COMPLETED = 23;
4491
+
4492
+ const ALLOWED_PRIMITIVES = ['true', 'false', 'null'];
4493
+
4494
+ /**
4495
+ * Complete an incomplete JSON string.
4496
+ * This will ensure that the last element always has a `"~~"` to indicate it was truncated.
4497
+ * For example, `[1,2,` will be completed to `[1,2,"~~"]`
4498
+ * and `{"aa":"b` will be completed to `{"aa":"b~~"}`
4499
+ */
4500
+ function completeJson(incompleteJson, stack) {
4501
+ if (!stack.length) {
4502
+ return incompleteJson;
4503
+ }
4504
+
4505
+ let json = incompleteJson;
4506
+
4507
+ // Most checks are only needed for the last step in the stack
4508
+ const lastPos = stack.length - 1;
4509
+ const lastStep = stack[lastPos];
4510
+
4511
+ json = _fixLastStep(json, lastStep);
4512
+
4513
+ // Complete remaining steps - just add closing brackets
4514
+ for (let i = lastPos; i >= 0; i--) {
4515
+ const step = stack[i];
4516
+
4517
+ switch (step) {
4518
+ case OBJ:
4519
+ json = `${json}}`;
4520
+ break;
4521
+ case ARR:
4522
+ json = `${json}]`;
4523
+ break;
4524
+ }
4525
+ }
4526
+
4527
+ return json;
4528
+ }
4529
+
4530
+ function _fixLastStep(json, lastStep) {
4531
+ switch (lastStep) {
4532
+ // Object cases
4533
+ case OBJ:
4534
+ return `${json}"~~":"~~"`;
4535
+ case OBJ_KEY:
4536
+ return `${json}:"~~"`;
4537
+ case OBJ_KEY_STR:
4538
+ return `${json}~~":"~~"`;
4539
+ case OBJ_VAL:
4540
+ return _maybeFixIncompleteObjValue(json);
4541
+ case OBJ_VAL_STR:
4542
+ return `${json}~~"`;
4543
+ case OBJ_VAL_COMPLETED:
4544
+ return `${json},"~~":"~~"`;
4545
+
4546
+ // Array cases
4547
+ case ARR:
4548
+ return `${json}"~~"`;
4549
+ case ARR_VAL:
4550
+ return _maybeFixIncompleteArrValue(json);
4551
+ case ARR_VAL_STR:
4552
+ return `${json}~~"`;
4553
+ case ARR_VAL_COMPLETED:
4554
+ return `${json},"~~"`;
4555
+ }
4556
+
4557
+ return json;
4558
+ }
4559
+
4560
+ function _maybeFixIncompleteArrValue(json) {
4561
+ const pos = _findLastArrayDelimiter(json);
4562
+
4563
+ if (pos > -1) {
4564
+ const part = json.slice(pos + 1);
4565
+
4566
+ if (ALLOWED_PRIMITIVES.includes(part.trim())) {
4567
+ return `${json},"~~"`;
4568
+ }
4569
+
4570
+ // Everything else is replaced with `"~~"`
4571
+ return `${json.slice(0, pos + 1)}"~~"`;
4572
+ }
4573
+
4574
+ // fallback, this shouldn't happen, to be save
4575
+ return json;
4576
+ }
4577
+
4578
+ function _findLastArrayDelimiter(json) {
4579
+ for (let i = json.length - 1; i >= 0; i--) {
4580
+ const char = json[i];
4581
+
4582
+ if (char === ',' || char === '[') {
4583
+ return i;
4584
+ }
4585
+ }
4586
+
4587
+ return -1;
4588
+ }
4589
+
4590
+ function _maybeFixIncompleteObjValue(json) {
4591
+ const startPos = json.lastIndexOf(':');
4592
+
4593
+ const part = json.slice(startPos + 1);
4594
+
4595
+ if (ALLOWED_PRIMITIVES.includes(part.trim())) {
4596
+ return `${json},"~~":"~~"`;
4597
+ }
4598
+
4599
+ // Everything else is replaced with `"~~"`
4600
+ // This also means we do not have incomplete numbers, e.g `[1` is replaced with `["~~"]`
4601
+ return `${json.slice(0, startPos + 1)}"~~"`;
4602
+ }
4603
+
4604
+ /**
4605
+ * Evaluate an (incomplete) JSON string.
4606
+ */
4607
+ function evaluateJson(json) {
4608
+ const stack = [];
4609
+
4610
+ for (let pos = 0; pos < json.length; pos++) {
4611
+ _evaluateJsonPos(stack, json, pos);
4612
+ }
4613
+
4614
+ return stack;
4615
+ }
4616
+
4617
+ function _evaluateJsonPos(stack, json, pos) {
4618
+ const curStep = stack[stack.length - 1];
4619
+
4620
+ const char = json[pos];
4621
+
4622
+ const whitespaceRegex = /\s/;
4623
+
4624
+ if (whitespaceRegex.test(char)) {
4625
+ return;
4626
+ }
4627
+
4628
+ if (char === '"' && !_isEscaped(json, pos)) {
4629
+ _handleQuote(stack, curStep);
4630
+ return;
4631
+ }
4632
+
4633
+ switch (char) {
4634
+ case '{':
4635
+ _handleObj(stack, curStep);
4636
+ break;
4637
+ case '[':
4638
+ _handleArr(stack, curStep);
4639
+ break;
4640
+ case ':':
4641
+ _handleColon(stack, curStep);
4642
+ break;
4643
+ case ',':
4644
+ _handleComma(stack, curStep);
4645
+ break;
4646
+ case '}':
4647
+ _handleObjClose(stack, curStep);
4648
+ break;
4649
+ case ']':
4650
+ _handleArrClose(stack, curStep);
4651
+ break;
4652
+ }
4653
+ }
4654
+
4655
+ function _handleQuote(stack, curStep) {
4656
+ // End of obj value
4657
+ if (curStep === OBJ_VAL_STR) {
4658
+ stack.pop();
4659
+ stack.push(OBJ_VAL_COMPLETED);
4660
+ return;
4661
+ }
4662
+
4663
+ // End of arr value
4664
+ if (curStep === ARR_VAL_STR) {
4665
+ stack.pop();
4666
+ stack.push(ARR_VAL_COMPLETED);
4667
+ return;
4668
+ }
4669
+
4670
+ // Start of obj value
4671
+ if (curStep === OBJ_VAL) {
4672
+ stack.push(OBJ_VAL_STR);
4673
+ return;
4674
+ }
4675
+
4676
+ // Start of arr value
4677
+ if (curStep === ARR_VAL) {
4678
+ stack.push(ARR_VAL_STR);
4679
+ return;
4680
+ }
4681
+
4682
+ // Start of obj key
4683
+ if (curStep === OBJ) {
4684
+ stack.push(OBJ_KEY_STR);
4685
+ return;
4686
+ }
4687
+
4688
+ // End of obj key
4689
+ if (curStep === OBJ_KEY_STR) {
4690
+ stack.pop();
4691
+ stack.push(OBJ_KEY);
4692
+ return;
4693
+ }
4694
+ }
4695
+
4696
+ function _handleObj(stack, curStep) {
4697
+ // Initial object
4698
+ if (!curStep) {
4699
+ stack.push(OBJ);
4700
+ return;
4701
+ }
4702
+
4703
+ // New object as obj value
4704
+ if (curStep === OBJ_VAL) {
4705
+ stack.push(OBJ);
4706
+ return;
4707
+ }
4708
+
4709
+ // New object as array element
4710
+ if (curStep === ARR_VAL) {
4711
+ stack.push(OBJ);
4712
+ }
4713
+
4714
+ // New object as first array element
4715
+ if (curStep === ARR) {
4716
+ stack.push(OBJ);
4717
+ return;
4718
+ }
4719
+ }
4720
+
4721
+ function _handleArr(stack, curStep) {
4722
+ // Initial array
4723
+ if (!curStep) {
4724
+ stack.push(ARR);
4725
+ stack.push(ARR_VAL);
4726
+ return;
4727
+ }
4728
+
4729
+ // New array as obj value
4730
+ if (curStep === OBJ_VAL) {
4731
+ stack.push(ARR);
4732
+ stack.push(ARR_VAL);
4733
+ return;
4734
+ }
4735
+
4736
+ // New array as array element
4737
+ if (curStep === ARR_VAL) {
4738
+ stack.push(ARR);
4739
+ stack.push(ARR_VAL);
4740
+ }
4741
+
4742
+ // New array as first array element
4743
+ if (curStep === ARR) {
4744
+ stack.push(ARR);
4745
+ stack.push(ARR_VAL);
4746
+ return;
4747
+ }
4748
+ }
4749
+
4750
+ function _handleColon(stack, curStep) {
4751
+ if (curStep === OBJ_KEY) {
4752
+ stack.pop();
4753
+ stack.push(OBJ_VAL);
4754
+ }
4755
+ }
4756
+
4757
+ function _handleComma(stack, curStep) {
4758
+ // Comma after obj value
4759
+ if (curStep === OBJ_VAL) {
4760
+ stack.pop();
4761
+ return;
4762
+ }
4763
+ if (curStep === OBJ_VAL_COMPLETED) {
4764
+ // Pop OBJ_VAL_COMPLETED & OBJ_VAL
4765
+ stack.pop();
4766
+ stack.pop();
4767
+ return;
4768
+ }
4769
+
4770
+ // Comma after arr value
4771
+ if (curStep === ARR_VAL) {
4772
+ // do nothing - basically we'd pop ARR_VAL but add it right back
4773
+ return;
4774
+ }
4775
+
4776
+ if (curStep === ARR_VAL_COMPLETED) {
4777
+ // Pop ARR_VAL_COMPLETED
4778
+ stack.pop();
4779
+
4780
+ // basically we'd pop ARR_VAL but add it right back
4781
+ return;
4782
+ }
4783
+ }
4784
+
4785
+ function _handleObjClose(stack, curStep) {
4786
+ // Empty object {}
4787
+ if (curStep === OBJ) {
4788
+ stack.pop();
4789
+ }
4790
+
4791
+ // Object with element
4792
+ if (curStep === OBJ_VAL) {
4793
+ // Pop OBJ_VAL, OBJ
4794
+ stack.pop();
4795
+ stack.pop();
4796
+ }
4797
+
4798
+ // Obj with element
4799
+ if (curStep === OBJ_VAL_COMPLETED) {
4800
+ // Pop OBJ_VAL_COMPLETED, OBJ_VAL, OBJ
4801
+ stack.pop();
4802
+ stack.pop();
4803
+ stack.pop();
4804
+ }
4805
+
4806
+ // if was obj value, complete it
4807
+ if (stack[stack.length - 1] === OBJ_VAL) {
4808
+ stack.push(OBJ_VAL_COMPLETED);
4809
+ }
4810
+
4811
+ // if was arr value, complete it
4812
+ if (stack[stack.length - 1] === ARR_VAL) {
4813
+ stack.push(ARR_VAL_COMPLETED);
4814
+ }
4815
+ }
4816
+
4817
+ function _handleArrClose(stack, curStep) {
4818
+ // Empty array []
4819
+ if (curStep === ARR) {
4820
+ stack.pop();
4821
+ }
4822
+
4823
+ // Array with element
4824
+ if (curStep === ARR_VAL) {
4825
+ // Pop ARR_VAL, ARR
4826
+ stack.pop();
4827
+ stack.pop();
4828
+ }
4829
+
4830
+ // Array with element
4831
+ if (curStep === ARR_VAL_COMPLETED) {
4832
+ // Pop ARR_VAL_COMPLETED, ARR_VAL, ARR
4833
+ stack.pop();
4834
+ stack.pop();
4835
+ stack.pop();
4836
+ }
4837
+
4838
+ // if was obj value, complete it
4839
+ if (stack[stack.length - 1] === OBJ_VAL) {
4840
+ stack.push(OBJ_VAL_COMPLETED);
4841
+ }
4842
+
4843
+ // if was arr value, complete it
4844
+ if (stack[stack.length - 1] === ARR_VAL) {
4845
+ stack.push(ARR_VAL_COMPLETED);
4846
+ }
4847
+ }
4848
+
4849
+ function _isEscaped(str, pos) {
4850
+ const previousChar = str[pos - 1];
4851
+
4852
+ return previousChar === '\\' && !_isEscaped(str, pos - 1);
4853
+ }
4854
+
4855
+ /* eslint-disable max-lines */
4856
+
4857
+ /**
4858
+ * Takes an incomplete JSON string, and returns a hopefully valid JSON string.
4859
+ * Note that this _can_ fail, so you should check the return value is valid JSON.
4860
+ */
4861
+ function fixJson(incompleteJson) {
4862
+ const stack = evaluateJson(incompleteJson);
4863
+
4864
+ return completeJson(incompleteJson, stack);
4865
+ }
4866
+
4477
4867
  /** Get the size of a body. */
4478
4868
  function getBodySize(
4479
4869
  body,
@@ -4567,51 +4957,57 @@ function makeNetworkReplayBreadcrumb(
4567
4957
  return result;
4568
4958
  }
4569
4959
 
4570
- /** Get either a JSON network body, or a text representation. */
4571
- function getNetworkBody(bodyText) {
4572
- if (!bodyText) {
4573
- return;
4574
- }
4575
-
4576
- try {
4577
- return JSON.parse(bodyText);
4578
- } catch (e2) {
4579
- // return text
4580
- }
4581
-
4582
- return bodyText;
4583
- }
4584
-
4585
4960
  /** Build the request or response part of a replay network breadcrumb. */
4586
4961
  function buildNetworkRequestOrResponse(
4962
+ headers,
4587
4963
  bodySize,
4588
4964
  body,
4589
4965
  ) {
4590
- if (!bodySize) {
4966
+ if (!bodySize && Object.keys(headers).length === 0) {
4591
4967
  return undefined;
4592
4968
  }
4593
4969
 
4970
+ if (!bodySize) {
4971
+ return {
4972
+ headers,
4973
+ };
4974
+ }
4975
+
4594
4976
  if (!body) {
4595
4977
  return {
4978
+ headers,
4596
4979
  size: bodySize,
4597
4980
  };
4598
4981
  }
4599
4982
 
4600
4983
  const info = {
4984
+ headers,
4601
4985
  size: bodySize,
4602
4986
  };
4603
4987
 
4604
- if (bodySize < NETWORK_BODY_MAX_SIZE) {
4605
- info.body = body;
4606
- } else {
4988
+ const { body: normalizedBody, warnings } = normalizeNetworkBody(body);
4989
+ info.body = normalizedBody;
4990
+ if (warnings.length > 0) {
4607
4991
  info._meta = {
4608
- errors: ['MAX_BODY_SIZE_EXCEEDED'],
4992
+ warnings,
4609
4993
  };
4610
4994
  }
4611
4995
 
4612
4996
  return info;
4613
4997
  }
4614
4998
 
4999
+ /** Filter a set of headers */
5000
+ function getAllowedHeaders(headers, allowedHeaders) {
5001
+ return Object.keys(headers).reduce((filteredHeaders, key) => {
5002
+ const normalizedKey = key.toLowerCase();
5003
+ // Avoid putting empty strings into the headers
5004
+ if (allowedHeaders.includes(normalizedKey) && headers[key]) {
5005
+ filteredHeaders[normalizedKey] = headers[key];
5006
+ }
5007
+ return filteredHeaders;
5008
+ }, {});
5009
+ }
5010
+
4615
5011
  function _serializeFormData(formData) {
4616
5012
  // This is a bit simplified, but gives us a decent estimate
4617
5013
  // This converts e.g. { name: 'Anne Smith', age: 13 } to 'name=Anne+Smith&age=13'
@@ -4619,6 +5015,48 @@ function _serializeFormData(formData) {
4619
5015
  return new URLSearchParams(formData).toString();
4620
5016
  }
4621
5017
 
5018
+ function normalizeNetworkBody(body)
5019
+
5020
+ {
5021
+ if (!body || typeof body !== 'string') {
5022
+ return {
5023
+ body,
5024
+ warnings: [],
5025
+ };
5026
+ }
5027
+
5028
+ const exceedsSizeLimit = body.length > NETWORK_BODY_MAX_SIZE;
5029
+
5030
+ if (_strIsProbablyJson(body)) {
5031
+ try {
5032
+ const json = exceedsSizeLimit ? fixJson(body.slice(0, NETWORK_BODY_MAX_SIZE)) : body;
5033
+ const normalizedBody = JSON.parse(json);
5034
+ return {
5035
+ body: normalizedBody,
5036
+ warnings: exceedsSizeLimit ? ['JSON_TRUNCATED'] : [],
5037
+ };
5038
+ } catch (e3) {
5039
+ return {
5040
+ body,
5041
+ warnings: ['INVALID_JSON'],
5042
+ };
5043
+ }
5044
+ }
5045
+
5046
+ return {
5047
+ body: exceedsSizeLimit ? `${body.slice(0, NETWORK_BODY_MAX_SIZE)}…` : body,
5048
+ warnings: exceedsSizeLimit ? ['TEXT_TRUNCATED'] : [],
5049
+ };
5050
+ }
5051
+
5052
+ function _strIsProbablyJson(str) {
5053
+ const first = str[0];
5054
+ const last = str[str.length - 1];
5055
+
5056
+ // Simple check: If this does not start & end with {} or [], it's not JSON
5057
+ return (first === '[' && last === ']') || (first === '{' && last === '}');
5058
+ }
5059
+
4622
5060
  /**
4623
5061
  * Capture a fetch breadcrumb to a replay.
4624
5062
  * This adds additional data (where approriate).
@@ -4626,7 +5064,9 @@ function _serializeFormData(formData) {
4626
5064
  async function captureFetchBreadcrumbToReplay(
4627
5065
  breadcrumb,
4628
5066
  hint,
4629
- options,
5067
+ options
5068
+
5069
+ ,
4630
5070
  ) {
4631
5071
  try {
4632
5072
  const data = await _prepareFetchData(breadcrumb, hint, options);
@@ -4653,6 +5093,7 @@ function enrichFetchBreadcrumb(
4653
5093
 
4654
5094
  const body = _getFetchRequestArgBody(input);
4655
5095
  const reqSize = getBodySize(body, options.textEncoder);
5096
+
4656
5097
  const resSize = response ? parseContentLengthHeader(response.headers.get('content-length')) : undefined;
4657
5098
 
4658
5099
  if (reqSize !== undefined) {
@@ -4666,7 +5107,9 @@ function enrichFetchBreadcrumb(
4666
5107
  async function _prepareFetchData(
4667
5108
  breadcrumb,
4668
5109
  hint,
4669
- options,
5110
+ options
5111
+
5112
+ ,
4670
5113
  ) {
4671
5114
  const { startTimestamp, endTimestamp } = hint;
4672
5115
 
@@ -4693,34 +5136,44 @@ async function _prepareFetchData(
4693
5136
  }
4694
5137
 
4695
5138
  function _getRequestInfo(
4696
- { captureBodies },
5139
+ { captureBodies, requestHeaders },
4697
5140
  input,
4698
5141
  requestBodySize,
4699
5142
  ) {
5143
+ const headers = getRequestHeaders(input, requestHeaders);
5144
+
4700
5145
  if (!captureBodies) {
4701
- return buildNetworkRequestOrResponse(requestBodySize, undefined);
5146
+ return buildNetworkRequestOrResponse(headers, requestBodySize, undefined);
4702
5147
  }
4703
5148
 
4704
5149
  // We only want to transmit string or string-like bodies
4705
5150
  const requestBody = _getFetchRequestArgBody(input);
4706
- const body = getNetworkBody(getBodyString(requestBody));
4707
- return buildNetworkRequestOrResponse(requestBodySize, body);
5151
+ const bodyStr = getBodyString(requestBody);
5152
+ return buildNetworkRequestOrResponse(headers, requestBodySize, bodyStr);
4708
5153
  }
4709
5154
 
4710
5155
  async function _getResponseInfo(
4711
- { captureBodies, textEncoder },
5156
+ {
5157
+ captureBodies,
5158
+ textEncoder,
5159
+ responseHeaders,
5160
+ }
5161
+
5162
+ ,
4712
5163
  response,
4713
5164
  responseBodySize,
4714
5165
  ) {
5166
+ const headers = getAllHeaders(response.headers, responseHeaders);
5167
+
4715
5168
  if (!captureBodies && responseBodySize !== undefined) {
4716
- return buildNetworkRequestOrResponse(responseBodySize, undefined);
5169
+ return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);
4717
5170
  }
4718
5171
 
4719
5172
  // Only clone the response if we need to
4720
5173
  try {
4721
5174
  // We have to clone this, as the body can only be read once
4722
5175
  const res = response.clone();
4723
- const { body, bodyText } = await _parseFetchBody(res);
5176
+ const bodyText = await _parseFetchBody(res);
4724
5177
 
4725
5178
  const size =
4726
5179
  bodyText && bodyText.length && responseBodySize === undefined
@@ -4728,35 +5181,22 @@ async function _getResponseInfo(
4728
5181
  : responseBodySize;
4729
5182
 
4730
5183
  if (captureBodies) {
4731
- return buildNetworkRequestOrResponse(size, body);
5184
+ return buildNetworkRequestOrResponse(headers, size, bodyText);
4732
5185
  }
4733
5186
 
4734
- return buildNetworkRequestOrResponse(size, undefined);
5187
+ return buildNetworkRequestOrResponse(headers, size, undefined);
4735
5188
  } catch (e) {
4736
5189
  // fallback
4737
- return buildNetworkRequestOrResponse(responseBodySize, undefined);
5190
+ return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);
4738
5191
  }
4739
5192
  }
4740
5193
 
4741
- async function _parseFetchBody(
4742
- response,
4743
- ) {
4744
- let bodyText;
4745
-
5194
+ async function _parseFetchBody(response) {
4746
5195
  try {
4747
- bodyText = await response.text();
5196
+ return await response.text();
4748
5197
  } catch (e2) {
4749
- return {};
4750
- }
4751
-
4752
- try {
4753
- const body = JSON.parse(bodyText);
4754
- return { body, bodyText };
4755
- } catch (e3) {
4756
- // just send bodyText
5198
+ return undefined;
4757
5199
  }
4758
-
4759
- return { bodyText, body: bodyText };
4760
5200
  }
4761
5201
 
4762
5202
  function _getFetchRequestArgBody(fetchArgs = []) {
@@ -4768,6 +5208,56 @@ function _getFetchRequestArgBody(fetchArgs = []) {
4768
5208
  return (fetchArgs[1] ).body;
4769
5209
  }
4770
5210
 
5211
+ function getAllHeaders(headers, allowedHeaders) {
5212
+ const allHeaders = {};
5213
+
5214
+ allowedHeaders.forEach(header => {
5215
+ if (headers.get(header)) {
5216
+ allHeaders[header] = headers.get(header) ;
5217
+ }
5218
+ });
5219
+
5220
+ return allHeaders;
5221
+ }
5222
+
5223
+ function getRequestHeaders(fetchArgs, allowedHeaders) {
5224
+ if (fetchArgs.length === 1 && typeof fetchArgs[0] !== 'string') {
5225
+ return getHeadersFromOptions(fetchArgs[0] , allowedHeaders);
5226
+ }
5227
+
5228
+ if (fetchArgs.length === 2) {
5229
+ return getHeadersFromOptions(fetchArgs[1] , allowedHeaders);
5230
+ }
5231
+
5232
+ return {};
5233
+ }
5234
+
5235
+ function getHeadersFromOptions(
5236
+ input,
5237
+ allowedHeaders,
5238
+ ) {
5239
+ if (!input) {
5240
+ return {};
5241
+ }
5242
+
5243
+ const headers = input.headers;
5244
+
5245
+ if (!headers) {
5246
+ return {};
5247
+ }
5248
+
5249
+ if (headers instanceof Headers) {
5250
+ return getAllHeaders(headers, allowedHeaders);
5251
+ }
5252
+
5253
+ // We do not support this, as it is not really documented (anymore?)
5254
+ if (Array.isArray(headers)) {
5255
+ return {};
5256
+ }
5257
+
5258
+ return getAllowedHeaders(headers, allowedHeaders);
5259
+ }
5260
+
4771
5261
  /**
4772
5262
  * Capture an XHR breadcrumb to a replay.
4773
5263
  * This adds additional data (where approriate).
@@ -4818,7 +5308,7 @@ function _prepareXhrData(
4818
5308
  hint,
4819
5309
  options,
4820
5310
  ) {
4821
- const { startTimestamp, endTimestamp, input } = hint;
5311
+ const { startTimestamp, endTimestamp, input, xhr } = hint;
4822
5312
 
4823
5313
  const {
4824
5314
  url,
@@ -4828,17 +5318,23 @@ function _prepareXhrData(
4828
5318
  response_body_size: responseBodySize,
4829
5319
  } = breadcrumb.data;
4830
5320
 
5321
+ const xhrInfo = xhr[SENTRY_XHR_DATA_KEY];
5322
+ const requestHeaders = xhrInfo ? getAllowedHeaders(xhrInfo.request_headers, options.requestHeaders) : {};
5323
+ const responseHeaders = getAllowedHeaders(getResponseHeaders(xhr), options.responseHeaders);
5324
+
4831
5325
  if (!url) {
4832
5326
  return null;
4833
5327
  }
4834
5328
 
4835
5329
  const request = buildNetworkRequestOrResponse(
5330
+ requestHeaders,
4836
5331
  requestBodySize,
4837
- options.captureBodies ? getNetworkBody(getBodyString(input)) : undefined,
5332
+ options.captureBodies ? getBodyString(input) : undefined,
4838
5333
  );
4839
5334
  const response = buildNetworkRequestOrResponse(
5335
+ responseHeaders,
4840
5336
  responseBodySize,
4841
- options.captureBodies ? getNetworkBody(hint.xhr.responseText) : undefined,
5337
+ options.captureBodies ? hint.xhr.responseText : undefined,
4842
5338
  );
4843
5339
 
4844
5340
  return {
@@ -4852,6 +5348,20 @@ function _prepareXhrData(
4852
5348
  };
4853
5349
  }
4854
5350
 
5351
+ function getResponseHeaders(xhr) {
5352
+ const headers = xhr.getAllResponseHeaders();
5353
+
5354
+ if (!headers) {
5355
+ return {};
5356
+ }
5357
+
5358
+ return headers.split('\r\n').reduce((acc, line) => {
5359
+ const [key, value] = line.split(': ');
5360
+ acc[key.toLowerCase()] = value;
5361
+ return acc;
5362
+ }, {});
5363
+ }
5364
+
4855
5365
  /**
4856
5366
  * This method does two things:
4857
5367
  * - It enriches the regular XHR/fetch breadcrumbs with request/response size data
@@ -4867,7 +5377,7 @@ function handleNetworkBreadcrumbs(replay) {
4867
5377
  const options = {
4868
5378
  replay,
4869
5379
  textEncoder,
4870
- captureBodies: replay.getOptions()._experiments.captureNetworkBodies || false,
5380
+ ...replay.getExperimentalOptions().network,
4871
5381
  };
4872
5382
 
4873
5383
  if (client && client.on) {
@@ -5472,7 +5982,6 @@ async function sendReplayRequest({
5472
5982
  recordingData,
5473
5983
  replayId,
5474
5984
  segmentId: segment_id,
5475
- includeReplayStartTimestamp,
5476
5985
  eventContext,
5477
5986
  timestamp,
5478
5987
  session,
@@ -5499,7 +6008,7 @@ async function sendReplayRequest({
5499
6008
 
5500
6009
  const baseEvent = {
5501
6010
  type: REPLAY_EVENT_NAME,
5502
- ...(includeReplayStartTimestamp ? { replay_start_timestamp: initialTimestamp / 1000 } : {}),
6011
+ replay_start_timestamp: initialTimestamp / 1000,
5503
6012
  timestamp: timestamp / 1000,
5504
6013
  error_ids: errorIds,
5505
6014
  trace_ids: traceIds,
@@ -5758,6 +6267,8 @@ class ReplayContainer {
5758
6267
  this._debouncedFlush = debounce(() => this._flush(), this._options.flushMinDelay, {
5759
6268
  maxWait: this._options.flushMaxDelay,
5760
6269
  });
6270
+
6271
+ this._experimentalOptions = _getExperimentalOptions(options);
5761
6272
  }
5762
6273
 
5763
6274
  /** Get the event context. */
@@ -5780,6 +6291,15 @@ class ReplayContainer {
5780
6291
  return this._options;
5781
6292
  }
5782
6293
 
6294
+ /**
6295
+ * Get the experimental options.
6296
+ * THIS IS INTERNAL AND SUBJECT TO CHANGE!
6297
+ * @hidden
6298
+ */
6299
+ getExperimentalOptions() {
6300
+ return this._experimentalOptions;
6301
+ }
6302
+
5783
6303
  /**
5784
6304
  * Initializes the plugin.
5785
6305
  *
@@ -6381,7 +6901,6 @@ class ReplayContainer {
6381
6901
  replayId,
6382
6902
  recordingData,
6383
6903
  segmentId,
6384
- includeReplayStartTimestamp: segmentId === 0,
6385
6904
  eventContext,
6386
6905
  session: this.session,
6387
6906
  options: this.getOptions(),
@@ -6489,6 +7008,23 @@ class ReplayContainer {
6489
7008
  };}
6490
7009
  }
6491
7010
 
7011
+ function _getExperimentalOptions(options) {
7012
+ const requestHeaders = options._experiments.captureRequestHeaders || [];
7013
+ const responseHeaders = options._experiments.captureResponseHeaders || [];
7014
+ const captureBodies = options._experiments.captureNetworkBodies || false;
7015
+
7016
+ // Add defaults
7017
+ const defaultHeaders = ['content-length', 'content-type', 'accept'];
7018
+
7019
+ return {
7020
+ network: {
7021
+ captureBodies,
7022
+ requestHeaders: [...defaultHeaders, ...requestHeaders.map(header => header.toLowerCase())],
7023
+ responseHeaders: [...defaultHeaders, ...responseHeaders.map(header => header.toLowerCase())],
7024
+ },
7025
+ };
7026
+ }
7027
+
6492
7028
  function getOption(
6493
7029
  selectors,
6494
7030
  defaultSelectors,
@@ -6800,6 +7336,17 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
6800
7336
  return this._replay.flushImmediate();
6801
7337
  }
6802
7338
 
7339
+ /**
7340
+ * Get the current session ID.
7341
+ */
7342
+ getReplayId() {
7343
+ if (!this._replay || !this._replay.isEnabled()) {
7344
+ return;
7345
+ }
7346
+
7347
+ return this._replay.getSessionId();
7348
+ }
7349
+
6803
7350
  /** Setup the integration. */
6804
7351
  _setup() {
6805
7352
  // Client is not available in constructor, so we need to wait until setupOnce