@sentry/replay 0.2.0-1 → 0.2.0-10

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
@@ -178,9 +178,38 @@ function createLargestContentfulPaint(entry) {
178
178
  end: start + duration,
179
179
  data: {
180
180
  size: size,
181
+ // @ts-expect-error Not sure why this errors, Node should be correct (Argument of type 'Node' is not assignable to parameter of type 'INode')
182
+ nodeId: rrweb.record.mirror.getId(entry.element),
181
183
  },
182
184
  };
183
185
  }
186
+ function createMemoryEntry(memoryEntry) {
187
+ var jsHeapSizeLimit = memoryEntry.jsHeapSizeLimit, totalJSHeapSize = memoryEntry.totalJSHeapSize, usedJSHeapSize = memoryEntry.usedJSHeapSize;
188
+ // we can't use getAbsoluteTime because it adds the event time to
189
+ // window.performance.timeOrigin, so we get right now instead.
190
+ var time = new Date().getTime() / 1000;
191
+ return {
192
+ type: 'memory',
193
+ name: 'memory',
194
+ start: time,
195
+ end: time,
196
+ data: {
197
+ memory: {
198
+ jsHeapSizeLimit: jsHeapSizeLimit,
199
+ totalJSHeapSize: totalJSHeapSize,
200
+ usedJSHeapSize: usedJSHeapSize,
201
+ },
202
+ },
203
+ };
204
+ }
205
+
206
+ var REPLAY_SESSION_KEY = 'sentryReplaySession';
207
+ var ROOT_REPLAY_NAME = 'sentry-replay';
208
+ var REPLAY_EVENT_NAME = 'sentry-replay-event';
209
+ // Grace period to keep a session when a user changes tabs or hides window
210
+ var VISIBILITY_CHANGE_TIMEOUT = 60000; // 1 minute
211
+ // The idle limit for a session
212
+ var SESSION_IDLE_DURATION = 900000; // 15 minutes
184
213
 
