@sentry/replay 0.2.0-0

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.
@@ -0,0 +1,466 @@
1
+ import * as Sentry from '@sentry/browser';
2
+ import { isDebugBuild, logger, uuid4 } from '@sentry/utils';
3
+ import { record } from 'rrweb';
4
+
5
+ /*! *****************************************************************************
6
+ Copyright (c) Microsoft Corporation.
7
+
8
+ Permission to use, copy, modify, and/or distribute this software for any
9
+ purpose with or without fee is hereby granted.
10
+
11
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
12
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
14
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
16
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17
+ PERFORMANCE OF THIS SOFTWARE.
18
+ ***************************************************************************** */
19
+
20
+ var __assign = function() {
21
+ __assign = Object.assign || function __assign(t) {
22
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
23
+ s = arguments[i];
24
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
25
+ }
26
+ return t;
27
+ };
28
+ return __assign.apply(this, arguments);
29
+ };
30
+
31
+ function __rest(s, e) {
32
+ var t = {};
33
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
34
+ t[p] = s[p];
35
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
36
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
37
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
38
+ t[p[i]] = s[p[i]];
39
+ }
40
+ return t;
41
+ }
42
+
43
+ function __awaiter(thisArg, _arguments, P, generator) {
44
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
45
+ return new (P || (P = Promise))(function (resolve, reject) {
46
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
47
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
48
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
49
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
50
+ });
51
+ }
52
+
53
+ function __generator(thisArg, body) {
54
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
55
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
56
+ function verb(n) { return function (v) { return step([n, v]); }; }
57
+ function step(op) {
58
+ if (f) throw new TypeError("Generator is already executing.");
59
+ while (_) try {
60
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
61
+ if (y = 0, t) op = [op[0] & 2, t.value];
62
+ switch (op[0]) {
63
+ case 0: case 1: t = op; break;
64
+ case 4: _.label++; return { value: op[1], done: false };
65
+ case 5: _.label++; y = op[1]; op = [0]; continue;
66
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
67
+ default:
68
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
69
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
70
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
71
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
72
+ if (t[2]) _.ops.pop();
73
+ _.trys.pop(); continue;
74
+ }
75
+ op = body.call(thisArg, _);
76
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
77
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
78
+ }
79
+ }
80
+
81
+ function __spreadArray(to, from, pack) {
82
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
83
+ if (ar || !(i in from)) {
84
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
85
+ ar[i] = from[i];
86
+ }
87
+ }
88
+ return to.concat(ar || Array.prototype.slice.call(from));
89
+ }
90
+
91
+ var _a;
92
+ // Map entryType -> function to normalize data for event
93
+ var ENTRY_TYPES = (_a = {
94
+ resource: createResourceEntry,
95
+ paint: createPaintEntry,
96
+ navigation: createNavigationEntry
97
+ },
98
+ _a['largest-contentful-paint'] = createLargestContentfulPaint,
99
+ _a);
100
+ function createPerformanceEntries(entries) {
101
+ return entries.map(createPerformanceEntry).filter(Boolean);
102
+ }
103
+ function createPerformanceEntry(entry) {
104
+ if (ENTRY_TYPES[entry.entryType] === undefined) {
105
+ return null;
106
+ }
107
+ return ENTRY_TYPES[entry.entryType](entry);
108
+ }
109
+ function getAbsoluteTime(time) {
110
+ return (window.performance.timeOrigin + time) / 1000;
111
+ }
112
+ function createPaintEntry(entry) {
113
+ var duration = entry.duration, entryType = entry.entryType, name = entry.name, startTime = entry.startTime;
114
+ var start = getAbsoluteTime(startTime);
115
+ return {
116
+ type: entryType,
117
+ name: name,
118
+ start: start,
119
+ end: start + duration,
120
+ };
121
+ }
122
+ function createNavigationEntry(entry) {
123
+ // TODO: There looks to be some more interesting bits in here (domComplete, domContentLoaded)
124
+ var entryType = entry.entryType, name = entry.name, domComplete = entry.domComplete, startTime = entry.startTime, transferSize = entry.transferSize, type = entry.type;
125
+ return {
126
+ type: "".concat(entryType, ".").concat(type),
127
+ start: getAbsoluteTime(startTime),
128
+ end: getAbsoluteTime(domComplete),
129
+ name: name,
130
+ data: {
131
+ size: transferSize,
132
+ },
133
+ };
134
+ }
135
+ function createResourceEntry(entry) {
136
+ var entryType = entry.entryType, initiatorType = entry.initiatorType, name = entry.name, responseEnd = entry.responseEnd, startTime = entry.startTime, transferSize = entry.transferSize;
137
+ return {
138
+ type: "".concat(entryType, ".").concat(initiatorType),
139
+ start: getAbsoluteTime(startTime),
140
+ end: getAbsoluteTime(responseEnd),
141
+ name: name,
142
+ data: {
143
+ size: transferSize,
144
+ },
145
+ };
146
+ }
147
+ function createLargestContentfulPaint(entry) {
148
+ var duration = entry.duration, entryType = entry.entryType, startTime = entry.startTime, size = entry.size;
149
+ var start = getAbsoluteTime(startTime);
150
+ return {
151
+ type: entryType,
152
+ name: entryType,
153
+ start: start,
154
+ end: start + duration,
155
+ data: {
156
+ size: size,
157
+ },
158
+ };
159
+ }
160
+
161
+ var VISIBILITY_CHANGE_TIMEOUT = 5000;
162
+ var SentryReplay = /** @class */ (function () {
163
+ function SentryReplay(_a) {
164
+ if (_a === void 0) { _a = {}; }
165
+ 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"]);
167
+ /**
168
+ * @inheritDoc
169
+ */
170
+ this.name = SentryReplay.id;
171
+ /**
172
+ * Buffer of rrweb events that will be serialized as JSON and saved as an attachment to a Sentry event
173
+ */
174
+ this.events = [];
175
+ this.performanceEvents = [];
176
+ this.performanceObserver = null;
177
+ /**
178
+ * Keep a list of performance entries that will be sent with a replay
179
+ */
180
+ this.handlePerformanceObserver = function (list
181
+ // observer: PerformanceObserver
182
+ ) {
183
+ _this.performanceEvents = __spreadArray(__spreadArray([], _this.performanceEvents, true), list.getEntries(), true);
184
+ };
185
+ /**
186
+ * Handle when visibility of the page changes. (e.g. new tab is opened)
187
+ */
188
+ 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();
198
+ return;
199
+ }
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);
207
+ };
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();
212
+ 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
221
+ if (_this.timeout) {
222
+ window.clearTimeout(_this.timeout);
223
+ }
224
+ // Always create a new Sentry event on checkouts and clear existing rrweb events
225
+ if (isCheckout) {
226
+ console.log('$$$$$ IS CHECKOUT');
227
+ _this.events = [event];
228
+ }
229
+ else {
230
+ _this.events.push(event);
231
+ }
232
+ // Set timer to send attachment to Sentry, will be cancelled if an
233
+ // event happens before `idleTimeout` elapses
234
+ _this.timeout = window.setTimeout(function () {
235
+ _this.isDebug &&
236
+ logger.log('[Replay] rrweb timeout hit, finishing replay event');
237
+ _this.finishReplayEvent();
238
+ }, idleTimeout);
239
+ } }));
240
+ 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
+ };
286
+ /**
287
+ * Creates a new replay "session". This will create a new Sentry event and
288
+ * then trigger rrweb to take a full snapshot.
289
+ */
290
+ SentryReplay.prototype.triggerNewSession = function () {
291
+ this.isDebug && logger.log('[Replay] taking full rrweb snapshot');
292
+ record.takeFullSnapshot(true);
293
+ };
294
+ /**
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).
298
+ */
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
+ },
310
+ });
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
+ };
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 () {
323
+ 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
+ },
331
+ });
332
+ Sentry.configureScope(function (scope) { return scope.setSpan(_this.replayEvent); });
333
+ return this.replayEvent;
334
+ };
335
+ /**
336
+ * Create a span for each performance entry. The parent transaction is `this.replayEvent`.
337
+ */
338
+ SentryReplay.prototype.createPerformanceSpans = function (entries) {
339
+ var _this = this;
340
+ entries.forEach(function (_a) {
341
+ var _b;
342
+ 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({
344
+ op: type,
345
+ description: name,
346
+ startTimestamp: start,
347
+ data: data,
348
+ });
349
+ span.finish(end);
350
+ });
351
+ };
352
+ /**
353
+ * Observed performance events are added to `this.performanceEvents`. These
354
+ * are included in the replay event before it is finished and sent to Sentry.
355
+ */
356
+ SentryReplay.prototype.addPerformanceEntries = function () {
357
+ // Copy and reset entries before processing
358
+ var entries = __spreadArray([], this.performanceEvents, true);
359
+ this.performanceEvents = [];
360
+ // Parse the entries
361
+ var entryEvents = createPerformanceEntries(entries);
362
+ // This current implementation is to create spans on the transaction referenced in `this.replayEvent`
363
+ this.createPerformanceSpans(entryEvents);
364
+ };
365
+ 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');
371
+ return;
372
+ }
373
+ this.sendReplay(eventId);
374
+ // include performance entries
375
+ 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();
379
+ };
380
+ /**
381
+ * Determine if there is browser support for `navigator.sendBeacon`
382
+ */
383
+ SentryReplay.prototype.hasSendBeacon = function () {
384
+ return 'navigator' in window && 'sendBeacon' in window.navigator;
385
+ };
386
+ /**
387
+ * Send replay attachment using either `sendBeacon()` or `fetch()`
388
+ */
389
+ SentryReplay.prototype.sendReplayRequest = function (endpoint, events) {
390
+ return __awaiter(this, void 0, void 0, function () {
391
+ var stringifiedPayload, formData, ex_1;
392
+ return __generator(this, function (_a) {
393
+ switch (_a.label) {
394
+ case 0:
395
+ stringifiedPayload = JSON.stringify({ events: events });
396
+ formData = new FormData();
397
+ formData.append('rrweb', new Blob([stringifiedPayload], {
398
+ type: 'application/json',
399
+ }), "rrweb-".concat(new Date().getTime(), ".json"));
400
+ // If sendBeacon is supported and payload is smol enough...
401
+ if (this.hasSendBeacon() && stringifiedPayload.length <= 65536) {
402
+ this.isDebug &&
403
+ logger.log("[Replay] uploading attachment via sendBeacon()");
404
+ window.navigator.sendBeacon(endpoint, formData);
405
+ return [2 /*return*/];
406
+ }
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
+ // Otherwise use `fetch`, which *WILL* get cancelled on page reloads/unloads
412
+ return [4 /*yield*/, fetch(endpoint, {
413
+ method: 'POST',
414
+ body: formData,
415
+ })];
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*/];
426
+ }
427
+ });
428
+ });
429
+ };
430
+ /**
431
+ * Finalize and send the current replay event to Sentry
432
+ */
433
+ SentryReplay.prototype.sendReplay = function (eventId) {
434
+ return __awaiter(this, void 0, void 0, function () {
435
+ var client, endpoint, ex_2;
436
+ return __generator(this, function (_a) {
437
+ switch (_a.label) {
438
+ case 0:
439
+ _a.trys.push([0, 2, , 3]);
440
+ // short circuit if theres no events to replay
441
+ if (!this.events.length)
442
+ return [2 /*return*/];
443
+ client = Sentry.getCurrentHub().getClient();
444
+ endpoint = SentryReplay.attachmentUrlFromDsn(client.getDsn(), eventId);
445
+ return [4 /*yield*/, this.sendReplayRequest(endpoint, this.events)];
446
+ case 1:
447
+ _a.sent();
448
+ this.events = [];
449
+ return [2 /*return*/, true];
450
+ case 2:
451
+ ex_2 = _a.sent();
452
+ console.error(ex_2);
453
+ return [2 /*return*/, false];
454
+ case 3: return [2 /*return*/];
455
+ }
456
+ });
457
+ });
458
+ };
459
+ /**
460
+ * @inheritDoc
461
+ */
462
+ SentryReplay.id = 'Replay';
463
+ return SentryReplay;
464
+ }());
465
+
466
+ export { SentryReplay };