@sentry/replay 0.4.8-3 → 0.5.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 (30) hide show
  1. package/README.md +15 -15
  2. package/dist/config/dist/src/api/captureReplay.d.ts +5 -3
  3. package/dist/config/dist/src/api/captureReplayUpdate.d.ts +5 -3
  4. package/dist/config/dist/src/coreHandlers/getBreadcrumbHandler.d.ts +3 -0
  5. package/dist/config/dist/src/coreHandlers/getSpanHandler.d.ts +5 -0
  6. package/dist/config/dist/src/coreHandlers/handleFetch.d.ts +19 -2
  7. package/dist/config/dist/src/coreHandlers/handleHistory.d.ts +7 -0
  8. package/dist/config/dist/src/coreHandlers/handleXhr.d.ts +21 -2
  9. package/dist/config/dist/src/eventBuffer.d.ts +11 -4
  10. package/dist/config/dist/src/index.d.ts +28 -13
  11. package/dist/config/dist/src/session/constants.d.ts +2 -2
  12. package/dist/config/dist/src/types.d.ts +22 -9
  13. package/dist/config/dist/src/util/createPayload.d.ts +5 -0
  14. package/dist/dist/api/captureReplay.d.ts +5 -3
  15. package/dist/dist/api/captureReplayUpdate.d.ts +5 -3
  16. package/dist/dist/coreHandlers/getBreadcrumbHandler.d.ts +3 -0
  17. package/dist/dist/coreHandlers/getSpanHandler.d.ts +5 -0
  18. package/dist/dist/coreHandlers/handleFetch.d.ts +19 -2
  19. package/dist/dist/coreHandlers/handleHistory.d.ts +7 -0
  20. package/dist/dist/coreHandlers/handleXhr.d.ts +21 -2
  21. package/dist/dist/eventBuffer.d.ts +11 -4
  22. package/dist/dist/index.d.ts +28 -13
  23. package/dist/dist/session/constants.d.ts +2 -2
  24. package/dist/dist/types.d.ts +22 -9
  25. package/dist/dist/util/createPayload.d.ts +5 -0
  26. package/dist/index.es.js +379 -222
  27. package/dist/index.js +377 -220
  28. package/dist/index.js.map +1 -1
  29. package/package.json +2 -2
  30. package/dist/dist/coreHandlers/index.d.ts +0 -4
package/dist/index.js CHANGED
@@ -93,34 +93,177 @@ function __spreadArray(to, from, pack) {
93
93
  }
94
94
 
95
95
  var REPLAY_SESSION_KEY = 'sentryReplaySession';
96
- var ROOT_REPLAY_NAME = 'sentry-replay';
97
- var REPLAY_EVENT_NAME = 'sentry-replay-event';
96
+ var REPLAY_EVENT_NAME = 'replay_event';
98
97
  // The idle limit for a session
99
98
  var SESSION_IDLE_DURATION = 900000; // 15 minutes
100
99
  // Grace period to keep a session when a user changes tabs or hides window
101
100
  var VISIBILITY_CHANGE_TIMEOUT = SESSION_IDLE_DURATION;
102
101
 
103
102
  function captureReplay(_a) {
104
- var session = _a.session, initialState = _a.initialState;
103
+ var session = _a.session, initialState = _a.initialState, errorIds = _a.errorIds, traceIds = _a.traceIds, urls = _a.urls;
105
104
  core.captureEvent({
106
- message: ROOT_REPLAY_NAME,
107
- tags: { segmentId: session.segmentId, url: initialState.url },
108
- timestamp: initialState.timestamp / 1000,
105
+ // @ts-expect-error replay_event is a new event type
106
+ type: REPLAY_EVENT_NAME,
107
+ replay_start_timestamp: initialState.timestamp / 1000,
108
+ error_ids: errorIds,
109
+ trace_ids: traceIds,
110
+ urls: urls,
111
+ replay_id: session.id,
112
+ segment_id: session.segmentId, // TODO: Should this increment?
109
113
  }, { event_id: session.id });
110
114
  }
111
115
 
112
116
  function captureReplayUpdate(_a) {
113
- var session = _a.session, timestamp = _a.timestamp;
117
+ var session = _a.session, timestamp = _a.timestamp, errorIds = _a.errorIds, traceIds = _a.traceIds, urls = _a.urls;
114
118
  core.captureEvent({
115
- timestamp: timestamp / 1000,
116
- message: "".concat(REPLAY_EVENT_NAME, "-").concat(utils.uuid4().substring(16)),
117
- tags: {
118
- replayId: session.id,
119
- segmentId: session.segmentId++,
120
- },
119
+ // @ts-expect-error replay_event is a new event type
120
+ type: REPLAY_EVENT_NAME,
121
+ replay_start_timestamp: timestamp / 1000,
122
+ error_ids: errorIds,
123
+ trace_ids: traceIds,
124
+ urls: urls,
125
+ replay_id: session.id,
126
+ segment_id: ++session.segmentId,
127
+ });
128
+ }
129
+
130
+ function createBreadcrumb(breadcrumb) {
131
+ return __assign({ timestamp: new Date().getTime() / 1000, type: 'default' }, breadcrumb);
132
+ }
133
+
134
+ function handleDom(handlerData) {
135
+ // Taken from https://github.com/getsentry/sentry-javascript/blob/master/packages/browser/src/integrations/breadcrumbs.ts#L112
136
+ var target;
137
+ var targetNode;
138
+ // Accessing event.target can throw (see getsentry/raven-js#838, #768)
139
+ try {
140
+ targetNode =
141
+ handlerData.event.target ||
142
+ handlerData.event;
143
+ target = utils.htmlTreeAsString(targetNode);
144
+ }
145
+ catch (e) {
146
+ target = '<unknown>';
147
+ }
148
+ if (target.length === 0) {
149
+ return null;
150
+ }
151
+ return createBreadcrumb({
152
+ category: "ui.".concat(handlerData.name),
153
+ message: target,
154
+ data: __assign({}, (targetNode ? { nodeId: rrweb.record.mirror.getId(targetNode) } : {})),
121
155
  });
122
156
  }
