@sentry/replay 0.4.8-2 → 0.4.9

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 (67) hide show
  1. package/README.md +15 -15
  2. package/dist/config/dist/jest.config.d.ts +3 -0
  3. package/dist/config/dist/jest.setup.d.ts +10 -0
  4. package/dist/config/dist/src/api/captureReplay.d.ts +10 -0
  5. package/dist/config/dist/src/api/captureReplayUpdate.d.ts +12 -0
  6. package/dist/config/dist/src/coreHandlers/getBreadcrumbHandler.d.ts +3 -0
  7. package/dist/config/dist/src/coreHandlers/getSpanHandler.d.ts +5 -0
  8. package/dist/config/dist/src/coreHandlers/handleDom.d.ts +1 -0
  9. package/dist/config/dist/src/coreHandlers/handleFetch.d.ts +19 -0
  10. package/dist/config/dist/src/coreHandlers/handleFetch.test.d.ts +1 -0
  11. package/dist/config/dist/src/coreHandlers/handleHistory.d.ts +7 -0
  12. package/dist/config/dist/src/coreHandlers/handleScope-unit.test.d.ts +1 -0
  13. package/dist/config/dist/src/coreHandlers/handleScope.d.ts +2 -0
  14. package/dist/config/dist/src/coreHandlers/handleScope.test.d.ts +1 -0
  15. package/dist/config/dist/src/coreHandlers/handleXhr.d.ts +21 -0
  16. package/dist/{dist → config/dist/src}/coreHandlers/index.d.ts +0 -0
  17. package/dist/config/dist/src/createPerformanceEntry.d.ts +42 -0
  18. package/dist/config/dist/src/createPerformanceEntry.test.d.ts +1 -0
  19. package/dist/config/dist/src/eventBuffer.d.ts +45 -0
  20. package/dist/config/dist/src/eventBuffer.test.d.ts +1 -0
  21. package/dist/config/dist/src/flags.d.ts +2 -0
  22. package/dist/config/dist/src/index-captureOnlyOnError.test.d.ts +1 -0
  23. package/dist/config/dist/src/index-noSticky.test.d.ts +1 -0
  24. package/dist/config/dist/src/index-sampling.test.d.ts +1 -0
  25. package/dist/config/dist/src/index.d.ts +225 -0
  26. package/dist/config/dist/src/index.test.d.ts +1 -0
  27. package/dist/config/dist/src/session/Session.d.ts +63 -0
  28. package/dist/config/dist/src/session/Session.test.d.ts +1 -0
  29. package/dist/config/dist/src/session/constants.d.ts +5 -0
  30. package/dist/config/dist/src/session/createSession.d.ts +19 -0
  31. package/dist/config/dist/src/session/createSession.test.d.ts +1 -0
  32. package/dist/config/dist/src/session/fetchSession.d.ts +5 -0
  33. package/dist/config/dist/src/session/fetchSession.test.d.ts +1 -0
  34. package/dist/config/dist/src/session/getSession.d.ts +28 -0
  35. package/dist/config/dist/src/session/getSession.test.d.ts +1 -0
  36. package/dist/config/dist/src/session/index.d.ts +1 -0
  37. package/dist/config/dist/src/session/saveSession.d.ts +2 -0
  38. package/dist/config/dist/src/session/saveSession.test.d.ts +1 -0
  39. package/dist/config/dist/src/types.d.ts +90 -0
  40. package/dist/config/dist/src/util/createBreadcrumb.d.ts +4 -0
  41. package/dist/config/dist/src/util/createPayload.d.ts +5 -0
  42. package/dist/config/dist/src/util/isExpired.d.ts +5 -0
  43. package/dist/config/dist/src/util/isExpired.test.d.ts +1 -0
  44. package/dist/config/dist/src/util/isIngestHost.d.ts +4 -0
  45. package/dist/config/dist/src/util/isSampled.d.ts +7 -0
  46. package/dist/config/dist/src/util/isSampled.test.d.ts +1 -0
  47. package/dist/config/dist/src/util/isSessionExpired.d.ts +5 -0
  48. package/dist/config/dist/src/util/isSessionExpired.test.d.ts +1 -0
  49. package/dist/config/dist/src/util/logger.d.ts +12 -0
  50. package/dist/config/dist/src/util/supportsSendBeacon.d.ts +4 -0
  51. package/dist/config/dist/test/index.d.ts +3 -0
  52. package/dist/config/dist/test/mocks/mockRrweb.d.ts +15 -0
  53. package/dist/config/dist/test/mocks/mockSdk.d.ts +11 -0
  54. package/dist/dist/api/captureReplay.d.ts +5 -3
  55. package/dist/dist/api/captureReplayUpdate.d.ts +5 -3
  56. package/dist/dist/coreHandlers/getBreadcrumbHandler.d.ts +3 -0
  57. package/dist/dist/coreHandlers/getSpanHandler.d.ts +5 -0
  58. package/dist/dist/coreHandlers/handleFetch.d.ts +19 -2
  59. package/dist/dist/coreHandlers/handleHistory.d.ts +7 -0
  60. package/dist/dist/coreHandlers/handleXhr.d.ts +21 -2
  61. package/dist/dist/eventBuffer.d.ts +11 -4
  62. package/dist/dist/index.d.ts +26 -10
  63. package/dist/dist/types.d.ts +20 -8
  64. package/dist/index.es.js +329 -199
  65. package/dist/index.js +328 -198
  66. package/dist/index.js.map +1 -1
  67. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -101,19 +101,27 @@ var SESSION_IDLE_DURATION = 900000; // 15 minutes
