@sentry/replay 0.5.1 → 0.5.4

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 (56) hide show
  1. package/dist/config/types/jest.config.d.ts +3 -0
  2. package/dist/config/types/jest.setup.d.ts +10 -0
  3. package/dist/config/types/src/api/captureReplay.d.ts +10 -0
  4. package/dist/config/types/src/api/captureReplayUpdate.d.ts +12 -0
  5. package/dist/config/types/src/coreHandlers/getBreadcrumbHandler.d.ts +3 -0
  6. package/dist/config/types/src/coreHandlers/getSpanHandler.d.ts +5 -0
  7. package/dist/config/types/src/coreHandlers/handleDom.d.ts +1 -0
  8. package/dist/config/types/src/coreHandlers/handleFetch.d.ts +19 -0
  9. package/dist/config/types/src/coreHandlers/handleFetch.test.d.ts +1 -0
  10. package/dist/config/types/src/coreHandlers/handleHistory.d.ts +7 -0
  11. package/dist/config/types/src/coreHandlers/handleScope-unit.test.d.ts +1 -0
  12. package/dist/config/types/src/coreHandlers/handleScope.d.ts +2 -0
  13. package/dist/config/types/src/coreHandlers/handleScope.test.d.ts +1 -0
  14. package/dist/config/types/src/coreHandlers/handleXhr.d.ts +21 -0
  15. package/dist/config/types/src/createPerformanceEntry.d.ts +42 -0
  16. package/dist/config/types/src/createPerformanceEntry.test.d.ts +1 -0
  17. package/dist/config/types/src/eventBuffer.d.ts +45 -0
  18. package/dist/config/types/src/eventBuffer.test.d.ts +1 -0
  19. package/dist/config/types/src/flags.d.ts +2 -0
  20. package/dist/config/types/src/index-captureOnlyOnError.test.d.ts +1 -0
  21. package/dist/config/types/src/index-noSticky.test.d.ts +1 -0
  22. package/dist/config/types/src/index-sampling.test.d.ts +1 -0
  23. package/dist/config/types/src/index.d.ts +234 -0
  24. package/dist/config/types/src/index.test.d.ts +1 -0
  25. package/dist/config/types/src/session/Session.d.ts +63 -0
  26. package/dist/config/types/src/session/Session.test.d.ts +1 -0
  27. package/dist/config/types/src/session/constants.d.ts +5 -0
  28. package/dist/config/types/src/session/createSession.d.ts +19 -0
  29. package/dist/config/types/src/session/createSession.test.d.ts +1 -0
  30. package/dist/config/types/src/session/fetchSession.d.ts +5 -0
  31. package/dist/config/types/src/session/fetchSession.test.d.ts +1 -0
  32. package/dist/config/types/src/session/getSession.d.ts +28 -0
  33. package/dist/config/types/src/session/getSession.test.d.ts +1 -0
  34. package/dist/config/types/src/session/index.d.ts +1 -0
  35. package/dist/config/types/src/session/saveSession.d.ts +2 -0
  36. package/dist/config/types/src/session/saveSession.test.d.ts +1 -0
  37. package/dist/config/types/src/types.d.ts +91 -0
  38. package/dist/config/types/src/util/createBreadcrumb.d.ts +4 -0
  39. package/dist/config/types/src/util/createPayload.d.ts +5 -0
  40. package/dist/config/types/src/util/isExpired.d.ts +5 -0
  41. package/dist/config/types/src/util/isExpired.test.d.ts +1 -0
  42. package/dist/config/types/src/util/isIngestHost.d.ts +4 -0
  43. package/dist/config/types/src/util/isSampled.d.ts +7 -0
  44. package/dist/config/types/src/util/isSampled.test.d.ts +1 -0
  45. package/dist/config/types/src/util/isSessionExpired.d.ts +5 -0
  46. package/dist/config/types/src/util/isSessionExpired.test.d.ts +1 -0
  47. package/dist/config/types/src/util/logger.d.ts +12 -0
  48. package/dist/{types → config/types}/src/util/supportsSendBeacon.d.ts +0 -0
  49. package/dist/config/types/test/index.d.ts +3 -0
  50. package/dist/config/types/test/mocks/mockRrweb.d.ts +15 -0
  51. package/dist/config/types/test/mocks/mockSdk.d.ts +11 -0
  52. package/dist/index.es.js +58 -36
  53. package/dist/index.js +57 -35
  54. package/dist/index.js.map +1 -1
  55. package/dist/types/src/index.d.ts +13 -3
  56. package/package.json +2 -1
