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