101
101
  var VISIBILITY_CHANGE_TIMEOUT = SESSION_IDLE_DURATION;
102
102
 
103
103
  function captureReplay(_a) {
104
- var session = _a.session, initialState = _a.initialState;
104
+ var session = _a.session, initialState = _a.initialState, errorIds = _a.errorIds, traceIds = _a.traceIds, urls = _a.urls;
105
105
  core.captureEvent({
106
106
  message: ROOT_REPLAY_NAME,
107
107
  tags: { segmentId: session.segmentId, url: initialState.url },
108
108
  timestamp: initialState.timestamp / 1000,
109
+ // @ts-expect-error replay event type accepts this
110
+ error_ids: errorIds,
111
+ trace_ids: traceIds,
112
+ urls: urls,
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
119
  timestamp: timestamp / 1000,
116
120
  message: "".concat(REPLAY_EVENT_NAME, "-").concat(utils.uuid4().substring(16)),
121
+ // @ts-expect-error replay event type accepts this
122
+ error_ids: errorIds,
123
+ trace_ids: traceIds,
124
+ urls: urls,
117
125
  tags: {
118
126
  replayId: session.id,
119
127
  segmentId: session.segmentId++,
@@ -121,6 +129,143 @@ function captureReplayUpdate(_a) {
121
129
  });
122
130
  }
123
131
 
132
+ function createBreadcrumb(breadcrumb) {
133
+ return __assign({ timestamp: new Date().getTime() / 1000, type: 'default' }, breadcrumb);
134
+ }
135
+
136
+ function handleDom(handlerData) {
137
+ // Taken from https://github.com/getsentry/sentry-javascript/blob/master/packages/browser/src/integrations/breadcrumbs.ts#L112
138
+ var target;
139
+ var targetNode;
140
+ // Accessing event.target can throw (see getsentry/raven-js#838, #768)
141
+ try {
142
+ targetNode =
143
+ handlerData.event.target ||
144
+ handlerData.event;
145
+ target = utils.htmlTreeAsString(targetNode);
146
+ }
147
+ catch (e) {
148
+ target = '<unknown>';
149
+ }
150
+ if (target.length === 0) {
151
+ return null;
152
+ }
153
+ return createBreadcrumb({
154
+ category: "ui.".concat(handlerData.name),
155
+ message: target,
156
+ data: __assign({}, (targetNode ? { nodeId: rrweb.record.mirror.getId(targetNode) } : {})),
157
+ });
158
+ }
159
+
160
+ var _LAST_BREADCRUMB = null;
161
+ function handleScope(scope) {
162
+ var _a;
163
+ //@ts-expect-error using private val
164
+ var newBreadcrumb = scope._breadcrumbs[scope._breadcrumbs.length - 1];
165
+ // Listener can be called when breadcrumbs have not changed, so we store the
166
+ // reference to the last crumb and only return a crumb if it has changed
167
+ if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {
168
+ return null;
169
+ }
170
+ _LAST_BREADCRUMB = newBreadcrumb;
171
+ if (['fetch', 'xhr', 'sentry.event', 'sentry.transaction'].includes(newBreadcrumb.category) ||
172
+ ((_a = newBreadcrumb.category) === null || _a === void 0 ? void 0 : _a.startsWith('ui.'))) {
173
+ return null;
174
+ }
175
+ return createBreadcrumb(newBreadcrumb);
176
+ }
177
+
178
+ function getBreadcrumbHandler(type) {
179
+ if (type === 'scope') {
180
+ return handleScope;
181
+ }
182
+ return handleDom;
183
+ }
184
+
185
+ /**
186
+ * Checks is `targetHost` is a Sentry ingestion host
187
+ */
188
+ function isIngestHost(targetHost) {
189
+ var _a = core.getCurrentHub().getClient().getDsn(), protocol = _a.protocol, host = _a.host;
190
+ return targetHost.startsWith("".concat(protocol, "://").concat(host));
191
+ }
192
+
193
+ function handleFetch(handlerData) {
194
+ if (!handlerData.endTimestamp) {
195
+ return null;
196
+ }
197
+ var startTimestamp = handlerData.startTimestamp, endTimestamp = handlerData.endTimestamp, fetchData = handlerData.fetchData, response = handlerData.response;
198
+ // Do not capture fetches to Sentry ingestion endpoint
199
+ if (isIngestHost(fetchData.url)) {
200
+ return null;
201
+ }
202
+ return {
203
+ type: 'resource.fetch',
204
+ start: startTimestamp / 1000,
205
+ end: endTimestamp / 1000,
206
+ name: fetchData.url,
207
+ data: {
208
+ method: fetchData.method,
209
+ statusCode: response.status,
210
+ },
211
+ };
212
+ }
213
+
214
+ function handleHistory(handlerData) {
215
+ var from = handlerData.from, to = handlerData.to;
216
+ var now = new Date().getTime() / 1000;
217
+ return {
218
+ type: 'navigation.push',
219
+ start: now,
220
+ end: now,
221
+ name: to,
222
+ data: {
223
+ previous: from,
224
+ },
225
+ };
226
+ }
227
+
228
+ function handleXhr(handlerData) {
229
+ if (handlerData.xhr.__sentry_own_request__) {
230
+ // Taken from sentry-javascript
231
+ // Only capture non-sentry requests
232
+ return null;
233
+ }
234
+ if (handlerData.startTimestamp) {
235
+ // TODO: See if this is still needed
236
+ handlerData.xhr.__sentry_xhr__.startTimestamp = handlerData.startTimestamp;
237
+ }
238
+ if (!handlerData.endTimestamp) {
239
+ return null;
240
+ }
241
+ var _a = handlerData.xhr.__sentry_xhr__ || {}, method = _a.method, url = _a.url, statusCode = _a.status_code;
242
+ // Do not capture fetches to Sentry ingestion endpoint
243
+ if (isIngestHost(url)) {
244
+ return null;
245
+ }
246
+ return {
247
+ type: 'resource.xhr',
248
+ name: url,
249
+ start: handlerData.xhr.__sentry_xhr__.startTimestamp / 1000 ||
250
+ handlerData.endTimestamp / 1000.0,
251
+ end: handlerData.endTimestamp / 1000.0,
252
+ data: {
253
+ method: method,
254
+ statusCode: statusCode,
255
+ },
256
+ };
257
+ }
258
+
259
+ function getSpanHandler(type) {
260
+ if (type === 'fetch') {
261
+ return handleFetch;
262
+ }
263
+ if (type === 'xhr') {
264
+ return handleXhr;
265
+ }
266
+ return handleHistory;
267
+ }
268
+
124
269
  /**
125
270
  * Given an initial timestamp and an expiry duration, checks to see if current
126
271
  * time should be considered as expired.
@@ -148,9 +293,11 @@ function isSessionExpired(session, expiry, targetTime) {
148
293
 
149
294
  function wrapLogger(logFn) {
150
295
  return function wrappedLog() {
151
- {
152
- return;
296
+ var args = [];
297
+ for (var _i = 0; _i < arguments.length; _i++) {
298
+ args[_i] = arguments[_i];
153
299
  }
300
+ return logFn.call.apply(logFn, __spreadArray([utils.logger, '[Replay]'], args, false));
154
301
  };
155
302
  }
156
303
  var logger = __assign(__assign({}, utils.logger), { error: wrapLogger(utils.logger.error), warn: wrapLogger(utils.logger.warn), log: wrapLogger(utils.logger.log) });
@@ -311,7 +458,6 @@ function getSession(_a) {
311
458
  // TODO: We should probably set a max age on this as well
312
459
  var isExpired = isSessionExpired(session, expiry);
313
460
  if (!isExpired) {
314
- logger.log("Using existing session: ".concat(session.id));
315
461
  return { type: 'saved', session: session };
316
462
  }
317
463
  else {
@@ -323,10 +469,6 @@ function getSession(_a) {
323
469
  return { type: 'new', session: newSession };
324
470
  }
325
471
 
326
- function createBreadcrumb(breadcrumb) {
327
- return __assign({ timestamp: new Date().getTime() / 1000, type: 'default' }, breadcrumb);
328
- }
329
-
330
472
  /**
331
473
  * Determine if there is browser support for `navigator.sendBeacon`
332
474
  */
@@ -334,92 +476,6 @@ function supportsSendBeacon() {
334
476
  return 'navigator' in window && 'sendBeacon' in window.navigator;
335
477
  }
336
478
 
337
- function handleDom(handlerData) {
338
- // Taken from https://github.com/getsentry/sentry-javascript/blob/master/packages/browser/src/integrations/breadcrumbs.ts#L112
339
- var target;
340
- var targetNode;
341
- // Accessing event.target can throw (see getsentry/raven-js#838, #768)
342
- try {
343
- targetNode =
344
- handlerData.event.target ||
345
- handlerData.event;
346
- target = utils.htmlTreeAsString(targetNode);
347
- }
348
- catch (e) {
349
- target = '<unknown>';
350
- }
351
- if (target.length === 0) {
352
- return null;
353
- }
354
- return createBreadcrumb({
355
- category: "ui.".concat(handlerData.name),
356
- message: target,
357
- data: __assign({}, (targetNode ? { nodeId: rrweb.record.mirror.getId(targetNode) } : {})),
358
- });
359
- }
360
-
361
- function handleFetch(handlerData) {
362
- if (!handlerData.endTimestamp) {
363
- return null;
364
- }
365
- var _a = handlerData.args, op = _a[0], description = _a[1];
366
- return {
367
- description: description,
368
- op: op,
369
- startTimestamp: handlerData.startTimestamp / 1000,
370
- endTimestamp: handlerData.endTimestamp / 1000,
371
- data: {
372
- statusCode: handlerData.response.status,
373
- },
374
- };
375
- }
376
-
377
- var _LAST_BREADCRUMB = null;
378
- function handleScope(scope) {
379
- var _a;
380
- //@ts-expect-error using private val
381
- var newBreadcrumb = scope._breadcrumbs[scope._breadcrumbs.length - 1];
382
- // Listener can be called when breadcrumbs have not changed, so we store the
383
- // reference to the last crumb and only return a crumb if it has changed
384
- if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {
385
- return null;
386
- }
387
- _LAST_BREADCRUMB = newBreadcrumb;
388
- if (['fetch', 'xhr', 'sentry.event', 'sentry.transaction'].includes(newBreadcrumb.category) ||
389
- ((_a = newBreadcrumb.category) === null || _a === void 0 ? void 0 : _a.startsWith('ui.'))) {
390
- return null;
391
- }
392
- return createBreadcrumb(newBreadcrumb);
393
- }
394
-
395
- function handleXhr(handlerData) {
396
- if (handlerData.startTimestamp) {
397
- handlerData.xhr.__sentry_xhr__.startTimestamp = handlerData.startTimestamp;
398
- }
399
- if (!handlerData.endTimestamp) {
400
- return null;
401
- }
402
- var _a = handlerData.args, op = _a[0], description = _a[1];
403
- return {
404
- description: description,
405
- op: op,
406
- startTimestamp: handlerData.xhr.__sentry_xhr__.startTimestamp / 1000 ||
407
- handlerData.endTimestamp / 1000.0,
408
- endTimestamp: handlerData.endTimestamp / 1000.0,
409
- data: {
410
- statusCode: handlerData.response.status,
411
- },
412
- };
413
- }
414
-
415
- /**
416
- * Checks is `targetHost` is a Sentry ingestion host
417
- */
418
- function isIngestHost(targetHost) {
419
- var _a = core.getCurrentHub().getClient().getDsn(), protocol = _a.protocol, host = _a.host;
420
- return targetHost.startsWith("".concat(protocol, "://").concat(host));
421
- }
422
-
423
479
  var _a;
424
480
  // Map entryType -> function to normalize data for event
425
481
  var ENTRY_TYPES = (_a = {
@@ -470,6 +526,10 @@ function createResourceEntry(entry) {
470
526
  if (isIngestHost(name)) {
471
527
  return null;
472
528
  }
529
+ // Core SDK handles these
530
+ if (['fetch', 'xmlhttprequest'].includes(initiatorType)) {
531
+ return null;
532
+ }
473
533
  return {
474
534
  type: "".concat(entryType, ".").concat(initiatorType),
475
535
  start: getAbsoluteTime(startTime),
@@ -530,7 +590,6 @@ function createEventBuffer(_a) {
530
590
  return new EventBufferCompressionWorker(worker);
531
591
  }
532
592
  else {
533
- // TODO: Debugging
534
593
  core.captureException(new Error('Unable to create compression worker'));
535
594
  }
536
595
  }
@@ -583,39 +642,25 @@ var EventBufferCompressionWorker = /** @class */ (function () {
583
642
  this.eventBufferItemLength = 0;
584
643
  this._id = 0;
585
644
  this.sendEventToWorker = function (event) {
586
- _this.postMessage({
645
+ var promise = _this.postMessage({
587
646
  id: _this.id,
588
647
  method: 'addEvent',
589
648
  args: [event],
590
649
  });
591
- logger.log('Message posted to compression worker');
650
+ logger.log('Message posted to worker');
651
+ // XXX: See note in `get length()`
592
652
  _this.eventBufferItemLength++;
653
+ return promise;
593
654
  };
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: [] });
655
+ this.finishRequest = function (id) { return __awaiter(_this, void 0, void 0, function () {
656
+ var promise;
657
+ return __generator(this, function (_a) {
658
+ promise = this.postMessage({ id: id, method: 'finish', args: [] });
659
+ // XXX: See note in `get length()`
660
+ this.eventBufferItemLength = 0;
661
+ return [2 /*return*/, promise];
617
662
  });
618
- };
663
+ }); };
619
664
  this.worker = worker;
620
665
  }
621
666
  Object.defineProperty(EventBufferCompressionWorker.prototype, "id", {
@@ -628,8 +673,38 @@ var EventBufferCompressionWorker = /** @class */ (function () {
628
673
  enumerable: false,
629
674
  configurable: true
630
675
  });
631
- EventBufferCompressionWorker.prototype.postMessage = function (args) {
632
- this.worker.postMessage(args);
676
+ /**
677
+ * Post message to worker and wait for response before resolving promise.
678
+ */
679
+ EventBufferCompressionWorker.prototype.postMessage = function (_a) {
680
+ var _this = this;
681
+ var id = _a.id, method = _a.method, args = _a.args;
682
+ return new Promise(function (resolve, reject) {
683
+ var listener = function (_a) {
684
+ var data = _a.data;
685
+ if (data.method !== method) {
686
+ return;
687
+ }
688
+ // There can be multiple listeners for a single method, the id ensures
689
+ // that the response matches the caller.
690
+ if (data.id !== id) {
691
+ return;
692
+ }
693
+ // At this point, we'll always want to remove listener regardless of result status
694
+ _this.worker.removeEventListener('message', listener);
695
+ if (!data.success) {
696
+ // TODO: Do some error handling, not sure what
697
+ logger.error(data.response);
698
+ reject(new Error('Error in compression worker'));
699
+ return;
700
+ }
701
+ resolve(data.response);
702
+ };
703
+ // Note: we can't use `once` option because it's possible it needs to
704
+ // listen to multiple messages
705
+ _this.worker.addEventListener('message', listener);
706
+ _this.worker.postMessage({ id: id, method: method, args: args });
707
+ });
633
708
  };
634
709
  EventBufferCompressionWorker.prototype.init = function () {
635
710
  this.postMessage({ id: this.id, method: 'init', args: [] });
@@ -641,6 +716,10 @@ var EventBufferCompressionWorker = /** @class */ (function () {
641
716
  this.worker = null;
642
717
  };
643
718
  Object.defineProperty(EventBufferCompressionWorker.prototype, "length", {
719
+ /**
720
+ * Note that this may not reflect what is actually in the event buffer. This
721
+ * is only a local count of the buffer size since `addEvent` is async.
722
+ */
644
723
  get: function () {
645
724
  return this.eventBufferItemLength;
646
725
  },
@@ -648,39 +727,31 @@ var EventBufferCompressionWorker = /** @class */ (function () {
648
727
  configurable: true
649
728
  });
650
729
  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
730
  return __awaiter(this, void 0, void 0, function () {
676
731
  return __generator(this, function (_a) {
677
732
  switch (_a.label) {
678
- case 0: return [4 /*yield*/, this.finishRequest(this.id)];
679
- case 1: return [2 /*return*/, _a.sent()];
733
+ case 0:
734
+ if (!isCheckout) return [3 /*break*/, 2];
735
+ // This event is a checkout, make sure worker buffer is cleared before
736
+ // proceeding.
737
+ return [4 /*yield*/, this.postMessage({
738
+ id: this.id,
739
+ method: 'init',
740
+ args: [],
741
+ })];
742
+ case 1:
743
+ // This event is a checkout, make sure worker buffer is cleared before
744
+ // proceeding.
745
+ _a.sent();
746
+ _a.label = 2;
747
+ case 2: return [2 /*return*/, this.sendEventToWorker(event)];
680
748
  }
681
749
  });
682
750
  });
683
751
  };
752
+ EventBufferCompressionWorker.prototype.finish = function () {
753
+ return this.finishRequest(this.id);
754
+ };
684
755
  return EventBufferCompressionWorker;
685
756
  }());
686
757
 
@@ -701,10 +772,6 @@ var SentryReplay = /** @class */ (function () {
701
772
  * Buffer of breadcrumbs to be uploaded
702
773
  */
703
774
  this.breadcrumbs = [];
704
- /**
705
- * Buffer of replay spans to be uploaded
706
- */
707
- this.replaySpans = [];
708
775
  /**
709
776
  * List of PerformanceEntry from PerformanceObserver
710
777
  */
@@ -725,19 +792,33 @@ var SentryReplay = /** @class */ (function () {
725
792
  * immediately before sending recording)
726
793
  */
727
794
  this.needsCaptureReplay = false;
795
+ this.context = {
796
+ errorIds: new Set(),
797
+ traceIds: new Set(),
798
+ urls: [],
799
+ };
728
800
  /**
729
801
  * Core Sentry SDK global event handler. Attaches `replayId` to all [non-replay]
730
802
  * events as a tag. Also handles the case where we only want to capture a reply
731
803
  * when an error occurs.
732
804
  **/
733
805
  this.handleGlobalEvent = function (event) {
734
- var _a;
806
+ var _a, _b;
735
807
  // Do not apply replayId to the root event
736
808
  if (event.message === ROOT_REPLAY_NAME ||
737
809
  ((_a = event.message) === null || _a === void 0 ? void 0 : _a.startsWith(REPLAY_EVENT_NAME))) {
810
+ // Replays have separate set of breadcrumbs, do not include breadcrumbs
811
+ // from core SDK
812
+ delete event.breadcrumbs;
738
813
  return event;
739
814
  }
740
815
  event.tags = __assign(__assign({}, event.tags), { replayId: _this.session.id });
816
+ if (event.type === 'transaction') {
817
+ _this.context.traceIds.add(String(((_b = event.contexts) === null || _b === void 0 ? void 0 : _b.trace.trace_id) || ''));
818
+ return event;
819
+ }
820
+ // XXX: Is it safe to assume that all other events are error events?
821
+ _this.context.errorIds.add(event.event_id);
741
822
  // Need to be very careful that this does not cause an infinite loop
742
823
  if (_this.options.captureOnlyOnError && event.exception) {
743
824
  // TODO: Do we continue to record after?
@@ -828,25 +909,35 @@ var SentryReplay = /** @class */ (function () {
828
909
  /**
829
910
  * Handler for Sentry Core SDK events.
830
911
  *
831
- * Transforms core SDK events into replay events.
912
+ * These specific events will create span-like objects in the recording.
832
913
  *
833
914
  */
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));
915
+ this.handleCoreSpanListener = function (type) { return function (handlerData) {
916
+ var handler = getSpanHandler(type);
917
+ var result = handler(handlerData);
918
+ if (result === null) {
919
+ return;
920
+ }
921
+ if (type === 'history') {
922
+ // Need to collect visited URLs
923
+ _this.context.urls.push(result.name);
843
924
  }
844
- var _a = handlerMap[type], handlerFn = _a[0], eventType = _a[1];
845
- var result = handlerFn(handlerData);
925
+ _this.addUpdate(function () {
926
+ _this.createPerformanceSpans([result]);
927
+ });
928
+ }; };
929
+ /**
930
+ * Handler for Sentry Core SDK events.
931
+ *
932
+ * These events will create breadcrumb-like objects in the recording.
933
+ */
934
+ this.handleCoreBreadcrumbListener = function (type) { return function (handlerData) {
935
+ var handler = getBreadcrumbHandler(type);
936
+ var result = handler(handlerData);
846
937
  if (result === null) {
847
938
  return;
848
939
  }
849
- if (['sentry.transaction'].includes(result.category)) {
940
+ if (result.category === 'sentry.transaction') {
850
941
  return;
851
942
  }
852
943
  _this.addUpdate(function () {
@@ -854,10 +945,9 @@ var SentryReplay = /** @class */ (function () {
854
945
  type: rrweb.EventType.Custom,
855
946
  // TODO: We were converting from ms to seconds for breadcrumbs, spans,
856
947
  // but maybe we should just keep them as milliseconds
857
- timestamp: result.timestamp * 1000 ||
858
- result.startTimestamp * 1000,
948
+ timestamp: result.timestamp * 1000,
859
949
  data: {
860
- tag: eventType,
950
+ tag: 'breadcrumb',
861
951
  payload: result,
862
952
  },
863
953
  });
@@ -931,12 +1021,15 @@ var SentryReplay = /** @class */ (function () {
931
1021
  // replay ID so that we can reference them later in the UI
932
1022
  core.addGlobalEventProcessor(this.handleGlobalEvent);
933
1023
  rrweb.record(__assign(__assign({}, this.recordingOptions), { emit: this.handleRecordingEmit }));
1024
+ var urlPath = "".concat(window.location.pathname).concat(window.location.hash).concat(window.location.search);
1025
+ var url = "".concat(window.location.origin).concat(urlPath);
934
1026
  // Otherwise, these will be captured after the first flush, which means the
935
1027
  // URL and timestamps could be incorrect
936
1028
  this.initialState = {
937
1029
  timestamp: new Date().getTime(),
938
- url: "".concat(window.location.origin).concat(window.location.pathname),
1030
+ url: url,
939
1031
  };
1032
+ this.context.urls.push(url);
940
1033
  };
941
1034
  /**
942
1035
  * We want to batch uploads of replay events. Save events only if
@@ -993,7 +1086,6 @@ var SentryReplay = /** @class */ (function () {
993
1086
  SentryReplay.prototype.destroy = function () {
994
1087
  logger.log('Destroying instance');
995
1088
  this.removeListeners();
996
- // this.eventBuffer.clear();
997
1089
  };
998
1090
  SentryReplay.prototype.clearSession = function () {
999
1091
  this.session = null;
@@ -1032,8 +1124,11 @@ var SentryReplay = /** @class */ (function () {
1032
1124
  window.addEventListener('beforeunload', this.handleWindowUnload);
1033
1125
  // Listeners from core SDK //
1034
1126
  var scope = core.getCurrentHub().getScope();
1035
- scope.addScopeListener(this.handleCoreListener('scope'));
1036
- utils.addInstrumentationHandler('dom', this.handleCoreListener('dom'));
1127
+ scope.addScopeListener(this.handleCoreBreadcrumbListener('scope'));
1128
+ utils.addInstrumentationHandler('dom', this.handleCoreBreadcrumbListener('dom'));
1129
+ utils.addInstrumentationHandler('fetch', this.handleCoreSpanListener('fetch'));
1130
+ utils.addInstrumentationHandler('xhr', this.handleCoreSpanListener('xhr'));
1131
+ utils.addInstrumentationHandler('history', this.handleCoreSpanListener('history'));
1037
1132
  // PerformanceObserver //
1038
1133
  if (!('PerformanceObserver' in window)) {
1039
1134
  return;
@@ -1144,13 +1239,13 @@ var SentryReplay = /** @class */ (function () {
1144
1239
  });
1145
1240
  };
1146
1241
  /**
1147
- * Create a span for each performance entry. The parent transaction is `this.replayEvent`.
1242
+ * Create a "span" for each performance entry. The parent transaction is `this.replayEvent`.
1148
1243
  */
1149
1244
  SentryReplay.prototype.createPerformanceSpans = function (entries) {
1150
1245
  var _this = this;
1151
- entries.forEach(function (_a) {
1246
+ return Promise.all(entries.map(function (_a) {
1152
1247
  var type = _a.type, start = _a.start, end = _a.end, name = _a.name, data = _a.data;
1153
- _this.eventBuffer.addEvent({
1248
+ return _this.eventBuffer.addEvent({
1154
1249
  type: rrweb.EventType.Custom,
1155
1250
  timestamp: start,
1156
1251
  data: {
@@ -1164,7 +1259,7 @@ var SentryReplay = /** @class */ (function () {
1164
1259
  },
1165
1260
  },
1166
1261
  });
1167
- });
1262
+ }));
1168
1263
  };
1169
1264
  /**
1170
1265
  * Observed performance events are added to `this.performanceEvents`. These
@@ -1174,15 +1269,22 @@ var SentryReplay = /** @class */ (function () {
1174
1269
  // Copy and reset entries before processing
1175
1270
  var entries = __spreadArray([], this.performanceEvents, true);
1176
1271
  this.performanceEvents = [];
1177
- // Parse the entries
1178
- var entryEvents = createPerformanceEntries(entries);
1272
+ return this.createPerformanceSpans(createPerformanceEntries(entries));
1273
+ };
1274
+ /**
1275
+ * Create a "span" for the total amount of memory being used by JS objects
1276
+ * (including v8 internal objects).
1277
+ */
1278
+ SentryReplay.prototype.addMemoryEntry = function () {
1179
1279
  // window.performance.memory is a non-standard API and doesn't work on all browsers
1180
1280
  // 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));
1281
+ if (!('memory' in window.performance)) {
1282
+ return;
1184
1283
  }
1185
- this.createPerformanceSpans(entryEvents);
1284
+ return this.createPerformanceSpans([
1285
+ // @ts-expect-error memory doesn't exist on type Performance as the API is non-standard (we check that it exists above)
1286
+ createMemoryEntry(window.performance.memory),
1287
+ ]);
1186
1288
  };
1187
1289
  /**
1188
1290
  *
@@ -1216,6 +1318,24 @@ var SentryReplay = /** @class */ (function () {
1216
1318
  }
1217
1319
  return this.flushUpdate(lastActivity);
1218
1320
  };
1321
+ /**
1322
+ * Return and clear context
1323
+ */
1324
+ SentryReplay.prototype.popEventContext = function (_a) {
1325
+ var timestamp = _a.timestamp;
1326
+ var context = {
1327
+ session: this.session,
1328
+ initialState: this.initialState,
1329
+ timestamp: timestamp,
1330
+ errorIds: Array.from(this.context.errorIds).filter(Boolean),
1331
+ traceIds: Array.from(this.context.traceIds).filter(Boolean),
1332
+ urls: this.context.urls,
1333
+ };
1334
+ this.context.errorIds.clear();
1335
+ this.context.traceIds.clear();
1336
+ this.context.urls = [];
1337
+ return context;
1338
+ };
1219
1339
  /**
1220
1340
  * Flushes replay event buffer to Sentry.
1221
1341
  *
@@ -1236,28 +1356,37 @@ var SentryReplay = /** @class */ (function () {
1236
1356
  console.error(new Error('[Sentry]: No transaction, no replay'));
1237
1357
  return [2 /*return*/];
1238
1358
  }
1239
- this.addPerformanceEntries();
1359
+ // Since already flushing, ensure other queued flushes are cancelled
1360
+ clearTimeout(this.timeout);
1361
+ return [4 /*yield*/, this.addPerformanceEntries()];
1362
+ case 1:
1363
+ _a.sent();
1240
1364
  if (!this.eventBuffer.length) {
1241
1365
  return [2 /*return*/];
1242
1366
  }
1367
+ // Only attach memory event if eventBuffer is not empty
1368
+ return [4 /*yield*/, this.addMemoryEntry()];
1369
+ case 2:
1370
+ // Only attach memory event if eventBuffer is not empty
1371
+ _a.sent();
1372
+ timestamp = lastActivity !== null && lastActivity !== void 0 ? lastActivity : new Date().getTime();
1243
1373
  // Only want to create replay event if session is new
1244
1374
  if (this.needsCaptureReplay) {
1245
1375
  // This event needs to exist before calling `sendReplay`
1246
- captureReplay({ session: this.session, initialState: this.initialState });
1376
+ captureReplay(this.popEventContext({ timestamp: timestamp }));
1247
1377
  this.needsCaptureReplay = false;
1248
1378
  }
1249
1379
  // Reset this to null regardless of `sendReplay` result so that future
1250
1380
  // events will get flushed properly
1251
1381
  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();
1382
+ _a.label = 3;
1383
+ case 3:
1384
+ _a.trys.push([3, 6, , 7]);
1256
1385
  return [4 /*yield*/, this.eventBuffer.finish()];
1257
- case 2:
1386
+ case 4:
1258
1387
  recordingData = _a.sent();
1259
1388
  return [4 /*yield*/, this.sendReplay(this.session.id, recordingData)];
1260
- case 3:
1389
+ case 5:
1261
1390
  _a.sent();
1262
1391
  // The below will only happen after successfully sending replay //
1263
1392
  // TBD: Alternatively we could update this after every rrweb event
@@ -1265,13 +1394,14 @@ var SentryReplay = /** @class */ (function () {
1265
1394
  // of the event is passed as an argument in the case where a timeout
1266
1395
  // occurs.
1267
1396
  this.updateLastActivity(timestamp);
1268
- captureReplayUpdate({ session: this.session, timestamp: timestamp });
1269
- return [3 /*break*/, 5];
1270
- case 4:
1397
+ captureReplayUpdate(this.popEventContext({ timestamp: timestamp }));
1398
+ return [3 /*break*/, 7];
1399
+ case 6:
1271
1400
  err_1 = _a.sent();
1401
+ core.captureException(err_1);
1272
1402
  console.error(err_1);
1273
- return [3 /*break*/, 5];
1274
- case 5: return [2 /*return*/];
1403
+ return [3 /*break*/, 7];
1404
+ case 7: return [2 /*return*/];
1275
1405
  }
1276
1406
  });
1277
1407
  });