@sentry/replay 0.2.0-1 → 0.2.0-13

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
@@ -3,8 +3,8 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var Sentry = require('@sentry/browser');
6
- var rrweb = require('rrweb');
7
6
  var utils = require('@sentry/utils');
7
+ var rrweb = require('rrweb');
8
8
 
9
9
  function _interopNamespace(e) {
10
10
  if (e && e.__esModule) return e;
@@ -178,10 +178,39 @@ function createLargestContentfulPaint(entry) {
178
178
  end: start + duration,
179
179
  data: {
180
180
  size: size,
181
+ // 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),
183
+ },
184
+ };
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
+ },
181
202
  },
182
203
  };
183
204
  }
184
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
213
+
185
214
  /**
186
215
  * Given an initial timestamp and an expiry duration, checks to see if current
187
216
  * time should be considered as expired.
@@ -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) {
@@ -244,25 +270,18 @@ function saveSession(session) {
244
270
  function createSession(_a) {
245
271
  var _b = _a.stickySession, stickySession = _b === void 0 ? false : _b;
246
272
  var currentDate = new Date().getTime();
247
- // Create root replay event, this is where attachments will be saved
248
- var transaction = Sentry__namespace.getCurrentHub().startTransaction({
249
- name: 'sentry-replay',
250
- tags: {
251
- isReplayRoot: 'yes',
252
- },
253
- });
254
- // We have to finish the transaction to get an event ID to be able to
255
- // upload an attachment for that event
256
- // @ts-expect-error This returns an eventId (string), but is not typed as such
257
- var id = transaction.finish();
258
- logger.log("Creating new session: ".concat(id));
273
+ var hub = Sentry.getCurrentHub();
259
274
  var session = {
260
- id: id,
261
- spanId: transaction.spanId,
262
- traceId: transaction.traceId,
275
+ id: utils.uuid4(),
263
276
  started: currentDate,
264
277
  lastActivity: currentDate,
278
+ sequenceId: 0,
265
279
  };
280
+ hub.captureEvent({
281
+ message: ROOT_REPLAY_NAME,
282
+ tags: { sequenceId: session.sequenceId },
283
+ }, { event_id: session.id });
284
+ logger.log("Creating new session: ".concat(session.id));
266
285
  if (stickySession) {
267
286
  saveSession(session);
268
287
  }
@@ -286,8 +305,8 @@ function fetchSession() {
286
305
  * Get or create a session
287
306
  */
