@sentry/replay 0.2.0-0 → 0.2.0-3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -3,8 +3,8 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var Sentry = require('@sentry/browser');
6
- var utils = require('@sentry/utils');
7
6
  var rrweb = require('rrweb');
7
+ var utils = require('@sentry/utils');
8
8
 
9
9
  function _interopNamespace(e) {
10
10
  if (e && e.__esModule) return e;
@@ -182,12 +182,159 @@ function createLargestContentfulPaint(entry) {
182
182
  };
183
183
  }
184
184
 
185
- var VISIBILITY_CHANGE_TIMEOUT = 5000;
185
+ var REPLAY_SESSION_KEY = 'sentryReplaySession';
186
+ var ROOT_REPLAY_NAME = 'sentry-replay';
187
+ var REPLAY_EVENT_NAME = 'sentry-replay-event';
188
+ // Grace period to keep a session when a user changes tabs or hides window
189
+ var VISIBILITY_CHANGE_TIMEOUT = 60000; // 1 minute
190
+ // The idle limit for a session
191
+ var SESSION_IDLE_DURATION = 900000; // 15 minutes
192
+
193
+ /**
194
+ * Given an initial timestamp and an expiry duration, checks to see if current
195
+ * time should be considered as expired.
196
+ */
197
+ function isExpired(initialTime, expiry, targetTime) {
198
+ if (targetTime === void 0) { targetTime = +new Date(); }
199
+ // Always expired if < 0
200
+ if (expiry < 0) {
201
+ return true;
202
+ }
203
+ // Never expires if == 0
204
+ if (expiry === 0) {
205
+ return false;
206
+ }
207
+ return initialTime + expiry <= targetTime;
208
+ }
209
+
210
+ /**
211
+ * Checks to see if session is expired
212
+ */
213
+ function isSessionExpired(session, expiry, targetTime) {
214
+ if (targetTime === void 0) { targetTime = +new Date(); }
215
+ return isExpired(session.lastActivity, expiry, targetTime);
216
+ }
217
+
218
+ function wrapLogger(logFn) {
219
+ return function wrappedLog() {
220
+ var args = [];
221
+ for (var _i = 0; _i < arguments.length; _i++) {
222
+ args[_i] = arguments[_i];
223
+ }
224
+ {
225
+ return;
226
+ }
227
+ };
228
+ }
229
+ var logger = __assign(__assign({}, utils.logger), { error: wrapLogger(utils.logger.error), warn: wrapLogger(utils.logger.warn), log: wrapLogger(utils.logger.log) });
230
+
231
+ function saveSession(session) {
232
+ var hasSessionStorage = 'sessionStorage' in window;
233
+ if (!hasSessionStorage) {
234
+ return;
235
+ }
236
+ try {
237
+ window.sessionStorage.setItem(REPLAY_SESSION_KEY, JSON.stringify(session));
238
+ }
239
+ catch (_a) {
240
+ // this shouldn't happen
241
+ }
242
+ }
243
+
244
+ /**
245
+ * Create a new session, which in its current implementation is a Sentry event
246
+ * that all replays will be saved to as attachments. Currently, we only expect
247
+ * one of these Sentry events per "replay session".
248
+ */
249
+ function createSession(_a) {
250
+ var _b = _a.stickySession, stickySession = _b === void 0 ? false : _b;
251
+ var currentDate = new Date().getTime();
252
+ // Create root replay event, this is where attachments will be saved
253
+ var transaction = Sentry__namespace.getCurrentHub().startTransaction({
254
+ name: ROOT_REPLAY_NAME,
255
+ tags: {
256
+ isReplayRoot: 'yes',
257
+ },
258
+ });
259
+ // We have to finish the transaction to get an event ID to be able to
260
+ // upload an attachment for that event
261
+ // @ts-expect-error This returns an eventId (string), but is not typed as such
262
+ var id = transaction.finish();
263
+ logger.log("Creating new session: ".concat(id));
264
+ var session = {
265
+ id: id,
266
+ spanId: transaction.spanId,
267
+ traceId: transaction.traceId,
268
+ started: currentDate,
269
+ lastActivity: currentDate,
270
+ };
271
+ if (stickySession) {
272
+ saveSession(session);
273
+ }
274
+ return session;
275
+ }
276
+
277
+ function fetchSession() {
278
+ var hasSessionStorage = 'sessionStorage' in window;
279
+ if (!hasSessionStorage) {
280
+ return null;
281
+ }
282
+ try {
283
+ return JSON.parse(window.sessionStorage.getItem(REPLAY_SESSION_KEY));
284
+ }
285
+ catch (_a) {
286
+ return null;
287
+ }
288
+ }
289
+
290
+ /**
291
+ * Get or create a session
292
+ */
293
+ function getSession(_a) {
294
+ var expiry = _a.expiry, stickySession = _a.stickySession;
295
+ var session = stickySession && fetchSession();
296
+ if (session) {
297
+ // If there is a session, check if it is valid (e.g. "last activity" time should be within the "session idle time")
298
+ // TODO: We should probably set a max age on this as well
299
+ var isExpired = isSessionExpired(session, expiry);
300
+ if (!isExpired) {
301
+ logger.log("Using existing session: ".concat(session.id));
302
+ return session;
303
+ }
304
+ else {
305
+ logger.log("Session has expired");
306
+ }
307
+ // Otherwise continue to create a new session
308
+ }
309
+ var newSession = createSession({ stickySession: stickySession });
310
+ return newSession;
311
+ }
312
+
313
+ function updateSessionActivity(_a) {
314
+ var stickySession = _a.stickySession;
315
+ // Nothing to do if there are no sticky sessions
316
+ if (!stickySession) {
317
+ return;
318
+ }
319
+ var existingSession = fetchSession();
320
+ // If user manually deleted from session storage, create a new session
321
+ if (!existingSession) {
322
+ // TBD: There was an issue here where sessions weren't saving and this
323
+ // caused lots of transactions to be created
324
+ return createSession({ stickySession: stickySession });
325
+ }
326
+ var newSession = __assign(__assign({}, existingSession), { lastActivity: new Date().getTime() });
327
+ saveSession(newSession);
328
+ return newSession;
329
+ }
330
+
186
331
  var SentryReplay = /** @class */ (function () {
187
332
  function SentryReplay(_a) {
188
333
  if (_a === void 0) { _a = {}; }
189
334
  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"]);
335
+ 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
336
+ _e = _a.rrwebConfig, // TBD: Making this opt-in for now
337
+ _f = _e === void 0 ? {} : _e, _g = _f.maskAllInputs, maskAllInputs = _g === void 0 ? true : _g, rrwebRecordOptions = __rest(_f, ["maskAllInputs"]);
191
338
  /**
192
339
  * @inheritDoc
193
340
  */
@@ -197,6 +344,11 @@ var SentryReplay = /** @class */ (function () {
197
344
  */
198
345
  this.events = [];
199
346
  this.performanceEvents = [];
347
+ /**
348
+ * The timestamp of the first event since the last flush.
349
+ * This is used to determine if the maximum allowed time has passed before we should flush events again.
350
+ */
351
+ this.initialEventTimestampSinceFlush = null;
200
352
  this.performanceObserver = null;
201
353
  /**
202
354
  * Keep a list of performance entries that will be sent with a replay
@@ -210,70 +362,45 @@ var SentryReplay = /** @class */ (function () {
210
362
  * Handle when visibility of the page changes. (e.g. new tab is opened)
211
363
  */
212
364
  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();
365
+ var isExpired = isSessionExpired(_this.session, VISIBILITY_CHANGE_TIMEOUT);
366
+ if (isExpired) {
367
+ if (document.visibilityState === 'visible') {
368
+ // If the user has come back to the page within VISIBILITY_CHANGE_TIMEOUT
369
+ // ms, we will re-use the existing session, otherwise create a new
370
+ // session
371
+ logger.log('Document has become active, but session has expired');
372
+ _this.triggerFullSnapshot();
373
+ }
374
+ // We definitely want to return if visibilityState is "visible", and I
375
+ // think we also want to do the same when "hidden", as there shouldn't be
376
+ // any action to take if user has gone idle for a long period and then
377
+ // comes back to hide the tab. We don't trigger a full snapshot because
378
+ // we don't want to start a new session as they immediately have hidden
379
+ // the tab.
222
380
  return;
223
381
  }
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);
382
+ // Otherwise if session is not expired...
383
+ // Update with current timestamp as the last session activity
384
+ // Only updating session on visibility change to be conservative about
385
+ // writing to session storage. This could be changed in the future.
386
+ updateSessionActivity({
387
+ stickySession: _this.options.stickySession,
388
+ });
389
+ // Send replay when the page/tab becomes hidden. There is no reason to send
390
+ // replay if it becomes visible, since no actions we care about were done
391
+ // while it was hidden
392
+ if (document.visibilityState !== 'visible') {
393
+ _this.finishReplayEvent();
394
+ }
231
395
  };
232
396
  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();
397
+ this.options = { uploadMinDelay: uploadMinDelay, uploadMaxDelay: uploadMaxDelay, stickySession: stickySession };
236
398
  this.events = [];
237
- 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
245
- if (_this.timeout) {
246
- window.clearTimeout(_this.timeout);
247
- }
248
- // Always create a new Sentry event on checkouts and clear existing rrweb events
249
- if (isCheckout) {
250
- console.log('$$$$$ IS CHECKOUT');
251
- _this.events = [event];
252
- }
253
- else {
254
- _this.events.push(event);
255
- }
256
- // Set timer to send attachment to Sentry, will be cancelled if an
257
- // event happens before `idleTimeout` elapses
258
- _this.timeout = window.setTimeout(function () {
259
- _this.isDebug &&
260
- utils.logger.log('[Replay] rrweb timeout hit, finishing replay event');
261
- _this.finishReplayEvent();
262
- }, idleTimeout);
263
- } }));
264
- this.addListeners();
265
399
  }