123
157
 
158
+ var _LAST_BREADCRUMB = null;
159
+ function handleScope(scope) {
160
+ var _a;
161
+ //@ts-expect-error using private val
162
+ var newBreadcrumb = scope._breadcrumbs[scope._breadcrumbs.length - 1];
163
+ // Listener can be called when breadcrumbs have not changed, so we store the
164
+ // reference to the last crumb and only return a crumb if it has changed
165
+ if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {
166
+ return null;
167
+ }
168
+ _LAST_BREADCRUMB = newBreadcrumb;
169
+ if (['fetch', 'xhr', 'sentry.event', 'sentry.transaction'].includes(newBreadcrumb.category) ||
170
+ ((_a = newBreadcrumb.category) === null || _a === void 0 ? void 0 : _a.startsWith('ui.'))) {
171
+ return null;
172
+ }
173
+ return createBreadcrumb(newBreadcrumb);
174
+ }
175
+
176
+ function getBreadcrumbHandler(type) {
177
+ if (type === 'scope') {
178
+ return handleScope;
179
+ }
180
+ return handleDom;
181
+ }
182
+
183
+ /**
184
+ * Checks is `targetHost` is a Sentry ingestion host
185
+ */
186
+ function isIngestHost(targetHost) {
187
+ var _a = core.getCurrentHub().getClient().getDsn(), protocol = _a.protocol, host = _a.host;
188
+ return targetHost.startsWith("".concat(protocol, "://").concat(host));
189
+ }
190
+
191
+ function handleFetch(handlerData) {
192
+ if (!handlerData.endTimestamp) {
193
+ return null;
194
+ }
195
+ var startTimestamp = handlerData.startTimestamp, endTimestamp = handlerData.endTimestamp, fetchData = handlerData.fetchData, response = handlerData.response;
196
+ // Do not capture fetches to Sentry ingestion endpoint
197
+ if (isIngestHost(fetchData.url)) {
198
+ return null;
199
+ }
200
+ return {
201
+ type: 'resource.fetch',
202
+ start: startTimestamp / 1000,
203
+ end: endTimestamp / 1000,
204
+ name: fetchData.url,
205
+ data: {
206
+ method: fetchData.method,
207
+ statusCode: response.status,
208
+ },
209
+ };
210
+ }
211
+
212
+ function handleHistory(handlerData) {
213
+ var from = handlerData.from, to = handlerData.to;
214
+ var now = new Date().getTime() / 1000;
215
+ return {
216
+ type: 'navigation.push',
217
+ start: now,
218
+ end: now,
219
+ name: to,
220
+ data: {
221
+ previous: from,
222
+ },
223
+ };
224
+ }
225
+
226
+ function handleXhr(handlerData) {
227
+ if (handlerData.xhr.__sentry_own_request__) {
228
+ // Taken from sentry-javascript
229
+ // Only capture non-sentry requests
230
+ return null;
231
+ }
232
+ if (handlerData.startTimestamp) {
233
+ // TODO: See if this is still needed
234
+ handlerData.xhr.__sentry_xhr__.startTimestamp = handlerData.startTimestamp;
235
+ }
236
+ if (!handlerData.endTimestamp) {
237
+ return null;
238
+ }
239
+ var _a = handlerData.xhr.__sentry_xhr__ || {}, method = _a.method, url = _a.url, statusCode = _a.status_code;
240
+ // Do not capture fetches to Sentry ingestion endpoint
241
+ if (isIngestHost(url)) {
242
+ return null;
243
+ }
244
+ return {
245
+ type: 'resource.xhr',
246
+ name: url,
247
+ start: handlerData.xhr.__sentry_xhr__.startTimestamp / 1000 ||
248
+ handlerData.endTimestamp / 1000.0,
249
+ end: handlerData.endTimestamp / 1000.0,
250
+ data: {
251
+ method: method,
252
+ statusCode: statusCode,
253
+ },
254
+ };
255
+ }
256
+
257
+ function getSpanHandler(type) {
258
+ if (type === 'fetch') {
259
+ return handleFetch;
260
+ }
261
+ if (type === 'xhr') {
262
+ return handleXhr;
263
+ }
264
+ return handleHistory;
265
+ }
266
+
124
267
  /**
125
268
  * Given an initial timestamp and an expiry duration, checks to see if current
126
269
  * time should be considered as expired.
@@ -324,8 +467,24 @@ function getSession(_a) {
324
467
  return { type: 'new', session: newSession };
325
468
  }
326
469
 
327
- function createBreadcrumb(breadcrumb) {
328
- return __assign({ timestamp: new Date().getTime() / 1000, type: 'default' }, breadcrumb);
470
+ function createPayload(_a) {
471
+ var events = _a.events, headers = _a.headers;
472
+ var payloadWithSequence;
473
+ // XXX: newline is needed to separate sequence id from events
474
+ var replayHeaders = "".concat(JSON.stringify(headers), "\n");
475
+ if (typeof events === 'string') {
476
+ payloadWithSequence = "".concat(replayHeaders).concat(events);
477
+ }
478
+ else {
479
+ var enc = new TextEncoder();
480
+ // XXX: newline is needed to separate sequence id from events
481
+ var sequence = enc.encode(replayHeaders);
482
+ // Merge the two Uint8Arrays
483
+ payloadWithSequence = new Uint8Array(sequence.length + events.length);
484
+ payloadWithSequence.set(sequence);
485
+ payloadWithSequence.set(events, sequence.length);
486
+ }
487
+ return payloadWithSequence;
329
488
  }
330
489
 
331
490
  /**
@@ -335,92 +494,6 @@ function supportsSendBeacon() {
335
494
  return 'navigator' in window && 'sendBeacon' in window.navigator;
336
495
  }
337
496
 
338
- function handleDom(handlerData) {
339
- // Taken from https://github.com/getsentry/sentry-javascript/blob/master/packages/browser/src/integrations/breadcrumbs.ts#L112
340
- var target;
341
- var targetNode;
342
- // Accessing event.target can throw (see getsentry/raven-js#838, #768)
343
- try {
344
- targetNode =
345
- handlerData.event.target ||
346
- handlerData.event;
347
- target = utils.htmlTreeAsString(targetNode);
348
- }
349
- catch (e) {
350
- target = '<unknown>';
351
- }
352
- if (target.length === 0) {
353
- return null;
354
- }
355
- return createBreadcrumb({
356
- category: "ui.".concat(handlerData.name),
357
- message: target,
358
- data: __assign({}, (targetNode ? { nodeId: rrweb.record.mirror.getId(targetNode) } : {})),
359
- });
360
- }
361
-
362
- function handleFetch(handlerData) {
363
- if (!handlerData.endTimestamp) {
364
- return null;
365
- }
366
- var _a = handlerData.args, op = _a[0], description = _a[1];
367
- return {
368
- description: description,
369
- op: op,
370
- startTimestamp: handlerData.startTimestamp / 1000,
371
- endTimestamp: handlerData.endTimestamp / 1000,
372
- data: {
373
- statusCode: handlerData.response.status,
374
- },
375
- };
376
- }
377
-
378
- var _LAST_BREADCRUMB = null;
379
- function handleScope(scope) {
380
- var _a;
381
- //@ts-expect-error using private val
382
- var newBreadcrumb = scope._breadcrumbs[scope._breadcrumbs.length - 1];
383
- // Listener can be called when breadcrumbs have not changed, so we store the
384
- // reference to the last crumb and only return a crumb if it has changed
385
- if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {
386
- return null;
387
- }
388
- _LAST_BREADCRUMB = newBreadcrumb;
389
- if (['fetch', 'xhr', 'sentry.event', 'sentry.transaction'].includes(newBreadcrumb.category) ||
390
- ((_a = newBreadcrumb.category) === null || _a === void 0 ? void 0 : _a.startsWith('ui.'))) {
391
- return null;
392
- }
393
- return createBreadcrumb(newBreadcrumb);
394
- }
395
-
396
- function handleXhr(handlerData) {
397
- if (handlerData.startTimestamp) {
398
- handlerData.xhr.__sentry_xhr__.startTimestamp = handlerData.startTimestamp;
399
- }
400
- if (!handlerData.endTimestamp) {
401
- return null;
402
- }
403
- var _a = handlerData.args, op = _a[0], description = _a[1];
404
- return {
405
- description: description,
406
- op: op,
407
- startTimestamp: handlerData.xhr.__sentry_xhr__.startTimestamp / 1000 ||
408
- handlerData.endTimestamp / 1000.0,
409
- endTimestamp: handlerData.endTimestamp / 1000.0,
410
- data: {
411
- statusCode: handlerData.response.status,
412
- },
413
- };
414
- }
415
-
416
- /**
417
- * Checks is `targetHost` is a Sentry ingestion host
418
- */
419
- function isIngestHost(targetHost) {
420
- var _a = core.getCurrentHub().getClient().getDsn(), protocol = _a.protocol, host = _a.host;
421
- return targetHost.startsWith("".concat(protocol, "://").concat(host));
422
- }
423
-
424
497
  var _a;
