@sentry/replay 0.2.0-0 → 0.2.0-11

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,16 +178,247 @@ 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
213
+
214
+ /**
215
+ * Given an initial timestamp and an expiry duration, checks to see if current
216
+ * time should be considered as expired.
217
+ */
218
+ function isExpired(initialTime, expiry, targetTime) {
219
+ if (targetTime === void 0) { targetTime = +new Date(); }
220
+ // Always expired if < 0
221
+ if (expiry < 0) {
222
+ return true;
223
+ }
224
+ // Never expires if == 0
225
+ if (expiry === 0) {
226
+ return false;
227
+ }
228
+ return initialTime + expiry <= targetTime;
229
+ }
230
+
231
+ /**
232
+ * Checks to see if session is expired
233
+ */
234
+ function isSessionExpired(session, expiry, targetTime) {
235
+ if (targetTime === void 0) { targetTime = +new Date(); }
236
+ return isExpired(session.lastActivity, expiry, targetTime);
237
+ }
238
+
239
+ function wrapLogger(logFn) {
240
+ return function wrappedLog() {
241
+ var args = [];
242
+ for (var _i = 0; _i < arguments.length; _i++) {
243
+ args[_i] = arguments[_i];
244
+ }
245
+ {
246
+ return;
247
+ }
248
+ };
249
+ }
250
+ var logger = __assign(__assign({}, utils.logger), { error: wrapLogger(utils.logger.error), warn: wrapLogger(utils.logger.warn), log: wrapLogger(utils.logger.log) });
251
+
252
+ function saveSession(session) {
253
+ var hasSessionStorage = 'sessionStorage' in window;
254
+ if (!hasSessionStorage) {
255
+ return;
256
+ }
257
+ try {
258
+ window.sessionStorage.setItem(REPLAY_SESSION_KEY, JSON.stringify(session));
259
+ }
260
+ catch (_a) {
261
+ // this shouldn't happen
262
+ }
263
+ }
264
+
265
+ /**
266
+ * Create a new session, which in its current implementation is a Sentry event
267
+ * that all replays will be saved to as attachments. Currently, we only expect
268
+ * one of these Sentry events per "replay session".
269
+ */
270
+ function createSession(_a) {
271
+ var _b = _a.stickySession, stickySession = _b === void 0 ? false : _b;
272
+ var currentDate = new Date().getTime();
273
+ var hub = Sentry.getCurrentHub();
274
+ var session = {
275
+ id: utils.uuid4(),
276
+ started: currentDate,
277
+ lastActivity: currentDate,
278
+ sequenceId: 0,
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));
285
+ if (stickySession) {
286
+ saveSession(session);
287
+ }
288
+ return session;
289
+ }
290
+
291
+ function fetchSession() {
292
+ var hasSessionStorage = 'sessionStorage' in window;
293
+ if (!hasSessionStorage) {
294
+ return null;
295
+ }
296
+ try {
297
+ return JSON.parse(window.sessionStorage.getItem(REPLAY_SESSION_KEY));
298
+ }
299
+ catch (_a) {
300
+ return null;
301
+ }
302
+ }
303
+
304
+ /**
305
+ * Get or create a session
306
+ */
307
+ function getSession(_a) {
308
+ var expiry = _a.expiry, stickySession = _a.stickySession;
309
+ var session = stickySession && fetchSession();
310
+ if (session) {
311
+ // If there is a session, check if it is valid (e.g. "last activity" time should be within the "session idle time")
312
+ // TODO: We should probably set a max age on this as well
313
+ var isExpired = isSessionExpired(session, expiry);
314
+ if (!isExpired) {
315
+ logger.log("Using existing session: ".concat(session.id));
316
+ return session;
317
+ }
318
+ else {
319
+ logger.log("Session has expired");
320
+ }
321
+ // Otherwise continue to create a new session
322
+ }
323
+ var newSession = createSession({ stickySession: stickySession });
324
+ return newSession;
325
+ }
326
+
327
+ function updateSessionActivity(_a) {
328
+ var stickySession = _a.stickySession;
329
+ // Nothing to do if there are no sticky sessions
330
+ if (!stickySession) {
331
+ return;
332
+ }
333
+ var existingSession = fetchSession();
334
+ // If user manually deleted from session storage, create a new session
335
+ if (!existingSession) {
336
+ // TBD: There was an issue here where sessions weren't saving and this
337
+ // caused lots of transactions to be created
338
+ return createSession({ stickySession: stickySession });
339
+ }
340
+ var newSession = __assign(__assign({}, existingSession), { lastActivity: new Date().getTime() });
341
+ saveSession(newSession);
342
+ return newSession;
343
+ }
344
+
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
+ // @ts-expect-error Not sure why this errors, Node should be correct (Argument of type 'Node' is not assignable to parameter of type 'INode')
384
+ nodeId: targetNode ? 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
+ }
184
414
 
