@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.es.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { captureEvent, getCurrentHub, captureException, addGlobalEventProcessor } from '@sentry/core';
2
- import { uuid4, logger as logger$1, htmlTreeAsString, addInstrumentationHandler } from '@sentry/utils';
2
+ import { uuid4, htmlTreeAsString, logger as logger$1, addInstrumentationHandler } from '@sentry/utils';
3
3
  import { record, EventType } from 'rrweb';
4
4
 
5
5
  /******************************************************************************
@@ -97,19 +97,27 @@ var SESSION_IDLE_DURATION = 900000; // 15 minutes
97
97
  var VISIBILITY_CHANGE_TIMEOUT = SESSION_IDLE_DURATION;
98
98
 
99
99
  function captureReplay(_a) {
100
- var session = _a.session, initialState = _a.initialState;
100
+ var session = _a.session, initialState = _a.initialState, errorIds = _a.errorIds, traceIds = _a.traceIds, urls = _a.urls;
101
101
  captureEvent({
102
102
  message: ROOT_REPLAY_NAME,
103
103
  tags: { segmentId: session.segmentId, url: initialState.url },
104
104
  timestamp: initialState.timestamp / 1000,
105
+ // @ts-expect-error replay event type accepts this
106
+ error_ids: errorIds,
107
+ trace_ids: traceIds,
108
+ urls: urls,
105
109
  }, { event_id: session.id });
106
110
  }
107
111
 
108
112
  function captureReplayUpdate(_a) {
109
- var session = _a.session, timestamp = _a.timestamp;
113
+ var session = _a.session, timestamp = _a.timestamp, errorIds = _a.errorIds, traceIds = _a.traceIds, urls = _a.urls;
110
114
  captureEvent({
111
115
  timestamp: timestamp / 1000,
112
116
  message: "".concat(REPLAY_EVENT_NAME, "-").concat(uuid4().substring(16)),
117
+ // @ts-expect-error replay event type accepts this
118
+ error_ids: errorIds,
119
+ trace_ids: traceIds,
120
+ urls: urls,
113
121
  tags: {
114
122
  replayId: session.id,
115
123
  segmentId: session.segmentId++,
@@ -117,6 +125,143 @@ function captureReplayUpdate(_a) {
117
125
  });
118
126
  }
119
127
 
128
+ function createBreadcrumb(breadcrumb) {
129
+ return __assign({ timestamp: new Date().getTime() / 1000, type: 'default' }, breadcrumb);
130
+ }
131
+
132
+ function handleDom(handlerData) {
133
+ // Taken from https://github.com/getsentry/sentry-javascript/blob/master/packages/browser/src/integrations/breadcrumbs.ts#L112
134
+ var target;
135
+ var targetNode;
136
+ // Accessing event.target can throw (see getsentry/raven-js#838, #768)
137
+ try {
138
+ targetNode =
139
+ handlerData.event.target ||
140
+ handlerData.event;
141
+ target = htmlTreeAsString(targetNode);
142
+ }
143
+ catch (e) {
144
+ target = '<unknown>';
145
+ }
146
+ if (target.length === 0) {
147
+ return null;
148
+ }
149
+ return createBreadcrumb({
150
+ category: "ui.".concat(handlerData.name),
151
+ message: target,
152
+ data: __assign({}, (targetNode ? { nodeId: record.mirror.getId(targetNode) } : {})),
153
+ });
154
+ }
155
+
156
+ var _LAST_BREADCRUMB = null;
157
+ function handleScope(scope) {
158
+ var _a;
159
+ //@ts-expect-error using private val
160
+ var newBreadcrumb = scope._breadcrumbs[scope._breadcrumbs.length - 1];
161
+ // Listener can be called when breadcrumbs have not changed, so we store the
162
+ // reference to the last crumb and only return a crumb if it has changed
163
+ if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {
164
+ return null;
165
+ }
166
+ _LAST_BREADCRUMB = newBreadcrumb;
167
+ if (['fetch', 'xhr', 'sentry.event', 'sentry.transaction'].includes(newBreadcrumb.category) ||
168
+ ((_a = newBreadcrumb.category) === null || _a === void 0 ? void 0 : _a.startsWith('ui.'))) {
169
+ return null;
170
+ }
171
+ return createBreadcrumb(newBreadcrumb);
172
+ }
173
+
174
+ function getBreadcrumbHandler(type) {
175
+ if (type === 'scope') {
176
+ return handleScope;
177
+ }
178
+ return handleDom;
179
+ }
180
+
181
+ /**
182
+ * Checks is `targetHost` is a Sentry ingestion host
183
+ */
184
+ function isIngestHost(targetHost) {
185
+ var _a = getCurrentHub().getClient().getDsn(), protocol = _a.protocol, host = _a.host;
186
+ return targetHost.startsWith("".concat(protocol, "://").concat(host));
187
+ }
188
+
189
+ function handleFetch(handlerData) {
190
+ if (!handlerData.endTimestamp) {
191
+ return null;
192
+ }
193
+ var startTimestamp = handlerData.startTimestamp, endTimestamp = handlerData.endTimestamp, fetchData = handlerData.fetchData, response = handlerData.response;
194
+ // Do not capture fetches to Sentry ingestion endpoint
195
+ if (isIngestHost(fetchData.url)) {
196
+ return null;
197
+ }
198
+ return {
199
+ type: 'resource.fetch',
200
+ start: startTimestamp / 1000,
201
+ end: endTimestamp / 1000,
202
+ name: fetchData.url,
203
+ data: {
204
+ method: fetchData.method,
205
+ statusCode: response.status,
206
+ },
207
+ };
208
+ }
209
+
210
+ function handleHistory(handlerData) {
211
+ var from = handlerData.from, to = handlerData.to;
212
+ var now = new Date().getTime() / 1000;
213
+ return {
214
+ type: 'navigation.push',
215
+ start: now,
216
+ end: now,
217
+ name: to,
218
+ data: {
219
+ previous: from,
220
+ },
221
+ };
222
+ }
223
+
224
+ function handleXhr(handlerData) {
225
+ if (handlerData.xhr.__sentry_own_request__) {
226
+ // Taken from sentry-javascript
227
+ // Only capture non-sentry requests
228
+ return null;
229
+ }
230
+ if (handlerData.startTimestamp) {
231
+ // TODO: See if this is still needed
232
+ handlerData.xhr.__sentry_xhr__.startTimestamp = handlerData.startTimestamp;
233
+ }
234
+ if (!handlerData.endTimestamp) {
235
+ return null;
236
+ }
237
+ var _a = handlerData.xhr.__sentry_xhr__ || {}, method = _a.method, url = _a.url, statusCode = _a.status_code;
238
+ // Do not capture fetches to Sentry ingestion endpoint
239
+ if (isIngestHost(url)) {
240
+ return null;
241
+ }
242
+ return {
243
+ type: 'resource.xhr',
244
+ name: url,
245
+ start: handlerData.xhr.__sentry_xhr__.startTimestamp / 1000 ||
246
+ handlerData.endTimestamp / 1000.0,
247
+ end: handlerData.endTimestamp / 1000.0,
248
+ data: {
249
+ method: method,
250
+ statusCode: statusCode,
251
+ },
252
+ };
253
+ }
254
+
255
+ function getSpanHandler(type) {
256
+ if (type === 'fetch') {
257
+ return handleFetch;
258
+ }
259
+ if (type === 'xhr') {
260
+ return handleXhr;
261
+ }
262
+ return handleHistory;
263
+ }
264
+
120
265
  /**
121
266
  * Given an initial timestamp and an expiry duration, checks to see if current
122
267
  * time should be considered as expired.
@@ -144,9 +289,11 @@ function isSessionExpired(session, expiry, targetTime) {
144
289
 
145
290
  function wrapLogger(logFn) {
146
291
  return function wrappedLog() {
147
- {
148
- return;
292
+ var args = [];
293
+ for (var _i = 0; _i < arguments.length; _i++) {
294
+ args[_i] = arguments[_i];
149
295
  }
296
+ return logFn.call.apply(logFn, __spreadArray([logger$1, '[Replay]'], args, false));
150
297
  };
151
298
  }
152
299
  var logger = __assign(__assign({}, logger$1), { error: wrapLogger(logger$1.error), warn: wrapLogger(logger$1.warn), log: wrapLogger(logger$1.log) });
@@ -307,7 +454,6 @@ function getSession(_a) {
307
454
  // TODO: We should probably set a max age on this as well
308
455
  var isExpired = isSessionExpired(session, expiry);
309
456
  if (!isExpired) {
310
- logger.log("Using existing session: ".concat(session.id));
311
457
  return { type: 'saved', session: session };
312
458
  }
313
459
  else {
@@ -319,10 +465,6 @@ function getSession(_a) {
319
465
  return { type: 'new', session: newSession };
320
466
  }
321
467
 
322
- function createBreadcrumb(breadcrumb) {
323
- return __assign({ timestamp: new Date().getTime() / 1000, type: 'default' }, breadcrumb);
324
- }
325
-
326
468
  /**
327
469
  * Determine if there is browser support for `navigator.sendBeacon`
328
470
  */
