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