266
400
  SentryReplay.attachmentUrlFromDsn = function (dsn, eventId) {
267
401
  var host = dsn.host, path = dsn.path, projectId = dsn.projectId, port = dsn.port, protocol = dsn.protocol, user = dsn.user;
268
402
  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
403
  };
270
- Object.defineProperty(SentryReplay.prototype, "isDebug", {
271
- get: function () {
272
- return utils.isDebugBuild();
273
- },
274
- enumerable: false,
275
- configurable: true
276
- });
277
404
  Object.defineProperty(SentryReplay.prototype, "instance", {
278
405
  /**
279
406
  * Get integration's instance on the current hub
@@ -286,17 +413,91 @@ var SentryReplay = /** @class */ (function () {
286
413
  });
287
414
  SentryReplay.prototype.setupOnce = function () {
288
415
  var _this = this;
416
+ /**
417
+ * Because we create a transaction in `setupOnce`, we can potentially create a
418
+ * transaction before some native SDK integrations have run and applied their
419
+ * own global event processor. An example is:
420
+ * https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts
421
+ *
422
+ * So we do this as a workaround to wait for other global event processors to finish
423
+ */
424
+ window.setTimeout(function () { return _this.setup(); });
425
+ };
426
+ SentryReplay.prototype.setup = function () {
427
+ var _this = this;
428
+ this.loadSession({ expiry: SESSION_IDLE_DURATION });
429
+ // If there is no session, then something bad has happened - can't continue
430
+ if (!this.session) {
431
+ throw new Error('Invalid session');
432
+ }
289
433
  // Tag all (non replay) events that get sent to Sentry with the current
290
434
  // replay ID so that we can reference them later in the UI
291
435
  Sentry__namespace.addGlobalEventProcessor(function (event) {
292
- event.tags = __assign(__assign({}, event.tags), { replayId: _this.replayId });
436
+ // Do not apply replayId to the root transaction
437
+ if (event.transaction === ROOT_REPLAY_NAME) {
438
+ return event;
439
+ }
440
+ event.tags = __assign(__assign({}, event.tags), { replayId: _this.session.id });
293
441
  return event;
294
442
  });
443
+ rrweb.record(__assign(__assign({}, this.rrwebRecordOptions), { emit: function (event, isCheckout) {
444
+ // We want to batch uploads of replay events. Save events only if
445
+ // `<uploadMinDelay>` milliseconds have elapsed since the last event
446
+ // *OR* if `<uploadMaxDelay>` milliseconds have elapsed.
447
+ var now = new Date().getTime();
448
+ // Timestamp of the first replay event since the last flush, this gets
449
+ // reset when we finish the replay event
450
+ if (!_this.initialEventTimestampSinceFlush) {
451
+ _this.initialEventTimestampSinceFlush = now;
452
+ }
453
+ var uploadMaxDelayExceeded = isExpired(_this.initialEventTimestampSinceFlush, _this.options.uploadMaxDelay, now);
454
+ // Do not finish the replay event if we receive a new replay event
455
+ // unless `<uploadMaxDelay>` ms have elapsed since the last time we
456
+ // finished the replay
457
+ if (_this.timeout && !uploadMaxDelayExceeded) {
458
+ window.clearTimeout(_this.timeout);
459
+ }
460
+ // We need to clear existing events on a checkout, otherwise they are
461
+ // incremental event updates and should be appended
462
+ if (isCheckout) {
463
+ _this.events = [event];
464
+ }
465
+ else {
466
+ _this.events.push(event);
467
+ }
468
+ // This event type is a fullsnapshot, we should save immediately when this occurs
469
+ // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16
470
+ if (event.type === 2) {
471
+ // A fullsnapshot happens on initial load and if we need to start a
472
+ // new replay due to idle timeout. In the later case we will need to
473
+ // create a new session before finishing the replay.
474
+ _this.loadSession({ expiry: SESSION_IDLE_DURATION });
475
+ _this.finishReplayEvent();
476
+ return;
477
+ }
478
+ // Set timer to finish replay event and send replay attachment to
479
+ // Sentry. Will be cancelled if an event happens before `uploadMinDelay`
480
+ // elapses.
481
+ _this.timeout = window.setTimeout(function () {
482
+ logger.log('rrweb timeout hit, finishing replay event');
483
+ _this.finishReplayEvent();
484
+ }, _this.options.uploadMinDelay);
485
+ } }));
486
+ this.addListeners();
295
487
  // XXX: this needs to be in `setupOnce` vs `constructor`, otherwise SDK is
296
488
  // not fully initialized and the event will not get properly sent to Sentry
297
- this.createRootEvent();
298
489
  this.createReplayEvent();
299
490
  };
491
+ /**
492
+ * Loads a session from storage, or creates a new one
493
+ */
494
+ SentryReplay.prototype.loadSession = function (_a) {
495
+ var expiry = _a.expiry;
496
+ this.session = getSession({
497
+ expiry: expiry,
498
+ stickySession: this.options.stickySession,
499
+ });
500
+ };
300
501
  SentryReplay.prototype.addListeners = function () {
301
502
  document.addEventListener('visibilitychange', this.handleVisibilityChange);
302
503
  if ('PerformanceObserver' in window) {
@@ -308,36 +509,13 @@ var SentryReplay = /** @class */ (function () {
308
509
  }
309
510
  };
310
511
  /**
311
- * Creates a new replay "session". This will create a new Sentry event and
312
- * then trigger rrweb to take a full snapshot.
512
+ * Trigger rrweb to take a full snapshot which will cause this plugin to
513
+ * create a new Replay event.
313
514
  */
314
- SentryReplay.prototype.triggerNewSession = function () {
315
- this.isDebug && utils.logger.log('[Replay] taking full rrweb snapshot');
515
+ SentryReplay.prototype.triggerFullSnapshot = function () {
516
+ logger.log('Taking full rrweb snapshot');
316
517
  rrweb.record.takeFullSnapshot(true);
317
518
  };
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
519
  /**
342
520
  * This is our pseudo replay event disguised as a transaction. It will be
343
521
  * used to store performance entries and breadcrumbs for every incremental
@@ -345,12 +523,14 @@ var SentryReplay = /** @class */ (function () {
345
523
  **/
346
524
  SentryReplay.prototype.createReplayEvent = function () {
347
525
  var _this = this;
348
- console.log('createReplayEvent rootReplayId', this.eventId);
526
+ logger.log('CreateReplayEvent rootReplayId', this.session.id);
527
+ console.error(new Error('creating replay event'), new Date());
349
528
  this.replayEvent = Sentry__namespace.startTransaction({
350
- name: 'sentry-replay-event',
529
+ name: REPLAY_EVENT_NAME,
530
+ parentSpanId: this.session.spanId,
531
+ traceId: this.session.traceId,
351
532
  tags: {
352
- rootReplayId: this.eventId,
353
- replayId: this.replayId,
533
+ replayId: this.session.id,
354
534
  },
355
535
  });
356
536
  Sentry__namespace.configureScope(function (scope) { return scope.setSpan(_this.replayEvent); });
@@ -389,12 +569,22 @@ var SentryReplay = /** @class */ (function () {
389
569
  SentryReplay.prototype.finishReplayEvent = function () {
390
570
  // if (!this.instance) return;
391
571
  var _a;
392
- var eventId = this.eventId || this.createRootEvent();
393
- if (!eventId) {
394
- console.error('[Sentry]: No transaction, no replay');
572
+ // Ensure that our existing session has not expired
573
+ var isExpired = isSessionExpired(this.session, SESSION_IDLE_DURATION);
574
+ if (isExpired) {
575
+ // TBD: If it is expired, we do not send any events...we could send to
576
+ // the expired session, but not sure if that's great
577
+ console.error(new Error('Attempting to finish replay event after session expired.'));
578
+ return;
579
+ }
580
+ if (!this.session.id) {
581
+ console.error(new Error('[Sentry]: No transaction, no replay'));
395
582
  return;
396
583
  }
397
- this.sendReplay(eventId);
584
+ this.sendReplay(this.session.id);
585
+ this.initialEventTimestampSinceFlush = null;
586
+ // TBD: Alternatively we could update this after every rrweb event
587
+ this.session.lastActivity = new Date().getTime();
398
588
  // include performance entries
399
589
  this.addPerformanceEntries();
400
590
  // Close out existing replay event and create a new one
@@ -421,17 +611,17 @@ var SentryReplay = /** @class */ (function () {
421
611
  formData.append('rrweb', new Blob([stringifiedPayload], {
422
612
  type: 'application/json',
423
613
  }), "rrweb-".concat(new Date().getTime(), ".json"));
614
+ console.log('sendReplayRequest: ', endpoint);
424
615
  // If sendBeacon is supported and payload is smol enough...
425
616
  if (this.hasSendBeacon() && stringifiedPayload.length <= 65536) {
426
- this.isDebug &&
427
- utils.logger.log("[Replay] uploading attachment via sendBeacon()");
617
+ logger.log("uploading attachment via sendBeacon()");
428
618
  window.navigator.sendBeacon(endpoint, formData);
429
619
  return [2 /*return*/];
430
620
  }
431
621
  _a.label = 1;
432
622
  case 1:
433
623
  _a.trys.push([1, 3, , 4]);
434
- this.isDebug && utils.logger.log("[Replay] uploading attachment via fetch()");
624
+ logger.log("uploading attachment via fetch()");
435
625
  // Otherwise use `fetch`, which *WILL* get cancelled on page reloads/unloads
436
626
  return [4 /*yield*/, fetch(endpoint, {
437
627
  method: 'POST',