@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/README.md CHANGED
@@ -38,7 +38,7 @@ Sentry.init({
38
38
  integrations: [
39
39
  new SentryReplay({
40
40
  stickySession: true, // Default is false
41
- rrwebOptions: {
41
+ rrwebConfig: {
42
42
  maskAllInputs: false, // Default is true
43
43
  },
44
44
  }),
package/dist/index.es.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as Sentry from '@sentry/browser';
2
2
  import { record } from 'rrweb';
3
- import { logger as logger$1, isDebugBuild } from '@sentry/utils';
3
+ import { logger as logger$1 } from '@sentry/utils';
4
4
 
5
5
  /*! *****************************************************************************
6
6
  Copyright (c) Microsoft Corporation.
@@ -154,9 +154,38 @@ function createLargestContentfulPaint(entry) {
154
154
  end: start + duration,
155
155
  data: {
156
156
  size: size,
157
+ // @ts-expect-error Not sure why this errors, Node should be correct (Argument of type 'Node' is not assignable to parameter of type 'INode')
158
+ nodeId: record.mirror.getId(entry.element),
157
159
  },
158
160
  };
159
161
  }
162
+ function createMemoryEntry(memoryEntry) {
163
+ var jsHeapSizeLimit = memoryEntry.jsHeapSizeLimit, totalJSHeapSize = memoryEntry.totalJSHeapSize, usedJSHeapSize = memoryEntry.usedJSHeapSize;
164
+ // we can't use getAbsoluteTime because it adds the event time to
165
+ // window.performance.timeOrigin, so we get right now instead.
166
+ var time = new Date().getTime() / 1000;
167
+ return {
168
+ type: 'memory',
169
+ name: 'memory',
170
+ start: time,
171
+ end: time,
172
+ data: {
173
+ memory: {
174
+ jsHeapSizeLimit: jsHeapSizeLimit,
175
+ totalJSHeapSize: totalJSHeapSize,
176
+ usedJSHeapSize: usedJSHeapSize,
177
+ },
178
+ },
179
+ };
180
+ }
181
+
182
+ var REPLAY_SESSION_KEY = 'sentryReplaySession';
183
+ var ROOT_REPLAY_NAME = 'sentry-replay';
184
+ var REPLAY_EVENT_NAME = 'sentry-replay-event';
185
+ // Grace period to keep a session when a user changes tabs or hides window
186
+ var VISIBILITY_CHANGE_TIMEOUT = 60000; // 1 minute
187
+ // The idle limit for a session
188
+ var SESSION_IDLE_DURATION = 900000; // 15 minutes
160
189
 
161
190
  /**
162
191
  * Given an initial timestamp and an expiry duration, checks to see if current
@@ -189,16 +218,13 @@ function wrapLogger(logFn) {
189
218
  for (var _i = 0; _i < arguments.length; _i++) {
190
219
  args[_i] = arguments[_i];
191
220
  }
192
- if (!isDebugBuild()) {
221
+ {
193
222
  return;
194
223
  }
195
- return logFn.call.apply(logFn, __spreadArray([logger$1, '[Replay]'], args, false));
196
224
  };
197
225
  }
198
226
  var logger = __assign(__assign({}, logger$1), { error: wrapLogger(logger$1.error), warn: wrapLogger(logger$1.warn), log: wrapLogger(logger$1.log) });
199
227
 
200
- var REPLAY_SESSION_KEY = 'sentryReplaySession';
201
-
202
228
  function saveSession(session) {
203
229
  var hasSessionStorage = 'sessionStorage' in window;
204
230
  if (!hasSessionStorage) {
@@ -222,7 +248,7 @@ function createSession(_a) {
222
248
  var currentDate = new Date().getTime();
223
249
  // Create root replay event, this is where attachments will be saved
224
250
  var transaction = Sentry.getCurrentHub().startTransaction({
225
- name: 'sentry-replay',
251
+ name: ROOT_REPLAY_NAME,
226
252
  tags: {
227
253
  isReplayRoot: 'yes',
228
254
  },
@@ -299,15 +325,13 @@ function updateSessionActivity(_a) {
299
325
  return newSession;
300
326
  }
301
327
 
302
- var VISIBILITY_CHANGE_TIMEOUT = 60000; // 1 minute
303
- var SESSION_IDLE_DURATION = 900000; // 15 minutes
304
328
  var SentryReplay = /** @class */ (function () {
305
329
  function SentryReplay(_a) {
306
330
  if (_a === void 0) { _a = {}; }
307
331
  var _this = this;
308
332
  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
309
333
  _e = _a.rrwebConfig, // TBD: Making this opt-in for now
310
- _f = _e === void 0 ? {} : _e, _g = _f.maskAllInputs, maskAllInputs = _g === void 0 ? true : _g, rrwebRecordOptions = __rest(_f, ["maskAllInputs"]);
334
+ _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"]);
311
335
  /**
312
336
  * @inheritDoc
313
337
  */
@@ -342,6 +366,7 @@ var SentryReplay = /** @class */ (function () {
342
366
  // ms, we will re-use the existing session, otherwise create a new
343
367
  // session
344
368
  logger.log('Document has become active, but session has expired');
369
+ _this.loadSession({ expiry: VISIBILITY_CHANGE_TIMEOUT });
345
370
  _this.triggerFullSnapshot();
346
371
  }
347
372
  // We definitely want to return if visibilityState is "visible", and I
@@ -366,25 +391,29 @@ var SentryReplay = /** @class */ (function () {
366
391
  _this.finishReplayEvent();
367
392
  }
368
393
  };
369
- this.rrwebRecordOptions = __assign({ maskAllInputs: maskAllInputs }, rrwebRecordOptions);
394
+ this.rrwebRecordOptions = __assign({ maskAllInputs: maskAllInputs, blockClass: blockClass, ignoreClass: ignoreClass, maskTextClass: maskTextClass }, rrwebRecordOptions);
370
395
  this.options = { uploadMinDelay: uploadMinDelay, uploadMaxDelay: uploadMaxDelay, stickySession: stickySession };
371
396
  this.events = [];
372
397
  }
373
398
  SentryReplay.attachmentUrlFromDsn = function (dsn, eventId) {
374
- var host = dsn.host, path = dsn.path, projectId = dsn.projectId, port = dsn.port, protocol = dsn.protocol, user = dsn.user;
375
- 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");
399
+ var host = dsn.host, projectId = dsn.projectId, protocol = dsn.protocol, user = dsn.user;
400
+ var port = dsn.port !== '' ? ":".concat(dsn.port) : '';
401
+ var path = dsn.path !== '' ? "/".concat(dsn.path) : '';
402
+ 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");
376
403
  };
377
- Object.defineProperty(SentryReplay.prototype, "instance", {
404
+ SentryReplay.prototype.setupOnce = function () {
405
+ var _this = this;
378
406
  /**
379
- * Get integration's instance on the current hub
407
+ * Because we create a transaction in `setupOnce`, we can potentially create a
408
+ * transaction before some native SDK integrations have run and applied their
409
+ * own global event processor. An example is:
410
+ * https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts
411
+ *
412
+ * So we do this as a workaround to wait for other global event processors to finish
380
413
  */
381
- get: function () {
382
- return Sentry.getCurrentHub().getIntegration(SentryReplay);
383
- },
384
- enumerable: false,
385
- configurable: true
386
- });
387
- SentryReplay.prototype.setupOnce = function () {
414
+ window.setTimeout(function () { return _this.setup(); });
415
+ };
416
+ SentryReplay.prototype.setup = function () {
388
417
  var _this = this;
389
418
  this.loadSession({ expiry: SESSION_IDLE_DURATION });
390
419
  // If there is no session, then something bad has happened - can't continue
@@ -394,9 +423,15 @@ var SentryReplay = /** @class */ (function () {
394
423
  // Tag all (non replay) events that get sent to Sentry with the current
395
424
  // replay ID so that we can reference them later in the UI
396
425
  Sentry.addGlobalEventProcessor(function (event) {
426
+ // Do not apply replayId to the root transaction
427
+ if (event.transaction === ROOT_REPLAY_NAME) {
428
+ return event;
429
+ }
397
430
  event.tags = __assign(__assign({}, event.tags), { replayId: _this.session.id });
398
431
  return event;
399
432
  });
433
+ // not fully initialized and the event will not get properly sent to Sentry
434
+ this.createReplayEvent();
400
435
  record(__assign(__assign({}, this.rrwebRecordOptions), { emit: function (event, isCheckout) {
401
436
  // We want to batch uploads of replay events. Save events only if
402
437
  // `<uploadMinDelay>` milliseconds have elapsed since the last event
@@ -407,13 +442,15 @@ var SentryReplay = /** @class */ (function () {
407
442
  if (!_this.initialEventTimestampSinceFlush) {
408
443
  _this.initialEventTimestampSinceFlush = now;
409
444
  }
410
- var uploadMaxDelayExceeded = isExpired(_this.initialEventTimestampSinceFlush, _this.options.uploadMaxDelay, now);
411
445
  // Do not finish the replay event if we receive a new replay event
412
- // unless `<uploadMaxDelay>` ms have elapsed since the last time we
413
- // finished the replay
414
- if (_this.timeout && !uploadMaxDelayExceeded) {
446
+ if (_this.timeout) {
415
447
  window.clearTimeout(_this.timeout);
416
448
  }
449
+ // If this is false, it means session is expired, create and a new session and wait for checkout
450
+ if (!_this.checkAndHandleExpiredSession()) {
451
+ logger.error(new Error('Received replay event after session expired.'));
452
+ return;
453
+ }
417
454
  // We need to clear existing events on a checkout, otherwise they are
418
455
  // incremental event updates and should be appended
419
456
  if (isCheckout) {
@@ -426,9 +463,16 @@ var SentryReplay = /** @class */ (function () {
426
463
  // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16
427
464
  if (event.type === 2) {
428
465
  // A fullsnapshot happens on initial load and if we need to start a
429
- // new replay due to idle timeout. In the later case we will need to
430
- // create a new session before finishing the replay.
431
- _this.loadSession({ expiry: SESSION_IDLE_DURATION });
466
+ // new replay due to idle timeout. In the latter case, a new session *should* have been started
467
+ // before triggering a new checkout
468
+ _this.finishReplayEvent();
469
+ return;
470
+ }
471
+ var uploadMaxDelayExceeded = isExpired(_this.initialEventTimestampSinceFlush, _this.options.uploadMaxDelay, now);
472
+ // If `uploadMaxDelayExceeded` is true, then we should finish the replay event immediately,
473
+ // Otherwise schedule it to be finished in `this.options.uploadMinDelay`
474
+ if (uploadMaxDelayExceeded) {
475
+ logger.log('replay max delay exceeded, finishing replay event');
432
476
  _this.finishReplayEvent();
433
477
  return;
434
478
  }
@@ -436,14 +480,17 @@ var SentryReplay = /** @class */ (function () {
436
480
  // Sentry. Will be cancelled if an event happens before `uploadMinDelay`
437
481
  // elapses.
438
482
  _this.timeout = window.setTimeout(function () {
439
- logger.log('rrweb timeout hit, finishing replay event');
483
+ logger.log('replay timeout exceeded, finishing replay event');
440
484
  _this.finishReplayEvent();
441
485
  }, _this.options.uploadMinDelay);
442
486
  } }));
443
487
  this.addListeners();
444
- // XXX: this needs to be in `setupOnce` vs `constructor`, otherwise SDK is
445
- // not fully initialized and the event will not get properly sent to Sentry
446
- this.createReplayEvent();
488
+ };
489
+ /**
490
+ * Currently, this needs to be manually called (e.g. for tests). Sentry SDK does not support a teardown
491
+ */
492
+ SentryReplay.prototype.teardown = function () {
493
+ this.removeListeners();
447
494
  };
448
495
  /**
449
496
  * Loads a session from storage, or creates a new one
@@ -456,13 +503,35 @@ var SentryReplay = /** @class */ (function () {
456
503
  });
457
504
  };
458
505
  SentryReplay.prototype.addListeners = function () {
506
+ var _this = this;
459
507
  document.addEventListener('visibilitychange', this.handleVisibilityChange);
460
- if ('PerformanceObserver' in window) {
461
- this.performanceObserver = new PerformanceObserver(this.handlePerformanceObserver);
462
- // Observe everything for now
463
- this.performanceObserver.observe({
464
- entryTypes: __spreadArray([], PerformanceObserver.supportedEntryTypes, true),
508
+ if (!('PerformanceObserver' in window)) {
509
+ return;
510
+ }
511
+ this.performanceObserver = new PerformanceObserver(this.handlePerformanceObserver);
512
+ // Observe almost everything for now (no mark/measure)
513
+ [
514
+ 'element',
515
+ 'event',
516
+ 'first-input',
517
+ 'largest-contentful-paint',
518
+ 'layout-shift',
519
+ 'longtask',
520
+ 'navigation',
521
+ 'paint',
522
+ 'resource',
523
+ ].forEach(function (type) {
524
+ return _this.performanceObserver.observe({
525
+ type: type,
526
+ buffered: true,
465
527
  });
528
+ });
529
+ };
530
+ SentryReplay.prototype.removeListeners = function () {
531
+ document.removeEventListener('visibilitychange', this.handleVisibilityChange);
532
+ if (this.performanceObserver) {
533
+ this.performanceObserver.disconnect();
534
+ this.performanceObserver = null;
466
535
  }
467
536
  };
468
537
  /**
@@ -481,8 +550,8 @@ var SentryReplay = /** @class */ (function () {
481
550
  SentryReplay.prototype.createReplayEvent = function () {
482
551
  var _this = this;
483
552
  logger.log('CreateReplayEvent rootReplayId', this.session.id);
484
- this.replayEvent = Sentry.startTransaction({
485
- name: 'sentry-replay-event',
553
+ this.replayEvent = Sentry.getCurrentHub().startTransaction({
554
+ name: REPLAY_EVENT_NAME,
486
555
  parentSpanId: this.session.spanId,
487
556
  traceId: this.session.traceId,
488
557
  tags: {
@@ -519,19 +588,42 @@ var SentryReplay = /** @class */ (function () {
519
588
  this.performanceEvents = [];
520
589
  // Parse the entries
521
590
  var entryEvents = createPerformanceEntries(entries);
591
+ // window.performance.memory is a non-standard API and doesn't work on all browsers
592
+ // so we check before creating the event.
593
+ if ('memory' in window.performance) {
594
+ // @ts-expect-error memory doesn't exist on type Performance as the API is non-standard
595
+ entryEvents.push(createMemoryEntry(window.performance.memory));
596
+ }
522
597
  // This current implementation is to create spans on the transaction referenced in `this.replayEvent`
523
598
  this.createPerformanceSpans(entryEvents);
524
599
  };
600
+ /**
601
+ *
602
+ *
603
+ * Returns true if session is not expired, false otherwise.
604
+ */
605
+ SentryReplay.prototype.checkAndHandleExpiredSession = function (expiry) {
606
+ if (expiry === void 0) { expiry = SESSION_IDLE_DURATION; }
607
+ var oldSessionId = this.session.id;
608
+ // This will create a new session if expired, based on expiry length
609
+ this.loadSession({ expiry: expiry });
610
+ // Session was expired if session ids do not match
611
+ var isExpired = oldSessionId !== this.session.id;
612
+ if (!isExpired) {
613
+ return true;
614
+ }
615
+ // TODO: We could potentially figure out a way to save the last session,
616
+ // and produce a checkout based on a previous checkout + updates, and then
617
+ // replay the event on top. Or maybe replay the event on top of a refresh
618
+ // snapshot.
619
+ // For now create a new snapshot
620
+ this.triggerFullSnapshot();
621
+ return false;
622
+ };
525
623
  SentryReplay.prototype.finishReplayEvent = function () {
526
- // if (!this.instance) return;
527
624
  var _a;
528
- // Ensure that our existing session has not expired
529
- var isExpired = isSessionExpired(this.session, SESSION_IDLE_DURATION);
530
- if (isExpired) {
531
- // TBD: If it is expired, we do not send any events...we could send to
532
- // the expired session, but not sure if that's great
533
- console.error(new Error('Attempting to finish replay event after session expired.'));
534
- return;
625
+ if (!this.checkAndHandleExpiredSession()) {
626
+ logger.error(new Error('Attempting to finish replay event after session expired.'));
535
627
  }
536
628
  if (!this.session.id) {
537
629
  console.error(new Error('[Sentry]: No transaction, no replay'));
@@ -558,7 +650,7 @@ var SentryReplay = /** @class */ (function () {
558
650
  */
559
651
  SentryReplay.prototype.sendReplayRequest = function (endpoint, events) {
560
652
  return __awaiter(this, void 0, void 0, function () {
561
- var stringifiedPayload, formData, ex_1;
653
+ var stringifiedPayload, formData;
562
654
  return __generator(this, function (_a) {
563
655
  switch (_a.label) {
564
656
  case 0:
@@ -573,25 +665,15 @@ var SentryReplay = /** @class */ (function () {
573
665
  window.navigator.sendBeacon(endpoint, formData);
574
666
  return [2 /*return*/];
575
667
  }
576
- _a.label = 1;
577
- case 1:
578
- _a.trys.push([1, 3, , 4]);
579
- logger.log("uploading attachment via fetch()");
580
668
  // Otherwise use `fetch`, which *WILL* get cancelled on page reloads/unloads
669
+ logger.log("uploading attachment via fetch()");
581
670
  return [4 /*yield*/, fetch(endpoint, {
582
671
  method: 'POST',
583
672
  body: formData,
584
673
  })];
585
- case 2:
586
- // Otherwise use `fetch`, which *WILL* get cancelled on page reloads/unloads
674
+ case 1:
587
675
  _a.sent();
588
- return [3 /*break*/, 4];
589
- case 3:
590
- ex_1 = _a.sent();
591
- // we have to catch this otherwise it throws an infinite loop in Sentry
592
- console.error(ex_1);
593
- return [3 /*break*/, 4];
594
- case 4: return [2 /*return*/];
676
+ return [2 /*return*/];
595
677
  }
596
678
  });
597
679
  });
@@ -601,26 +683,32 @@ var SentryReplay = /** @class */ (function () {
601
683
  */
602
684
  SentryReplay.prototype.sendReplay = function (eventId) {
603
685
  return __awaiter(this, void 0, void 0, function () {
604
- var client, endpoint, ex_2;
686
+ var events, client, endpoint, ex_1;
605
687
  return __generator(this, function (_a) {
606
688
  switch (_a.label) {
607
689
  case 0:
608
- _a.trys.push([0, 2, , 3]);
609
690
  // short circuit if theres no events to replay
610
691
  if (!this.events.length)
611
692
  return [2 /*return*/];
693
+ events = this.events;
694
+ this.events = [];
612
695
  client = Sentry.getCurrentHub().getClient();
613
696
  endpoint = SentryReplay.attachmentUrlFromDsn(client.getDsn(), eventId);
614
- return [4 /*yield*/, this.sendReplayRequest(endpoint, this.events)];
697
+ _a.label = 1;
615
698
  case 1:
699
+ _a.trys.push([1, 3, , 4]);
700
+ return [4 /*yield*/, this.sendReplayRequest(endpoint, events)];
701
+ case 2:
616
702
  _a.sent();
617
- this.events = [];
618
703
  return [2 /*return*/, true];
619
- case 2:
620
- ex_2 = _a.sent();
621
- console.error(ex_2);
704
+ case 3:
705
+ ex_1 = _a.sent();
706
+ // we have to catch this otherwise it throws an infinite loop in Sentry
707
+ console.error(ex_1);
708
+ // If an error happened here, it's likely that uploading the attachment failed, we'll want to restore the events that failed to upload
709
+ this.events = __spreadArray(__spreadArray([], events, true), this.events, true);
622
710
  return [2 /*return*/, false];
623
- case 3: return [2 /*return*/];
711
+ case 4: return [2 /*return*/];
624
712
  }
625
713
  });
626
714
  });