@@ -330,92 +472,6 @@ function supportsSendBeacon() {
330
472
  return 'navigator' in window && 'sendBeacon' in window.navigator;
331
473
  }
332
474
 
333
- function handleDom(handlerData) {
334
- // Taken from https://github.com/getsentry/sentry-javascript/blob/master/packages/browser/src/integrations/breadcrumbs.ts#L112
335
- var target;
336
- var targetNode;
337
- // Accessing event.target can throw (see getsentry/raven-js#838, #768)
338
- try {
339
- targetNode =
340
- handlerData.event.target ||
341
- handlerData.event;
342
- target = htmlTreeAsString(targetNode);
343
- }
344
- catch (e) {
345
- target = '<unknown>';
346
- }
347
- if (target.length === 0) {
348
- return null;
349
- }
350
- return createBreadcrumb({
351
- category: "ui.".concat(handlerData.name),
352
- message: target,
353
- data: __assign({}, (targetNode ? { nodeId: record.mirror.getId(targetNode) } : {})),
354
- });
355
- }
356
-
357
- function handleFetch(handlerData) {
358
- if (!handlerData.endTimestamp) {
359
- return null;
360
- }
361
- var _a = handlerData.args, op = _a[0], description = _a[1];
362
- return {
363
- description: description,
364
- op: op,
365
- startTimestamp: handlerData.startTimestamp / 1000,
366
- endTimestamp: handlerData.endTimestamp / 1000,
367
- data: {
368
- statusCode: handlerData.response.status,
369
- },
370
- };
371
- }
372
-
373
- var _LAST_BREADCRUMB = null;
374
- function handleScope(scope) {
375
- var _a;
376
- //@ts-expect-error using private val
377
- var newBreadcrumb = scope._breadcrumbs[scope._breadcrumbs.length - 1];
378
- // Listener can be called when breadcrumbs have not changed, so we store the
379
- // reference to the last crumb and only return a crumb if it has changed
380
- if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {
381
- return null;
382
- }
383
- _LAST_BREADCRUMB = newBreadcrumb;
384
- if (['fetch', 'xhr', 'sentry.event', 'sentry.transaction'].includes(newBreadcrumb.category) ||
385
- ((_a = newBreadcrumb.category) === null || _a === void 0 ? void 0 : _a.startsWith('ui.'))) {
386
- return null;
387
- }
388
- return createBreadcrumb(newBreadcrumb);
389
- }
390
-
391
- function handleXhr(handlerData) {
392
- if (handlerData.startTimestamp) {
393
- handlerData.xhr.__sentry_xhr__.startTimestamp = handlerData.startTimestamp;
394
- }
395
- if (!handlerData.endTimestamp) {
396
- return null;
397
- }
398
- var _a = handlerData.args, op = _a[0], description = _a[1];
399
- return {
400
- description: description,
401
- op: op,
402
- startTimestamp: handlerData.xhr.__sentry_xhr__.startTimestamp / 1000 ||
403
- handlerData.endTimestamp / 1000.0,
404
- endTimestamp: handlerData.endTimestamp / 1000.0,
405
- data: {
406
- statusCode: handlerData.response.status,
407
- },
408
- };
409
- }
410
-
411
- /**
412
- * Checks is `targetHost` is a Sentry ingestion host
413
- */
414
- function isIngestHost(targetHost) {
415
- var _a = getCurrentHub().getClient().getDsn(), protocol = _a.protocol, host = _a.host;
416
- return targetHost.startsWith("".concat(protocol, "://").concat(host));
417
- }
418
-
419
475
  var _a;