185
214
  /**
186
215
  * Given an initial timestamp and an expiry duration, checks to see if current
@@ -213,16 +242,13 @@ function wrapLogger(logFn) {
213
242
  for (var _i = 0; _i < arguments.length; _i++) {
214
243
  args[_i] = arguments[_i];
215
244
  }
216
- if (!utils.isDebugBuild()) {
245
+ {
217
246
  return;
218
247
  }
219
- return logFn.call.apply(logFn, __spreadArray([utils.logger, '[Replay]'], args, false));
220
248
  };
221
249
  }
222
250
  var logger = __assign(__assign({}, utils.logger), { error: wrapLogger(utils.logger.error), warn: wrapLogger(utils.logger.warn), log: wrapLogger(utils.logger.log) });
223
251
 
224
- var REPLAY_SESSION_KEY = 'sentryReplaySession';
225
-
226
252
  function saveSession(session) {
227
253
  var hasSessionStorage = 'sessionStorage' in window;
228
254
  if (!hasSessionStorage) {
@@ -246,7 +272,7 @@ function createSession(_a) {
246
272
  var currentDate = new Date().getTime();
247
273
  // Create root replay event, this is where attachments will be saved
248
274
  var transaction = Sentry__namespace.getCurrentHub().startTransaction({
249
- name: 'sentry-replay',
275
+ name: ROOT_REPLAY_NAME,
250
276
  tags: {
251
277
  isReplayRoot: 'yes',
252
278
  },
@@ -323,15 +349,13 @@ function updateSessionActivity(_a) {
323
349
  return newSession;
324
350
  }
325
351
 
326
- var VISIBILITY_CHANGE_TIMEOUT = 60000; // 1 minute
327
- var SESSION_IDLE_DURATION = 900000; // 15 minutes
328
352
  var SentryReplay = /** @class */ (function () {
329
353
  function SentryReplay(_a) {
330
354
  if (_a === void 0) { _a = {}; }
331
355
  var _this = this;
332
356
  var _b = _a.uploadMinDelay, uploadMinDelay = _b === void 0 ? 5000 : _b, _c = _a.uploadMaxDelay, uploadMaxDelay = _c === void 0 ? 15000 : _c, _d = _a.stickySession, stickySession = _d === void 0 ? false : _d, // TBD: Making this opt-in for now
333
357
  _e = _a.rrwebConfig, // TBD: Making this opt-in for now
334
- _f = _e === void 0 ? {} : _e, _g = _f.maskAllInputs, maskAllInputs = _g === void 0 ? true : _g, rrwebRecordOptions = __rest(_f, ["maskAllInputs"]);
358
+ _f = _e === void 0 ? {} : _e, _g = _f.maskAllInputs, maskAllInputs = _g === void 0 ? true : _g, _h = _f.blockClass, blockClass = _h === void 0 ? 'sr-block' : _h, _j = _f.ignoreClass, ignoreClass = _j === void 0 ? 'sr-ignore' : _j, _k = _f.maskTextClass, maskTextClass = _k === void 0 ? 'sr-mask' : _k, rrwebRecordOptions = __rest(_f, ["maskAllInputs", "blockClass", "ignoreClass", "maskTextClass"]);
335
359
  /**
336
360
  * @inheritDoc
337
361
  */
@@ -366,6 +390,7 @@ var SentryReplay = /** @class */ (function () {
366
390
  // ms, we will re-use the existing session, otherwise create a new
367
391
  // session
368
392
  logger.log('Document has become active, but session has expired');
393
+ _this.loadSession({ expiry: VISIBILITY_CHANGE_TIMEOUT });
369
394
  _this.triggerFullSnapshot();
370
395
  }
371
396
  // We definitely want to return if visibilityState is "visible", and I
@@ -390,25 +415,29 @@ var SentryReplay = /** @class */ (function () {
390
415
  _this.finishReplayEvent();
391
416
  }
392
417
  };
393
- this.rrwebRecordOptions = __assign({ maskAllInputs: maskAllInputs }, rrwebRecordOptions);
418
+ this.rrwebRecordOptions = __assign({ maskAllInputs: maskAllInputs, blockClass: blockClass, ignoreClass: ignoreClass, maskTextClass: maskTextClass }, rrwebRecordOptions);
394
419
  this.options = { uploadMinDelay: uploadMinDelay, uploadMaxDelay: uploadMaxDelay, stickySession: stickySession };
395
420
  this.events = [];
396
421
  }
397
422
  SentryReplay.attachmentUrlFromDsn = function (dsn, eventId) {
398
- var host = dsn.host, path = dsn.path, projectId = dsn.projectId, port = dsn.port, protocol = dsn.protocol, user = dsn.user;
399
- return "".concat(protocol, "://").concat(host).concat(port !== '' ? ":".concat(port) : '').concat(path !== '' ? "/".concat(path) : '', "/api/").concat(projectId, "/events/").concat(eventId, "/attachments/?sentry_key=").concat(user, "&sentry_version=7&sentry_client=replay");
423
+ var host = dsn.host, projectId = dsn.projectId, protocol = dsn.protocol, user = dsn.user;
424
+ var port = dsn.port !== '' ? ":".concat(dsn.port) : '';
425
+ var path = dsn.path !== '' ? "/".concat(dsn.path) : '';
426
+ return "".concat(protocol, "://").concat(host).concat(port).concat(path, "/api/").concat(projectId, "/events/").concat(eventId, "/attachments/?sentry_key=").concat(user, "&sentry_version=7&sentry_client=replay");
400
427
  };
401
- Object.defineProperty(SentryReplay.prototype, "instance", {
428
+ SentryReplay.prototype.setupOnce = function () {
429
+ var _this = this;
402
430
  /**
403
- * Get integration's instance on the current hub
431
+ * Because we create a transaction in `setupOnce`, we can potentially create a
432
+ * transaction before some native SDK integrations have run and applied their
433
+ * own global event processor. An example is:
434
+ * https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts
435
+ *
436
+ * So we do this as a workaround to wait for other global event processors to finish
404
437
  */
405
- get: function () {
406
- return Sentry__namespace.getCurrentHub().getIntegration(SentryReplay);
407
- },
408
- enumerable: false,
409
- configurable: true
410
- });
411
- SentryReplay.prototype.setupOnce = function () {
438
+ window.setTimeout(function () { return _this.setup(); });
439
+ };
440
+ SentryReplay.prototype.setup = function () {
412
441
  var _this = this;
413
442
  this.loadSession({ expiry: SESSION_IDLE_DURATION });
414
443
  // If there is no session, then something bad has happened - can't continue
@@ -418,9 +447,15 @@ var SentryReplay = /** @class */ (function () {
418
447
  // Tag all (non replay) events that get sent to Sentry with the current
419
448
  // replay ID so that we can reference them later in the UI
420
449
  Sentry__namespace.addGlobalEventProcessor(function (event) {
450
+ // Do not apply replayId to the root transaction
451
+ if (event.transaction === ROOT_REPLAY_NAME) {
452
+ return event;
453
+ }
421
454
  event.tags = __assign(__assign({}, event.tags), { replayId: _this.session.id });
422
455
  return event;
423
456
  });
457
+ // not fully initialized and the event will not get properly sent to Sentry
458
+ this.createReplayEvent();
424
459
  rrweb.record(__assign(__assign({}, this.rrwebRecordOptions), { emit: function (event, isCheckout) {
425
460
  // We want to batch uploads of replay events. Save events only if
426
461
  // `<uploadMinDelay>` milliseconds have elapsed since the last event
@@ -431,13 +466,15 @@ var SentryReplay = /** @class */ (function () {
431
466
  if (!_this.initialEventTimestampSinceFlush) {
432
467
  _this.initialEventTimestampSinceFlush = now;
433
468
  }
434
- var uploadMaxDelayExceeded = isExpired(_this.initialEventTimestampSinceFlush, _this.options.uploadMaxDelay, now);
435
469
  // Do not finish the replay event if we receive a new replay event
436
- // unless `<uploadMaxDelay>` ms have elapsed since the last time we
437
- // finished the replay
438
- if (_this.timeout && !uploadMaxDelayExceeded) {
470
+ if (_this.timeout) {
439
471
  window.clearTimeout(_this.timeout);
440
472
  }
473
+ // If this is false, it means session is expired, create and a new session and wait for checkout
474
+ if (!_this.checkAndHandleExpiredSession()) {
475
+ logger.error(new Error('Received replay event after session expired.'));
476
+ return;
477
+ }
441
478
  // We need to clear existing events on a checkout, otherwise they are
442
479
  // incremental event updates and should be appended
443
480
  if (isCheckout) {
@@ -450,9 +487,16 @@ var SentryReplay = /** @class */ (function () {
450
487
  // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16
451
488
  if (event.type === 2) {
452
489
  // A fullsnapshot happens on initial load and if we need to start a
453
- // new replay due to idle timeout. In the later case we will need to
454
- // create a new session before finishing the replay.
455
- _this.loadSession({ expiry: SESSION_IDLE_DURATION });
490
+ // new replay due to idle timeout. In the latter case, a new session *should* have been started
491
+ // before triggering a new checkout
492
+ _this.finishReplayEvent();
493
+ return;
494
+ }
495
+ var uploadMaxDelayExceeded = isExpired(_this.initialEventTimestampSinceFlush, _this.options.uploadMaxDelay, now);
496
+ // If `uploadMaxDelayExceeded` is true, then we should finish the replay event immediately,
497
+ // Otherwise schedule it to be finished in `this.options.uploadMinDelay`
498
+ if (uploadMaxDelayExceeded) {
499
+ logger.log('replay max delay exceeded, finishing replay event');
456
500
  _this.finishReplayEvent();
457
501
  return;
458
502
  }
@@ -460,14 +504,17 @@ var SentryReplay = /** @class */ (function () {
460
504
  // Sentry. Will be cancelled if an event happens before `uploadMinDelay`
461
505
  // elapses.
462
506
  _this.timeout = window.setTimeout(function () {
463
- logger.log('rrweb timeout hit, finishing replay event');
507
+ logger.log('replay timeout exceeded, finishing replay event');
464
508
  _this.finishReplayEvent();
465
509
  }, _this.options.uploadMinDelay);
466
510
  } }));
467
511
  this.addListeners();
468
- // XXX: this needs to be in `setupOnce` vs `constructor`, otherwise SDK is
469
- // not fully initialized and the event will not get properly sent to Sentry
470
- this.createReplayEvent();
512
+ };
513
+ /**
514
+ * Currently, this needs to be manually called (e.g. for tests). Sentry SDK does not support a teardown
515
+ */
516
+ SentryReplay.prototype.teardown = function () {
517
+ this.removeListeners();
471
518
  };
472
519
  /**
473
520
  * Loads a session from storage, or creates a new one
@@ -480,13 +527,35 @@ var SentryReplay = /** @class */ (function () {
480
527
  });
481
528
  };
482
529
  SentryReplay.prototype.addListeners = function () {
530
+ var _this = this;
483
531
  document.addEventListener('visibilitychange', this.handleVisibilityChange);
484
- if ('PerformanceObserver' in window) {
485
- this.performanceObserver = new PerformanceObserver(this.handlePerformanceObserver);
486
- // Observe everything for now
487
- this.performanceObserver.observe({
488
- entryTypes: __spreadArray([], PerformanceObserver.supportedEntryTypes, true),
532
+ if (!('PerformanceObserver' in window)) {
533
+ return;
534
+ }
535
+ this.performanceObserver = new PerformanceObserver(this.handlePerformanceObserver);
536
+ // Observe almost everything for now (no mark/measure)
537
+ [
538
+ 'element',
539
+ 'event',
540
+ 'first-input',
541
+ 'largest-contentful-paint',
542
+ 'layout-shift',
543
+ 'longtask',
544
+ 'navigation',
545
+ 'paint',
546
+ 'resource',
547
+ ].forEach(function (type) {
548
+ return _this.performanceObserver.observe({
549
+ type: type,
550
+ buffered: true,
489
551
  });
552
+ });
553
+ };
554
+ SentryReplay.prototype.removeListeners = function () {
555
+ document.removeEventListener('visibilitychange', this.handleVisibilityChange);
556
+ if (this.performanceObserver) {
557
+ this.performanceObserver.disconnect();
558
+ this.performanceObserver = null;
490
559
  }
491
560
  };
492
561
  /**
@@ -505,8 +574,8 @@ var SentryReplay = /** @class */ (function () {
505
574
  SentryReplay.prototype.createReplayEvent = function () {
506
575
  var _this = this;
507
576
  logger.log('CreateReplayEvent rootReplayId', this.session.id);
508
- this.replayEvent = Sentry__namespace.startTransaction({
509
- name: 'sentry-replay-event',
577
+ this.replayEvent = Sentry__namespace.getCurrentHub().startTransaction({
578
+ name: REPLAY_EVENT_NAME,
510
579
  parentSpanId: this.session.spanId,
511
580
  traceId: this.session.traceId,
512
581
  tags: {
@@ -543,19 +612,42 @@ var SentryReplay = /** @class */ (function () {
543
612
  this.performanceEvents = [];
544
613
  // Parse the entries
545
614
  var entryEvents = createPerformanceEntries(entries);
615
+ // window.performance.memory is a non-standard API and doesn't work on all browsers
616
+ // so we check before creating the event.
617
+ if ('memory' in window.performance) {
618
+ // @ts-expect-error memory doesn't exist on type Performance as the API is non-standard
619
+ entryEvents.push(createMemoryEntry(window.performance.memory));
620
+ }
546
621
  // This current implementation is to create spans on the transaction referenced in `this.replayEvent`
547
622
  this.createPerformanceSpans(entryEvents);
548
623
  };
624
+ /**
625
+ *
626
+ *
627
+ * Returns true if session is not expired, false otherwise.
628
+ */
629
+ SentryReplay.prototype.checkAndHandleExpiredSession = function (expiry) {
630
+ if (expiry === void 0) { expiry = SESSION_IDLE_DURATION; }
631
+ var oldSessionId = this.session.id;
632
+ // This will create a new session if expired, based on expiry length
633
+ this.loadSession({ expiry: expiry });
634
+ // Session was expired if session ids do not match
635
+ var isExpired = oldSessionId !== this.session.id;
636
+ if (!isExpired) {
637
+ return true;
638
+ }
639
+ // TODO: We could potentially figure out a way to save the last session,
640
+ // and produce a checkout based on a previous checkout + updates, and then
641
+ // replay the event on top. Or maybe replay the event on top of a refresh
642
+ // snapshot.
643
+ // For now create a new snapshot
644
+ this.triggerFullSnapshot();
645
+ return false;
646
+ };
549
647
  SentryReplay.prototype.finishReplayEvent = function () {
550
- // if (!this.instance) return;
551
648
  var _a;
552
- // Ensure that our existing session has not expired
553
- var isExpired = isSessionExpired(this.session, SESSION_IDLE_DURATION);
554
- if (isExpired) {
555
- // TBD: If it is expired, we do not send any events...we could send to
556
- // the expired session, but not sure if that's great
557
- console.error(new Error('Attempting to finish replay event after session expired.'));
558
- return;
649
+ if (!this.checkAndHandleExpiredSession()) {
650
+ logger.error(new Error('Attempting to finish replay event after session expired.'));
559
651
  }
560
652
  if (!this.session.id) {
561
653
  console.error(new Error('[Sentry]: No transaction, no replay'));
@@ -582,7 +674,7 @@ var SentryReplay = /** @class */ (function () {
582
674
  */
583
675
  SentryReplay.prototype.sendReplayRequest = function (endpoint, events) {
584
676
  return __awaiter(this, void 0, void 0, function () {
585
- var stringifiedPayload, formData, ex_1;
677
+ var stringifiedPayload, formData;
586
678
  return __generator(this, function (_a) {
587
679
  switch (_a.label) {
588
680
  case 0:
@@ -597,25 +689,15 @@ var SentryReplay = /** @class */ (function () {
597
689
  window.navigator.sendBeacon(endpoint, formData);
598
690
  return [2 /*return*/];
599
691
  }
600
- _a.label = 1;
601
- case 1:
602
- _a.trys.push([1, 3, , 4]);
603
- logger.log("uploading attachment via fetch()");
604
692
  // Otherwise use `fetch`, which *WILL* get cancelled on page reloads/unloads
693
+ logger.log("uploading attachment via fetch()");
605
694
  return [4 /*yield*/, fetch(endpoint, {
606
695
  method: 'POST',
607
696
  body: formData,
608
697
  })];
609
- case 2:
610
- // Otherwise use `fetch`, which *WILL* get cancelled on page reloads/unloads
698
+ case 1:
611
699
  _a.sent();
612
- return [3 /*break*/, 4];
613
- case 3:
614
- ex_1 = _a.sent();
615
- // we have to catch this otherwise it throws an infinite loop in Sentry
616
- console.error(ex_1);
617
- return [3 /*break*/, 4];
618
- case 4: return [2 /*return*/];
700
+ return [2 /*return*/];
619
701
  }
620
702
  });
621
703
  });
@@ -625,26 +707,32 @@ var SentryReplay = /** @class */ (function () {
625
707
  */
626
708
  SentryReplay.prototype.sendReplay = function (eventId) {
627
709
  return __awaiter(this, void 0, void 0, function () {
628
- var client, endpoint, ex_2;
710
+ var events, client, endpoint, ex_1;
629
711
  return __generator(this, function (_a) {
630
712
  switch (_a.label) {
631
713
  case 0:
632
- _a.trys.push([0, 2, , 3]);
633
714
  // short circuit if theres no events to replay
634
715
  if (!this.events.length)
635
716
  return [2 /*return*/];
717
+ events = this.events;
718
+ this.events = [];
636
719
  client = Sentry__namespace.getCurrentHub().getClient();
637
720
  endpoint = SentryReplay.attachmentUrlFromDsn(client.getDsn(), eventId);
638
- return [4 /*yield*/, this.sendReplayRequest(endpoint, this.events)];
721
+ _a.label = 1;
639
722
  case 1:
723
+ _a.trys.push([1, 3, , 4]);
724
+ return [4 /*yield*/, this.sendReplayRequest(endpoint, events)];
725
+ case 2:
640
726
  _a.sent();
641
- this.events = [];
642
727
  return [2 /*return*/, true];
643
- case 2:
644
- ex_2 = _a.sent();
645
- console.error(ex_2);
728
+ case 3:
729
+ ex_1 = _a.sent();
730
+ // we have to catch this otherwise it throws an infinite loop in Sentry
731
+ console.error(ex_1);
732
+ // If an error happened here, it's likely that uploading the attachment failed, we'll want to restore the events that failed to upload
733
+ this.events = __spreadArray(__spreadArray([], events, true), this.events, true);
646
734
  return [2 /*return*/, false];
647
- case 3: return [2 /*return*/];
735
+ case 4: return [2 /*return*/];
648
736
  }
649
737
  });
650
738
  });