185
- var VISIBILITY_CHANGE_TIMEOUT = 5000;
186
415
  var SentryReplay = /** @class */ (function () {
187
416
  function SentryReplay(_a) {
188
417
  if (_a === void 0) { _a = {}; }
189
418
  var _this = this;
190
- var _b = _a.idleTimeout, idleTimeout = _b === void 0 ? 15000 : _b, _c = _a.rrwebConfig, _d = _c === void 0 ? {} : _c, _e = _d.maskAllInputs, maskAllInputs = _e === void 0 ? true : _e, rrwebRecordOptions = __rest(_d, ["maskAllInputs"]);
419
+ 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
420
+ _e = _a.rrwebConfig, // TBD: Making this opt-in for now
421
+ _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"]);
191
422
  /**
192
423
  * @inheritDoc
193
424
  */
@@ -197,6 +428,13 @@ var SentryReplay = /** @class */ (function () {
197
428
  */
198
429
  this.events = [];
199
430
  this.performanceEvents = [];
431
+ this.breadcrumbs = [];
432
+ /**
433
+ * The timestamp of the first event since the last flush.
434
+ * This is used to determine if the maximum allowed time has passed before we should flush events again.
435
+ */
436
+ this.initialEventTimestampSinceFlush = null;
437
+ this.replaySpans = [];
200
438
  this.performanceObserver = null;
201
439
  /**
202
440
  * Keep a list of performance entries that will be sent with a replay
@@ -210,167 +448,204 @@ var SentryReplay = /** @class */ (function () {
210
448
  * Handle when visibility of the page changes. (e.g. new tab is opened)
211
449
  */
212
450
  this.handleVisibilityChange = function () {
213
- if (document.visibilityState === 'visible' &&
214
- _this.visibilityChangeTimer === null) {
215
- // Page has become active/visible again after `VISIBILITY_CHANGE_TIMEOUT`
216
- // ms have elapsed, which means we will consider this a new session
217
- //
218
- // TBD if this is the behavior we want
219
- _this.isDebug &&
220
- utils.logger.log('[Replay] document has become active, creating new "session"');
221
- _this.triggerNewSession();
451
+ var isExpired = isSessionExpired(_this.session, VISIBILITY_CHANGE_TIMEOUT);
452
+ if (isExpired) {
453
+ if (document.visibilityState === 'visible') {
454
+ // If the user has come back to the page within VISIBILITY_CHANGE_TIMEOUT
455
+ // ms, we will re-use the existing session, otherwise create a new
456
+ // session
457
+ logger.log('Document has become active, but session has expired');
458
+ _this.loadSession({ expiry: VISIBILITY_CHANGE_TIMEOUT });
459
+ _this.triggerFullSnapshot();
460
+ }
461
+ // We definitely want to return if visibilityState is "visible", and I
462
+ // think we also want to do the same when "hidden", as there shouldn't be
463
+ // any action to take if user has gone idle for a long period and then
464
+ // comes back to hide the tab. We don't trigger a full snapshot because
465
+ // we don't want to start a new session as they immediately have hidden
466
+ // the tab.
222
467
  return;
223
468
  }
224
- // Send replay when the page/tab becomes hidden
225
- _this.finishReplayEvent();
226
- // VISIBILITY_CHANGE_TIMEOUT gives the user buffer room to come back to the
227
- // page before we create a new session.
228
- _this.visibilityChangeTimer = window.setTimeout(function () {
229
- _this.visibilityChangeTimer = null;
230
- }, VISIBILITY_CHANGE_TIMEOUT);
469
+ // Otherwise if session is not expired...
470
+ // Update with current timestamp as the last session activity
471
+ // Only updating session on visibility change to be conservative about
472
+ // writing to session storage. This could be changed in the future.
473
+ updateSessionActivity({
474
+ stickySession: _this.options.stickySession,
475
+ });
476
+ // Send replay when the page/tab becomes hidden. There is no reason to send
477
+ // replay if it becomes visible, since no actions we care about were done
478
+ // while it was hidden
479
+ if (document.visibilityState !== 'visible') {
480
+ _this.finishReplayEvent();
481
+ }
231
482
  };
232
- this.rrwebRecordOptions = __assign({ maskAllInputs: maskAllInputs }, rrwebRecordOptions);
233
- // Creates a new replay ID everytime we initialize the plugin (e.g. on every pageload).
234
- // TBD on behavior here (e.g. should this be saved to localStorage/cookies)
235
- this.replayId = utils.uuid4();
483
+ this.rrwebRecordOptions = __assign({ maskAllInputs: maskAllInputs, blockClass: blockClass, ignoreClass: ignoreClass, maskTextClass: maskTextClass }, rrwebRecordOptions);
484
+ this.options = { uploadMinDelay: uploadMinDelay, uploadMaxDelay: uploadMaxDelay, stickySession: stickySession };
236
485
  this.events = [];
486
+ }
487
+ SentryReplay.attachmentUrlFromDsn = function (dsn, eventId) {
488
+ var host = dsn.host, projectId = dsn.projectId, protocol = dsn.protocol, publicKey = dsn.publicKey;
489
+ var port = dsn.port !== '' ? ":".concat(dsn.port) : '';
490
+ var path = dsn.path !== '' ? "/".concat(dsn.path) : '';
491
+ 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");
492
+ };
493
+ SentryReplay.prototype.setupOnce = function () {
494
+ var _this = this;
495
+ /**
496
+ * Because we create a transaction in `setupOnce`, we can potentially create a
497
+ * transaction before some native SDK integrations have run and applied their
498
+ * own global event processor. An example is:
499
+ * https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts
500
+ *
501
+ * So we do this as a workaround to wait for other global event processors to finish
502
+ */
503
+ window.setTimeout(function () { return _this.setup(); });
504
+ };
505
+ SentryReplay.prototype.setup = function () {
506
+ var _this = this;
507
+ var hub = Sentry__namespace.getCurrentHub();
508
+ var scope = hub.getStackTop().scope;
509
+ addInstrumentationListeners(scope, this);
510
+ this.loadSession({ expiry: SESSION_IDLE_DURATION });
511
+ // If there is no session, then something bad has happened - can't continue
512
+ if (!this.session) {
513
+ throw new Error('Invalid session');
514
+ }
515
+ // Tag all (non replay) events that get sent to Sentry with the current
516
+ // replay ID so that we can reference them later in the UI
517
+ Sentry__namespace.addGlobalEventProcessor(function (event) {
518
+ // Do not apply replayId to the root transaction
519
+ if (event.transaction === ROOT_REPLAY_NAME) {
520
+ return event;
521
+ }
522
+ event.tags = __assign(__assign({}, event.tags), { replayId: _this.session.id });
523
+ return event;
524
+ });
237
525
  rrweb.record(__assign(__assign({}, this.rrwebRecordOptions), { emit: function (event, isCheckout) {
238
- // "debounce" by `idleTimeout`, how often we save replay events i.e. we
239
- // will save events only if 15 seconds have elapsed since the last
240
- // event
241
- //
242
- // TODO: We probably want to have a hard timeout where we save
243
- // so that it does not grow infinitely and we never have a replay
244
- // saved
526
+ // We want to batch uploads of replay events. Save events only if
527
+ // `<uploadMinDelay>` milliseconds have elapsed since the last event
528
+ // *OR* if `<uploadMaxDelay>` milliseconds have elapsed.
529
+ var now = new Date().getTime();
530
+ // Timestamp of the first replay event since the last flush, this gets
531
+ // reset when we finish the replay event
532
+ if (!_this.initialEventTimestampSinceFlush) {
533
+ _this.initialEventTimestampSinceFlush = now;
534
+ }
535
+ // Do not finish the replay event if we receive a new replay event
245
536
  if (_this.timeout) {
246
537
  window.clearTimeout(_this.timeout);
247
538
  }
248
- // Always create a new Sentry event on checkouts and clear existing rrweb events
539
+ // If this is false, it means session is expired, create and a new session and wait for checkout
540
+ if (!_this.checkAndHandleExpiredSession()) {
541
+ logger.error(new Error('Received replay event after session expired.'));
542
+ return;
543
+ }
544
+ // We need to clear existing events on a checkout, otherwise they are
545
+ // incremental event updates and should be appended
249
546
  if (isCheckout) {
250
- console.log('$$$$$ IS CHECKOUT');
251
547
  _this.events = [event];
252
548
  }
253
549
  else {
254
550
  _this.events.push(event);
255
551
  }
256
- // Set timer to send attachment to Sentry, will be cancelled if an
257
- // event happens before `idleTimeout` elapses
552
+ // This event type is a fullsnapshot, we should save immediately when this occurs
553
+ // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16
554
+ if (event.type === 2) {
555
+ // A fullsnapshot happens on initial load and if we need to start a
556
+ // new replay due to idle timeout. In the latter case, a new session *should* have been started
557
+ // before triggering a new checkout
558
+ _this.finishReplayEvent();
559
+ return;
560
+ }
561
+ var uploadMaxDelayExceeded = isExpired(_this.initialEventTimestampSinceFlush, _this.options.uploadMaxDelay, now);
562
+ // If `uploadMaxDelayExceeded` is true, then we should finish the replay event immediately,
563
+ // Otherwise schedule it to be finished in `this.options.uploadMinDelay`
564
+ if (uploadMaxDelayExceeded) {
565
+ logger.log('replay max delay exceeded, finishing replay event');
566
+ _this.finishReplayEvent();
567
+ return;
568
+ }
569
+ // Set timer to finish replay event and send replay attachment to
570
+ // Sentry. Will be cancelled if an event happens before `uploadMinDelay`
571
+ // elapses.
258
572
  _this.timeout = window.setTimeout(function () {
259
- _this.isDebug &&
260
- utils.logger.log('[Replay] rrweb timeout hit, finishing replay event');
573
+ logger.log('replay timeout exceeded, finishing replay event');
261
574
  _this.finishReplayEvent();
262
- }, idleTimeout);
575
+ }, _this.options.uploadMinDelay);
263
576
  } }));
264
577
  this.addListeners();
265
- }
266
- SentryReplay.attachmentUrlFromDsn = function (dsn, eventId) {
267
- var host = dsn.host, path = dsn.path, projectId = dsn.projectId, port = dsn.port, protocol = dsn.protocol, user = dsn.user;
268
- 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");
269
578
  };
270
- Object.defineProperty(SentryReplay.prototype, "isDebug", {
271
- get: function () {
272
- return utils.isDebugBuild();
273
- },
274
- enumerable: false,
275
- configurable: true
276
- });
277
- Object.defineProperty(SentryReplay.prototype, "instance", {
278
- /**
279
- * Get integration's instance on the current hub
280
- */
281
- get: function () {
282
- return Sentry__namespace.getCurrentHub().getIntegration(SentryReplay);
283
- },
284
- enumerable: false,
285
- configurable: true
286
- });
287
- SentryReplay.prototype.setupOnce = function () {
288
- var _this = this;
289
- // Tag all (non replay) events that get sent to Sentry with the current
290
- // replay ID so that we can reference them later in the UI
291
- Sentry__namespace.addGlobalEventProcessor(function (event) {
292
- event.tags = __assign(__assign({}, event.tags), { replayId: _this.replayId });
293
- return event;
579
+ /**
580
+ * Currently, this needs to be manually called (e.g. for tests). Sentry SDK does not support a teardown
581
+ */
582
+ SentryReplay.prototype.teardown = function () {
583
+ this.removeListeners();
584
+ };
585
+ /**
586
+ * Loads a session from storage, or creates a new one
587
+ */
588
+ SentryReplay.prototype.loadSession = function (_a) {
589
+ var expiry = _a.expiry;
590
+ this.session = getSession({
591
+ expiry: expiry,
592
+ stickySession: this.options.stickySession,
294
593
  });
295
- // XXX: this needs to be in `setupOnce` vs `constructor`, otherwise SDK is
296
- // not fully initialized and the event will not get properly sent to Sentry
297
- this.createRootEvent();
298
- this.createReplayEvent();
299
594
  };
300
595
  SentryReplay.prototype.addListeners = function () {
596
+ var _this = this;
301
597
  document.addEventListener('visibilitychange', this.handleVisibilityChange);
302
- if ('PerformanceObserver' in window) {
303
- this.performanceObserver = new PerformanceObserver(this.handlePerformanceObserver);
304
- // Observe everything for now
305
- this.performanceObserver.observe({
306
- entryTypes: __spreadArray([], PerformanceObserver.supportedEntryTypes, true),
598
+ if (!('PerformanceObserver' in window)) {
599
+ return;
600
+ }
601
+ this.performanceObserver = new PerformanceObserver(this.handlePerformanceObserver);
602
+ // Observe almost everything for now (no mark/measure)
603
+ [
604
+ 'element',
605
+ 'event',
606
+ 'first-input',
607
+ 'largest-contentful-paint',
608
+ 'layout-shift',
609
+ 'longtask',
610
+ 'navigation',
611
+ 'paint',
612
+ 'resource',
613
+ ].forEach(function (type) {
614
+ return _this.performanceObserver.observe({
615
+ type: type,
616
+ buffered: true,
307
617
  });
618
+ });
619
+ };
620
+ SentryReplay.prototype.removeListeners = function () {
621
+ document.removeEventListener('visibilitychange', this.handleVisibilityChange);
622
+ if (this.performanceObserver) {
623
+ this.performanceObserver.disconnect();
624
+ this.performanceObserver = null;
308
625
  }
309
626
  };
310
627
  /**
311
- * Creates a new replay "session". This will create a new Sentry event and
312
- * then trigger rrweb to take a full snapshot.
628
+ * Trigger rrweb to take a full snapshot which will cause this plugin to
629
+ * create a new Replay event.
313
630
  */
314
- SentryReplay.prototype.triggerNewSession = function () {
315
- this.isDebug && utils.logger.log('[Replay] taking full rrweb snapshot');
631
+ SentryReplay.prototype.triggerFullSnapshot = function () {
632
+ logger.log('Taking full rrweb snapshot');
316
633
  rrweb.record.takeFullSnapshot(true);
317
634
  };
318
- /**
319
- * Creates the Sentry event that all replays will be saved to as attachments.
320
- * Currently, we only expect one of these per "replay session" (which is not
321
- * explicitly defined yet).
322
- */
323
- SentryReplay.prototype.createRootEvent = function () {
324
- // TODO: Figure out if we need to do this, when this gets called from `setupOnce`, `this.instance` is still undefined.
325
- // if (!this.instance) return;
326
- this.isDebug && utils.logger.log("[Replay] creating root replay event");
327
- // Create a transaction to attach event to
328
- var transaction = Sentry__namespace.getCurrentHub().startTransaction({
329
- name: 'sentry-replay',
330
- tags: {
331
- hasReplay: 'yes',
332
- replayId: this.replayId,
333
- },
334
- });
335
- // We have to finish the transaction to get an event ID to be able to
336
- // upload an attachment for that event
337
- // @ts-expect-error This returns an eventId (string), but is not typed as such
338
- this.eventId = transaction.finish();
339
- return this.eventId;
340
- };
341
- /**
342
- * This is our pseudo replay event disguised as a transaction. It will be
343
- * used to store performance entries and breadcrumbs for every incremental
344
- * replay event.
345
- **/
346
- SentryReplay.prototype.createReplayEvent = function () {
347
- var _this = this;
348
- console.log('createReplayEvent rootReplayId', this.eventId);
349
- this.replayEvent = Sentry__namespace.startTransaction({
350
- name: 'sentry-replay-event',
351
- tags: {
352
- rootReplayId: this.eventId,
353
- replayId: this.replayId,
354
- },
355
- });
356
- Sentry__namespace.configureScope(function (scope) { return scope.setSpan(_this.replayEvent); });
357
- return this.replayEvent;
358
- };
359
635
  /**
360
636
  * Create a span for each performance entry. The parent transaction is `this.replayEvent`.
361
637
  */
362
638
  SentryReplay.prototype.createPerformanceSpans = function (entries) {
363
639
  var _this = this;
364
640
  entries.forEach(function (_a) {
365
- var _b;
366
641
  var type = _a.type, start = _a.start, end = _a.end, name = _a.name, data = _a.data;
367
- var span = (_b = _this.replayEvent) === null || _b === void 0 ? void 0 : _b.startChild({
642
+ _this.replaySpans.push({
368
643
  op: type,
369
644
  description: name,
370
645
  startTimestamp: start,
646
+ endTimestamp: end,
371
647
  data: data,
372
648
  });
373
- span.finish(end);
374
649
  });
375
650
  };
376
651
  /**
@@ -383,23 +658,58 @@ var SentryReplay = /** @class */ (function () {
383
658
  this.performanceEvents = [];
384
659
  // Parse the entries
385
660
  var entryEvents = createPerformanceEntries(entries);
386
- // This current implementation is to create spans on the transaction referenced in `this.replayEvent`
661
+ // window.performance.memory is a non-standard API and doesn't work on all browsers
662
+ // so we check before creating the event.
663
+ if ('memory' in window.performance) {
664
+ // @ts-expect-error memory doesn't exist on type Performance as the API is non-standard
665
+ entryEvents.push(createMemoryEntry(window.performance.memory));
666
+ }
387
667
  this.createPerformanceSpans(entryEvents);
388
668
  };
669
+ /**
670
+ *
671
+ *
672
+ * Returns true if session is not expired, false otherwise.
673
+ */
674
+ SentryReplay.prototype.checkAndHandleExpiredSession = function (expiry) {
675
+ if (expiry === void 0) { expiry = SESSION_IDLE_DURATION; }
676
+ var oldSessionId = this.session.id;
677
+ // This will create a new session if expired, based on expiry length
678
+ this.loadSession({ expiry: expiry });
679
+ // Session was expired if session ids do not match
680
+ var isExpired = oldSessionId !== this.session.id;
681
+ if (!isExpired) {
682
+ return true;
683
+ }
684
+ // TODO: We could potentially figure out a way to save the last session,
685
+ // and produce a checkout based on a previous checkout + updates, and then
686
+ // replay the event on top. Or maybe replay the event on top of a refresh
687
+ // snapshot.
688
+ // For now create a new snapshot
689
+ this.triggerFullSnapshot();
690
+ return false;
691
+ };
389
692
  SentryReplay.prototype.finishReplayEvent = function () {
390
- // if (!this.instance) return;
391
- var _a;
392
- var eventId = this.eventId || this.createRootEvent();
393
- if (!eventId) {
394
- console.error('[Sentry]: No transaction, no replay');
693
+ if (!this.checkAndHandleExpiredSession()) {
694
+ logger.error(new Error('Attempting to finish replay event after session expired.'));
695
+ }
696
+ if (!this.session.id) {
697
+ console.error(new Error('[Sentry]: No transaction, no replay'));
395
698
  return;
396
699
  }
397
- this.sendReplay(eventId);
398
- // include performance entries
700
+ // TEMP: keep sending a replay event just for the duration
701
+ Sentry.captureEvent({
702
+ message: "".concat(REPLAY_EVENT_NAME, "-").concat(utils.uuid4().substring(16)),
703
+ tags: {
704
+ replayId: this.session.id,
705
+ sequenceId: this.session.sequenceId++,
706
+ },
707
+ });
399
708
  this.addPerformanceEntries();
400
- // Close out existing replay event and create a new one
401
- (_a = this.replayEvent) === null || _a === void 0 ? void 0 : _a.setStatus('ok').finish();
402
- this.createReplayEvent();
709
+ this.sendReplay(this.session.id);
710
+ this.initialEventTimestampSinceFlush = null;
711
+ // TBD: Alternatively we could update this after every rrweb event
712
+ this.session.lastActivity = new Date().getTime();
403
713
  };
404
714
  /**
405
715
  * Determine if there is browser support for `navigator.sendBeacon`
@@ -410,43 +720,37 @@ var SentryReplay = /** @class */ (function () {
410
720
  /**
411
721
  * Send replay attachment using either `sendBeacon()` or `fetch()`
412
722
  */
413
- SentryReplay.prototype.sendReplayRequest = function (endpoint, events) {
723
+ SentryReplay.prototype.sendReplayRequest = function (_a) {
724
+ var endpoint = _a.endpoint, events = _a.events, replaySpans = _a.replaySpans, breadcrumbs = _a.breadcrumbs;
414
725
  return __awaiter(this, void 0, void 0, function () {
415
- var stringifiedPayload, formData, ex_1;
416
- return __generator(this, function (_a) {
417
- switch (_a.label) {
726
+ var stringifiedPayload, formData;
727
+ return __generator(this, function (_b) {
728
+ switch (_b.label) {
418
729
  case 0:
419
- stringifiedPayload = JSON.stringify({ events: events });
730
+ stringifiedPayload = JSON.stringify({
731
+ recording: events,
732
+ replaySpans: replaySpans,
733
+ breadcrumbs: breadcrumbs,
734
+ });
420
735
  formData = new FormData();
421
736
  formData.append('rrweb', new Blob([stringifiedPayload], {
422
737
  type: 'application/json',
423
738
  }), "rrweb-".concat(new Date().getTime(), ".json"));
424
739
  // If sendBeacon is supported and payload is smol enough...
425
740
  if (this.hasSendBeacon() && stringifiedPayload.length <= 65536) {
426
- this.isDebug &&
427
- utils.logger.log("[Replay] uploading attachment via sendBeacon()");
741
+ logger.log("uploading attachment via sendBeacon()");
428
742
  window.navigator.sendBeacon(endpoint, formData);
429
743
  return [2 /*return*/];
430
744
  }
431
- _a.label = 1;
432
- case 1:
433
- _a.trys.push([1, 3, , 4]);
434
- this.isDebug && utils.logger.log("[Replay] uploading attachment via fetch()");
435
745
  // Otherwise use `fetch`, which *WILL* get cancelled on page reloads/unloads
746
+ logger.log("uploading attachment via fetch()");
436
747
  return [4 /*yield*/, fetch(endpoint, {
437
748
  method: 'POST',
438
749
  body: formData,
439
750
  })];
440
- case 2:
441
- // Otherwise use `fetch`, which *WILL* get cancelled on page reloads/unloads
442
- _a.sent();
443
- return [3 /*break*/, 4];
444
- case 3:
445
- ex_1 = _a.sent();
446
- // we have to catch this otherwise it throws an infinite loop in Sentry
447
- console.error(ex_1);
448
- return [3 /*break*/, 4];
449
- case 4: return [2 /*return*/];
751
+ case 1:
752
+ _b.sent();
753
+ return [2 /*return*/];
450
754
  }
451
755
  });
452
756
  });
@@ -456,26 +760,41 @@ var SentryReplay = /** @class */ (function () {
456
760
  */
457
761
  SentryReplay.prototype.sendReplay = function (eventId) {
458
762
  return __awaiter(this, void 0, void 0, function () {
459
- var client, endpoint, ex_2;
763
+ var events, replaySpans, breadcrumbs, client, endpoint, ex_1;
460
764
  return __generator(this, function (_a) {
461
765
  switch (_a.label) {
462
766
  case 0:
463
- _a.trys.push([0, 2, , 3]);
464
767
  // short circuit if theres no events to replay
465
768
  if (!this.events.length)
466
769
  return [2 /*return*/];
770
+ events = this.events;
771
+ replaySpans = this.replaySpans;
772
+ breadcrumbs = this.breadcrumbs;
773
+ this.replaySpans = [];
774
+ this.breadcrumbs = [];
775
+ this.events = [];
467
776
  client = Sentry__namespace.getCurrentHub().getClient();
468
777
  endpoint = SentryReplay.attachmentUrlFromDsn(client.getDsn(), eventId);
469
- return [4 /*yield*/, this.sendReplayRequest(endpoint, this.events)];
778
+ _a.label = 1;
470
779
  case 1:
780
+ _a.trys.push([1, 3, , 4]);
781
+ return [4 /*yield*/, this.sendReplayRequest({
782
+ endpoint: endpoint,
783
+ events: events,
784
+ replaySpans: replaySpans,
785
+ breadcrumbs: breadcrumbs,
786
+ })];
787
+ case 2:
471
788
  _a.sent();
472
- this.events = [];
473
789
  return [2 /*return*/, true];
474
- case 2:
475
- ex_2 = _a.sent();
476
- console.error(ex_2);
790
+ case 3:
791
+ ex_1 = _a.sent();
792
+ // we have to catch this otherwise it throws an infinite loop in Sentry
793
+ console.error(ex_1);
794
+ // If an error happened here, it's likely that uploading the attachment failed, we'll want to restore the events that failed to upload
795
+ this.events = __spreadArray(__spreadArray([], events, true), this.events, true);
477
796
  return [2 /*return*/, false];
478
- case 3: return [2 /*return*/];
797
+ case 4: return [2 /*return*/];
479
798
  }
480
799
  });
481
800
  });