420
476
  // Map entryType -> function to normalize data for event
421
477
  var ENTRY_TYPES = (_a = {
@@ -466,6 +522,10 @@ function createResourceEntry(entry) {
466
522
  if (isIngestHost(name)) {
467
523
  return null;
468
524
  }
525
+ // Core SDK handles these
526
+ if (['fetch', 'xmlhttprequest'].includes(initiatorType)) {
527
+ return null;
528
+ }
469
529
  return {
470
530
  type: "".concat(entryType, ".").concat(initiatorType),
471
531
  start: getAbsoluteTime(startTime),
@@ -526,7 +586,6 @@ function createEventBuffer(_a) {
526
586
  return new EventBufferCompressionWorker(worker);
527
587
  }
528
588
  else {
529
- // TODO: Debugging
530
589
  captureException(new Error('Unable to create compression worker'));
531
590
  }
532
591
  }
@@ -579,39 +638,25 @@ var EventBufferCompressionWorker = /** @class */ (function () {
579
638
  this.eventBufferItemLength = 0;
580
639
  this._id = 0;
581
640
  this.sendEventToWorker = function (event) {
582
- _this.postMessage({
641
+ var promise = _this.postMessage({
583
642
  id: _this.id,
584
643
  method: 'addEvent',
585
644
  args: [event],
586
645
  });
587
- logger.log('Message posted to compression worker');
646
+ logger.log('Message posted to worker');
647
+ // XXX: See note in `get length()`
588
648
  _this.eventBufferItemLength++;
649
+ return promise;
589
650
  };
590
- this.finishRequest = function (id) {
591
- return new Promise(function (resolve, reject) {
592
- var finishListener = function (_a) {
593
- var data = _a.data;
594
- if (data.method !== 'finish') {
595
- return;
596
- }
597
- if (data.id !== id) {
598
- return;
599
- }
600
- if (!data.success) {
601
- // TODO: Do some error handling, not sure what
602
- logger.error(data.response);
603
- reject(new Error('Error in compression worker'));
604
- return;
605
- }
606
- resolve(data.response);
607
- logger.log('Worker responded with compressed payload');
608
- _this.eventBufferItemLength = 0;
609
- _this.worker.removeEventListener('message', finishListener);
610
- };
611
- _this.worker.addEventListener('message', finishListener);
612
- _this.postMessage({ id: id, method: 'finish', args: [] });
651
+ this.finishRequest = function (id) { return __awaiter(_this, void 0, void 0, function () {
652
+ var promise;
653
+ return __generator(this, function (_a) {
654
+ promise = this.postMessage({ id: id, method: 'finish', args: [] });
655
+ // XXX: See note in `get length()`
656
+ this.eventBufferItemLength = 0;
657
+ return [2 /*return*/, promise];
613
658
  });
614
- };
659
+ }); };
615
660
  this.worker = worker;
616
661
  }
617
662
  Object.defineProperty(EventBufferCompressionWorker.prototype, "id", {
@@ -624,8 +669,38 @@ var EventBufferCompressionWorker = /** @class */ (function () {
624
669
  enumerable: false,
625
670
  configurable: true
626
671
  });
627
- EventBufferCompressionWorker.prototype.postMessage = function (args) {
628
- this.worker.postMessage(args);
672
+ /**
673
+ * Post message to worker and wait for response before resolving promise.
674
+ */
675
+ EventBufferCompressionWorker.prototype.postMessage = function (_a) {
676
+ var _this = this;
677
+ var id = _a.id, method = _a.method, args = _a.args;
678
+ return new Promise(function (resolve, reject) {
679
+ var listener = function (_a) {
680
+ var data = _a.data;
681
+ if (data.method !== method) {
682
+ return;
683
+ }
684
+ // There can be multiple listeners for a single method, the id ensures
685
+ // that the response matches the caller.
686
+ if (data.id !== id) {
687
+ return;
688
+ }
689
+ // At this point, we'll always want to remove listener regardless of result status
690
+ _this.worker.removeEventListener('message', listener);
691
+ if (!data.success) {
692
+ // TODO: Do some error handling, not sure what
693
+ logger.error(data.response);
694
+ reject(new Error('Error in compression worker'));
695
+ return;
696
+ }
697
+ resolve(data.response);
698
+ };
699
+ // Note: we can't use `once` option because it's possible it needs to
700
+ // listen to multiple messages
701
+ _this.worker.addEventListener('message', listener);
702
+ _this.worker.postMessage({ id: id, method: method, args: args });
703
+ });
629
704
  };
630
705
  EventBufferCompressionWorker.prototype.init = function () {
631
706
  this.postMessage({ id: this.id, method: 'init', args: [] });
@@ -637,6 +712,10 @@ var EventBufferCompressionWorker = /** @class */ (function () {
637
712
  this.worker = null;
638
713
  };
639
714
  Object.defineProperty(EventBufferCompressionWorker.prototype, "length", {
715
+ /**
716
+ * Note that this may not reflect what is actually in the event buffer. This
717
+ * is only a local count of the buffer size since `addEvent` is async.
718
+ */
640
719
  get: function () {
641
720
  return this.eventBufferItemLength;
642
721
  },
@@ -644,39 +723,31 @@ var EventBufferCompressionWorker = /** @class */ (function () {
644
723
  configurable: true
645
724
  });
646
725
  EventBufferCompressionWorker.prototype.addEvent = function (event, isCheckout) {
647
- var _this = this;
648
- // If it is a checkout we should make sure worker buffer is cleared before proceeding
649
- if (!isCheckout) {
650
- this.sendEventToWorker(event);
651
- return;
652
- }
653
- var initListener = function (_a) {
654
- var data = _a.data;
655
- if (data.method !== 'init') {
656
- return;
657
- }
658
- if (!data.success) {
659
- // TODO: Do some error handling, not sure what
660
- logger.error(data.response);
661
- return;
662
- }
663
- // Worker has been re-initialized, can add event now
664
- _this.sendEventToWorker(event);
665
- _this.worker.removeEventListener('message', initListener);
666
- };
667
- this.worker.addEventListener('message', initListener);
668
- this.postMessage({ id: this.id, method: 'init', args: [] });
669
- };
670
- EventBufferCompressionWorker.prototype.finish = function () {
671
726
  return __awaiter(this, void 0, void 0, function () {
672
727
  return __generator(this, function (_a) {
673
728
  switch (_a.label) {
674
- case 0: return [4 /*yield*/, this.finishRequest(this.id)];
675
- case 1: return [2 /*return*/, _a.sent()];
729
+ case 0:
730
+ if (!isCheckout) return [3 /*break*/, 2];
731
+ // This event is a checkout, make sure worker buffer is cleared before
732
+ // proceeding.
733
+ return [4 /*yield*/, this.postMessage({
734
+ id: this.id,
735
+ method: 'init',
736
+ args: [],
737
+ })];
738
+ case 1:
739
+ // This event is a checkout, make sure worker buffer is cleared before
740
+ // proceeding.
741
+ _a.sent();
742
+ _a.label = 2;
743
+ case 2: return [2 /*return*/, this.sendEventToWorker(event)];
676
744
  }
677
745
  });
678
746
  });
679
747
  };
748
+ EventBufferCompressionWorker.prototype.finish = function () {
749
+ return this.finishRequest(this.id);
750
+ };
680
751
  return EventBufferCompressionWorker;
681
752
  }());
682
753
 
@@ -697,10 +768,6 @@ var SentryReplay = /** @class */ (function () {
697
768
  * Buffer of breadcrumbs to be uploaded
698
769
  */
699
770
  this.breadcrumbs = [];
700
- /**
701
- * Buffer of replay spans to be uploaded
702
- */
703
- this.replaySpans = [];
704
771
  /**
705
772
  * List of PerformanceEntry from PerformanceObserver
706
773
  */
@@ -721,19 +788,33 @@ var SentryReplay = /** @class */ (function () {
721
788
  * immediately before sending recording)
722
789
  */
723
790
  this.needsCaptureReplay = false;
791
+ this.context = {
792
+ errorIds: new Set(),
793
+ traceIds: new Set(),
794
+ urls: [],
795
+ };
724
796
  /**
725
797
  * Core Sentry SDK global event handler. Attaches `replayId` to all [non-replay]
726
798
  * events as a tag. Also handles the case where we only want to capture a reply
727
799
  * when an error occurs.
728
800
  **/
729
801
  this.handleGlobalEvent = function (event) {
730
- var _a;
802
+ var _a, _b;
731
803
  // Do not apply replayId to the root event
732
804
  if (event.message === ROOT_REPLAY_NAME ||
733
805
  ((_a = event.message) === null || _a === void 0 ? void 0 : _a.startsWith(REPLAY_EVENT_NAME))) {
806
+ // Replays have separate set of breadcrumbs, do not include breadcrumbs
807
+ // from core SDK
808
+ delete event.breadcrumbs;
734
809
  return event;
735
810
  }
736
811
  event.tags = __assign(__assign({}, event.tags), { replayId: _this.session.id });
812
+ if (event.type === 'transaction') {
813
+ _this.context.traceIds.add(String(((_b = event.contexts) === null || _b === void 0 ? void 0 : _b.trace.trace_id) || ''));
814
+ return event;
815
+ }
816
+ // XXX: Is it safe to assume that all other events are error events?
817
+ _this.context.errorIds.add(event.event_id);
737
818
  // Need to be very careful that this does not cause an infinite loop
738
819
  if (_this.options.captureOnlyOnError && event.exception) {
739
820
  // TODO: Do we continue to record after?
@@ -824,25 +905,35 @@ var SentryReplay = /** @class */ (function () {
824
905
  /**
825
906
  * Handler for Sentry Core SDK events.
826
907
  *
827
- * Transforms core SDK events into replay events.
908
+ * These specific events will create span-like objects in the recording.
828
909
  *
829
910
  */
830
- this.handleCoreListener = function (type) { return function (handlerData) {
831
- var handlerMap = {
832
- scope: [handleScope, 'breadcrumb'],
833
- dom: [handleDom, 'breadcrumb'],
834
- fetch: [handleFetch, 'span'],
835
- xhr: [handleXhr, 'span'],
836
- };
837
- if (!(type in handlerMap)) {
838
- throw new Error("No handler defined for type: ".concat(type));
911
+ this.handleCoreSpanListener = function (type) { return function (handlerData) {
912
+ var handler = getSpanHandler(type);
913
+ var result = handler(handlerData);
914
+ if (result === null) {
915
+ return;
916
+ }
917
+ if (type === 'history') {
918
+ // Need to collect visited URLs
919
+ _this.context.urls.push(result.name);
839
920
  }
840
- var _a = handlerMap[type], handlerFn = _a[0], eventType = _a[1];
841
- var result = handlerFn(handlerData);
921
+ _this.addUpdate(function () {
922
+ _this.createPerformanceSpans([result]);
923
+ });
924
+ }; };
925
+ /**
926
+ * Handler for Sentry Core SDK events.
927
+ *
928
+ * These events will create breadcrumb-like objects in the recording.
929
+ */
930
+ this.handleCoreBreadcrumbListener = function (type) { return function (handlerData) {
931
+ var handler = getBreadcrumbHandler(type);
932
+ var result = handler(handlerData);
842
933
  if (result === null) {
843
934
  return;
844
935
  }
845
- if (['sentry.transaction'].includes(result.category)) {
936
+ if (result.category === 'sentry.transaction') {
846
937
  return;
847
938
  }
848
939
  _this.addUpdate(function () {
@@ -850,10 +941,9 @@ var SentryReplay = /** @class */ (function () {
850
941
  type: EventType.Custom,
851
942
  // TODO: We were converting from ms to seconds for breadcrumbs, spans,
852
943
  // but maybe we should just keep them as milliseconds
853
- timestamp: result.timestamp * 1000 ||
854
- result.startTimestamp * 1000,
944
+ timestamp: result.timestamp * 1000,
855
945
  data: {
856
- tag: eventType,
946
+ tag: 'breadcrumb',
857
947
  payload: result,
858
948
  },
859
949
  });
@@ -927,12 +1017,15 @@ var SentryReplay = /** @class */ (function () {
927
1017
  // replay ID so that we can reference them later in the UI
928
1018
  addGlobalEventProcessor(this.handleGlobalEvent);
929
1019
  record(__assign(__assign({}, this.recordingOptions), { emit: this.handleRecordingEmit }));
1020
+ var urlPath = "".concat(window.location.pathname).concat(window.location.hash).concat(window.location.search);
1021
+ var url = "".concat(window.location.origin).concat(urlPath);
930
1022
  // Otherwise, these will be captured after the first flush, which means the
931
1023
  // URL and timestamps could be incorrect
932
1024
  this.initialState = {
933
1025
  timestamp: new Date().getTime(),
934
- url: "".concat(window.location.origin).concat(window.location.pathname),
1026
+ url: url,
935
1027
  };
1028
+ this.context.urls.push(url);
936
1029
  };
937
1030
  /**
938
1031
  * We want to batch uploads of replay events. Save events only if
@@ -989,7 +1082,6 @@ var SentryReplay = /** @class */ (function () {
989
1082
  SentryReplay.prototype.destroy = function () {
990
1083
  logger.log('Destroying instance');
991
1084
  this.removeListeners();
992
- // this.eventBuffer.clear();
993
1085
  };
994
1086
  SentryReplay.prototype.clearSession = function () {
995
1087
  this.session = null;
@@ -1028,8 +1120,11 @@ var SentryReplay = /** @class */ (function () {
1028
1120
  window.addEventListener('beforeunload', this.handleWindowUnload);
1029
1121
  // Listeners from core SDK //
1030
1122
  var scope = getCurrentHub().getScope();
1031
- scope.addScopeListener(this.handleCoreListener('scope'));
1032
- addInstrumentationHandler('dom', this.handleCoreListener('dom'));
1123
+ scope.addScopeListener(this.handleCoreBreadcrumbListener('scope'));
1124
+ addInstrumentationHandler('dom', this.handleCoreBreadcrumbListener('dom'));
1125
+ addInstrumentationHandler('fetch', this.handleCoreSpanListener('fetch'));
1126
+ addInstrumentationHandler('xhr', this.handleCoreSpanListener('xhr'));
1127
+ addInstrumentationHandler('history', this.handleCoreSpanListener('history'));
1033
1128
  // PerformanceObserver //
1034
1129
  if (!('PerformanceObserver' in window)) {
1035
1130
  return;
@@ -1140,13 +1235,13 @@ var SentryReplay = /** @class */ (function () {
1140
1235
  });
1141
1236
  };
1142
1237
  /**
1143
- * Create a span for each performance entry. The parent transaction is `this.replayEvent`.
1238
+ * Create a "span" for each performance entry. The parent transaction is `this.replayEvent`.
1144
1239
  */
1145
1240
  SentryReplay.prototype.createPerformanceSpans = function (entries) {
1146
1241
  var _this = this;
1147
- entries.forEach(function (_a) {
1242
+ return Promise.all(entries.map(function (_a) {
1148
1243
  var type = _a.type, start = _a.start, end = _a.end, name = _a.name, data = _a.data;
1149
- _this.eventBuffer.addEvent({
1244
+ return _this.eventBuffer.addEvent({
1150
1245
  type: EventType.Custom,
1151
1246
  timestamp: start,
1152
1247
  data: {
@@ -1160,7 +1255,7 @@ var SentryReplay = /** @class */ (function () {
1160
1255
  },
1161
1256
  },
1162
1257
  });
1163
- });
1258
+ }));
1164
1259
  };
1165
1260
  /**
1166
1261
  * Observed performance events are added to `this.performanceEvents`. These
@@ -1170,15 +1265,22 @@ var SentryReplay = /** @class */ (function () {
1170
1265
  // Copy and reset entries before processing
1171
1266
  var entries = __spreadArray([], this.performanceEvents, true);
1172
1267
  this.performanceEvents = [];
1173
- // Parse the entries
1174
- var entryEvents = createPerformanceEntries(entries);
1268
+ return this.createPerformanceSpans(createPerformanceEntries(entries));
1269
+ };
1270
+ /**
1271
+ * Create a "span" for the total amount of memory being used by JS objects
1272
+ * (including v8 internal objects).
1273
+ */
1274
+ SentryReplay.prototype.addMemoryEntry = function () {
1175
1275
  // window.performance.memory is a non-standard API and doesn't work on all browsers
1176
1276
  // so we check before creating the event.
1177
- if ('memory' in window.performance) {
1178
- // @ts-expect-error memory doesn't exist on type Performance as the API is non-standard
1179
- entryEvents.push(createMemoryEntry(window.performance.memory));
1277
+ if (!('memory' in window.performance)) {
1278
+ return;
1180
1279
  }
1181
- this.createPerformanceSpans(entryEvents);
1280
+ return this.createPerformanceSpans([
1281
+ // @ts-expect-error memory doesn't exist on type Performance as the API is non-standard (we check that it exists above)
1282
+ createMemoryEntry(window.performance.memory),
1283
+ ]);
1182
1284
  };
1183
1285
  /**
1184
1286
  *
@@ -1212,6 +1314,24 @@ var SentryReplay = /** @class */ (function () {
1212
1314
  }
1213
1315
  return this.flushUpdate(lastActivity);
1214
1316
  };
1317
+ /**
1318
+ * Return and clear context
1319
+ */
1320
+ SentryReplay.prototype.popEventContext = function (_a) {
1321
+ var timestamp = _a.timestamp;
1322
+ var context = {
1323
+ session: this.session,
1324
+ initialState: this.initialState,
1325
+ timestamp: timestamp,
1326
+ errorIds: Array.from(this.context.errorIds).filter(Boolean),
1327
+ traceIds: Array.from(this.context.traceIds).filter(Boolean),
1328
+ urls: this.context.urls,
1329
+ };
1330
+ this.context.errorIds.clear();
1331
+ this.context.traceIds.clear();
1332
+ this.context.urls = [];
1333
+ return context;
1334
+ };
1215
1335
  /**
1216
1336
  * Flushes replay event buffer to Sentry.
1217
1337
  *
@@ -1232,28 +1352,37 @@ var SentryReplay = /** @class */ (function () {
1232
1352
  console.error(new Error('[Sentry]: No transaction, no replay'));
1233
1353
  return [2 /*return*/];
1234
1354
  }
1235
- this.addPerformanceEntries();
1355
+ // Since already flushing, ensure other queued flushes are cancelled
1356
+ clearTimeout(this.timeout);
1357
+ return [4 /*yield*/, this.addPerformanceEntries()];
1358
+ case 1:
1359
+ _a.sent();
1236
1360
  if (!this.eventBuffer.length) {
1237
1361
  return [2 /*return*/];
1238
1362
  }
1363
+ // Only attach memory event if eventBuffer is not empty
1364
+ return [4 /*yield*/, this.addMemoryEntry()];
1365
+ case 2:
1366
+ // Only attach memory event if eventBuffer is not empty
1367
+ _a.sent();
1368
+ timestamp = lastActivity !== null && lastActivity !== void 0 ? lastActivity : new Date().getTime();
1239
1369
  // Only want to create replay event if session is new
1240
1370
  if (this.needsCaptureReplay) {
1241
1371
  // This event needs to exist before calling `sendReplay`
1242
- captureReplay({ session: this.session, initialState: this.initialState });
1372
+ captureReplay(this.popEventContext({ timestamp: timestamp }));
1243
1373
  this.needsCaptureReplay = false;
1244
1374
  }
1245
1375
  // Reset this to null regardless of `sendReplay` result so that future
1246
1376
  // events will get flushed properly
1247
1377
  this.initialEventTimestampSinceFlush = null;
1248
- _a.label = 1;
1249
- case 1:
1250
- _a.trys.push([1, 4, , 5]);
1251
- timestamp = lastActivity !== null && lastActivity !== void 0 ? lastActivity : new Date().getTime();
1378
+ _a.label = 3;
1379
+ case 3:
1380
+ _a.trys.push([3, 6, , 7]);
1252
1381
  return [4 /*yield*/, this.eventBuffer.finish()];
1253
- case 2:
1382
+ case 4:
1254
1383
  recordingData = _a.sent();
1255
1384
  return [4 /*yield*/, this.sendReplay(this.session.id, recordingData)];
1256
- case 3:
1385
+ case 5:
1257
1386
  _a.sent();
1258
1387
  // The below will only happen after successfully sending replay //
1259
1388
  // TBD: Alternatively we could update this after every rrweb event
@@ -1261,13 +1390,14 @@ var SentryReplay = /** @class */ (function () {
1261
1390
  // of the event is passed as an argument in the case where a timeout
1262
1391
  // occurs.
1263
1392
  this.updateLastActivity(timestamp);
1264
- captureReplayUpdate({ session: this.session, timestamp: timestamp });
1265
- return [3 /*break*/, 5];
1266
- case 4:
1393
+ captureReplayUpdate(this.popEventContext({ timestamp: timestamp }));
1394
+ return [3 /*break*/, 7];
1395
+ case 6:
1267
1396
  err_1 = _a.sent();
1397
+ captureException(err_1);
1268
1398
  console.error(err_1);
1269
- return [3 /*break*/, 5];
1270
- case 5: return [2 /*return*/];
1399
+ return [3 /*break*/, 7];
1400
+ case 7: return [2 /*return*/];
1271
1401
  }
1272
1402
  });
1273
1403
  });