425
498
  // Map entryType -> function to normalize data for event
426
499
  var ENTRY_TYPES = (_a = {
@@ -471,6 +544,10 @@ function createResourceEntry(entry) {
471
544
  if (isIngestHost(name)) {
472
545
  return null;
473
546
  }
547
+ // Core SDK handles these
548
+ if (['fetch', 'xmlhttprequest'].includes(initiatorType)) {
549
+ return null;
550
+ }
474
551
  return {
475
552
  type: "".concat(entryType, ".").concat(initiatorType),
476
553
  start: getAbsoluteTime(startTime),
@@ -531,7 +608,6 @@ function createEventBuffer(_a) {
531
608
  return new EventBufferCompressionWorker(worker);
532
609
  }
533
610
  else {
534
- // TODO: Debugging
535
611
  core.captureException(new Error('Unable to create compression worker'));
536
612
  }
537
613
  }
@@ -584,38 +660,25 @@ var EventBufferCompressionWorker = /** @class */ (function () {
584
660
  this.eventBufferItemLength = 0;
585
661
  this._id = 0;
586
662
  this.sendEventToWorker = function (event) {
587
- _this.postMessage({
663
+ var promise = _this.postMessage({
588
664
  id: _this.id,
589
665
  method: 'addEvent',
590
666
  args: [event],
591
667
  });
668
+ logger.log('Message posted to worker');
669
+ // XXX: See note in `get length()`
592
670
  _this.eventBufferItemLength++;
671
+ return promise;
593
672
  };
594
- this.finishRequest = function (id) {
595
- return new Promise(function (resolve, reject) {
596
- var finishListener = function (_a) {
597
- var data = _a.data;
598
- if (data.method !== 'finish') {
599
- return;
600
- }
601
- if (data.id !== id) {
602
- return;
603
- }
604
- if (!data.success) {
605
- // TODO: Do some error handling, not sure what
606
- logger.error(data.response);
607
- reject(new Error('Error in compression worker'));
608
- return;
609
- }
610
- resolve(data.response);
611
- logger.log('Worker responded with compressed payload');
612
- _this.eventBufferItemLength = 0;
613
- _this.worker.removeEventListener('message', finishListener);
614
- };
615
- _this.worker.addEventListener('message', finishListener);
616
- _this.postMessage({ id: id, method: 'finish', args: [] });
673
+ this.finishRequest = function (id) { return __awaiter(_this, void 0, void 0, function () {
674
+ var promise;
675
+ return __generator(this, function (_a) {
676
+ promise = this.postMessage({ id: id, method: 'finish', args: [] });
677
+ // XXX: See note in `get length()`
678
+ this.eventBufferItemLength = 0;
679
+ return [2 /*return*/, promise];
617
680
  });
618
- };
681
+ }); };
619
682
  this.worker = worker;
620
683
  }
621
684
  Object.defineProperty(EventBufferCompressionWorker.prototype, "id", {
@@ -628,8 +691,38 @@ var EventBufferCompressionWorker = /** @class */ (function () {
628
691
  enumerable: false,
629
692
  configurable: true
630
693
  });
631
- EventBufferCompressionWorker.prototype.postMessage = function (args) {
632
- this.worker.postMessage(args);
694
+ /**
695
+ * Post message to worker and wait for response before resolving promise.
696
+ */
697
+ EventBufferCompressionWorker.prototype.postMessage = function (_a) {
698
+ var _this = this;
699
+ var id = _a.id, method = _a.method, args = _a.args;
700
+ return new Promise(function (resolve, reject) {
701
+ var listener = function (_a) {
702
+ var data = _a.data;
703
+ if (data.method !== method) {
704
+ return;
705
+ }
706
+ // There can be multiple listeners for a single method, the id ensures
707
+ // that the response matches the caller.
708
+ if (data.id !== id) {
709
+ return;
710
+ }
711
+ // At this point, we'll always want to remove listener regardless of result status
712
+ _this.worker.removeEventListener('message', listener);
713
+ if (!data.success) {
714
+ // TODO: Do some error handling, not sure what
715
+ logger.error(data.response);
716
+ reject(new Error('Error in compression worker'));
717
+ return;
718
+ }
719
+ resolve(data.response);
720
+ };
721
+ // Note: we can't use `once` option because it's possible it needs to
722
+ // listen to multiple messages
723
+ _this.worker.addEventListener('message', listener);
724
+ _this.worker.postMessage({ id: id, method: method, args: args });
725
+ });
633
726
  };
634
727
  EventBufferCompressionWorker.prototype.init = function () {
635
728
  this.postMessage({ id: this.id, method: 'init', args: [] });
@@ -641,6 +734,10 @@ var EventBufferCompressionWorker = /** @class */ (function () {
641
734
  this.worker = null;
642
735
  };
643
736
  Object.defineProperty(EventBufferCompressionWorker.prototype, "length", {
737
+ /**
738
+ * Note that this may not reflect what is actually in the event buffer. This
739
+ * is only a local count of the buffer size since `addEvent` is async.
740
+ */
644
741
  get: function () {
645
742
  return this.eventBufferItemLength;
646
743
  },
@@ -648,39 +745,31 @@ var EventBufferCompressionWorker = /** @class */ (function () {
648
745
  configurable: true
649
746
  });
650
747
  EventBufferCompressionWorker.prototype.addEvent = function (event, isCheckout) {
651
- var _this = this;
652
- // If it is a checkout we should make sure worker buffer is cleared before proceeding
653
- if (!isCheckout) {
654
- this.sendEventToWorker(event);
655
- return;
656
- }
657
- var initListener = function (_a) {
658
- var data = _a.data;
659
- if (data.method !== 'init') {
660
- return;
661
- }
662
- if (!data.success) {
663
- // TODO: Do some error handling, not sure what
664
- logger.error(data.response);
665
- return;
666
- }
667
- // Worker has been re-initialized, can add event now
668
- _this.sendEventToWorker(event);
669
- _this.worker.removeEventListener('message', initListener);
670
- };
671
- this.worker.addEventListener('message', initListener);
672
- this.postMessage({ id: this.id, method: 'init', args: [] });
673
- };
674
- EventBufferCompressionWorker.prototype.finish = function () {
675
748
  return __awaiter(this, void 0, void 0, function () {
676
749
  return __generator(this, function (_a) {
677
750
  switch (_a.label) {
678
- case 0: return [4 /*yield*/, this.finishRequest(this.id)];
679
- case 1: return [2 /*return*/, _a.sent()];
751
+ case 0:
752
+ if (!isCheckout) return [3 /*break*/, 2];
753
+ // This event is a checkout, make sure worker buffer is cleared before
754
+ // proceeding.
755
+ return [4 /*yield*/, this.postMessage({
756
+ id: this.id,
757
+ method: 'init',
758
+ args: [],
759
+ })];
760
+ case 1:
761
+ // This event is a checkout, make sure worker buffer is cleared before
762
+ // proceeding.
763
+ _a.sent();
764
+ _a.label = 2;
765
+ case 2: return [2 /*return*/, this.sendEventToWorker(event)];
680
766
  }
681
767
  });
682
768
  });
683
769
  };
770
+ EventBufferCompressionWorker.prototype.finish = function () {
771
+ return this.finishRequest(this.id);
772
+ };
684
773
  return EventBufferCompressionWorker;
685
774
  }());
686
775
 
@@ -701,10 +790,6 @@ var SentryReplay = /** @class */ (function () {
701
790
  * Buffer of breadcrumbs to be uploaded
702
791
  */
703
792
  this.breadcrumbs = [];
704
- /**
705
- * Buffer of replay spans to be uploaded
706
- */
707
- this.replaySpans = [];
708
793
  /**
709
794
  * List of PerformanceEntry from PerformanceObserver
710
795
  */
@@ -725,6 +810,11 @@ var SentryReplay = /** @class */ (function () {
725
810
  * immediately before sending recording)
726
811
  */
727
812
  this.needsCaptureReplay = false;
813
+ this.context = {
814
+ errorIds: new Set(),
815
+ traceIds: new Set(),
816
+ urls: [],
817
+ };
728
818
  /**
729
819
  * Core Sentry SDK global event handler. Attaches `replayId` to all [non-replay]
730
820
  * events as a tag. Also handles the case where we only want to capture a reply
@@ -733,11 +823,21 @@ var SentryReplay = /** @class */ (function () {
733
823
  this.handleGlobalEvent = function (event) {
734
824
  var _a;
735
825
  // Do not apply replayId to the root event
736
- if (event.message === ROOT_REPLAY_NAME ||
737
- ((_a = event.message) === null || _a === void 0 ? void 0 : _a.startsWith(REPLAY_EVENT_NAME))) {
826
+ if (
827
+ // @ts-expect-error new event type
828
+ event.type === REPLAY_EVENT_NAME) {
829
+ // Replays have separate set of breadcrumbs, do not include breadcrumbs
830
+ // from core SDK
831
+ delete event.breadcrumbs;
738
832
  return event;
739
833
  }
740
834
  event.tags = __assign(__assign({}, event.tags), { replayId: _this.session.id });
835
+ if (event.type === 'transaction') {
836
+ _this.context.traceIds.add(String(((_a = event.contexts) === null || _a === void 0 ? void 0 : _a.trace.trace_id) || ''));
837
+ return event;
838
+ }
839
+ // XXX: Is it safe to assume that all other events are error events?
840
+ _this.context.errorIds.add(event.event_id);
741
841
  // Need to be very careful that this does not cause an infinite loop
742
842
  if (_this.options.captureOnlyOnError && event.exception) {
743
843
  // TODO: Do we continue to record after?
@@ -828,25 +928,35 @@ var SentryReplay = /** @class */ (function () {
828
928
  /**
829
929
  * Handler for Sentry Core SDK events.
830
930
  *
831
- * Transforms core SDK events into replay events.
931
+ * These specific events will create span-like objects in the recording.
832
932
  *
833
933
  */
834
- this.handleCoreListener = function (type) { return function (handlerData) {
835
- var handlerMap = {
836
- scope: [handleScope, 'breadcrumb'],
837
- dom: [handleDom, 'breadcrumb'],
838
- fetch: [handleFetch, 'span'],
839
- xhr: [handleXhr, 'span'],
840
- };
841
- if (!(type in handlerMap)) {
842
- throw new Error("No handler defined for type: ".concat(type));
934
+ this.handleCoreSpanListener = function (type) { return function (handlerData) {
935
+ var handler = getSpanHandler(type);
936
+ var result = handler(handlerData);
937
+ if (result === null) {
938
+ return;
939
+ }
940
+ if (type === 'history') {
941
+ // Need to collect visited URLs
942
+ _this.context.urls.push(result.name);
843
943
  }
844
- var _a = handlerMap[type], handlerFn = _a[0], eventType = _a[1];
845
- var result = handlerFn(handlerData);
944
+ _this.addUpdate(function () {
945
+ _this.createPerformanceSpans([result]);
946
+ });
947
+ }; };
948
+ /**
949
+ * Handler for Sentry Core SDK events.
950
+ *
951
+ * These events will create breadcrumb-like objects in the recording.
952
+ */
953
+ this.handleCoreBreadcrumbListener = function (type) { return function (handlerData) {
954
+ var handler = getBreadcrumbHandler(type);
955
+ var result = handler(handlerData);
846
956
  if (result === null) {
847
957
  return;
848
958
  }
849
- if (['sentry.transaction'].includes(result.category)) {
959
+ if (result.category === 'sentry.transaction') {
850
960
  return;
851
961
  }
852
962
  _this.addUpdate(function () {
@@ -854,10 +964,9 @@ var SentryReplay = /** @class */ (function () {
854
964
  type: rrweb.EventType.Custom,
855
965
  // TODO: We were converting from ms to seconds for breadcrumbs, spans,
856
966
  // but maybe we should just keep them as milliseconds
857
- timestamp: result.timestamp * 1000 ||
858
- result.startTimestamp * 1000,
967
+ timestamp: result.timestamp * 1000,
859
968
  data: {
860
- tag: eventType,
969
+ tag: 'breadcrumb',
861
970
  payload: result,
862
971
  },
863
972
  });
@@ -888,12 +997,6 @@ var SentryReplay = /** @class */ (function () {
888
997
  this.recordingOptions.checkoutEveryNms = 60000;
889
998
  }
890
999
  }
891
- SentryReplay.attachmentUrlFromDsn = function (dsn, eventId) {
892
- var host = dsn.host, projectId = dsn.projectId, protocol = dsn.protocol, publicKey = dsn.publicKey;
893
- var port = dsn.port !== '' ? ":".concat(dsn.port) : '';
894
- var path = dsn.path !== '' ? "/".concat(dsn.path) : '';
895
- return "".concat(protocol, "://").concat(host).concat(port).concat(path, "/api/").concat(projectId, "/events/").concat(eventId, "/attachments/?sentry_key=").concat(publicKey, "&sentry_version=7&sentry_client=replay");
896
- };
897
1000
  /**
898
1001
  * Because we create a transaction in `setupOnce`, we can potentially create a
899
1002
  * transaction before some native SDK integrations have run and applied their
@@ -931,12 +1034,15 @@ var SentryReplay = /** @class */ (function () {
931
1034
  // replay ID so that we can reference them later in the UI
932
1035
  core.addGlobalEventProcessor(this.handleGlobalEvent);
933
1036
  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);
934
1039
  // Otherwise, these will be captured after the first flush, which means the
935
1040
  // URL and timestamps could be incorrect
936
1041
  this.initialState = {
937
1042
  timestamp: new Date().getTime(),
938
- url: "".concat(window.location.origin).concat(window.location.pathname),
1043
+ url: url,
939
1044
  };
1045
+ this.context.urls.push(url);
940
1046
  };
941
1047
  /**
942
1048
  * We want to batch uploads of replay events. Save events only if
@@ -993,7 +1099,6 @@ var SentryReplay = /** @class */ (function () {
993
1099
  SentryReplay.prototype.destroy = function () {
994
1100
  logger.log('Destroying instance');
995
1101
  this.removeListeners();
996
- // this.eventBuffer.clear();
997
1102
  };
998
1103
  SentryReplay.prototype.clearSession = function () {
999
1104
  this.session = null;
@@ -1032,8 +1137,11 @@ var SentryReplay = /** @class */ (function () {
1032
1137
  window.addEventListener('beforeunload', this.handleWindowUnload);
1033
1138
  // Listeners from core SDK //
1034
1139
  var scope = core.getCurrentHub().getScope();
1035
- scope.addScopeListener(this.handleCoreListener('scope'));
1036
- utils.addInstrumentationHandler('dom', this.handleCoreListener('dom'));
1140
+ scope.addScopeListener(this.handleCoreBreadcrumbListener('scope'));
1141
+ utils.addInstrumentationHandler('dom', this.handleCoreBreadcrumbListener('dom'));
1142
+ utils.addInstrumentationHandler('fetch', this.handleCoreSpanListener('fetch'));
1143
+ utils.addInstrumentationHandler('xhr', this.handleCoreSpanListener('xhr'));
1144
+ utils.addInstrumentationHandler('history', this.handleCoreSpanListener('history'));
1037
1145
  // PerformanceObserver //
1038
1146
  if (!('PerformanceObserver' in window)) {
1039
1147
  return;
@@ -1144,13 +1252,13 @@ var SentryReplay = /** @class */ (function () {
1144
1252
  });
1145
1253
  };
1146
1254
  /**
1147
- * Create a span for each performance entry. The parent transaction is `this.replayEvent`.
1255
+ * Create a "span" for each performance entry. The parent transaction is `this.replayEvent`.
1148
1256
  */
1149
1257
  SentryReplay.prototype.createPerformanceSpans = function (entries) {
1150
1258
  var _this = this;
1151
- entries.forEach(function (_a) {
1259
+ return Promise.all(entries.map(function (_a) {
1152
1260
  var type = _a.type, start = _a.start, end = _a.end, name = _a.name, data = _a.data;
1153
- _this.eventBuffer.addEvent({
1261
+ return _this.eventBuffer.addEvent({
1154
1262
  type: rrweb.EventType.Custom,
1155
1263
  timestamp: start,
1156
1264
  data: {
@@ -1164,7 +1272,7 @@ var SentryReplay = /** @class */ (function () {
1164
1272
  },
1165
1273
  },
1166
1274
  });
1167
- });
1275
+ }));
1168
1276
  };
1169
1277
  /**
1170
1278
  * Observed performance events are added to `this.performanceEvents`. These
@@ -1174,15 +1282,22 @@ var SentryReplay = /** @class */ (function () {
1174
1282
  // Copy and reset entries before processing
1175
1283
  var entries = __spreadArray([], this.performanceEvents, true);
1176
1284
  this.performanceEvents = [];
1177
- // Parse the entries
1178
- var entryEvents = createPerformanceEntries(entries);
1285
+ return this.createPerformanceSpans(createPerformanceEntries(entries));
1286
+ };
1287
+ /**
1288
+ * Create a "span" for the total amount of memory being used by JS objects
1289
+ * (including v8 internal objects).
1290
+ */
1291
+ SentryReplay.prototype.addMemoryEntry = function () {
1179
1292
  // window.performance.memory is a non-standard API and doesn't work on all browsers
1180
1293
  // so we check before creating the event.
1181
- if ('memory' in window.performance) {
1182
- // @ts-expect-error memory doesn't exist on type Performance as the API is non-standard
1183
- entryEvents.push(createMemoryEntry(window.performance.memory));
1294
+ if (!('memory' in window.performance)) {
1295
+ return;
1184
1296
  }
1185
- this.createPerformanceSpans(entryEvents);
1297
+ return this.createPerformanceSpans([
1298
+ // @ts-expect-error memory doesn't exist on type Performance as the API is non-standard (we check that it exists above)
1299
+ createMemoryEntry(window.performance.memory),
1300
+ ]);
1186
1301
  };
1187
1302
  /**
1188
1303
  *
@@ -1216,6 +1331,24 @@ var SentryReplay = /** @class */ (function () {
1216
1331
  }
1217
1332
  return this.flushUpdate(lastActivity);
1218
1333
  };
1334
+ /**
1335
+ * Return and clear context
1336
+ */
1337
+ SentryReplay.prototype.popEventContext = function (_a) {
1338
+ var timestamp = _a.timestamp;
1339
+ var context = {
1340
+ session: this.session,
1341
+ initialState: this.initialState,
1342
+ timestamp: timestamp,
1343
+ errorIds: Array.from(this.context.errorIds).filter(Boolean),
1344
+ traceIds: Array.from(this.context.traceIds).filter(Boolean),
1345
+ urls: this.context.urls,
1346
+ };
1347
+ this.context.errorIds.clear();
1348
+ this.context.traceIds.clear();
1349
+ this.context.urls = [];
1350
+ return context;
1351
+ };
1219
1352
  /**
1220
1353
  * Flushes replay event buffer to Sentry.
1221
1354
  *
@@ -1236,28 +1369,37 @@ var SentryReplay = /** @class */ (function () {
1236
1369
  console.error(new Error('[Sentry]: No transaction, no replay'));
1237
1370
  return [2 /*return*/];
1238
1371
  }
1239
- this.addPerformanceEntries();
1372
+ // Since already flushing, ensure other queued flushes are cancelled
1373
+ clearTimeout(this.timeout);
1374
+ return [4 /*yield*/, this.addPerformanceEntries()];
1375
+ case 1:
1376
+ _a.sent();
1240
1377
  if (!this.eventBuffer.length) {
1241
1378
  return [2 /*return*/];
1242
1379
  }
1380
+ // Only attach memory event if eventBuffer is not empty
1381
+ return [4 /*yield*/, this.addMemoryEntry()];
1382
+ case 2:
1383
+ // Only attach memory event if eventBuffer is not empty
1384
+ _a.sent();
1385
+ timestamp = lastActivity !== null && lastActivity !== void 0 ? lastActivity : new Date().getTime();
1243
1386
  // Only want to create replay event if session is new
1244
1387
  if (this.needsCaptureReplay) {
1245
1388
  // This event needs to exist before calling `sendReplay`
1246
- captureReplay({ session: this.session, initialState: this.initialState });
1389
+ captureReplay(this.popEventContext({ timestamp: timestamp }));
1247
1390
  this.needsCaptureReplay = false;
1248
1391
  }
1249
1392
  // Reset this to null regardless of `sendReplay` result so that future
1250
1393
  // events will get flushed properly
1251
1394
  this.initialEventTimestampSinceFlush = null;
1252
- _a.label = 1;
1253
- case 1:
1254
- _a.trys.push([1, 4, , 5]);
1255
- timestamp = lastActivity !== null && lastActivity !== void 0 ? lastActivity : new Date().getTime();
1395
+ _a.label = 3;
1396
+ case 3:
1397
+ _a.trys.push([3, 6, , 7]);
1256
1398
  return [4 /*yield*/, this.eventBuffer.finish()];
1257
- case 2:
1399
+ case 4:
1258
1400
  recordingData = _a.sent();
1259
1401
  return [4 /*yield*/, this.sendReplay(this.session.id, recordingData)];
1260
- case 3:
1402
+ case 5:
1261
1403
  _a.sent();
1262
1404
  // The below will only happen after successfully sending replay //
1263
1405
  // TBD: Alternatively we could update this after every rrweb event
@@ -1265,13 +1407,14 @@ var SentryReplay = /** @class */ (function () {
1265
1407
  // of the event is passed as an argument in the case where a timeout
1266
1408
  // occurs.
1267
1409
  this.updateLastActivity(timestamp);
1268
- captureReplayUpdate({ session: this.session, timestamp: timestamp });
1269
- return [3 /*break*/, 5];
1270
- case 4:
1410
+ captureReplayUpdate(this.popEventContext({ timestamp: timestamp }));
1411
+ return [3 /*break*/, 7];
1412
+ case 6:
1271
1413
  err_1 = _a.sent();
1414
+ core.captureException(err_1);
1272
1415
  console.error(err_1);
1273
- return [3 /*break*/, 5];
1274
- case 5: return [2 /*return*/];
1416
+ return [3 /*break*/, 7];
1417
+ case 7: return [2 /*return*/];
1275
1418
  }
1276
1419
  });
1277
1420
  });
@@ -1282,27 +1425,41 @@ var SentryReplay = /** @class */ (function () {
1282
1425
  SentryReplay.prototype.sendReplayRequest = function (_a) {
1283
1426
  var endpoint = _a.endpoint, events = _a.events;
1284
1427
  return __awaiter(this, void 0, void 0, function () {
1285
- var formData, payloadBlob;
1428
+ var payloadWithSequence, envelope;
1286
1429
  return __generator(this, function (_b) {
1287
1430
  switch (_b.label) {
1288
1431
  case 0:
1289
- formData = new FormData();
1290
- payloadBlob = new Blob([events], {
1291
- type: 'application/json',
1432
+ payloadWithSequence = createPayload({
1433
+ events: events,
1434
+ headers: {
1435
+ segment_id: this.session.segmentId,
1436
+ },
1292
1437
  });
1293
- logger.log('blob size in bytes: ', payloadBlob.size);
1294
- formData.append('rrweb', payloadBlob, "rrweb-".concat(new Date().getTime(), ".json"));
1438
+ envelope = utils.createEnvelope({
1439
+ event_id: this.session.id,
1440
+ sent_at: new Date().toISOString(),
1441
+ sdk: { name: 'sentry.javascript.integration.replay', version: '1.0.0' },
1442
+ }, [
1443
+ [
1444
+ {
1445
+ // @ts-expect-error setting envelope
1446
+ type: 'replay_recording',
1447
+ length: payloadWithSequence.length,
1448
+ },
1449
+ payloadWithSequence,
1450
+ ],
1451
+ ]);
1295
1452
  // If sendBeacon is supported and payload is smol enough...
1296
- if (supportsSendBeacon() && payloadBlob.size <= 65535) {
1453
+ if (supportsSendBeacon() && events.length <= 65536) {
1297
1454
  logger.log("uploading attachment via sendBeacon()");
1298
- window.navigator.sendBeacon(endpoint, formData);
1455
+ window.navigator.sendBeacon(endpoint, utils.serializeEnvelope(envelope));
1299
1456
  return [2 /*return*/];
1300
1457
  }
1301
1458
  // Otherwise use `fetch`, which *WILL* get cancelled on page reloads/unloads
1302
1459
  logger.log("uploading attachment via fetch()");
1303
1460
  return [4 /*yield*/, fetch(endpoint, {
1304
1461
  method: 'POST',
1305
- body: formData,
1462
+ body: utils.serializeEnvelope(envelope),
1306
1463
  })];
1307
1464
  case 1:
1308
1465
  _b.sent();
@@ -1330,7 +1487,7 @@ var SentryReplay = /** @class */ (function () {
1330
1487
  return [2 /*return*/];
1331
1488
  }
1332
1489
  client = core.getCurrentHub().getClient();
1333
- endpoint = SentryReplay.attachmentUrlFromDsn(client.getDsn(), eventId);
1490
+ endpoint = core.getEnvelopeEndpointWithUrlEncodedAuth(client.getDsn());
1334
1491
  _b.label = 1;
1335
1492
  case 1:
1336
1493
  _b.trys.push([1, 3, , 8]);