@@ -0,0 +1,91 @@
1
+ import { record } from 'rrweb';
2
+ import type { eventWithTime } from 'rrweb/typings/types';
3
+ export declare type RecordingEvent = eventWithTime;
4
+ export declare type RecordingConfig = Parameters<typeof record>[0];
5
+ export declare type RecordedEvents = Uint8Array | string;
6
+ export interface ReplayRequest {
7
+ endpoint: string;
8
+ events: RecordedEvents;
9
+ }
10
+ export declare type InstrumentationTypeBreadcrumb = 'dom' | 'scope';
11
+ export declare type InstrumentationTypeSpan = 'fetch' | 'xhr' | 'history';
12
+ export declare type InstrumentationType = InstrumentationTypeBreadcrumb | InstrumentationTypeSpan | 'console' | 'error' | 'unhandledrejection';
13
+ /**
14
+ * The request payload to worker
15
+ */
16
+ export interface WorkerRequest {
17
+ id: number;
18
+ method: string;
19
+ args: any[];
20
+ }
21
+ /**
22
+ * The response from the worker
23
+ */
24
+ export interface WorkerResponse {
25
+ id: number;
26
+ method: string;
27
+ success: boolean;
28
+ response: string | Uint8Array;
29
+ }
30
+ export interface SentryReplayPluginOptions {
31
+ /**
32
+ * The amount of time to wait before sending a replay
33
+ */
34
+ flushMinDelay?: number;
35
+ /**
36
+ * The max amount of time to wait before sending a replay
37
+ */
38
+ flushMaxDelay?: number;
39
+ /**
40
+ * The amount of time to buffer the initial snapshot
41
+ */
42
+ initialFlushDelay?: number;
43
+ /**
44
+ * If false, will create a new session per pageload
45
+ */
46
+ stickySession?: boolean;
47
+ /**
48
+ * Attempt to use compression when web workers are available
49
+ *
50
+ * (default is true)
51
+ */
52
+ useCompression?: boolean;
53
+ /**
54
+ * Only capture replays when an error happens
55
+ */
56
+ captureOnlyOnError?: boolean;
57
+ /**
58
+ * The sampling rate for replays. 1.0 will record all replays, 0 will record none.
59
+ */
60
+ replaysSamplingRate?: number;
61
+ }
62
+ export interface SentryReplayConfiguration extends SentryReplayPluginOptions {
63
+ /**
64
+ * Options for `rrweb.record()`
65
+ */
66
+ recordingConfig?: RecordingConfig;
67
+ }
68
+ /**
69
+ * Some initial state captured before creating a root replay event
70
+ */
71
+ export interface InitialState {
72
+ timestamp: number;
73
+ url: string;
74
+ }
75
+ /**
76
+ * Additional context that will be sent w/ `replay_event`
77
+ */
78
+ export interface ReplayEventContext {
79
+ /**
80
+ * Set of Sentry error ids that have occurred during a replay segment
81
+ */
82
+ errorIds: Set<string>;
83
+ /**
84
+ * Set of Sentry trace ids that have occurred during a replay segment
85
+ */
86
+ traceIds: Set<string>;
87
+ /**
88
+ * Ordered list of URLs that have been visited during a replay segment
89
+ */
90
+ urls: string[];
91
+ }
@@ -0,0 +1,4 @@
1
+ import type { Breadcrumb } from '@sentry/types';
2
+ declare type RequiredProperties = 'category' | 'message';
3
+ export default function createBreadcrumb(breadcrumb: Pick<Breadcrumb, RequiredProperties> & Partial<Omit<Breadcrumb, RequiredProperties>>): Breadcrumb;
4
+ export {};
@@ -0,0 +1,5 @@
1
+ import { RecordedEvents } from '@/types';
2
+ export declare function createPayload({ events, headers, }: {
3
+ events: RecordedEvents;
4
+ headers: Record<string, any>;
5
+ }): string | Uint8Array;
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Given an initial timestamp and an expiry duration, checks to see if current
3
+ * time should be considered as expired.
4
+ */
5
+ export declare function isExpired(initialTime: number, expiry: number, targetTime?: number): boolean;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Checks is `targetHost` is a Sentry ingestion host
3
+ */
4
+ export declare function isIngestHost(targetHost: string): boolean;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Given a sample rate, returns true if replay should be sampled.
3
+ *
4
+ * 1.0 = 100% sampling
5
+ * 0.0 = 0% sampling
6
+ */
7
+ export declare function isSampled(sampleRate: number): boolean;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,5 @@
1
+ import { Session } from '@/session/Session';
2
+ /**
3
+ * Checks to see if session is expired
4
+ */
5
+ export declare function isSessionExpired(session: Session, expiry: number, targetTime?: number): boolean;
@@ -0,0 +1,12 @@
1
+ declare const logger: {
2
+ error: (...args: any[]) => any;
3
+ warn: (...args: any[]) => any;
4
+ log: (...args: any[]) => any;
5
+ disable(): void;
6
+ enable(): void;
7
+ info: (...args: unknown[]) => void;
8
+ debug: (...args: unknown[]) => void;
9
+ assert: (...args: unknown[]) => void;
10
+ trace: (...args: unknown[]) => void;
11
+ };
12
+ export { logger };
@@ -0,0 +1,3 @@
1
+ export * from './mocks/mockRrweb';
2
+ export * from './mocks/mockSdk';
3
+ export declare const BASE_TIMESTAMP: number;
@@ -0,0 +1,15 @@
1
+ /// <reference types="jest" />
2
+ import { RecordingEvent } from '@/types';
3
+ declare type RecordAdditionalProperties = {
4
+ takeFullSnapshot: jest.Mock;
5
+ addCustomEvent: () => void;
6
+ freezePage: () => void;
7
+ mirror: unknown;
8
+ _emitter: (event: RecordingEvent, ...args: any[]) => void;
9
+ };
10
+ export declare type RecordMock = jest.MockedFunction<typeof rrweb.record> & RecordAdditionalProperties;
11
+ import * as rrweb from 'rrweb';
12
+ export declare function mockRrweb(): {
13
+ record: RecordMock;
14
+ };
15
+ export {};
@@ -0,0 +1,11 @@
1
+ import { BrowserOptions } from '@sentry/browser';
2
+ import { SentryReplay } from '@';
3
+ import { SentryReplayConfiguration } from '@/types';
4
+ interface MockSdkParams {
5
+ replayOptions?: SentryReplayConfiguration;
6
+ sentryOptions?: BrowserOptions;
7
+ }
8
+ export declare function mockSdk({ replayOptions, sentryOptions, }?: MockSdkParams): {
9
+ replay: SentryReplay;
10
+ };
11
+ export {};
package/dist/index.es.js CHANGED
@@ -1,4 +1,4 @@
1
- import { captureEvent, getCurrentHub, captureException, addGlobalEventProcessor, getEnvelopeEndpointWithUrlEncodedAuth } from '@sentry/core';
1
+ import { captureEvent, getCurrentHub, captureException, addGlobalEventProcessor, setContext, getEnvelopeEndpointWithUrlEncodedAuth } from '@sentry/core';
2
2
  import { htmlTreeAsString, logger as logger$1, uuid4, addInstrumentationHandler, createEnvelope, serializeEnvelope } from '@sentry/utils';