288
307
  function getSession(_a) {
289
- var expiry = _a.expiry, stickySession = _a.stickySession;
290
- var session = stickySession && fetchSession();
308
+ var expiry = _a.expiry, currentSession = _a.currentSession, stickySession = _a.stickySession;
309
+ var session = stickySession ? fetchSession() : currentSession;
291
310
  if (session) {
292
311
  // If there is a session, check if it is valid (e.g. "last activity" time should be within the "session idle time")
293
312
  // TODO: We should probably set a max age on this as well
@@ -323,15 +342,85 @@ function updateSessionActivity(_a) {
323
342
  return newSession;
324
343
  }
325
344
 
326
- var VISIBILITY_CHANGE_TIMEOUT = 60000; // 1 minute
327
- var SESSION_IDLE_DURATION = 900000; // 15 minutes
345
+ function addInstrumentationListeners(scope, replay) {
346
+ scope.addScopeListener(scopeListenerCallback.bind(replay));
347
+ utils.addInstrumentationHandler('dom', domCallback.bind(replay));
348
+ utils.addInstrumentationHandler('xhr', xhrCallback.bind(replay));
349
+ utils.addInstrumentationHandler('fetch', fetchCallback.bind(replay));
350
+ }
351
+ function scopeListenerCallback(scope) {
352
+ //@ts-expect-error using private val
353
+ var newBreadcrumb = scope._breadcrumbs[scope._breadcrumbs.length - 1];
354
+ if (['fetch', 'xhr', 'sentry.event'].includes(newBreadcrumb.category) ||
355
+ newBreadcrumb.category.startsWith('ui.')) {
356
+ return;
357
+ }
358
+ this.breadcrumbs.push(__assign({ type: 'default' }, newBreadcrumb));
359
+ }
360
+ function domCallback(handlerData) {
361
+ // Taken from https://github.com/getsentry/sentry-javascript/blob/master/packages/browser/src/integrations/breadcrumbs.ts#L112
362
+ var target;
363
+ var targetNode;
364
+ // Accessing event.target can throw (see getsentry/raven-js#838, #768)
365
+ try {
366
+ targetNode =
367
+ handlerData.event.target ||
368
+ handlerData.event;
369
+ target = utils.htmlTreeAsString(targetNode);
370
+ }
371
+ catch (e) {
372
+ target = '<unknown>';
373
+ }
374
+ if (target.length === 0) {
375
+ return;
376
+ }
377
+ this.breadcrumbs.push({
378
+ timestamp: new Date().getTime() / 1000,
379
+ type: 'default',
380
+ category: "ui.".concat(handlerData.name),
381
+ message: target,
382
+ data: {
383
+ // Not sure why this errors, Node should be correct (Argument of type 'Node' is not assignable to parameter of type 'INode')
384
+ nodeId: targetNode ? rrweb.record.mirror.getId(targetNode) : undefined,
385
+ },
386
+ });
387
+ }
388
+ function xhrCallback(handlerData) {
389
+ // TODO: add status code into data, etc.
390
+ if (handlerData.startTimestamp) {
391
+ handlerData.xhr.__sentry_xhr__.startTimestamp = handlerData.startTimestamp;
392
+ }
393
+ if (handlerData.endTimestamp) {
394
+ this.spans.push({
395
+ description: handlerData.args[1],
396
+ op: handlerData.args[0],
397
+ startTimestamp: handlerData.xhr.__sentry_xhr__.startTimestamp / 1000 ||
398
+ handlerData.endTimestamp / 1000.0,
399
+ endTimestamp: handlerData.endTimestamp / 1000.0,
400
+ });
401
+ }
402
+ }
403
+ function fetchCallback(handlerData) {
404
+ // TODO: add status code into data, etc.
405
+ if (handlerData.endTimestamp) {
406
+ this.spans.push({
407
+ description: handlerData.args[1],
408
+ op: handlerData.args[0],
409
+ startTimestamp: handlerData.startTimestamp / 1000,
410
+ endTimestamp: handlerData.endTimestamp / 1000,
411
+ });
412
+ }
413
+ }
414
+
415
+ var BASE_RETRY_INTERVAL = 5000;
416
+ var MAX_RETRY_COUNT = 5;
328
417
  var SentryReplay = /** @class */ (function () {
329
418
  function SentryReplay(_a) {
330
419
  if (_a === void 0) { _a = {}; }
331
420
  var _this = this;
332
421
  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
422
  _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"]);
423
+ _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
424
  /**
336
425
  * @inheritDoc
337
426
  */
@@ -341,12 +430,16 @@ var SentryReplay = /** @class */ (function () {
341
430
  */
342
431
  this.events = [];
343
432
  this.performanceEvents = [];
433
+ this.breadcrumbs = [];
344
434
  /**
345
435
  * The timestamp of the first event since the last flush.
346
436
  * This is used to determine if the maximum allowed time has passed before we should flush events again.
347
437
  */
348
438
  this.initialEventTimestampSinceFlush = null;
439
+ this.replaySpans = [];
349
440
  this.performanceObserver = null;
441
+ this.retryCount = 0;
442
+ this.retryInterval = BASE_RETRY_INTERVAL;
350
443
  /**
351
444
  * Keep a list of performance entries that will be sent with a replay
352
445
  */
@@ -366,6 +459,7 @@ var SentryReplay = /** @class */ (function () {
366
459
  // ms, we will re-use the existing session, otherwise create a new
367
460
  // session
368
461
  logger.log('Document has become active, but session has expired');
462
+ _this.loadSession({ expiry: VISIBILITY_CHANGE_TIMEOUT });
369
463
  _this.triggerFullSnapshot();
370
464
  }
371
465
  // We definitely want to return if visibilityState is "visible", and I
@@ -380,9 +474,9 @@ var SentryReplay = /** @class */ (function () {
380
474
  // Update with current timestamp as the last session activity
381
475
  // Only updating session on visibility change to be conservative about
382
476
  // writing to session storage. This could be changed in the future.
383
- updateSessionActivity({
477
+ _this.updateSession(updateSessionActivity({
384
478
  stickySession: _this.options.stickySession,
385
- });
479
+ }));
386
480
  // Send replay when the page/tab becomes hidden. There is no reason to send
387
481
  // replay if it becomes visible, since no actions we care about were done
388
482
  // while it was hidden
@@ -390,26 +484,33 @@ var SentryReplay = /** @class */ (function () {
390
484
  _this.finishReplayEvent();
391
485
  }
392
486
  };
393
- this.rrwebRecordOptions = __assign({ maskAllInputs: maskAllInputs }, rrwebRecordOptions);
487
+ this.rrwebRecordOptions = __assign({ maskAllInputs: maskAllInputs, blockClass: blockClass, ignoreClass: ignoreClass, maskTextClass: maskTextClass }, rrwebRecordOptions);
394
488
  this.options = { uploadMinDelay: uploadMinDelay, uploadMaxDelay: uploadMaxDelay, stickySession: stickySession };
395
489
  this.events = [];
396
490
  }
397
491
  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");
492
+ var host = dsn.host, projectId = dsn.projectId, protocol = dsn.protocol, publicKey = dsn.publicKey;
493
+ var port = dsn.port !== '' ? ":".concat(dsn.port) : '';
494
+ var path = dsn.path !== '' ? "/".concat(dsn.path) : '';
495
+ return "".concat(protocol, "://").concat(host).concat(port).concat(path, "/api/").concat(projectId, "/events/").concat(eventId, "/attachments/?sentry_key=").concat(publicKey, "&sentry_version=7&sentry_client=replay");
400
496
  };
401
- Object.defineProperty(SentryReplay.prototype, "instance", {
497
+ SentryReplay.prototype.setupOnce = function () {
498
+ var _this = this;
402
499
  /**
403
- * Get integration's instance on the current hub
500
+ * Because we create a transaction in `setupOnce`, we can potentially create a
501
+ * transaction before some native SDK integrations have run and applied their
502
+ * own global event processor. An example is:
503
+ * https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts
504
+ *
505
+ * So we do this as a workaround to wait for other global event processors to finish
404
506
  */
405
- get: function () {
406
- return Sentry__namespace.getCurrentHub().getIntegration(SentryReplay);
407
- },
408
- enumerable: false,
409
- configurable: true
410
- });
411
- SentryReplay.prototype.setupOnce = function () {
507
+ window.setTimeout(function () { return _this.setup(); });
508
+ };
509
+ SentryReplay.prototype.setup = function () {
412
510
  var _this = this;
511
+ var hub = Sentry__namespace.getCurrentHub();
512
+ var scope = hub.getStackTop().scope;
513
+ addInstrumentationListeners(scope, this);
413
514
  this.loadSession({ expiry: SESSION_IDLE_DURATION });
414
515
  // If there is no session, then something bad has happened - can't continue
415
516
  if (!this.session) {
@@ -418,6 +519,10 @@ var SentryReplay = /** @class */ (function () {
418
519
  // Tag all (non replay) events that get sent to Sentry with the current
419
520
  // replay ID so that we can reference them later in the UI
420
521
  Sentry__namespace.addGlobalEventProcessor(function (event) {
522
+ // Do not apply replayId to the root transaction
523
+ if (event.transaction === ROOT_REPLAY_NAME) {
524
+ return event;
525
+ }
421
526
  event.tags = __assign(__assign({}, event.tags), { replayId: _this.session.id });
422
527
  return event;
423
528
  });
@@ -431,13 +536,15 @@ var SentryReplay = /** @class */ (function () {
431
536
  if (!_this.initialEventTimestampSinceFlush) {
432
537
  _this.initialEventTimestampSinceFlush = now;
433
538
  }
434
- var uploadMaxDelayExceeded = isExpired(_this.initialEventTimestampSinceFlush, _this.options.uploadMaxDelay, now);
435
539
  // 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) {
540
+ if (_this.timeout) {
439
541
  window.clearTimeout(_this.timeout);
440
542
  }
543
+ // If this is false, it means session is expired, create and a new session and wait for checkout
544
+ if (!_this.checkAndHandleExpiredSession()) {
545
+ logger.error(new Error('Received replay event after session expired.'));
546
+ return;
547
+ }
441
548
  // We need to clear existing events on a checkout, otherwise they are
442
549
  // incremental event updates and should be appended
443
550
  if (isCheckout) {
@@ -450,9 +557,16 @@ var SentryReplay = /** @class */ (function () {
450
557
  // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16
451
558
  if (event.type === 2) {
452
559
  // 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 });
560
+ // new replay due to idle timeout. In the latter case, a new session *should* have been started
561
+ // before triggering a new checkout
562
+ _this.finishReplayEvent();
563
+ return;
564
+ }
565
+ var uploadMaxDelayExceeded = isExpired(_this.initialEventTimestampSinceFlush, _this.options.uploadMaxDelay, now);
566
+ // If `uploadMaxDelayExceeded` is true, then we should finish the replay event immediately,
567
+ // Otherwise schedule it to be finished in `this.options.uploadMinDelay`
568
+ if (uploadMaxDelayExceeded) {
569
+ logger.log('replay max delay exceeded, finishing replay event');
456
570
  _this.finishReplayEvent();
457
571
  return;
458
572
  }
@@ -460,14 +574,20 @@ var SentryReplay = /** @class */ (function () {
460
574
  // Sentry. Will be cancelled if an event happens before `uploadMinDelay`
461
575
  // elapses.
462
576
  _this.timeout = window.setTimeout(function () {
463
- logger.log('rrweb timeout hit, finishing replay event');
577
+ logger.log('replay timeout exceeded, finishing replay event');
464
578
  _this.finishReplayEvent();
465
579
  }, _this.options.uploadMinDelay);
466
580
  } }));
467
581
  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();
582
+ };
583
+ /**
584
+ * Currently, this needs to be manually called (e.g. for tests). Sentry SDK does not support a teardown
585
+ */
586
+ SentryReplay.prototype.teardown = function () {
587
+ this.removeListeners();
588
+ };
589
+ SentryReplay.prototype.clearSession = function () {
590
+ this.session = null;
471
591
  };
472
592
  /**
473
593
  * Loads a session from storage, or creates a new one
@@ -477,16 +597,42 @@ var SentryReplay = /** @class */ (function () {
477
597
  this.session = getSession({
478
598
  expiry: expiry,
479
599
  stickySession: this.options.stickySession,
600
+ currentSession: this.session,
480
601
  });
481
602
  };
603
+ SentryReplay.prototype.updateSession = function (session) {
604
+ this.session = __assign(__assign({}, this.session), session);
605
+ };
482
606
  SentryReplay.prototype.addListeners = function () {
607
+ var _this = this;
483
608
  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),
609
+ if (!('PerformanceObserver' in window)) {
610
+ return;
611
+ }
612
+ this.performanceObserver = new PerformanceObserver(this.handlePerformanceObserver);
613
+ // Observe almost everything for now (no mark/measure)
614
+ [
615
+ 'element',
616
+ 'event',
617
+ 'first-input',
618
+ 'largest-contentful-paint',
619
+ 'layout-shift',
620
+ 'longtask',
621
+ 'navigation',
622
+ 'paint',
623
+ 'resource',
624
+ ].forEach(function (type) {
625
+ return _this.performanceObserver.observe({
626
+ type: type,
627
+ buffered: true,
489
628
  });
629
+ });
630
+ };
631
+ SentryReplay.prototype.removeListeners = function () {
632
+ document.removeEventListener('visibilitychange', this.handleVisibilityChange);
633
+ if (this.performanceObserver) {
634
+ this.performanceObserver.disconnect();
635
+ this.performanceObserver = null;
490
636
  }
491
637
  };
492
638
  /**
@@ -497,40 +643,20 @@ var SentryReplay = /** @class */ (function () {
497
643
  logger.log('Taking full rrweb snapshot');
498
644
  rrweb.record.takeFullSnapshot(true);
499
645
  };
500
- /**
501
- * This is our pseudo replay event disguised as a transaction. It will be
502
- * used to store performance entries and breadcrumbs for every incremental
503
- * replay event.
504
- **/
505
- SentryReplay.prototype.createReplayEvent = function () {
506
- var _this = this;
507
- logger.log('CreateReplayEvent rootReplayId', this.session.id);
508
- this.replayEvent = Sentry__namespace.startTransaction({
509
- name: 'sentry-replay-event',
510
- parentSpanId: this.session.spanId,
511
- traceId: this.session.traceId,
512
- tags: {
513
- replayId: this.session.id,
514
- },
515
- });
516
- Sentry__namespace.configureScope(function (scope) { return scope.setSpan(_this.replayEvent); });
517
- return this.replayEvent;
518
- };
519
646
  /**
520
647
  * Create a span for each performance entry. The parent transaction is `this.replayEvent`.
521
648
  */
522
649
  SentryReplay.prototype.createPerformanceSpans = function (entries) {
523
650
  var _this = this;
524
651
  entries.forEach(function (_a) {
525
- var _b;
526
652
  var type = _a.type, start = _a.start, end = _a.end, name = _a.name, data = _a.data;
527
- var span = (_b = _this.replayEvent) === null || _b === void 0 ? void 0 : _b.startChild({
653
+ _this.replaySpans.push({
528
654
  op: type,
529
655
  description: name,
530
656
  startTimestamp: start,
657
+ endTimestamp: end,
531
658
  data: data,
532
659
  });
533
- span.finish(end);
534
660
  });
535
661
  };
536
662
  /**
@@ -543,33 +669,61 @@ var SentryReplay = /** @class */ (function () {
543
669
  this.performanceEvents = [];
544
670
  // Parse the entries
545
671
  var entryEvents = createPerformanceEntries(entries);
546
- // This current implementation is to create spans on the transaction referenced in `this.replayEvent`
672
+ // window.performance.memory is a non-standard API and doesn't work on all browsers
673
+ // so we check before creating the event.
674
+ if ('memory' in window.performance) {
675
+ // @ts-expect-error memory doesn't exist on type Performance as the API is non-standard
676
+ entryEvents.push(createMemoryEntry(window.performance.memory));
677
+ }
547
678
  this.createPerformanceSpans(entryEvents);
548
679
  };
680
+ /**
681
+ *
682
+ *
683
+ * Returns true if session is not expired, false otherwise.
684
+ */
685
+ SentryReplay.prototype.checkAndHandleExpiredSession = function (expiry) {
686
+ // if (!this.options.stickySession) {
687
+ // return;
688
+ // }
689
+ if (expiry === void 0) { expiry = SESSION_IDLE_DURATION; }
690
+ var oldSessionId = this.session.id;
691
+ // This will create a new session if expired, based on expiry length
692
+ this.loadSession({ expiry: expiry });
693
+ // Session was expired if session ids do not match
694
+ var isExpired = oldSessionId !== this.session.id;
695
+ if (!isExpired) {
696
+ return true;
697
+ }
698
+ // TODO: We could potentially figure out a way to save the last session,
699
+ // and produce a checkout based on a previous checkout + updates, and then
700
+ // replay the event on top. Or maybe replay the event on top of a refresh
701
+ // snapshot.
702
+ // For now create a new snapshot
703
+ this.triggerFullSnapshot();
704
+ return false;
705
+ };
549
706
  SentryReplay.prototype.finishReplayEvent = function () {
550
- // if (!this.instance) return;
551
- 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;
707
+ if (!this.checkAndHandleExpiredSession()) {
708
+ logger.error(new Error('Attempting to finish replay event after session expired.'));
559
709
  }
560
710
  if (!this.session.id) {
561
711
  console.error(new Error('[Sentry]: No transaction, no replay'));
562
712
  return;
563
713
  }
714
+ // TEMP: keep sending a replay event just for the duration
715
+ Sentry.captureEvent({
716
+ message: "".concat(REPLAY_EVENT_NAME, "-").concat(utils.uuid4().substring(16)),
717
+ tags: {
718
+ replayId: this.session.id,
719
+ sequenceId: this.session.sequenceId++,
720
+ },
721
+ });
722
+ this.addPerformanceEntries();
564
723
  this.sendReplay(this.session.id);
565
724
  this.initialEventTimestampSinceFlush = null;
566
725
  // TBD: Alternatively we could update this after every rrweb event
567
726
  this.session.lastActivity = new Date().getTime();
568
- // include performance entries
569
- this.addPerformanceEntries();
570
- // Close out existing replay event and create a new one
571
- (_a = this.replayEvent) === null || _a === void 0 ? void 0 : _a.setStatus('ok').finish();
572
- this.createReplayEvent();
573
727
  };
574
728
  /**
575
729
  * Determine if there is browser support for `navigator.sendBeacon`
@@ -580,13 +734,18 @@ var SentryReplay = /** @class */ (function () {
580
734
  /**
581
735
  * Send replay attachment using either `sendBeacon()` or `fetch()`
582
736
  */
583
- SentryReplay.prototype.sendReplayRequest = function (endpoint, events) {
737
+ SentryReplay.prototype.sendReplayRequest = function (_a) {
738
+ var endpoint = _a.endpoint, events = _a.events, replaySpans = _a.replaySpans, breadcrumbs = _a.breadcrumbs;
584
739
  return __awaiter(this, void 0, void 0, function () {
585
- var stringifiedPayload, formData, ex_1;
586
- return __generator(this, function (_a) {
587
- switch (_a.label) {
740
+ var stringifiedPayload, formData;
741
+ return __generator(this, function (_b) {
742
+ switch (_b.label) {
588
743
  case 0:
589
- stringifiedPayload = JSON.stringify({ events: events });
744
+ stringifiedPayload = JSON.stringify({
745
+ recording: events,
746
+ replaySpans: replaySpans,
747
+ breadcrumbs: breadcrumbs,
748
+ });
590
749
  formData = new FormData();
591
750
  formData.append('rrweb', new Blob([stringifiedPayload], {
592
751
  type: 'application/json',
@@ -597,54 +756,76 @@ var SentryReplay = /** @class */ (function () {
597
756
  window.navigator.sendBeacon(endpoint, formData);
598
757
  return [2 /*return*/];
599
758
  }
600
- _a.label = 1;
601
- case 1:
602
- _a.trys.push([1, 3, , 4]);
603
- logger.log("uploading attachment via fetch()");
604
759
  // Otherwise use `fetch`, which *WILL* get cancelled on page reloads/unloads
760
+ logger.log("uploading attachment via fetch()");
605
761
  return [4 /*yield*/, fetch(endpoint, {
606
762
  method: 'POST',
607
763
  body: formData,
608
764
  })];
609
- case 2:
610
- // Otherwise use `fetch`, which *WILL* get cancelled on page reloads/unloads
611
- _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*/];
765
+ case 1:
766
+ _b.sent();
767
+ return [2 /*return*/];
619
768
  }
620
769
  });
621
770
  });
622
771
  };
772
+ SentryReplay.prototype.resetRetries = function () {
773
+ this.retryCount = 0;
774
+ this.retryInterval = BASE_RETRY_INTERVAL;
775
+ };
623
776
  /**
624
777
  * Finalize and send the current replay event to Sentry
625
778
  */
626
779
  SentryReplay.prototype.sendReplay = function (eventId) {
627
780
  return __awaiter(this, void 0, void 0, function () {
628
- var client, endpoint, ex_2;
781
+ var events, replaySpans, breadcrumbs, client, endpoint, ex_1;
782
+ var _this = this;
629
783
  return __generator(this, function (_a) {
630
784
  switch (_a.label) {
631
785
  case 0:
632
- _a.trys.push([0, 2, , 3]);
633
786
  // short circuit if theres no events to replay
634
787
  if (!this.events.length)
635
788
  return [2 /*return*/];
789
+ events = this.events;
790
+ replaySpans = this.replaySpans;
791
+ breadcrumbs = this.breadcrumbs;
792
+ this.replaySpans = [];
793
+ this.breadcrumbs = [];
794
+ this.events = [];
636
795
  client = Sentry__namespace.getCurrentHub().getClient();
637
796
  endpoint = SentryReplay.attachmentUrlFromDsn(client.getDsn(), eventId);
638
- return [4 /*yield*/, this.sendReplayRequest(endpoint, this.events)];
797
+ _a.label = 1;
639
798
  case 1:
799
+ _a.trys.push([1, 3, , 4]);
800
+ return [4 /*yield*/, this.sendReplayRequest({
801
+ endpoint: endpoint,
802
+ events: events,
803
+ replaySpans: replaySpans,
804
+ breadcrumbs: breadcrumbs,
805
+ })];
806
+ case 2:
640
807
  _a.sent();
641
- this.events = [];
808
+ this.resetRetries();
642
809
  return [2 /*return*/, true];
643
- case 2:
644
- ex_2 = _a.sent();
645
- console.error(ex_2);
810
+ case 3:
811
+ ex_1 = _a.sent();
812
+ // we have to catch this otherwise it throws an infinite loop in Sentry
813
+ console.error(ex_1);
814
+ // If an error happened here, it's likely that uploading the attachment failed, we'll want to restore the events that failed to upload
815
+ this.events = __spreadArray(__spreadArray([], events, true), this.events, true);
816
+ this.replaySpans = __spreadArray(__spreadArray([], replaySpans, true), this.replaySpans, true);
817
+ this.breadcrumbs = __spreadArray(__spreadArray([], replaySpans, true), this.breadcrumbs, true);
818
+ if (this.retryCount >= MAX_RETRY_COUNT) {
819
+ this.resetRetries();
820
+ }
821
+ else {
822
+ this.retryCount = this.retryCount + 1;
823
+ // will retry in intervals of 5, 10, 15, 20, 25 seconds
824
+ this.retryInterval = this.retryCount * this.retryInterval;
825
+ setTimeout(function () { return _this.sendReplay(eventId); }, this.retryInterval);
826
+ }
646
827
  return [2 /*return*/, false];
647
- case 3: return [2 /*return*/];
828
+ case 4: return [2 /*return*/];
648
829
  }
649
830
  });
650
831
  });