@sentry/replay 0.4.8-3 → 0.4.8

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.
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.
@@ -324,10 +469,6 @@ function getSession(_a) {
324
469
  return { type: 'new', session: newSession };
325
470
  }
326
471
 
327
- function createBreadcrumb(breadcrumb) {
328
- return __assign({ timestamp: new Date().getTime() / 1000, type: 'default' }, breadcrumb);
329
- }
330
-
331
472
  /**
332
473
  * Determine if there is browser support for `navigator.sendBeacon`
333
474
  */
@@ -335,92 +476,6 @@ function supportsSendBeacon() {
335
476
  return 'navigator' in window && 'sendBeacon' in window.navigator;
336
477
  }
337
478
 
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
479
  var _a;
425
480
  // Map entryType -> function to normalize data for event
426
481
  var ENTRY_TYPES = (_a = {
@@ -471,6 +526,10 @@ function createResourceEntry(entry) {
471
526
  if (isIngestHost(name)) {
472
527
  return null;
473
528
  }
529
+ // Core SDK handles these
530
+ if (['fetch', 'xmlhttprequest'].includes(initiatorType)) {
531
+ return null;
532
+ }
474
533
  return {
475
534
  type: "".concat(entryType, ".").concat(initiatorType),
476
535
  start: getAbsoluteTime(startTime),
@@ -531,7 +590,6 @@ function createEventBuffer(_a) {
531
590
  return new EventBufferCompressionWorker(worker);
532
591
  }
533
592
  else {
534
- // TODO: Debugging
535
593
  core.captureException(new Error('Unable to create compression worker'));
536
594
  }
537
595
  }
@@ -701,10 +759,6 @@ var SentryReplay = /** @class */ (function () {
701
759
  * Buffer of breadcrumbs to be uploaded
702
760
  */
703
761
  this.breadcrumbs = [];
704
- /**
705
- * Buffer of replay spans to be uploaded
706
- */
707
- this.replaySpans = [];
708
762
  /**
709
763
  * List of PerformanceEntry from PerformanceObserver
710
764
  */
@@ -725,19 +779,30 @@ var SentryReplay = /** @class */ (function () {
725
779
  * immediately before sending recording)
726
780
  */
727
781
  this.needsCaptureReplay = false;
782
+ this.context = {
783
+ errorIds: new Set(),
784
+ traceIds: new Set(),
785
+ urls: [],
786
+ };
728
787
  /**
729
788
  * Core Sentry SDK global event handler. Attaches `replayId` to all [non-replay]
730
789
  * events as a tag. Also handles the case where we only want to capture a reply
731
790
  * when an error occurs.
732
791
  **/
733
792
  this.handleGlobalEvent = function (event) {
734
- var _a;
793
+ var _a, _b;
735
794
  // Do not apply replayId to the root event
736
795
  if (event.message === ROOT_REPLAY_NAME ||
737
796
  ((_a = event.message) === null || _a === void 0 ? void 0 : _a.startsWith(REPLAY_EVENT_NAME))) {
738
797
  return event;
739
798
  }
740
799
  event.tags = __assign(__assign({}, event.tags), { replayId: _this.session.id });
800
+ if (event.type === 'transaction') {
801
+ _this.context.traceIds.add(String(((_b = event.contexts) === null || _b === void 0 ? void 0 : _b.trace.trace_id) || ''));
802
+ return event;
803
+ }
804
+ // XXX: Is it safe to assume that all other events are error events?
805
+ _this.context.errorIds.add(event.event_id);
741
806
  // Need to be very careful that this does not cause an infinite loop
742
807
  if (_this.options.captureOnlyOnError && event.exception) {
743
808
  // TODO: Do we continue to record after?
@@ -828,25 +893,35 @@ var SentryReplay = /** @class */ (function () {
828
893
  /**
829
894
  * Handler for Sentry Core SDK events.
830
895
  *
831
- * Transforms core SDK events into replay events.
896
+ * These specific events will create span-like objects in the recording.
832
897
  *
833
898
  */
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));
899
+ this.handleCoreSpanListener = function (type) { return function (handlerData) {
900
+ var handler = getSpanHandler(type);
901
+ var result = handler(handlerData);
902
+ if (result === null) {
903
+ return;
904
+ }
905
+ if (type === 'history') {
906
+ // Need to collect visited URLs
907
+ _this.context.urls.push(result.name);
843
908
  }
844
- var _a = handlerMap[type], handlerFn = _a[0], eventType = _a[1];
845
- var result = handlerFn(handlerData);
909
+ _this.addUpdate(function () {
910
+ _this.createPerformanceSpans([result]);
911
+ });
912
+ }; };
913
+ /**
914
+ * Handler for Sentry Core SDK events.
915
+ *
916
+ * These events will create breadcrumb-like objects in the recording.
917
+ */
918
+ this.handleCoreBreadcrumbListener = function (type) { return function (handlerData) {
919
+ var handler = getBreadcrumbHandler(type);
920
+ var result = handler(handlerData);
846
921
  if (result === null) {
847
922
  return;
848
923
  }
849
- if (['sentry.transaction'].includes(result.category)) {
924
+ if (result.category === 'sentry.transaction') {
850
925
  return;
851
926
  }
852
927
  _this.addUpdate(function () {
@@ -854,10 +929,9 @@ var SentryReplay = /** @class */ (function () {
854
929
  type: rrweb.EventType.Custom,
855
930
  // TODO: We were converting from ms to seconds for breadcrumbs, spans,
856
931
  // but maybe we should just keep them as milliseconds
857
- timestamp: result.timestamp * 1000 ||
858
- result.startTimestamp * 1000,
932
+ timestamp: result.timestamp * 1000,
859
933
  data: {
860
- tag: eventType,
934
+ tag: 'breadcrumb',
861
935
  payload: result,
862
936
  },
863
937
  });
@@ -931,12 +1005,15 @@ var SentryReplay = /** @class */ (function () {
931
1005
  // replay ID so that we can reference them later in the UI
932
1006
  core.addGlobalEventProcessor(this.handleGlobalEvent);
933
1007
  rrweb.record(__assign(__assign({}, this.recordingOptions), { emit: this.handleRecordingEmit }));
1008
+ var urlPath = "".concat(window.location.pathname).concat(window.location.hash).concat(window.location.search);
1009
+ var url = "".concat(window.location.origin).concat(urlPath);
934
1010
  // Otherwise, these will be captured after the first flush, which means the
935
1011
  // URL and timestamps could be incorrect
936
1012
  this.initialState = {
937
1013
  timestamp: new Date().getTime(),
938
- url: "".concat(window.location.origin).concat(window.location.pathname),
1014
+ url: url,
939
1015
  };
1016
+ this.context.urls.push(url);
940
1017
  };
941
1018
  /**
942
1019
  * We want to batch uploads of replay events. Save events only if
@@ -993,7 +1070,6 @@ var SentryReplay = /** @class */ (function () {
993
1070
  SentryReplay.prototype.destroy = function () {
994
1071
  logger.log('Destroying instance');
995
1072
  this.removeListeners();
996
- // this.eventBuffer.clear();
997
1073
  };
998
1074
  SentryReplay.prototype.clearSession = function () {
999
1075
  this.session = null;
@@ -1032,8 +1108,11 @@ var SentryReplay = /** @class */ (function () {
1032
1108
  window.addEventListener('beforeunload', this.handleWindowUnload);
1033
1109
  // Listeners from core SDK //
1034
1110
  var scope = core.getCurrentHub().getScope();
1035
- scope.addScopeListener(this.handleCoreListener('scope'));
1036
- utils.addInstrumentationHandler('dom', this.handleCoreListener('dom'));
1111
+ scope.addScopeListener(this.handleCoreBreadcrumbListener('scope'));
1112
+ utils.addInstrumentationHandler('dom', this.handleCoreBreadcrumbListener('dom'));
1113
+ utils.addInstrumentationHandler('fetch', this.handleCoreSpanListener('fetch'));
1114
+ utils.addInstrumentationHandler('xhr', this.handleCoreSpanListener('xhr'));
1115
+ utils.addInstrumentationHandler('history', this.handleCoreSpanListener('history'));
1037
1116
  // PerformanceObserver //
1038
1117
  if (!('PerformanceObserver' in window)) {
1039
1118
  return;
@@ -1216,6 +1295,24 @@ var SentryReplay = /** @class */ (function () {
1216
1295
  }
1217
1296
  return this.flushUpdate(lastActivity);
1218
1297
  };
1298
+ /**
1299
+ * Return and clear context
1300
+ */
1301
+ SentryReplay.prototype.popEventContext = function (_a) {
1302
+ var timestamp = _a.timestamp;
1303
+ var context = {
1304
+ session: this.session,
1305
+ initialState: this.initialState,
1306
+ timestamp: timestamp,
1307
+ errorIds: Array.from(this.context.errorIds).filter(Boolean),
1308
+ traceIds: Array.from(this.context.traceIds).filter(Boolean),
1309
+ urls: this.context.urls,
1310
+ };
1311
+ this.context.errorIds.clear();
1312
+ this.context.traceIds.clear();
1313
+ this.context.urls = [];
1314
+ return context;
1315
+ };
1219
1316
  /**
1220
1317
  * Flushes replay event buffer to Sentry.
1221
1318
  *
@@ -1240,10 +1337,11 @@ var SentryReplay = /** @class */ (function () {
1240
1337
  if (!this.eventBuffer.length) {
1241
1338
  return [2 /*return*/];
1242
1339
  }
1340
+ timestamp = lastActivity !== null && lastActivity !== void 0 ? lastActivity : new Date().getTime();
1243
1341
  // Only want to create replay event if session is new
1244
1342
  if (this.needsCaptureReplay) {
1245
1343
  // This event needs to exist before calling `sendReplay`
1246
- captureReplay({ session: this.session, initialState: this.initialState });
1344
+ captureReplay(this.popEventContext({ timestamp: timestamp }));
1247
1345
  this.needsCaptureReplay = false;
1248
1346
  }
1249
1347
  // Reset this to null regardless of `sendReplay` result so that future
@@ -1252,7 +1350,6 @@ var SentryReplay = /** @class */ (function () {
1252
1350
  _a.label = 1;
1253
1351
  case 1:
1254
1352
  _a.trys.push([1, 4, , 5]);
1255
- timestamp = lastActivity !== null && lastActivity !== void 0 ? lastActivity : new Date().getTime();
1256
1353
  return [4 /*yield*/, this.eventBuffer.finish()];
1257
1354
  case 2:
1258
1355
  recordingData = _a.sent();
@@ -1265,7 +1362,7 @@ var SentryReplay = /** @class */ (function () {
1265
1362
  // of the event is passed as an argument in the case where a timeout
1266
1363
  // occurs.
1267
1364
  this.updateLastActivity(timestamp);
1268
- captureReplayUpdate({ session: this.session, timestamp: timestamp });
1365
+ captureReplayUpdate(this.popEventContext({ timestamp: timestamp }));
1269
1366
  return [3 /*break*/, 5];
1270
1367
  case 4:
1271
1368
  err_1 = _a.sent();