3
3
  import { record, EventType } from 'rrweb';
4
4
 
@@ -483,13 +483,6 @@ function createPayload(_a) {
483
483
  return payloadWithSequence;
484
484
  }
485
485
 
486
- /**
487
- * Determine if there is browser support for `navigator.sendBeacon`
488
- */
489
- function supportsSendBeacon() {
490
- return 'navigator' in window && 'sendBeacon' in window.navigator;
491
- }
492
-
493
486
  var _a;
494
487
  // Map entryType -> function to normalize data for event
495
488
  var ENTRY_TYPES = (_a = {
@@ -771,6 +764,7 @@ var EventBufferCompressionWorker = /** @class */ (function () {
771
764
 
772
765
  var BASE_RETRY_INTERVAL = 5000;
773
766
  var MAX_RETRY_COUNT = 5;
767
+ var UNABLE_TO_SEND_REPLAY = 'Unable to send replay';
774
768
  var SentryReplay = /** @class */ (function () {
775
769
  function SentryReplay(_a) {
776
770
  if (_a === void 0) { _a = {}; }
@@ -835,7 +829,10 @@ var SentryReplay = /** @class */ (function () {
835
829
  // XXX: Is it safe to assume that all other events are error events?
836
830
  _this.context.errorIds.add(event.event_id);
837
831
  // Need to be very careful that this does not cause an infinite loop
838
- if (_this.options.captureOnlyOnError && event.exception) {
832
+ if (_this.options.captureOnlyOnError &&
833
+ event.exception &&
834
+ event.message !== UNABLE_TO_SEND_REPLAY // ignore this error because other we could loop indefinitely with trying to capture replay and failing
835
+ ) {
839
836
  // TODO: Do we continue to record after?
840
837
  // TODO: What happens if another error happens? Do we record in the same session?
841
838
  setTimeout(function () { return _this.flushUpdate(); });
@@ -856,7 +853,7 @@ var SentryReplay = /** @class */ (function () {
856
853
  _this.addUpdate(function () {
857
854
  // We need to clear existing events on a checkout, otherwise they are
858
855
  // incremental event updates and should be appended
859
- _this.eventBuffer.addEvent(event, isCheckout);
856
+ _this.addEvent(event, isCheckout);
860
857
  // Different behavior for full snapshots (type=2), ignore other event types
861
858
  // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16
862
859
  if (event.type !== 2) {
@@ -956,7 +953,7 @@ var SentryReplay = /** @class */ (function () {
956
953
  return;
957
954
  }
958
955
  _this.addUpdate(function () {
959
- _this.eventBuffer.addEvent({
956
+ _this.addEvent({
960
957
  type: EventType.Custom,
961
958
  // TODO: We were converting from ms to seconds for breadcrumbs, spans,
962
959
  // but maybe we should just keep them as milliseconds
@@ -1030,15 +1027,6 @@ var SentryReplay = /** @class */ (function () {
1030
1027
  // replay ID so that we can reference them later in the UI
1031
1028
  addGlobalEventProcessor(this.handleGlobalEvent);
1032
1029
  record(__assign(__assign({}, this.recordingOptions), { emit: this.handleRecordingEmit }));
1033
- var urlPath = "".concat(window.location.pathname).concat(window.location.hash).concat(window.location.search);
1034
- var url = "".concat(window.location.origin).concat(urlPath);
1035
- // Otherwise, these will be captured after the first flush, which means the
1036
- // URL and timestamps could be incorrect
1037
- this.initialState = {
1038
- timestamp: new Date().getTime(),
1039
- url: url,
1040
- };
1041
- this.context.urls.push(url);
1042
1030
  };
1043
1031
  /**
1044
1032
  * We want to batch uploads of replay events. Save events only if
@@ -1116,12 +1104,29 @@ var SentryReplay = /** @class */ (function () {
1116
1104
  // enable flag to create the root replay
1117
1105
  if (type === 'new') {
1118
1106
  this.needsCaptureReplay = true;
1107
+ this.setInitialState();
1119
1108
  }
1120
1109
  if (session.id !== ((_b = this.session) === null || _b === void 0 ? void 0 : _b.id)) {
1121
1110
  session.previousSessionId = (_c = this.session) === null || _c === void 0 ? void 0 : _c.id;
1122
1111
  }
1123
1112
  this.session = session;
1124
1113
  };
1114
+ /**
1115
+ * Capture some initial state that can change throughout the lifespan of the
1116
+ * replay. This is required because otherwise they would be captured at the
1117
+ * first flush.
1118
+ */
1119
+ SentryReplay.prototype.setInitialState = function () {
1120
+ var urlPath = "".concat(window.location.pathname).concat(window.location.hash).concat(window.location.search);
1121
+ var url = "".concat(window.location.origin).concat(urlPath);
1122
+ // Reset context as well
1123
+ this.popEventContext();
1124
+ this.initialState = {
1125
+ timestamp: new Date().getTime(),
1126
+ url: url,
1127
+ };
1128
+ this.context.urls.push(url);
1129
+ };
1125
1130
  /**
1126
1131
  * Adds listeners to record events for the replay
1127
1132
  */
@@ -1224,6 +1229,12 @@ var SentryReplay = /** @class */ (function () {
1224
1229
  logger.log('Taking full rrweb snapshot');
1225
1230
  record.takeFullSnapshot(true);
1226
1231
  };
1232
+ /**
1233
+ * Add an event to the event buffer
1234
+ */
1235
+ SentryReplay.prototype.addEvent = function (event, isCheckout) {
1236
+ this.eventBuffer.addEvent(event, isCheckout);
1237
+ };
1227
1238
  /**
1228
1239
  * Updates the session's last activity timestamp
1229
1240
  */
@@ -1237,7 +1248,7 @@ var SentryReplay = /** @class */ (function () {
1237
1248
  SentryReplay.prototype.createCustomBreadcrumb = function (breadcrumb) {
1238
1249
  var _this = this;
1239
1250
  this.addUpdate(function () {
1240
- _this.eventBuffer.addEvent({
1251
+ _this.addEvent({
1241
1252
  type: EventType.Custom,
1242
1253
  timestamp: breadcrumb.timestamp,
1243
1254
  data: {
@@ -1254,7 +1265,7 @@ var SentryReplay = /** @class */ (function () {
1254
1265
  var _this = this;
1255
1266
  return Promise.all(entries.map(function (_a) {
1256
1267
  var type = _a.type, start = _a.start, end = _a.end, name = _a.name, data = _a.data;
1257
- return _this.eventBuffer.addEvent({
1268
+ return _this.addEvent({
1258
1269
  type: EventType.Custom,
1259
1270
  timestamp: start,
1260
1271
  data: {
@@ -1331,7 +1342,7 @@ var SentryReplay = /** @class */ (function () {
1331
1342
  * Return and clear context
1332
1343
  */
1333
1344
  SentryReplay.prototype.popEventContext = function (_a) {
1334
- var timestamp = _a.timestamp;
1345
+ var _b = _a === void 0 ? {} : _a, timestamp = _b.timestamp;
1335
1346
  var context = {
1336
1347
  session: this.session,
1337
1348
  initialState: this.initialState,
@@ -1416,14 +1427,15 @@ var SentryReplay = /** @class */ (function () {
1416
1427
  });
1417
1428
  };
1418
1429
  /**
1419
- * Send replay attachment using either `sendBeacon()` or `fetch()`
1430
+ * Send replay attachment using `fetch()`
1420
1431
  */
1421
1432
  SentryReplay.prototype.sendReplayRequest = function (_a) {
1422
1433
  var endpoint = _a.endpoint, events = _a.events;
1423
1434
  return __awaiter(this, void 0, void 0, function () {
1424
- var payloadWithSequence, envelope;
1425
- return __generator(this, function (_b) {
1426
- switch (_b.label) {
1435
+ var payloadWithSequence, envelope, response, _b, _c;
1436
+ var _d;
1437
+ return __generator(this, function (_e) {
1438
+ switch (_e.label) {
1427
1439
  case 0:
1428
1440
  payloadWithSequence = createPayload({
1429
1441
  events: events,
@@ -1445,12 +1457,6 @@ var SentryReplay = /** @class */ (function () {
1445
1457
  payloadWithSequence,
1446
1458
  ],
1447
1459
  ]);
1448
- // If sendBeacon is supported and payload is smol enough...
1449
- if (supportsSendBeacon() && events.length <= 65536) {
1450
- logger.log("uploading attachment via sendBeacon()");
1451
- window.navigator.sendBeacon(endpoint, serializeEnvelope(envelope));
1452
- return [2 /*return*/];
1453
- }
1454
1460
  // Otherwise use `fetch`, which *WILL* get cancelled on page reloads/unloads
1455
1461
  logger.log("uploading attachment via fetch()");
1456
1462
  return [4 /*yield*/, fetch(endpoint, {
@@ -1458,8 +1464,19 @@ var SentryReplay = /** @class */ (function () {
1458
1464
  body: serializeEnvelope(envelope),
1459
1465
  })];
1460
1466
  case 1:
1461
- _b.sent();
1462
- return [2 /*return*/];
1467
+ response = _e.sent();
1468
+ if (!(response.status !== 200)) return [3 /*break*/, 3];
1469
+ _b = setContext;
1470
+ _c = ['Send Replay Response'];
1471
+ _d = {
1472
+ status: response.status
1473
+ };
1474
+ return [4 /*yield*/, response.text()];
1475
+ case 2:
1476
+ _b.apply(void 0, _c.concat([(_d.body = _e.sent(),
1477
+ _d)]));
1478
+ throw new Error(UNABLE_TO_SEND_REPLAY);
1479
+ case 3: return [2 /*return*/];
1463
1480
  }
1464
1481
  });
1465
1482
  });
@@ -1497,8 +1514,13 @@ var SentryReplay = /** @class */ (function () {
1497
1514
  return [2 /*return*/, true];
1498
1515
  case 3:
1499
1516
  ex_1 = _b.sent();
1500
- // we have to catch this otherwise it throws an infinite loop in Sentry
1501
1517
  console.error(ex_1);
1518
+ // Capture error for every failed replay
1519
+ // TODO: Remove this before GA as this will create an error on customer's project
1520
+ setContext('Replays', {
1521
+ retryCount: this.retryCount,
1522
+ });
1523
+ captureException(new Error(UNABLE_TO_SEND_REPLAY));
1502
1524
  // If an error happened here, it's likely that uploading the attachment
1503
1525
  // failed, we'll can retry with the same events payload
1504
1526
  if (this.retryCount >= MAX_RETRY_COUNT) {
package/dist/index.js CHANGED
@@ -487,13 +487,6 @@ function createPayload(_a) {
487
487
  return payloadWithSequence;
488
488
  }
489
489
 
490
- /**
491
- * Determine if there is browser support for `navigator.sendBeacon`
492
- */
493
- function supportsSendBeacon() {
494
- return 'navigator' in window && 'sendBeacon' in window.navigator;
495
- }
496
-
497
490
  var _a;
498
491
  // Map entryType -> function to normalize data for event
499
492
  var ENTRY_TYPES = (_a = {
@@ -775,6 +768,7 @@ var EventBufferCompressionWorker = /** @class */ (function () {
775
768
 
776
769
  var BASE_RETRY_INTERVAL = 5000;
777
770
  var MAX_RETRY_COUNT = 5;
771
+ var UNABLE_TO_SEND_REPLAY = 'Unable to send replay';
778
772
  var SentryReplay = /** @class */ (function () {
779
773
  function SentryReplay(_a) {
780
774
  if (_a === void 0) { _a = {}; }
@@ -839,7 +833,10 @@ var SentryReplay = /** @class */ (function () {
839
833
  // XXX: Is it safe to assume that all other events are error events?
840
834
  _this.context.errorIds.add(event.event_id);
841
835
  // Need to be very careful that this does not cause an infinite loop
842
- if (_this.options.captureOnlyOnError && event.exception) {
836
+ if (_this.options.captureOnlyOnError &&
837
+ event.exception &&
838
+ event.message !== UNABLE_TO_SEND_REPLAY // ignore this error because other we could loop indefinitely with trying to capture replay and failing
839
+ ) {
843
840
  // TODO: Do we continue to record after?
844
841
  // TODO: What happens if another error happens? Do we record in the same session?
845
842
  setTimeout(function () { return _this.flushUpdate(); });
@@ -860,7 +857,7 @@ var SentryReplay = /** @class */ (function () {
860
857
  _this.addUpdate(function () {
861
858
  // We need to clear existing events on a checkout, otherwise they are
862
859
  // incremental event updates and should be appended
863
- _this.eventBuffer.addEvent(event, isCheckout);
860
+ _this.addEvent(event, isCheckout);
864
861
  // Different behavior for full snapshots (type=2), ignore other event types
865
862
  // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16
866
863
  if (event.type !== 2) {
@@ -960,7 +957,7 @@ var SentryReplay = /** @class */ (function () {
960
957
  return;
961
958
  }
962
959
  _this.addUpdate(function () {
963
- _this.eventBuffer.addEvent({
960
+ _this.addEvent({
964
961
  type: rrweb.EventType.Custom,
965
962
  // TODO: We were converting from ms to seconds for breadcrumbs, spans,
966
963
  // but maybe we should just keep them as milliseconds
@@ -1034,15 +1031,6 @@ var SentryReplay = /** @class */ (function () {
1034
1031
  // replay ID so that we can reference them later in the UI
1035
1032
  core.addGlobalEventProcessor(this.handleGlobalEvent);
1036
1033
  rrweb.record(__assign(__assign({}, this.recordingOptions), { emit: this.handleRecordingEmit }));
1037
- var urlPath = "".concat(window.location.pathname).concat(window.location.hash).concat(window.location.search);
1038
- var url = "".concat(window.location.origin).concat(urlPath);
1039
- // Otherwise, these will be captured after the first flush, which means the
1040
- // URL and timestamps could be incorrect
1041
- this.initialState = {
1042
- timestamp: new Date().getTime(),
1043
- url: url,
1044
- };
1045
- this.context.urls.push(url);
1046
1034
  };
1047
1035
  /**
1048
1036
  * We want to batch uploads of replay events. Save events only if
@@ -1120,12 +1108,29 @@ var SentryReplay = /** @class */ (function () {
1120
1108
  // enable flag to create the root replay
1121
1109
  if (type === 'new') {
1122
1110
  this.needsCaptureReplay = true;
1111
+ this.setInitialState();
1123
1112
  }
1124
1113
  if (session.id !== ((_b = this.session) === null || _b === void 0 ? void 0 : _b.id)) {
1125
1114
  session.previousSessionId = (_c = this.session) === null || _c === void 0 ? void 0 : _c.id;
1126
1115
  }
1127
1116
  this.session = session;
1128
1117
  };
1118
+ /**
1119
+ * Capture some initial state that can change throughout the lifespan of the
1120
+ * replay. This is required because otherwise they would be captured at the
1121
+ * first flush.
1122
+ */
1123
+ SentryReplay.prototype.setInitialState = function () {
1124
+ var urlPath = "".concat(window.location.pathname).concat(window.location.hash).concat(window.location.search);
1125
+ var url = "".concat(window.location.origin).concat(urlPath);
1126
+ // Reset context as well
1127
+ this.popEventContext();
1128
+ this.initialState = {
1129
+ timestamp: new Date().getTime(),
1130
+ url: url,
1131
+ };
1132
+ this.context.urls.push(url);
1133
+ };
1129
1134
  /**
1130
1135
  * Adds listeners to record events for the replay
1131
1136
  */
@@ -1228,6 +1233,12 @@ var SentryReplay = /** @class */ (function () {
1228
1233
  logger.log('Taking full rrweb snapshot');
1229
1234
  rrweb.record.takeFullSnapshot(true);
1230
1235
  };
1236
+ /**
1237
+ * Add an event to the event buffer
1238
+ */
1239
+ SentryReplay.prototype.addEvent = function (event, isCheckout) {
1240
+ this.eventBuffer.addEvent(event, isCheckout);
1241
+ };
1231
1242
  /**
1232
1243
  * Updates the session's last activity timestamp
1233
1244
  */
@@ -1241,7 +1252,7 @@ var SentryReplay = /** @class */ (function () {
1241
1252
  SentryReplay.prototype.createCustomBreadcrumb = function (breadcrumb) {
1242
1253
  var _this = this;
1243
1254
  this.addUpdate(function () {
1244
- _this.eventBuffer.addEvent({
1255
+ _this.addEvent({
1245
1256
  type: rrweb.EventType.Custom,
1246
1257
  timestamp: breadcrumb.timestamp,
1247
1258
  data: {
@@ -1258,7 +1269,7 @@ var SentryReplay = /** @class */ (function () {
1258
1269
  var _this = this;
1259
1270
  return Promise.all(entries.map(function (_a) {
1260
1271
  var type = _a.type, start = _a.start, end = _a.end, name = _a.name, data = _a.data;
1261
- return _this.eventBuffer.addEvent({
1272
+ return _this.addEvent({
1262
1273
  type: rrweb.EventType.Custom,
1263
1274
  timestamp: start,
1264
1275
  data: {
@@ -1335,7 +1346,7 @@ var SentryReplay = /** @class */ (function () {
1335
1346
  * Return and clear context
1336
1347
  */
1337
1348
  SentryReplay.prototype.popEventContext = function (_a) {
1338
- var timestamp = _a.timestamp;
1349
+ var _b = _a === void 0 ? {} : _a, timestamp = _b.timestamp;
1339
1350
  var context = {
1340
1351
  session: this.session,
1341
1352
  initialState: this.initialState,
@@ -1420,14 +1431,15 @@ var SentryReplay = /** @class */ (function () {
1420
1431
  });
1421
1432
  };
1422
1433
  /**
1423
- * Send replay attachment using either `sendBeacon()` or `fetch()`
1434
+ * Send replay attachment using `fetch()`
1424
1435
  */
1425
1436
  SentryReplay.prototype.sendReplayRequest = function (_a) {
1426
1437
  var endpoint = _a.endpoint, events = _a.events;
1427
1438
  return __awaiter(this, void 0, void 0, function () {
1428
- var payloadWithSequence, envelope;
1429
- return __generator(this, function (_b) {
1430
- switch (_b.label) {
1439
+ var payloadWithSequence, envelope, response, _b, _c;
1440
+ var _d;
1441
+ return __generator(this, function (_e) {
1442
+ switch (_e.label) {
1431
1443
  case 0:
1432
1444
  payloadWithSequence = createPayload({
1433
1445
  events: events,
@@ -1449,12 +1461,6 @@ var SentryReplay = /** @class */ (function () {
1449
1461
  payloadWithSequence,
1450
1462
  ],
1451
1463
  ]);
1452
- // If sendBeacon is supported and payload is smol enough...
1453
- if (supportsSendBeacon() && events.length <= 65536) {
1454
- logger.log("uploading attachment via sendBeacon()");
1455
- window.navigator.sendBeacon(endpoint, utils.serializeEnvelope(envelope));
1456
- return [2 /*return*/];
1457
- }
1458
1464
  // Otherwise use `fetch`, which *WILL* get cancelled on page reloads/unloads
1459
1465
  logger.log("uploading attachment via fetch()");
1460
1466
  return [4 /*yield*/, fetch(endpoint, {
@@ -1462,8 +1468,19 @@ var SentryReplay = /** @class */ (function () {
1462
1468
  body: utils.serializeEnvelope(envelope),
1463
1469
  })];
1464
1470
  case 1:
1465
- _b.sent();
1466
- return [2 /*return*/];
1471
+ response = _e.sent();
1472
+ if (!(response.status !== 200)) return [3 /*break*/, 3];
1473
+ _b = core.setContext;
1474
+ _c = ['Send Replay Response'];
1475
+ _d = {
1476
+ status: response.status
1477
+ };
1478
+ return [4 /*yield*/, response.text()];
1479
+ case 2:
1480
+ _b.apply(void 0, _c.concat([(_d.body = _e.sent(),
1481
+ _d)]));
1482
+ throw new Error(UNABLE_TO_SEND_REPLAY);
1483
+ case 3: return [2 /*return*/];
1467
1484
  }
1468
1485
  });
1469
1486
  });
@@ -1501,8 +1518,13 @@ var SentryReplay = /** @class */ (function () {
1501
1518
  return [2 /*return*/, true];
1502
1519
  case 3:
1503
1520
  ex_1 = _b.sent();
1504
- // we have to catch this otherwise it throws an infinite loop in Sentry
1505
1521
  console.error(ex_1);
1522
+ // Capture error for every failed replay
1523
+ // TODO: Remove this before GA as this will create an error on customer's project
1524
+ core.setContext('Replays', {
1525
+ retryCount: this.retryCount,
1526
+ });
1527
+ core.captureException(new Error(UNABLE_TO_SEND_REPLAY));
1506
1528
  // If an error happened here, it's likely that uploading the attachment
1507
1529
  // failed, we'll can retry with the same events payload
1508
1530
  if (this.retryCount >= MAX_RETRY_COUNT) {