humanbehavior-js 0.0.1

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,4810 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
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
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
20
+
21
+
22
+ var __assign = function() {
23
+ __assign = Object.assign || function __assign(t) {
24
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
25
+ s = arguments[i];
26
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
27
+ }
28
+ return t;
29
+ };
30
+ return __assign.apply(this, arguments);
31
+ };
32
+
33
+ function __awaiter$1(thisArg, _arguments, P, generator) {
34
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
35
+ return new (P || (P = Promise))(function (resolve, reject) {
36
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
37
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
38
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
39
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
40
+ });
41
+ }
42
+
43
+ function __generator(thisArg, body) {
44
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
45
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
46
+ function verb(n) { return function (v) { return step([n, v]); }; }
47
+ function step(op) {
48
+ if (f) throw new TypeError("Generator is already executing.");
49
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
50
+ 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;
51
+ if (y = 0, t) op = [op[0] & 2, t.value];
52
+ switch (op[0]) {
53
+ case 0: case 1: t = op; break;
54
+ case 4: _.label++; return { value: op[1], done: false };
55
+ case 5: _.label++; y = op[1]; op = [0]; continue;
56
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
57
+ default:
58
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
59
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
60
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
61
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
62
+ if (t[2]) _.ops.pop();
63
+ _.trys.pop(); continue;
64
+ }
65
+ op = body.call(thisArg, _);
66
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
67
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
68
+ }
69
+ }
70
+
71
+ function __spreadArray(to, from, pack) {
72
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
73
+ if (ar || !(i in from)) {
74
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
75
+ ar[i] = from[i];
76
+ }
77
+ }
78
+ return to.concat(ar || Array.prototype.slice.call(from));
79
+ }
80
+
81
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
82
+ var e = new Error(message);
83
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
84
+ };
85
+
86
+ var NodeType;
87
+ (function (NodeType) {
88
+ NodeType[NodeType["Document"] = 0] = "Document";
89
+ NodeType[NodeType["DocumentType"] = 1] = "DocumentType";
90
+ NodeType[NodeType["Element"] = 2] = "Element";
91
+ NodeType[NodeType["Text"] = 3] = "Text";
92
+ NodeType[NodeType["CDATA"] = 4] = "CDATA";
93
+ NodeType[NodeType["Comment"] = 5] = "Comment";
94
+ })(NodeType || (NodeType = {}));
95
+
96
+ function isElement(n) {
97
+ return n.nodeType === n.ELEMENT_NODE;
98
+ }
99
+ function isShadowRoot(n) {
100
+ var host = n === null || n === void 0 ? void 0 : n.host;
101
+ return Boolean((host === null || host === void 0 ? void 0 : host.shadowRoot) === n);
102
+ }
103
+ function isNativeShadowDom(shadowRoot) {
104
+ return Object.prototype.toString.call(shadowRoot) === '[object ShadowRoot]';
105
+ }
106
+ function fixBrowserCompatibilityIssuesInCSS(cssText) {
107
+ if (cssText.includes(' background-clip: text;') &&
108
+ !cssText.includes(' -webkit-background-clip: text;')) {
109
+ cssText = cssText.replace(' background-clip: text;', ' -webkit-background-clip: text; background-clip: text;');
110
+ }
111
+ return cssText;
112
+ }
113
+ function getCssRulesString(s) {
114
+ try {
115
+ var rules = s.rules || s.cssRules;
116
+ return rules
117
+ ? fixBrowserCompatibilityIssuesInCSS(Array.from(rules).map(getCssRuleString).join(''))
118
+ : null;
119
+ }
120
+ catch (error) {
121
+ return null;
122
+ }
123
+ }
124
+ function getCssRuleString(rule) {
125
+ var cssStringified = rule.cssText;
126
+ if (isCSSImportRule(rule)) {
127
+ try {
128
+ cssStringified = getCssRulesString(rule.styleSheet) || cssStringified;
129
+ }
130
+ catch (_a) {
131
+ }
132
+ }
133
+ return cssStringified;
134
+ }
135
+ function isCSSImportRule(rule) {
136
+ return 'styleSheet' in rule;
137
+ }
138
+ var Mirror = (function () {
139
+ function Mirror() {
140
+ this.idNodeMap = new Map();
141
+ this.nodeMetaMap = new WeakMap();
142
+ }
143
+ Mirror.prototype.getId = function (n) {
144
+ var _a;
145
+ if (!n)
146
+ return -1;
147
+ var id = (_a = this.getMeta(n)) === null || _a === void 0 ? void 0 : _a.id;
148
+ return id !== null && id !== void 0 ? id : -1;
149
+ };
150
+ Mirror.prototype.getNode = function (id) {
151
+ return this.idNodeMap.get(id) || null;
152
+ };
153
+ Mirror.prototype.getIds = function () {
154
+ return Array.from(this.idNodeMap.keys());
155
+ };
156
+ Mirror.prototype.getMeta = function (n) {
157
+ return this.nodeMetaMap.get(n) || null;
158
+ };
159
+ Mirror.prototype.removeNodeFromMap = function (n) {
160
+ var _this = this;
161
+ var id = this.getId(n);
162
+ this.idNodeMap["delete"](id);
163
+ if (n.childNodes) {
164
+ n.childNodes.forEach(function (childNode) {
165
+ return _this.removeNodeFromMap(childNode);
166
+ });
167
+ }
168
+ };
169
+ Mirror.prototype.has = function (id) {
170
+ return this.idNodeMap.has(id);
171
+ };
172
+ Mirror.prototype.hasNode = function (node) {
173
+ return this.nodeMetaMap.has(node);
174
+ };
175
+ Mirror.prototype.add = function (n, meta) {
176
+ var id = meta.id;
177
+ this.idNodeMap.set(id, n);
178
+ this.nodeMetaMap.set(n, meta);
179
+ };
180
+ Mirror.prototype.replace = function (id, n) {
181
+ var oldNode = this.getNode(id);
182
+ if (oldNode) {
183
+ var meta = this.nodeMetaMap.get(oldNode);
184
+ if (meta)
185
+ this.nodeMetaMap.set(n, meta);
186
+ }
187
+ this.idNodeMap.set(id, n);
188
+ };
189
+ Mirror.prototype.reset = function () {
190
+ this.idNodeMap = new Map();
191
+ this.nodeMetaMap = new WeakMap();
192
+ };
193
+ return Mirror;
194
+ }());
195
+ function createMirror() {
196
+ return new Mirror();
197
+ }
198
+ function maskInputValue(_a) {
199
+ var maskInputOptions = _a.maskInputOptions, tagName = _a.tagName, type = _a.type, value = _a.value, maskInputFn = _a.maskInputFn;
200
+ var text = value || '';
201
+ if (maskInputOptions[tagName.toLowerCase()] ||
202
+ maskInputOptions[type]) {
203
+ if (maskInputFn) {
204
+ text = maskInputFn(text);
205
+ }
206
+ else {
207
+ text = '*'.repeat(text.length);
208
+ }
209
+ }
210
+ return text;
211
+ }
212
+ var ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';
213
+ function is2DCanvasBlank(canvas) {
214
+ var ctx = canvas.getContext('2d');
215
+ if (!ctx)
216
+ return true;
217
+ var chunkSize = 50;
218
+ for (var x = 0; x < canvas.width; x += chunkSize) {
219
+ for (var y = 0; y < canvas.height; y += chunkSize) {
220
+ var getImageData = ctx.getImageData;
221
+ var originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData
222
+ ? getImageData[ORIGINAL_ATTRIBUTE_NAME]
223
+ : getImageData;
224
+ var pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);
225
+ if (pixelBuffer.some(function (pixel) { return pixel !== 0; }))
226
+ return false;
227
+ }
228
+ }
229
+ return true;
230
+ }
231
+
232
+ var _id = 1;
233
+ var tagNameRegex = new RegExp('[^a-z0-9-_:]');
234
+ var IGNORED_NODE = -2;
235
+ function genId() {
236
+ return _id++;
237
+ }
238
+ function getValidTagName(element) {
239
+ if (element instanceof HTMLFormElement) {
240
+ return 'form';
241
+ }
242
+ var processedTagName = element.tagName.toLowerCase().trim();
243
+ if (tagNameRegex.test(processedTagName)) {
244
+ return 'div';
245
+ }
246
+ return processedTagName;
247
+ }
248
+ function stringifyStyleSheet(sheet) {
249
+ return sheet.cssRules
250
+ ? Array.from(sheet.cssRules)
251
+ .map(function (rule) { return rule.cssText || ''; })
252
+ .join('')
253
+ : '';
254
+ }
255
+ function extractOrigin(url) {
256
+ var origin = '';
257
+ if (url.indexOf('//') > -1) {
258
+ origin = url.split('/').slice(0, 3).join('/');
259
+ }
260
+ else {
261
+ origin = url.split('/')[0];
262
+ }
263
+ origin = origin.split('?')[0];
264
+ return origin;
265
+ }
266
+ var canvasService;
267
+ var canvasCtx;
268
+ var URL_IN_CSS_REF = /url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm;
269
+ var RELATIVE_PATH = /^(?!www\.|(?:http|ftp)s?:\/\/|[A-Za-z]:\\|\/\/|#).*/;
270
+ var DATA_URI = /^(data:)([^,]*),(.*)/i;
271
+ function absoluteToStylesheet(cssText, href) {
272
+ return (cssText || '').replace(URL_IN_CSS_REF, function (origin, quote1, path1, quote2, path2, path3) {
273
+ var filePath = path1 || path2 || path3;
274
+ var maybeQuote = quote1 || quote2 || '';
275
+ if (!filePath) {
276
+ return origin;
277
+ }
278
+ if (!RELATIVE_PATH.test(filePath)) {
279
+ return "url(".concat(maybeQuote).concat(filePath).concat(maybeQuote, ")");
280
+ }
281
+ if (DATA_URI.test(filePath)) {
282
+ return "url(".concat(maybeQuote).concat(filePath).concat(maybeQuote, ")");
283
+ }
284
+ if (filePath[0] === '/') {
285
+ return "url(".concat(maybeQuote).concat(extractOrigin(href) + filePath).concat(maybeQuote, ")");
286
+ }
287
+ var stack = href.split('/');
288
+ var parts = filePath.split('/');
289
+ stack.pop();
290
+ for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
291
+ var part = parts_1[_i];
292
+ if (part === '.') {
293
+ continue;
294
+ }
295
+ else if (part === '..') {
296
+ stack.pop();
297
+ }
298
+ else {
299
+ stack.push(part);
300
+ }
301
+ }
302
+ return "url(".concat(maybeQuote).concat(stack.join('/')).concat(maybeQuote, ")");
303
+ });
304
+ }
305
+ var SRCSET_NOT_SPACES = /^[^ \t\n\r\u000c]+/;
306
+ var SRCSET_COMMAS_OR_SPACES = /^[, \t\n\r\u000c]+/;
307
+ function getAbsoluteSrcsetString(doc, attributeValue) {
308
+ if (attributeValue.trim() === '') {
309
+ return attributeValue;
310
+ }
311
+ var pos = 0;
312
+ function collectCharacters(regEx) {
313
+ var chars;
314
+ var match = regEx.exec(attributeValue.substring(pos));
315
+ if (match) {
316
+ chars = match[0];
317
+ pos += chars.length;
318
+ return chars;
319
+ }
320
+ return '';
321
+ }
322
+ var output = [];
323
+ while (true) {
324
+ collectCharacters(SRCSET_COMMAS_OR_SPACES);
325
+ if (pos >= attributeValue.length) {
326
+ break;
327
+ }
328
+ var url = collectCharacters(SRCSET_NOT_SPACES);
329
+ if (url.slice(-1) === ',') {
330
+ url = absoluteToDoc(doc, url.substring(0, url.length - 1));
331
+ output.push(url);
332
+ }
333
+ else {
334
+ var descriptorsStr = '';
335
+ url = absoluteToDoc(doc, url);
336
+ var inParens = false;
337
+ while (true) {
338
+ var c = attributeValue.charAt(pos);
339
+ if (c === '') {
340
+ output.push((url + descriptorsStr).trim());
341
+ break;
342
+ }
343
+ else if (!inParens) {
344
+ if (c === ',') {
345
+ pos += 1;
346
+ output.push((url + descriptorsStr).trim());
347
+ break;
348
+ }
349
+ else if (c === '(') {
350
+ inParens = true;
351
+ }
352
+ }
353
+ else {
354
+ if (c === ')') {
355
+ inParens = false;
356
+ }
357
+ }
358
+ descriptorsStr += c;
359
+ pos += 1;
360
+ }
361
+ }
362
+ }
363
+ return output.join(', ');
364
+ }
365
+ function absoluteToDoc(doc, attributeValue) {
366
+ if (!attributeValue || attributeValue.trim() === '') {
367
+ return attributeValue;
368
+ }
369
+ var a = doc.createElement('a');
370
+ a.href = attributeValue;
371
+ return a.href;
372
+ }
373
+ function isSVGElement(el) {
374
+ return Boolean(el.tagName === 'svg' || el.ownerSVGElement);
375
+ }
376
+ function getHref() {
377
+ var a = document.createElement('a');
378
+ a.href = '';
379
+ return a.href;
380
+ }
381
+ function transformAttribute(doc, tagName, name, value) {
382
+ if (name === 'src' ||
383
+ (name === 'href' && value && !(tagName === 'use' && value[0] === '#'))) {
384
+ return absoluteToDoc(doc, value);
385
+ }
386
+ else if (name === 'xlink:href' && value && value[0] !== '#') {
387
+ return absoluteToDoc(doc, value);
388
+ }
389
+ else if (name === 'background' &&
390
+ value &&
391
+ (tagName === 'table' || tagName === 'td' || tagName === 'th')) {
392
+ return absoluteToDoc(doc, value);
393
+ }
394
+ else if (name === 'srcset' && value) {
395
+ return getAbsoluteSrcsetString(doc, value);
396
+ }
397
+ else if (name === 'style' && value) {
398
+ return absoluteToStylesheet(value, getHref());
399
+ }
400
+ else if (tagName === 'object' && name === 'data' && value) {
401
+ return absoluteToDoc(doc, value);
402
+ }
403
+ else {
404
+ return value;
405
+ }
406
+ }
407
+ function _isBlockedElement(element, blockClass, blockSelector) {
408
+ if (typeof blockClass === 'string') {
409
+ if (element.classList.contains(blockClass)) {
410
+ return true;
411
+ }
412
+ }
413
+ else {
414
+ for (var eIndex = element.classList.length; eIndex--;) {
415
+ var className = element.classList[eIndex];
416
+ if (blockClass.test(className)) {
417
+ return true;
418
+ }
419
+ }
420
+ }
421
+ if (blockSelector) {
422
+ return element.matches(blockSelector);
423
+ }
424
+ return false;
425
+ }
426
+ function classMatchesRegex(node, regex, checkAncestors) {
427
+ if (!node)
428
+ return false;
429
+ if (node.nodeType !== node.ELEMENT_NODE) {
430
+ if (!checkAncestors)
431
+ return false;
432
+ return classMatchesRegex(node.parentNode, regex, checkAncestors);
433
+ }
434
+ for (var eIndex = node.classList.length; eIndex--;) {
435
+ var className = node.classList[eIndex];
436
+ if (regex.test(className)) {
437
+ return true;
438
+ }
439
+ }
440
+ if (!checkAncestors)
441
+ return false;
442
+ return classMatchesRegex(node.parentNode, regex, checkAncestors);
443
+ }
444
+ function needMaskingText(node, maskTextClass, maskTextSelector) {
445
+ var el = node.nodeType === node.ELEMENT_NODE
446
+ ? node
447
+ : node.parentElement;
448
+ if (el === null)
449
+ return false;
450
+ if (typeof maskTextClass === 'string') {
451
+ if (el.classList.contains(maskTextClass))
452
+ return true;
453
+ if (el.closest(".".concat(maskTextClass)))
454
+ return true;
455
+ }
456
+ else {
457
+ if (classMatchesRegex(el, maskTextClass, true))
458
+ return true;
459
+ }
460
+ if (maskTextSelector) {
461
+ if (el.matches(maskTextSelector))
462
+ return true;
463
+ if (el.closest(maskTextSelector))
464
+ return true;
465
+ }
466
+ return false;
467
+ }
468
+ function onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {
469
+ var win = iframeEl.contentWindow;
470
+ if (!win) {
471
+ return;
472
+ }
473
+ var fired = false;
474
+ var readyState;
475
+ try {
476
+ readyState = win.document.readyState;
477
+ }
478
+ catch (error) {
479
+ return;
480
+ }
481
+ if (readyState !== 'complete') {
482
+ var timer_1 = setTimeout(function () {
483
+ if (!fired) {
484
+ listener();
485
+ fired = true;
486
+ }
487
+ }, iframeLoadTimeout);
488
+ iframeEl.addEventListener('load', function () {
489
+ clearTimeout(timer_1);
490
+ fired = true;
491
+ listener();
492
+ });
493
+ return;
494
+ }
495
+ var blankUrl = 'about:blank';
496
+ if (win.location.href !== blankUrl ||
497
+ iframeEl.src === blankUrl ||
498
+ iframeEl.src === '') {
499
+ setTimeout(listener, 0);
500
+ return iframeEl.addEventListener('load', listener);
501
+ }
502
+ iframeEl.addEventListener('load', listener);
503
+ }
504
+ function onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {
505
+ var fired = false;
506
+ var styleSheetLoaded;
507
+ try {
508
+ styleSheetLoaded = link.sheet;
509
+ }
510
+ catch (error) {
511
+ return;
512
+ }
513
+ if (styleSheetLoaded)
514
+ return;
515
+ var timer = setTimeout(function () {
516
+ if (!fired) {
517
+ listener();
518
+ fired = true;
519
+ }
520
+ }, styleSheetLoadTimeout);
521
+ link.addEventListener('load', function () {
522
+ clearTimeout(timer);
523
+ fired = true;
524
+ listener();
525
+ });
526
+ }
527
+ function serializeNode(n, options) {
528
+ var doc = options.doc, mirror = options.mirror, blockClass = options.blockClass, blockSelector = options.blockSelector, maskTextClass = options.maskTextClass, maskTextSelector = options.maskTextSelector, inlineStylesheet = options.inlineStylesheet, _a = options.maskInputOptions, maskInputOptions = _a === void 0 ? {} : _a, maskTextFn = options.maskTextFn, maskInputFn = options.maskInputFn, _b = options.dataURLOptions, dataURLOptions = _b === void 0 ? {} : _b, inlineImages = options.inlineImages, recordCanvas = options.recordCanvas, keepIframeSrcFn = options.keepIframeSrcFn, _c = options.newlyAddedElement, newlyAddedElement = _c === void 0 ? false : _c;
529
+ var rootId = getRootId(doc, mirror);
530
+ switch (n.nodeType) {
531
+ case n.DOCUMENT_NODE:
532
+ if (n.compatMode !== 'CSS1Compat') {
533
+ return {
534
+ type: NodeType.Document,
535
+ childNodes: [],
536
+ compatMode: n.compatMode
537
+ };
538
+ }
539
+ else {
540
+ return {
541
+ type: NodeType.Document,
542
+ childNodes: []
543
+ };
544
+ }
545
+ case n.DOCUMENT_TYPE_NODE:
546
+ return {
547
+ type: NodeType.DocumentType,
548
+ name: n.name,
549
+ publicId: n.publicId,
550
+ systemId: n.systemId,
551
+ rootId: rootId
552
+ };
553
+ case n.ELEMENT_NODE:
554
+ return serializeElementNode(n, {
555
+ doc: doc,
556
+ blockClass: blockClass,
557
+ blockSelector: blockSelector,
558
+ inlineStylesheet: inlineStylesheet,
559
+ maskInputOptions: maskInputOptions,
560
+ maskInputFn: maskInputFn,
561
+ dataURLOptions: dataURLOptions,
562
+ inlineImages: inlineImages,
563
+ recordCanvas: recordCanvas,
564
+ keepIframeSrcFn: keepIframeSrcFn,
565
+ newlyAddedElement: newlyAddedElement,
566
+ rootId: rootId
567
+ });
568
+ case n.TEXT_NODE:
569
+ return serializeTextNode(n, {
570
+ maskTextClass: maskTextClass,
571
+ maskTextSelector: maskTextSelector,
572
+ maskTextFn: maskTextFn,
573
+ rootId: rootId
574
+ });
575
+ case n.CDATA_SECTION_NODE:
576
+ return {
577
+ type: NodeType.CDATA,
578
+ textContent: '',
579
+ rootId: rootId
580
+ };
581
+ case n.COMMENT_NODE:
582
+ return {
583
+ type: NodeType.Comment,
584
+ textContent: n.textContent || '',
585
+ rootId: rootId
586
+ };
587
+ default:
588
+ return false;
589
+ }
590
+ }
591
+ function getRootId(doc, mirror) {
592
+ if (!mirror.hasNode(doc))
593
+ return undefined;
594
+ var docId = mirror.getId(doc);
595
+ return docId === 1 ? undefined : docId;
596
+ }
597
+ function serializeTextNode(n, options) {
598
+ var _a;
599
+ var maskTextClass = options.maskTextClass, maskTextSelector = options.maskTextSelector, maskTextFn = options.maskTextFn, rootId = options.rootId;
600
+ var parentTagName = n.parentNode && n.parentNode.tagName;
601
+ var textContent = n.textContent;
602
+ var isStyle = parentTagName === 'STYLE' ? true : undefined;
603
+ var isScript = parentTagName === 'SCRIPT' ? true : undefined;
604
+ if (isStyle && textContent) {
605
+ try {
606
+ if (n.nextSibling || n.previousSibling) {
607
+ }
608
+ else if ((_a = n.parentNode.sheet) === null || _a === void 0 ? void 0 : _a.cssRules) {
609
+ textContent = stringifyStyleSheet(n.parentNode.sheet);
610
+ }
611
+ }
612
+ catch (err) {
613
+ console.warn("Cannot get CSS styles from text's parentNode. Error: ".concat(err), n);
614
+ }
615
+ textContent = absoluteToStylesheet(textContent, getHref());
616
+ }
617
+ if (isScript) {
618
+ textContent = 'SCRIPT_PLACEHOLDER';
619
+ }
620
+ if (!isStyle &&
621
+ !isScript &&
622
+ textContent &&
623
+ needMaskingText(n, maskTextClass, maskTextSelector)) {
624
+ textContent = maskTextFn
625
+ ? maskTextFn(textContent)
626
+ : textContent.replace(/[\S]/g, '*');
627
+ }
628
+ return {
629
+ type: NodeType.Text,
630
+ textContent: textContent || '',
631
+ isStyle: isStyle,
632
+ rootId: rootId
633
+ };
634
+ }
635
+ function serializeElementNode(n, options) {
636
+ var doc = options.doc, blockClass = options.blockClass, blockSelector = options.blockSelector, inlineStylesheet = options.inlineStylesheet, _a = options.maskInputOptions, maskInputOptions = _a === void 0 ? {} : _a, maskInputFn = options.maskInputFn, _b = options.dataURLOptions, dataURLOptions = _b === void 0 ? {} : _b, inlineImages = options.inlineImages, recordCanvas = options.recordCanvas, keepIframeSrcFn = options.keepIframeSrcFn, _c = options.newlyAddedElement, newlyAddedElement = _c === void 0 ? false : _c, rootId = options.rootId;
637
+ var needBlock = _isBlockedElement(n, blockClass, blockSelector);
638
+ var tagName = getValidTagName(n);
639
+ var attributes = {};
640
+ var len = n.attributes.length;
641
+ for (var i = 0; i < len; i++) {
642
+ var attr = n.attributes[i];
643
+ attributes[attr.name] = transformAttribute(doc, tagName, attr.name, attr.value);
644
+ }
645
+ if (tagName === 'link' && inlineStylesheet) {
646
+ var stylesheet = Array.from(doc.styleSheets).find(function (s) {
647
+ return s.href === n.href;
648
+ });
649
+ var cssText = null;
650
+ if (stylesheet) {
651
+ cssText = getCssRulesString(stylesheet);
652
+ }
653
+ if (cssText) {
654
+ delete attributes.rel;
655
+ delete attributes.href;
656
+ attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);
657
+ }
658
+ }
659
+ if (tagName === 'style' &&
660
+ n.sheet &&
661
+ !(n.innerText || n.textContent || '').trim().length) {
662
+ var cssText = getCssRulesString(n.sheet);
663
+ if (cssText) {
664
+ attributes._cssText = absoluteToStylesheet(cssText, getHref());
665
+ }
666
+ }
667
+ if (tagName === 'input' || tagName === 'textarea' || tagName === 'select') {
668
+ var value = n.value;
669
+ var checked = n.checked;
670
+ if (attributes.type !== 'radio' &&
671
+ attributes.type !== 'checkbox' &&
672
+ attributes.type !== 'submit' &&
673
+ attributes.type !== 'button' &&
674
+ value) {
675
+ attributes.value = maskInputValue({
676
+ type: attributes.type,
677
+ tagName: tagName,
678
+ value: value,
679
+ maskInputOptions: maskInputOptions,
680
+ maskInputFn: maskInputFn
681
+ });
682
+ }
683
+ else if (checked) {
684
+ attributes.checked = checked;
685
+ }
686
+ }
687
+ if (tagName === 'option') {
688
+ if (n.selected && !maskInputOptions['select']) {
689
+ attributes.selected = true;
690
+ }
691
+ else {
692
+ delete attributes.selected;
693
+ }
694
+ }
695
+ if (tagName === 'canvas' && recordCanvas) {
696
+ if (n.__context === '2d') {
697
+ if (!is2DCanvasBlank(n)) {
698
+ attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);
699
+ }
700
+ }
701
+ else if (!('__context' in n)) {
702
+ var canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);
703
+ var blankCanvas = document.createElement('canvas');
704
+ blankCanvas.width = n.width;
705
+ blankCanvas.height = n.height;
706
+ var blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);
707
+ if (canvasDataURL !== blankCanvasDataURL) {
708
+ attributes.rr_dataURL = canvasDataURL;
709
+ }
710
+ }
711
+ }
712
+ if (tagName === 'img' && inlineImages) {
713
+ if (!canvasService) {
714
+ canvasService = doc.createElement('canvas');
715
+ canvasCtx = canvasService.getContext('2d');
716
+ }
717
+ var image_1 = n;
718
+ var oldValue_1 = image_1.crossOrigin;
719
+ image_1.crossOrigin = 'anonymous';
720
+ var recordInlineImage = function () {
721
+ try {
722
+ canvasService.width = image_1.naturalWidth;
723
+ canvasService.height = image_1.naturalHeight;
724
+ canvasCtx.drawImage(image_1, 0, 0);
725
+ attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);
726
+ }
727
+ catch (err) {
728
+ console.warn("Cannot inline img src=".concat(image_1.currentSrc, "! Error: ").concat(err));
729
+ }
730
+ oldValue_1
731
+ ? (attributes.crossOrigin = oldValue_1)
732
+ : image_1.removeAttribute('crossorigin');
733
+ };
734
+ if (image_1.complete && image_1.naturalWidth !== 0)
735
+ recordInlineImage();
736
+ else
737
+ image_1.onload = recordInlineImage;
738
+ }
739
+ if (tagName === 'audio' || tagName === 'video') {
740
+ attributes.rr_mediaState = n.paused
741
+ ? 'paused'
742
+ : 'played';
743
+ attributes.rr_mediaCurrentTime = n.currentTime;
744
+ }
745
+ if (!newlyAddedElement) {
746
+ if (n.scrollLeft) {
747
+ attributes.rr_scrollLeft = n.scrollLeft;
748
+ }
749
+ if (n.scrollTop) {
750
+ attributes.rr_scrollTop = n.scrollTop;
751
+ }
752
+ }
753
+ if (needBlock) {
754
+ var _d = n.getBoundingClientRect(), width = _d.width, height = _d.height;
755
+ attributes = {
756
+ "class": attributes["class"],
757
+ rr_width: "".concat(width, "px"),
758
+ rr_height: "".concat(height, "px")
759
+ };
760
+ }
761
+ if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src)) {
762
+ if (!n.contentDocument) {
763
+ attributes.rr_src = attributes.src;
764
+ }
765
+ delete attributes.src;
766
+ }
767
+ return {
768
+ type: NodeType.Element,
769
+ tagName: tagName,
770
+ attributes: attributes,
771
+ childNodes: [],
772
+ isSVG: isSVGElement(n) || undefined,
773
+ needBlock: needBlock,
774
+ rootId: rootId
775
+ };
776
+ }
777
+ function lowerIfExists(maybeAttr) {
778
+ if (maybeAttr === undefined) {
779
+ return '';
780
+ }
781
+ else {
782
+ return maybeAttr.toLowerCase();
783
+ }
784
+ }
785
+ function slimDOMExcluded(sn, slimDOMOptions) {
786
+ if (slimDOMOptions.comment && sn.type === NodeType.Comment) {
787
+ return true;
788
+ }
789
+ else if (sn.type === NodeType.Element) {
790
+ if (slimDOMOptions.script &&
791
+ (sn.tagName === 'script' ||
792
+ (sn.tagName === 'link' &&
793
+ sn.attributes.rel === 'preload' &&
794
+ sn.attributes.as === 'script') ||
795
+ (sn.tagName === 'link' &&
796
+ sn.attributes.rel === 'prefetch' &&
797
+ typeof sn.attributes.href === 'string' &&
798
+ sn.attributes.href.endsWith('.js')))) {
799
+ return true;
800
+ }
801
+ else if (slimDOMOptions.headFavicon &&
802
+ ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||
803
+ (sn.tagName === 'meta' &&
804
+ (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) ||
805
+ lowerIfExists(sn.attributes.name) === 'application-name' ||
806
+ lowerIfExists(sn.attributes.rel) === 'icon' ||
807
+ lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||
808
+ lowerIfExists(sn.attributes.rel) === 'shortcut icon')))) {
809
+ return true;
810
+ }
811
+ else if (sn.tagName === 'meta') {
812
+ if (slimDOMOptions.headMetaDescKeywords &&
813
+ lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {
814
+ return true;
815
+ }
816
+ else if (slimDOMOptions.headMetaSocial &&
817
+ (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) ||
818
+ lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||
819
+ lowerIfExists(sn.attributes.name) === 'pinterest')) {
820
+ return true;
821
+ }
822
+ else if (slimDOMOptions.headMetaRobots &&
823
+ (lowerIfExists(sn.attributes.name) === 'robots' ||
824
+ lowerIfExists(sn.attributes.name) === 'googlebot' ||
825
+ lowerIfExists(sn.attributes.name) === 'bingbot')) {
826
+ return true;
827
+ }
828
+ else if (slimDOMOptions.headMetaHttpEquiv &&
829
+ sn.attributes['http-equiv'] !== undefined) {
830
+ return true;
831
+ }
832
+ else if (slimDOMOptions.headMetaAuthorship &&
833
+ (lowerIfExists(sn.attributes.name) === 'author' ||
834
+ lowerIfExists(sn.attributes.name) === 'generator' ||
835
+ lowerIfExists(sn.attributes.name) === 'framework' ||
836
+ lowerIfExists(sn.attributes.name) === 'publisher' ||
837
+ lowerIfExists(sn.attributes.name) === 'progid' ||
838
+ lowerIfExists(sn.attributes.property).match(/^article:/) ||
839
+ lowerIfExists(sn.attributes.property).match(/^product:/))) {
840
+ return true;
841
+ }
842
+ else if (slimDOMOptions.headMetaVerification &&
843
+ (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||
844
+ lowerIfExists(sn.attributes.name) === 'yandex-verification' ||
845
+ lowerIfExists(sn.attributes.name) === 'csrf-token' ||
846
+ lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||
847
+ lowerIfExists(sn.attributes.name) === 'verify-v1' ||
848
+ lowerIfExists(sn.attributes.name) === 'verification' ||
849
+ lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {
850
+ return true;
851
+ }
852
+ }
853
+ }
854
+ return false;
855
+ }
856
+ function serializeNodeWithId(n, options) {
857
+ var doc = options.doc, mirror = options.mirror, blockClass = options.blockClass, blockSelector = options.blockSelector, maskTextClass = options.maskTextClass, maskTextSelector = options.maskTextSelector, _a = options.skipChild, skipChild = _a === void 0 ? false : _a, _b = options.inlineStylesheet, inlineStylesheet = _b === void 0 ? true : _b, _c = options.maskInputOptions, maskInputOptions = _c === void 0 ? {} : _c, maskTextFn = options.maskTextFn, maskInputFn = options.maskInputFn, slimDOMOptions = options.slimDOMOptions, _d = options.dataURLOptions, dataURLOptions = _d === void 0 ? {} : _d, _e = options.inlineImages, inlineImages = _e === void 0 ? false : _e, _f = options.recordCanvas, recordCanvas = _f === void 0 ? false : _f, onSerialize = options.onSerialize, onIframeLoad = options.onIframeLoad, _g = options.iframeLoadTimeout, iframeLoadTimeout = _g === void 0 ? 5000 : _g, onStylesheetLoad = options.onStylesheetLoad, _h = options.stylesheetLoadTimeout, stylesheetLoadTimeout = _h === void 0 ? 5000 : _h, _j = options.keepIframeSrcFn, keepIframeSrcFn = _j === void 0 ? function () { return false; } : _j, _k = options.newlyAddedElement, newlyAddedElement = _k === void 0 ? false : _k;
858
+ var _l = options.preserveWhiteSpace, preserveWhiteSpace = _l === void 0 ? true : _l;
859
+ var _serializedNode = serializeNode(n, {
860
+ doc: doc,
861
+ mirror: mirror,
862
+ blockClass: blockClass,
863
+ blockSelector: blockSelector,
864
+ maskTextClass: maskTextClass,
865
+ maskTextSelector: maskTextSelector,
866
+ inlineStylesheet: inlineStylesheet,
867
+ maskInputOptions: maskInputOptions,
868
+ maskTextFn: maskTextFn,
869
+ maskInputFn: maskInputFn,
870
+ dataURLOptions: dataURLOptions,
871
+ inlineImages: inlineImages,
872
+ recordCanvas: recordCanvas,
873
+ keepIframeSrcFn: keepIframeSrcFn,
874
+ newlyAddedElement: newlyAddedElement
875
+ });
876
+ if (!_serializedNode) {
877
+ console.warn(n, 'not serialized');
878
+ return null;
879
+ }
880
+ var id;
881
+ if (mirror.hasNode(n)) {
882
+ id = mirror.getId(n);
883
+ }
884
+ else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||
885
+ (!preserveWhiteSpace &&
886
+ _serializedNode.type === NodeType.Text &&
887
+ !_serializedNode.isStyle &&
888
+ !_serializedNode.textContent.replace(/^\s+|\s+$/gm, '').length)) {
889
+ id = IGNORED_NODE;
890
+ }
891
+ else {
892
+ id = genId();
893
+ }
894
+ var serializedNode = Object.assign(_serializedNode, { id: id });
895
+ mirror.add(n, serializedNode);
896
+ if (id === IGNORED_NODE) {
897
+ return null;
898
+ }
899
+ if (onSerialize) {
900
+ onSerialize(n);
901
+ }
902
+ var recordChild = !skipChild;
903
+ if (serializedNode.type === NodeType.Element) {
904
+ recordChild = recordChild && !serializedNode.needBlock;
905
+ delete serializedNode.needBlock;
906
+ var shadowRoot = n.shadowRoot;
907
+ if (shadowRoot && isNativeShadowDom(shadowRoot))
908
+ serializedNode.isShadowHost = true;
909
+ }
910
+ if ((serializedNode.type === NodeType.Document ||
911
+ serializedNode.type === NodeType.Element) &&
912
+ recordChild) {
913
+ if (slimDOMOptions.headWhitespace &&
914
+ serializedNode.type === NodeType.Element &&
915
+ serializedNode.tagName === 'head') {
916
+ preserveWhiteSpace = false;
917
+ }
918
+ var bypassOptions = {
919
+ doc: doc,
920
+ mirror: mirror,
921
+ blockClass: blockClass,
922
+ blockSelector: blockSelector,
923
+ maskTextClass: maskTextClass,
924
+ maskTextSelector: maskTextSelector,
925
+ skipChild: skipChild,
926
+ inlineStylesheet: inlineStylesheet,
927
+ maskInputOptions: maskInputOptions,
928
+ maskTextFn: maskTextFn,
929
+ maskInputFn: maskInputFn,
930
+ slimDOMOptions: slimDOMOptions,
931
+ dataURLOptions: dataURLOptions,
932
+ inlineImages: inlineImages,
933
+ recordCanvas: recordCanvas,
934
+ preserveWhiteSpace: preserveWhiteSpace,
935
+ onSerialize: onSerialize,
936
+ onIframeLoad: onIframeLoad,
937
+ iframeLoadTimeout: iframeLoadTimeout,
938
+ onStylesheetLoad: onStylesheetLoad,
939
+ stylesheetLoadTimeout: stylesheetLoadTimeout,
940
+ keepIframeSrcFn: keepIframeSrcFn
941
+ };
942
+ for (var _i = 0, _m = Array.from(n.childNodes); _i < _m.length; _i++) {
943
+ var childN = _m[_i];
944
+ var serializedChildNode = serializeNodeWithId(childN, bypassOptions);
945
+ if (serializedChildNode) {
946
+ serializedNode.childNodes.push(serializedChildNode);
947
+ }
948
+ }
949
+ if (isElement(n) && n.shadowRoot) {
950
+ for (var _o = 0, _p = Array.from(n.shadowRoot.childNodes); _o < _p.length; _o++) {
951
+ var childN = _p[_o];
952
+ var serializedChildNode = serializeNodeWithId(childN, bypassOptions);
953
+ if (serializedChildNode) {
954
+ isNativeShadowDom(n.shadowRoot) &&
955
+ (serializedChildNode.isShadow = true);
956
+ serializedNode.childNodes.push(serializedChildNode);
957
+ }
958
+ }
959
+ }
960
+ }
961
+ if (n.parentNode &&
962
+ isShadowRoot(n.parentNode) &&
963
+ isNativeShadowDom(n.parentNode)) {
964
+ serializedNode.isShadow = true;
965
+ }
966
+ if (serializedNode.type === NodeType.Element &&
967
+ serializedNode.tagName === 'iframe') {
968
+ onceIframeLoaded(n, function () {
969
+ var iframeDoc = n.contentDocument;
970
+ if (iframeDoc && onIframeLoad) {
971
+ var serializedIframeNode = serializeNodeWithId(iframeDoc, {
972
+ doc: iframeDoc,
973
+ mirror: mirror,
974
+ blockClass: blockClass,
975
+ blockSelector: blockSelector,
976
+ maskTextClass: maskTextClass,
977
+ maskTextSelector: maskTextSelector,
978
+ skipChild: false,
979
+ inlineStylesheet: inlineStylesheet,
980
+ maskInputOptions: maskInputOptions,
981
+ maskTextFn: maskTextFn,
982
+ maskInputFn: maskInputFn,
983
+ slimDOMOptions: slimDOMOptions,
984
+ dataURLOptions: dataURLOptions,
985
+ inlineImages: inlineImages,
986
+ recordCanvas: recordCanvas,
987
+ preserveWhiteSpace: preserveWhiteSpace,
988
+ onSerialize: onSerialize,
989
+ onIframeLoad: onIframeLoad,
990
+ iframeLoadTimeout: iframeLoadTimeout,
991
+ onStylesheetLoad: onStylesheetLoad,
992
+ stylesheetLoadTimeout: stylesheetLoadTimeout,
993
+ keepIframeSrcFn: keepIframeSrcFn
994
+ });
995
+ if (serializedIframeNode) {
996
+ onIframeLoad(n, serializedIframeNode);
997
+ }
998
+ }
999
+ }, iframeLoadTimeout);
1000
+ }
1001
+ if (serializedNode.type === NodeType.Element &&
1002
+ serializedNode.tagName === 'link' &&
1003
+ serializedNode.attributes.rel === 'stylesheet') {
1004
+ onceStylesheetLoaded(n, function () {
1005
+ if (onStylesheetLoad) {
1006
+ var serializedLinkNode = serializeNodeWithId(n, {
1007
+ doc: doc,
1008
+ mirror: mirror,
1009
+ blockClass: blockClass,
1010
+ blockSelector: blockSelector,
1011
+ maskTextClass: maskTextClass,
1012
+ maskTextSelector: maskTextSelector,
1013
+ skipChild: false,
1014
+ inlineStylesheet: inlineStylesheet,
1015
+ maskInputOptions: maskInputOptions,
1016
+ maskTextFn: maskTextFn,
1017
+ maskInputFn: maskInputFn,
1018
+ slimDOMOptions: slimDOMOptions,
1019
+ dataURLOptions: dataURLOptions,
1020
+ inlineImages: inlineImages,
1021
+ recordCanvas: recordCanvas,
1022
+ preserveWhiteSpace: preserveWhiteSpace,
1023
+ onSerialize: onSerialize,
1024
+ onIframeLoad: onIframeLoad,
1025
+ iframeLoadTimeout: iframeLoadTimeout,
1026
+ onStylesheetLoad: onStylesheetLoad,
1027
+ stylesheetLoadTimeout: stylesheetLoadTimeout,
1028
+ keepIframeSrcFn: keepIframeSrcFn
1029
+ });
1030
+ if (serializedLinkNode) {
1031
+ onStylesheetLoad(n, serializedLinkNode);
1032
+ }
1033
+ }
1034
+ }, stylesheetLoadTimeout);
1035
+ }
1036
+ return serializedNode;
1037
+ }
1038
+ function snapshot(n, options) {
1039
+ var _a = options || {}, _b = _a.mirror, mirror = _b === void 0 ? new Mirror() : _b, _c = _a.blockClass, blockClass = _c === void 0 ? 'rr-block' : _c, _d = _a.blockSelector, blockSelector = _d === void 0 ? null : _d, _e = _a.maskTextClass, maskTextClass = _e === void 0 ? 'rr-mask' : _e, _f = _a.maskTextSelector, maskTextSelector = _f === void 0 ? null : _f, _g = _a.inlineStylesheet, inlineStylesheet = _g === void 0 ? true : _g, _h = _a.inlineImages, inlineImages = _h === void 0 ? false : _h, _j = _a.recordCanvas, recordCanvas = _j === void 0 ? false : _j, _k = _a.maskAllInputs, maskAllInputs = _k === void 0 ? false : _k, maskTextFn = _a.maskTextFn, maskInputFn = _a.maskInputFn, _l = _a.slimDOM, slimDOM = _l === void 0 ? false : _l, dataURLOptions = _a.dataURLOptions, preserveWhiteSpace = _a.preserveWhiteSpace, onSerialize = _a.onSerialize, onIframeLoad = _a.onIframeLoad, iframeLoadTimeout = _a.iframeLoadTimeout, onStylesheetLoad = _a.onStylesheetLoad, stylesheetLoadTimeout = _a.stylesheetLoadTimeout, _m = _a.keepIframeSrcFn, keepIframeSrcFn = _m === void 0 ? function () { return false; } : _m;
1040
+ var maskInputOptions = maskAllInputs === true
1041
+ ? {
1042
+ color: true,
1043
+ date: true,
1044
+ 'datetime-local': true,
1045
+ email: true,
1046
+ month: true,
1047
+ number: true,
1048
+ range: true,
1049
+ search: true,
1050
+ tel: true,
1051
+ text: true,
1052
+ time: true,
1053
+ url: true,
1054
+ week: true,
1055
+ textarea: true,
1056
+ select: true,
1057
+ password: true
1058
+ }
1059
+ : maskAllInputs === false
1060
+ ? {
1061
+ password: true
1062
+ }
1063
+ : maskAllInputs;
1064
+ var slimDOMOptions = slimDOM === true || slimDOM === 'all'
1065
+ ?
1066
+ {
1067
+ script: true,
1068
+ comment: true,
1069
+ headFavicon: true,
1070
+ headWhitespace: true,
1071
+ headMetaDescKeywords: slimDOM === 'all',
1072
+ headMetaSocial: true,
1073
+ headMetaRobots: true,
1074
+ headMetaHttpEquiv: true,
1075
+ headMetaAuthorship: true,
1076
+ headMetaVerification: true
1077
+ }
1078
+ : slimDOM === false
1079
+ ? {}
1080
+ : slimDOM;
1081
+ return serializeNodeWithId(n, {
1082
+ doc: n,
1083
+ mirror: mirror,
1084
+ blockClass: blockClass,
1085
+ blockSelector: blockSelector,
1086
+ maskTextClass: maskTextClass,
1087
+ maskTextSelector: maskTextSelector,
1088
+ skipChild: false,
1089
+ inlineStylesheet: inlineStylesheet,
1090
+ maskInputOptions: maskInputOptions,
1091
+ maskTextFn: maskTextFn,
1092
+ maskInputFn: maskInputFn,
1093
+ slimDOMOptions: slimDOMOptions,
1094
+ dataURLOptions: dataURLOptions,
1095
+ inlineImages: inlineImages,
1096
+ recordCanvas: recordCanvas,
1097
+ preserveWhiteSpace: preserveWhiteSpace,
1098
+ onSerialize: onSerialize,
1099
+ onIframeLoad: onIframeLoad,
1100
+ iframeLoadTimeout: iframeLoadTimeout,
1101
+ onStylesheetLoad: onStylesheetLoad,
1102
+ stylesheetLoadTimeout: stylesheetLoadTimeout,
1103
+ keepIframeSrcFn: keepIframeSrcFn,
1104
+ newlyAddedElement: false
1105
+ });
1106
+ }
1107
+
1108
+ function on(type, fn, target = document) {
1109
+ const options = { capture: true, passive: true };
1110
+ target.addEventListener(type, fn, options);
1111
+ return () => target.removeEventListener(type, fn, options);
1112
+ }
1113
+ const DEPARTED_MIRROR_ACCESS_WARNING = 'Please stop import mirror directly. Instead of that,' +
1114
+ '\r\n' +
1115
+ 'now you can use replayer.getMirror() to access the mirror instance of a replayer,' +
1116
+ '\r\n' +
1117
+ 'or you can use record.mirror to access the mirror instance during recording.';
1118
+ let _mirror = {
1119
+ map: {},
1120
+ getId() {
1121
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
1122
+ return -1;
1123
+ },
1124
+ getNode() {
1125
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
1126
+ return null;
1127
+ },
1128
+ removeNodeFromMap() {
1129
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
1130
+ },
1131
+ has() {
1132
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
1133
+ return false;
1134
+ },
1135
+ reset() {
1136
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
1137
+ },
1138
+ };
1139
+ if (typeof window !== 'undefined' && window.Proxy && window.Reflect) {
1140
+ _mirror = new Proxy(_mirror, {
1141
+ get(target, prop, receiver) {
1142
+ if (prop === 'map') {
1143
+ console.error(DEPARTED_MIRROR_ACCESS_WARNING);
1144
+ }
1145
+ return Reflect.get(target, prop, receiver);
1146
+ },
1147
+ });
1148
+ }
1149
+ function throttle(func, wait, options = {}) {
1150
+ let timeout = null;
1151
+ let previous = 0;
1152
+ return function (...args) {
1153
+ const now = Date.now();
1154
+ if (!previous && options.leading === false) {
1155
+ previous = now;
1156
+ }
1157
+ const remaining = wait - (now - previous);
1158
+ const context = this;
1159
+ if (remaining <= 0 || remaining > wait) {
1160
+ if (timeout) {
1161
+ clearTimeout(timeout);
1162
+ timeout = null;
1163
+ }
1164
+ previous = now;
1165
+ func.apply(context, args);
1166
+ }
1167
+ else if (!timeout && options.trailing !== false) {
1168
+ timeout = setTimeout(() => {
1169
+ previous = options.leading === false ? 0 : Date.now();
1170
+ timeout = null;
1171
+ func.apply(context, args);
1172
+ }, remaining);
1173
+ }
1174
+ };
1175
+ }
1176
+ function hookSetter(target, key, d, isRevoked, win = window) {
1177
+ const original = win.Object.getOwnPropertyDescriptor(target, key);
1178
+ win.Object.defineProperty(target, key, isRevoked
1179
+ ? d
1180
+ : {
1181
+ set(value) {
1182
+ setTimeout(() => {
1183
+ d.set.call(this, value);
1184
+ }, 0);
1185
+ if (original && original.set) {
1186
+ original.set.call(this, value);
1187
+ }
1188
+ },
1189
+ });
1190
+ return () => hookSetter(target, key, original || {}, true);
1191
+ }
1192
+ function patch(source, name, replacement) {
1193
+ try {
1194
+ if (!(name in source)) {
1195
+ return () => {
1196
+ };
1197
+ }
1198
+ const original = source[name];
1199
+ const wrapped = replacement(original);
1200
+ if (typeof wrapped === 'function') {
1201
+ wrapped.prototype = wrapped.prototype || {};
1202
+ Object.defineProperties(wrapped, {
1203
+ __rrweb_original__: {
1204
+ enumerable: false,
1205
+ value: original,
1206
+ },
1207
+ });
1208
+ }
1209
+ source[name] = wrapped;
1210
+ return () => {
1211
+ source[name] = original;
1212
+ };
1213
+ }
1214
+ catch (_a) {
1215
+ return () => {
1216
+ };
1217
+ }
1218
+ }
1219
+ function getWindowHeight() {
1220
+ return (window.innerHeight ||
1221
+ (document.documentElement && document.documentElement.clientHeight) ||
1222
+ (document.body && document.body.clientHeight));
1223
+ }
1224
+ function getWindowWidth() {
1225
+ return (window.innerWidth ||
1226
+ (document.documentElement && document.documentElement.clientWidth) ||
1227
+ (document.body && document.body.clientWidth));
1228
+ }
1229
+ function isBlocked(node, blockClass, blockSelector, checkAncestors) {
1230
+ if (!node) {
1231
+ return false;
1232
+ }
1233
+ const el = node.nodeType === node.ELEMENT_NODE
1234
+ ? node
1235
+ : node.parentElement;
1236
+ if (!el)
1237
+ return false;
1238
+ if (typeof blockClass === 'string') {
1239
+ if (el.classList.contains(blockClass))
1240
+ return true;
1241
+ if (checkAncestors && el.closest('.' + blockClass) !== null)
1242
+ return true;
1243
+ }
1244
+ else {
1245
+ if (classMatchesRegex(el, blockClass, checkAncestors))
1246
+ return true;
1247
+ }
1248
+ if (blockSelector) {
1249
+ if (node.matches(blockSelector))
1250
+ return true;
1251
+ if (checkAncestors && el.closest(blockSelector) !== null)
1252
+ return true;
1253
+ }
1254
+ return false;
1255
+ }
1256
+ function isSerialized(n, mirror) {
1257
+ return mirror.getId(n) !== -1;
1258
+ }
1259
+ function isIgnored(n, mirror) {
1260
+ return mirror.getId(n) === IGNORED_NODE;
1261
+ }
1262
+ function isAncestorRemoved(target, mirror) {
1263
+ if (isShadowRoot(target)) {
1264
+ return false;
1265
+ }
1266
+ const id = mirror.getId(target);
1267
+ if (!mirror.has(id)) {
1268
+ return true;
1269
+ }
1270
+ if (target.parentNode &&
1271
+ target.parentNode.nodeType === target.DOCUMENT_NODE) {
1272
+ return false;
1273
+ }
1274
+ if (!target.parentNode) {
1275
+ return true;
1276
+ }
1277
+ return isAncestorRemoved(target.parentNode, mirror);
1278
+ }
1279
+ function isTouchEvent(event) {
1280
+ return Boolean(event.changedTouches);
1281
+ }
1282
+ function polyfill(win = window) {
1283
+ if ('NodeList' in win && !win.NodeList.prototype.forEach) {
1284
+ win.NodeList.prototype.forEach = Array.prototype
1285
+ .forEach;
1286
+ }
1287
+ if ('DOMTokenList' in win && !win.DOMTokenList.prototype.forEach) {
1288
+ win.DOMTokenList.prototype.forEach = Array.prototype
1289
+ .forEach;
1290
+ }
1291
+ if (!Node.prototype.contains) {
1292
+ Node.prototype.contains = (...args) => {
1293
+ let node = args[0];
1294
+ if (!(0 in args)) {
1295
+ throw new TypeError('1 argument is required');
1296
+ }
1297
+ do {
1298
+ if (this === node) {
1299
+ return true;
1300
+ }
1301
+ } while ((node = node && node.parentNode));
1302
+ return false;
1303
+ };
1304
+ }
1305
+ }
1306
+ function isSerializedIframe(n, mirror) {
1307
+ return Boolean(n.nodeName === 'IFRAME' && mirror.getMeta(n));
1308
+ }
1309
+ function isSerializedStylesheet(n, mirror) {
1310
+ return Boolean(n.nodeName === 'LINK' &&
1311
+ n.nodeType === n.ELEMENT_NODE &&
1312
+ n.getAttribute &&
1313
+ n.getAttribute('rel') === 'stylesheet' &&
1314
+ mirror.getMeta(n));
1315
+ }
1316
+ function hasShadowRoot(n) {
1317
+ return Boolean(n === null || n === void 0 ? void 0 : n.shadowRoot);
1318
+ }
1319
+ class StyleSheetMirror {
1320
+ constructor() {
1321
+ this.id = 1;
1322
+ this.styleIDMap = new WeakMap();
1323
+ this.idStyleMap = new Map();
1324
+ }
1325
+ getId(stylesheet) {
1326
+ var _a;
1327
+ return (_a = this.styleIDMap.get(stylesheet)) !== null && _a !== void 0 ? _a : -1;
1328
+ }
1329
+ has(stylesheet) {
1330
+ return this.styleIDMap.has(stylesheet);
1331
+ }
1332
+ add(stylesheet, id) {
1333
+ if (this.has(stylesheet))
1334
+ return this.getId(stylesheet);
1335
+ let newId;
1336
+ if (id === undefined) {
1337
+ newId = this.id++;
1338
+ }
1339
+ else
1340
+ newId = id;
1341
+ this.styleIDMap.set(stylesheet, newId);
1342
+ this.idStyleMap.set(newId, stylesheet);
1343
+ return newId;
1344
+ }
1345
+ getStyle(id) {
1346
+ return this.idStyleMap.get(id) || null;
1347
+ }
1348
+ reset() {
1349
+ this.styleIDMap = new WeakMap();
1350
+ this.idStyleMap = new Map();
1351
+ this.id = 1;
1352
+ }
1353
+ generateId() {
1354
+ return this.id++;
1355
+ }
1356
+ }
1357
+
1358
+ var EventType = /* @__PURE__ */ ((EventType2) => {
1359
+ EventType2[EventType2["DomContentLoaded"] = 0] = "DomContentLoaded";
1360
+ EventType2[EventType2["Load"] = 1] = "Load";
1361
+ EventType2[EventType2["FullSnapshot"] = 2] = "FullSnapshot";
1362
+ EventType2[EventType2["IncrementalSnapshot"] = 3] = "IncrementalSnapshot";
1363
+ EventType2[EventType2["Meta"] = 4] = "Meta";
1364
+ EventType2[EventType2["Custom"] = 5] = "Custom";
1365
+ EventType2[EventType2["Plugin"] = 6] = "Plugin";
1366
+ return EventType2;
1367
+ })(EventType || {});
1368
+ var IncrementalSource = /* @__PURE__ */ ((IncrementalSource2) => {
1369
+ IncrementalSource2[IncrementalSource2["Mutation"] = 0] = "Mutation";
1370
+ IncrementalSource2[IncrementalSource2["MouseMove"] = 1] = "MouseMove";
1371
+ IncrementalSource2[IncrementalSource2["MouseInteraction"] = 2] = "MouseInteraction";
1372
+ IncrementalSource2[IncrementalSource2["Scroll"] = 3] = "Scroll";
1373
+ IncrementalSource2[IncrementalSource2["ViewportResize"] = 4] = "ViewportResize";
1374
+ IncrementalSource2[IncrementalSource2["Input"] = 5] = "Input";
1375
+ IncrementalSource2[IncrementalSource2["TouchMove"] = 6] = "TouchMove";
1376
+ IncrementalSource2[IncrementalSource2["MediaInteraction"] = 7] = "MediaInteraction";
1377
+ IncrementalSource2[IncrementalSource2["StyleSheetRule"] = 8] = "StyleSheetRule";
1378
+ IncrementalSource2[IncrementalSource2["CanvasMutation"] = 9] = "CanvasMutation";
1379
+ IncrementalSource2[IncrementalSource2["Font"] = 10] = "Font";
1380
+ IncrementalSource2[IncrementalSource2["Log"] = 11] = "Log";
1381
+ IncrementalSource2[IncrementalSource2["Drag"] = 12] = "Drag";
1382
+ IncrementalSource2[IncrementalSource2["StyleDeclaration"] = 13] = "StyleDeclaration";
1383
+ IncrementalSource2[IncrementalSource2["Selection"] = 14] = "Selection";
1384
+ IncrementalSource2[IncrementalSource2["AdoptedStyleSheet"] = 15] = "AdoptedStyleSheet";
1385
+ return IncrementalSource2;
1386
+ })(IncrementalSource || {});
1387
+ var MouseInteractions = /* @__PURE__ */ ((MouseInteractions2) => {
1388
+ MouseInteractions2[MouseInteractions2["MouseUp"] = 0] = "MouseUp";
1389
+ MouseInteractions2[MouseInteractions2["MouseDown"] = 1] = "MouseDown";
1390
+ MouseInteractions2[MouseInteractions2["Click"] = 2] = "Click";
1391
+ MouseInteractions2[MouseInteractions2["ContextMenu"] = 3] = "ContextMenu";
1392
+ MouseInteractions2[MouseInteractions2["DblClick"] = 4] = "DblClick";
1393
+ MouseInteractions2[MouseInteractions2["Focus"] = 5] = "Focus";
1394
+ MouseInteractions2[MouseInteractions2["Blur"] = 6] = "Blur";
1395
+ MouseInteractions2[MouseInteractions2["TouchStart"] = 7] = "TouchStart";
1396
+ MouseInteractions2[MouseInteractions2["TouchMove_Departed"] = 8] = "TouchMove_Departed";
1397
+ MouseInteractions2[MouseInteractions2["TouchEnd"] = 9] = "TouchEnd";
1398
+ MouseInteractions2[MouseInteractions2["TouchCancel"] = 10] = "TouchCancel";
1399
+ return MouseInteractions2;
1400
+ })(MouseInteractions || {});
1401
+ var CanvasContext = /* @__PURE__ */ ((CanvasContext2) => {
1402
+ CanvasContext2[CanvasContext2["2D"] = 0] = "2D";
1403
+ CanvasContext2[CanvasContext2["WebGL"] = 1] = "WebGL";
1404
+ CanvasContext2[CanvasContext2["WebGL2"] = 2] = "WebGL2";
1405
+ return CanvasContext2;
1406
+ })(CanvasContext || {});
1407
+
1408
+ function isNodeInLinkedList(n) {
1409
+ return '__ln' in n;
1410
+ }
1411
+ class DoubleLinkedList {
1412
+ constructor() {
1413
+ this.length = 0;
1414
+ this.head = null;
1415
+ }
1416
+ get(position) {
1417
+ if (position >= this.length) {
1418
+ throw new Error('Position outside of list range');
1419
+ }
1420
+ let current = this.head;
1421
+ for (let index = 0; index < position; index++) {
1422
+ current = (current === null || current === void 0 ? void 0 : current.next) || null;
1423
+ }
1424
+ return current;
1425
+ }
1426
+ addNode(n) {
1427
+ const node = {
1428
+ value: n,
1429
+ previous: null,
1430
+ next: null,
1431
+ };
1432
+ n.__ln = node;
1433
+ if (n.previousSibling && isNodeInLinkedList(n.previousSibling)) {
1434
+ const current = n.previousSibling.__ln.next;
1435
+ node.next = current;
1436
+ node.previous = n.previousSibling.__ln;
1437
+ n.previousSibling.__ln.next = node;
1438
+ if (current) {
1439
+ current.previous = node;
1440
+ }
1441
+ }
1442
+ else if (n.nextSibling &&
1443
+ isNodeInLinkedList(n.nextSibling) &&
1444
+ n.nextSibling.__ln.previous) {
1445
+ const current = n.nextSibling.__ln.previous;
1446
+ node.previous = current;
1447
+ node.next = n.nextSibling.__ln;
1448
+ n.nextSibling.__ln.previous = node;
1449
+ if (current) {
1450
+ current.next = node;
1451
+ }
1452
+ }
1453
+ else {
1454
+ if (this.head) {
1455
+ this.head.previous = node;
1456
+ }
1457
+ node.next = this.head;
1458
+ this.head = node;
1459
+ }
1460
+ this.length++;
1461
+ }
1462
+ removeNode(n) {
1463
+ const current = n.__ln;
1464
+ if (!this.head) {
1465
+ return;
1466
+ }
1467
+ if (!current.previous) {
1468
+ this.head = current.next;
1469
+ if (this.head) {
1470
+ this.head.previous = null;
1471
+ }
1472
+ }
1473
+ else {
1474
+ current.previous.next = current.next;
1475
+ if (current.next) {
1476
+ current.next.previous = current.previous;
1477
+ }
1478
+ }
1479
+ if (n.__ln) {
1480
+ delete n.__ln;
1481
+ }
1482
+ this.length--;
1483
+ }
1484
+ }
1485
+ const moveKey = (id, parentId) => `${id}@${parentId}`;
1486
+ class MutationBuffer {
1487
+ constructor() {
1488
+ this.frozen = false;
1489
+ this.locked = false;
1490
+ this.texts = [];
1491
+ this.attributes = [];
1492
+ this.removes = [];
1493
+ this.mapRemoves = [];
1494
+ this.movedMap = {};
1495
+ this.addedSet = new Set();
1496
+ this.movedSet = new Set();
1497
+ this.droppedSet = new Set();
1498
+ this.processMutations = (mutations) => {
1499
+ mutations.forEach(this.processMutation);
1500
+ this.emit();
1501
+ };
1502
+ this.emit = () => {
1503
+ if (this.frozen || this.locked) {
1504
+ return;
1505
+ }
1506
+ const adds = [];
1507
+ const addList = new DoubleLinkedList();
1508
+ const getNextId = (n) => {
1509
+ let ns = n;
1510
+ let nextId = IGNORED_NODE;
1511
+ while (nextId === IGNORED_NODE) {
1512
+ ns = ns && ns.nextSibling;
1513
+ nextId = ns && this.mirror.getId(ns);
1514
+ }
1515
+ return nextId;
1516
+ };
1517
+ const pushAdd = (n) => {
1518
+ var _a, _b, _c, _d;
1519
+ let shadowHost = null;
1520
+ if (((_b = (_a = n.getRootNode) === null || _a === void 0 ? void 0 : _a.call(n)) === null || _b === void 0 ? void 0 : _b.nodeType) === Node.DOCUMENT_FRAGMENT_NODE &&
1521
+ n.getRootNode().host)
1522
+ shadowHost = n.getRootNode().host;
1523
+ let rootShadowHost = shadowHost;
1524
+ while (((_d = (_c = rootShadowHost === null || rootShadowHost === void 0 ? void 0 : rootShadowHost.getRootNode) === null || _c === void 0 ? void 0 : _c.call(rootShadowHost)) === null || _d === void 0 ? void 0 : _d.nodeType) ===
1525
+ Node.DOCUMENT_FRAGMENT_NODE &&
1526
+ rootShadowHost.getRootNode().host)
1527
+ rootShadowHost = rootShadowHost.getRootNode().host;
1528
+ const notInDoc = !this.doc.contains(n) &&
1529
+ (!rootShadowHost || !this.doc.contains(rootShadowHost));
1530
+ if (!n.parentNode || notInDoc) {
1531
+ return;
1532
+ }
1533
+ const parentId = isShadowRoot(n.parentNode)
1534
+ ? this.mirror.getId(shadowHost)
1535
+ : this.mirror.getId(n.parentNode);
1536
+ const nextId = getNextId(n);
1537
+ if (parentId === -1 || nextId === -1) {
1538
+ return addList.addNode(n);
1539
+ }
1540
+ const sn = serializeNodeWithId(n, {
1541
+ doc: this.doc,
1542
+ mirror: this.mirror,
1543
+ blockClass: this.blockClass,
1544
+ blockSelector: this.blockSelector,
1545
+ maskTextClass: this.maskTextClass,
1546
+ maskTextSelector: this.maskTextSelector,
1547
+ skipChild: true,
1548
+ newlyAddedElement: true,
1549
+ inlineStylesheet: this.inlineStylesheet,
1550
+ maskInputOptions: this.maskInputOptions,
1551
+ maskTextFn: this.maskTextFn,
1552
+ maskInputFn: this.maskInputFn,
1553
+ slimDOMOptions: this.slimDOMOptions,
1554
+ dataURLOptions: this.dataURLOptions,
1555
+ recordCanvas: this.recordCanvas,
1556
+ inlineImages: this.inlineImages,
1557
+ onSerialize: (currentN) => {
1558
+ if (isSerializedIframe(currentN, this.mirror)) {
1559
+ this.iframeManager.addIframe(currentN);
1560
+ }
1561
+ if (isSerializedStylesheet(currentN, this.mirror)) {
1562
+ this.stylesheetManager.trackLinkElement(currentN);
1563
+ }
1564
+ if (hasShadowRoot(n)) {
1565
+ this.shadowDomManager.addShadowRoot(n.shadowRoot, this.doc);
1566
+ }
1567
+ },
1568
+ onIframeLoad: (iframe, childSn) => {
1569
+ this.iframeManager.attachIframe(iframe, childSn);
1570
+ this.shadowDomManager.observeAttachShadow(iframe);
1571
+ },
1572
+ onStylesheetLoad: (link, childSn) => {
1573
+ this.stylesheetManager.attachLinkElement(link, childSn);
1574
+ },
1575
+ });
1576
+ if (sn) {
1577
+ adds.push({
1578
+ parentId,
1579
+ nextId,
1580
+ node: sn,
1581
+ });
1582
+ }
1583
+ };
1584
+ while (this.mapRemoves.length) {
1585
+ this.mirror.removeNodeFromMap(this.mapRemoves.shift());
1586
+ }
1587
+ for (const n of Array.from(this.movedSet.values())) {
1588
+ if (isParentRemoved(this.removes, n, this.mirror) &&
1589
+ !this.movedSet.has(n.parentNode)) {
1590
+ continue;
1591
+ }
1592
+ pushAdd(n);
1593
+ }
1594
+ for (const n of Array.from(this.addedSet.values())) {
1595
+ if (!isAncestorInSet(this.droppedSet, n) &&
1596
+ !isParentRemoved(this.removes, n, this.mirror)) {
1597
+ pushAdd(n);
1598
+ }
1599
+ else if (isAncestorInSet(this.movedSet, n)) {
1600
+ pushAdd(n);
1601
+ }
1602
+ else {
1603
+ this.droppedSet.add(n);
1604
+ }
1605
+ }
1606
+ let candidate = null;
1607
+ while (addList.length) {
1608
+ let node = null;
1609
+ if (candidate) {
1610
+ const parentId = this.mirror.getId(candidate.value.parentNode);
1611
+ const nextId = getNextId(candidate.value);
1612
+ if (parentId !== -1 && nextId !== -1) {
1613
+ node = candidate;
1614
+ }
1615
+ }
1616
+ if (!node) {
1617
+ for (let index = addList.length - 1; index >= 0; index--) {
1618
+ const _node = addList.get(index);
1619
+ if (_node) {
1620
+ const parentId = this.mirror.getId(_node.value.parentNode);
1621
+ const nextId = getNextId(_node.value);
1622
+ if (nextId === -1)
1623
+ continue;
1624
+ else if (parentId !== -1) {
1625
+ node = _node;
1626
+ break;
1627
+ }
1628
+ else {
1629
+ const unhandledNode = _node.value;
1630
+ if (unhandledNode.parentNode &&
1631
+ unhandledNode.parentNode.nodeType ===
1632
+ Node.DOCUMENT_FRAGMENT_NODE) {
1633
+ const shadowHost = unhandledNode.parentNode
1634
+ .host;
1635
+ const parentId = this.mirror.getId(shadowHost);
1636
+ if (parentId !== -1) {
1637
+ node = _node;
1638
+ break;
1639
+ }
1640
+ }
1641
+ }
1642
+ }
1643
+ }
1644
+ }
1645
+ if (!node) {
1646
+ while (addList.head) {
1647
+ addList.removeNode(addList.head.value);
1648
+ }
1649
+ break;
1650
+ }
1651
+ candidate = node.previous;
1652
+ addList.removeNode(node.value);
1653
+ pushAdd(node.value);
1654
+ }
1655
+ const payload = {
1656
+ texts: this.texts
1657
+ .map((text) => ({
1658
+ id: this.mirror.getId(text.node),
1659
+ value: text.value,
1660
+ }))
1661
+ .filter((text) => this.mirror.has(text.id)),
1662
+ attributes: this.attributes
1663
+ .map((attribute) => ({
1664
+ id: this.mirror.getId(attribute.node),
1665
+ attributes: attribute.attributes,
1666
+ }))
1667
+ .filter((attribute) => this.mirror.has(attribute.id)),
1668
+ removes: this.removes,
1669
+ adds,
1670
+ };
1671
+ if (!payload.texts.length &&
1672
+ !payload.attributes.length &&
1673
+ !payload.removes.length &&
1674
+ !payload.adds.length) {
1675
+ return;
1676
+ }
1677
+ this.texts = [];
1678
+ this.attributes = [];
1679
+ this.removes = [];
1680
+ this.addedSet = new Set();
1681
+ this.movedSet = new Set();
1682
+ this.droppedSet = new Set();
1683
+ this.movedMap = {};
1684
+ this.mutationCb(payload);
1685
+ };
1686
+ this.processMutation = (m) => {
1687
+ if (isIgnored(m.target, this.mirror)) {
1688
+ return;
1689
+ }
1690
+ switch (m.type) {
1691
+ case 'characterData': {
1692
+ const value = m.target.textContent;
1693
+ if (!isBlocked(m.target, this.blockClass, this.blockSelector, false) &&
1694
+ value !== m.oldValue) {
1695
+ this.texts.push({
1696
+ value: needMaskingText(m.target, this.maskTextClass, this.maskTextSelector) && value
1697
+ ? this.maskTextFn
1698
+ ? this.maskTextFn(value)
1699
+ : value.replace(/[\S]/g, '*')
1700
+ : value,
1701
+ node: m.target,
1702
+ });
1703
+ }
1704
+ break;
1705
+ }
1706
+ case 'attributes': {
1707
+ const target = m.target;
1708
+ let value = m.target.getAttribute(m.attributeName);
1709
+ if (m.attributeName === 'value') {
1710
+ value = maskInputValue({
1711
+ maskInputOptions: this.maskInputOptions,
1712
+ tagName: m.target.tagName,
1713
+ type: m.target.getAttribute('type'),
1714
+ value,
1715
+ maskInputFn: this.maskInputFn,
1716
+ });
1717
+ }
1718
+ if (isBlocked(m.target, this.blockClass, this.blockSelector, false) ||
1719
+ value === m.oldValue) {
1720
+ return;
1721
+ }
1722
+ let item = this.attributes.find((a) => a.node === m.target);
1723
+ if (target.tagName === 'IFRAME' &&
1724
+ m.attributeName === 'src' &&
1725
+ !this.keepIframeSrcFn(value)) {
1726
+ if (!target.contentDocument) {
1727
+ m.attributeName = 'rr_src';
1728
+ }
1729
+ else {
1730
+ return;
1731
+ }
1732
+ }
1733
+ if (!item) {
1734
+ item = {
1735
+ node: m.target,
1736
+ attributes: {},
1737
+ };
1738
+ this.attributes.push(item);
1739
+ }
1740
+ if (m.attributeName === 'style') {
1741
+ const old = this.doc.createElement('span');
1742
+ if (m.oldValue) {
1743
+ old.setAttribute('style', m.oldValue);
1744
+ }
1745
+ if (item.attributes.style === undefined ||
1746
+ item.attributes.style === null) {
1747
+ item.attributes.style = {};
1748
+ }
1749
+ const styleObj = item.attributes.style;
1750
+ for (const pname of Array.from(target.style)) {
1751
+ const newValue = target.style.getPropertyValue(pname);
1752
+ const newPriority = target.style.getPropertyPriority(pname);
1753
+ if (newValue !== old.style.getPropertyValue(pname) ||
1754
+ newPriority !== old.style.getPropertyPriority(pname)) {
1755
+ if (newPriority === '') {
1756
+ styleObj[pname] = newValue;
1757
+ }
1758
+ else {
1759
+ styleObj[pname] = [newValue, newPriority];
1760
+ }
1761
+ }
1762
+ }
1763
+ for (const pname of Array.from(old.style)) {
1764
+ if (target.style.getPropertyValue(pname) === '') {
1765
+ styleObj[pname] = false;
1766
+ }
1767
+ }
1768
+ }
1769
+ else {
1770
+ item.attributes[m.attributeName] = transformAttribute(this.doc, target.tagName, m.attributeName, value);
1771
+ }
1772
+ break;
1773
+ }
1774
+ case 'childList': {
1775
+ if (isBlocked(m.target, this.blockClass, this.blockSelector, true))
1776
+ return;
1777
+ m.addedNodes.forEach((n) => this.genAdds(n, m.target));
1778
+ m.removedNodes.forEach((n) => {
1779
+ const nodeId = this.mirror.getId(n);
1780
+ const parentId = isShadowRoot(m.target)
1781
+ ? this.mirror.getId(m.target.host)
1782
+ : this.mirror.getId(m.target);
1783
+ if (isBlocked(m.target, this.blockClass, this.blockSelector, false) ||
1784
+ isIgnored(n, this.mirror) ||
1785
+ !isSerialized(n, this.mirror)) {
1786
+ return;
1787
+ }
1788
+ if (this.addedSet.has(n)) {
1789
+ deepDelete(this.addedSet, n);
1790
+ this.droppedSet.add(n);
1791
+ }
1792
+ else if (this.addedSet.has(m.target) && nodeId === -1) ;
1793
+ else if (isAncestorRemoved(m.target, this.mirror)) ;
1794
+ else if (this.movedSet.has(n) &&
1795
+ this.movedMap[moveKey(nodeId, parentId)]) {
1796
+ deepDelete(this.movedSet, n);
1797
+ }
1798
+ else {
1799
+ this.removes.push({
1800
+ parentId,
1801
+ id: nodeId,
1802
+ isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target)
1803
+ ? true
1804
+ : undefined,
1805
+ });
1806
+ }
1807
+ this.mapRemoves.push(n);
1808
+ });
1809
+ break;
1810
+ }
1811
+ }
1812
+ };
1813
+ this.genAdds = (n, target) => {
1814
+ if (this.mirror.hasNode(n)) {
1815
+ if (isIgnored(n, this.mirror)) {
1816
+ return;
1817
+ }
1818
+ this.movedSet.add(n);
1819
+ let targetId = null;
1820
+ if (target && this.mirror.hasNode(target)) {
1821
+ targetId = this.mirror.getId(target);
1822
+ }
1823
+ if (targetId && targetId !== -1) {
1824
+ this.movedMap[moveKey(this.mirror.getId(n), targetId)] = true;
1825
+ }
1826
+ }
1827
+ else {
1828
+ this.addedSet.add(n);
1829
+ this.droppedSet.delete(n);
1830
+ }
1831
+ if (!isBlocked(n, this.blockClass, this.blockSelector, false))
1832
+ n.childNodes.forEach((childN) => this.genAdds(childN));
1833
+ };
1834
+ }
1835
+ init(options) {
1836
+ [
1837
+ 'mutationCb',
1838
+ 'blockClass',
1839
+ 'blockSelector',
1840
+ 'maskTextClass',
1841
+ 'maskTextSelector',
1842
+ 'inlineStylesheet',
1843
+ 'maskInputOptions',
1844
+ 'maskTextFn',
1845
+ 'maskInputFn',
1846
+ 'keepIframeSrcFn',
1847
+ 'recordCanvas',
1848
+ 'inlineImages',
1849
+ 'slimDOMOptions',
1850
+ 'dataURLOptions',
1851
+ 'doc',
1852
+ 'mirror',
1853
+ 'iframeManager',
1854
+ 'stylesheetManager',
1855
+ 'shadowDomManager',
1856
+ 'canvasManager',
1857
+ ].forEach((key) => {
1858
+ this[key] = options[key];
1859
+ });
1860
+ }
1861
+ freeze() {
1862
+ this.frozen = true;
1863
+ this.canvasManager.freeze();
1864
+ }
1865
+ unfreeze() {
1866
+ this.frozen = false;
1867
+ this.canvasManager.unfreeze();
1868
+ this.emit();
1869
+ }
1870
+ isFrozen() {
1871
+ return this.frozen;
1872
+ }
1873
+ lock() {
1874
+ this.locked = true;
1875
+ this.canvasManager.lock();
1876
+ }
1877
+ unlock() {
1878
+ this.locked = false;
1879
+ this.canvasManager.unlock();
1880
+ this.emit();
1881
+ }
1882
+ reset() {
1883
+ this.shadowDomManager.reset();
1884
+ this.canvasManager.reset();
1885
+ }
1886
+ }
1887
+ function deepDelete(addsSet, n) {
1888
+ addsSet.delete(n);
1889
+ n.childNodes.forEach((childN) => deepDelete(addsSet, childN));
1890
+ }
1891
+ function isParentRemoved(removes, n, mirror) {
1892
+ if (removes.length === 0)
1893
+ return false;
1894
+ return _isParentRemoved(removes, n, mirror);
1895
+ }
1896
+ function _isParentRemoved(removes, n, mirror) {
1897
+ const { parentNode } = n;
1898
+ if (!parentNode) {
1899
+ return false;
1900
+ }
1901
+ const parentId = mirror.getId(parentNode);
1902
+ if (removes.some((r) => r.id === parentId)) {
1903
+ return true;
1904
+ }
1905
+ return _isParentRemoved(removes, parentNode, mirror);
1906
+ }
1907
+ function isAncestorInSet(set, n) {
1908
+ if (set.size === 0)
1909
+ return false;
1910
+ return _isAncestorInSet(set, n);
1911
+ }
1912
+ function _isAncestorInSet(set, n) {
1913
+ const { parentNode } = n;
1914
+ if (!parentNode) {
1915
+ return false;
1916
+ }
1917
+ if (set.has(parentNode)) {
1918
+ return true;
1919
+ }
1920
+ return _isAncestorInSet(set, parentNode);
1921
+ }
1922
+
1923
+ const mutationBuffers = [];
1924
+ const isCSSGroupingRuleSupported = typeof CSSGroupingRule !== 'undefined';
1925
+ const isCSSMediaRuleSupported = typeof CSSMediaRule !== 'undefined';
1926
+ const isCSSSupportsRuleSupported = typeof CSSSupportsRule !== 'undefined';
1927
+ const isCSSConditionRuleSupported = typeof CSSConditionRule !== 'undefined';
1928
+ function getEventTarget(event) {
1929
+ try {
1930
+ if ('composedPath' in event) {
1931
+ const path = event.composedPath();
1932
+ if (path.length) {
1933
+ return path[0];
1934
+ }
1935
+ }
1936
+ else if ('path' in event && event.path.length) {
1937
+ return event.path[0];
1938
+ }
1939
+ return event.target;
1940
+ }
1941
+ catch (_a) {
1942
+ return event.target;
1943
+ }
1944
+ }
1945
+ function initMutationObserver(options, rootEl) {
1946
+ var _a, _b;
1947
+ const mutationBuffer = new MutationBuffer();
1948
+ mutationBuffers.push(mutationBuffer);
1949
+ mutationBuffer.init(options);
1950
+ let mutationObserverCtor = window.MutationObserver ||
1951
+ window.__rrMutationObserver;
1952
+ const angularZoneSymbol = (_b = (_a = window === null || window === void 0 ? void 0 : window.Zone) === null || _a === void 0 ? void 0 : _a.__symbol__) === null || _b === void 0 ? void 0 : _b.call(_a, 'MutationObserver');
1953
+ if (angularZoneSymbol &&
1954
+ window[angularZoneSymbol]) {
1955
+ mutationObserverCtor = window[angularZoneSymbol];
1956
+ }
1957
+ const observer = new mutationObserverCtor(mutationBuffer.processMutations.bind(mutationBuffer));
1958
+ observer.observe(rootEl, {
1959
+ attributes: true,
1960
+ attributeOldValue: true,
1961
+ characterData: true,
1962
+ characterDataOldValue: true,
1963
+ childList: true,
1964
+ subtree: true,
1965
+ });
1966
+ return observer;
1967
+ }
1968
+ function initMoveObserver({ mousemoveCb, sampling, doc, mirror, }) {
1969
+ if (sampling.mousemove === false) {
1970
+ return () => {
1971
+ };
1972
+ }
1973
+ const threshold = typeof sampling.mousemove === 'number' ? sampling.mousemove : 50;
1974
+ const callbackThreshold = typeof sampling.mousemoveCallback === 'number'
1975
+ ? sampling.mousemoveCallback
1976
+ : 500;
1977
+ let positions = [];
1978
+ let timeBaseline;
1979
+ const wrappedCb = throttle((source) => {
1980
+ const totalOffset = Date.now() - timeBaseline;
1981
+ mousemoveCb(positions.map((p) => {
1982
+ p.timeOffset -= totalOffset;
1983
+ return p;
1984
+ }), source);
1985
+ positions = [];
1986
+ timeBaseline = null;
1987
+ }, callbackThreshold);
1988
+ const updatePosition = throttle((evt) => {
1989
+ const target = getEventTarget(evt);
1990
+ const { clientX, clientY } = isTouchEvent(evt)
1991
+ ? evt.changedTouches[0]
1992
+ : evt;
1993
+ if (!timeBaseline) {
1994
+ timeBaseline = Date.now();
1995
+ }
1996
+ positions.push({
1997
+ x: clientX,
1998
+ y: clientY,
1999
+ id: mirror.getId(target),
2000
+ timeOffset: Date.now() - timeBaseline,
2001
+ });
2002
+ wrappedCb(typeof DragEvent !== 'undefined' && evt instanceof DragEvent
2003
+ ? IncrementalSource.Drag
2004
+ : evt instanceof MouseEvent
2005
+ ? IncrementalSource.MouseMove
2006
+ : IncrementalSource.TouchMove);
2007
+ }, threshold, {
2008
+ trailing: false,
2009
+ });
2010
+ const handlers = [
2011
+ on('mousemove', updatePosition, doc),
2012
+ on('touchmove', updatePosition, doc),
2013
+ on('drag', updatePosition, doc),
2014
+ ];
2015
+ return () => {
2016
+ handlers.forEach((h) => h());
2017
+ };
2018
+ }
2019
+ function initMouseInteractionObserver({ mouseInteractionCb, doc, mirror, blockClass, blockSelector, sampling, }) {
2020
+ if (sampling.mouseInteraction === false) {
2021
+ return () => {
2022
+ };
2023
+ }
2024
+ const disableMap = sampling.mouseInteraction === true ||
2025
+ sampling.mouseInteraction === undefined
2026
+ ? {}
2027
+ : sampling.mouseInteraction;
2028
+ const handlers = [];
2029
+ const getHandler = (eventKey) => {
2030
+ return (event) => {
2031
+ const target = getEventTarget(event);
2032
+ if (isBlocked(target, blockClass, blockSelector, true)) {
2033
+ return;
2034
+ }
2035
+ const e = isTouchEvent(event) ? event.changedTouches[0] : event;
2036
+ if (!e) {
2037
+ return;
2038
+ }
2039
+ const id = mirror.getId(target);
2040
+ const { clientX, clientY } = e;
2041
+ mouseInteractionCb({
2042
+ type: MouseInteractions[eventKey],
2043
+ id,
2044
+ x: clientX,
2045
+ y: clientY,
2046
+ });
2047
+ };
2048
+ };
2049
+ Object.keys(MouseInteractions)
2050
+ .filter((key) => Number.isNaN(Number(key)) &&
2051
+ !key.endsWith('_Departed') &&
2052
+ disableMap[key] !== false)
2053
+ .forEach((eventKey) => {
2054
+ const eventName = eventKey.toLowerCase();
2055
+ const handler = getHandler(eventKey);
2056
+ handlers.push(on(eventName, handler, doc));
2057
+ });
2058
+ return () => {
2059
+ handlers.forEach((h) => h());
2060
+ };
2061
+ }
2062
+ function initScrollObserver({ scrollCb, doc, mirror, blockClass, blockSelector, sampling, }) {
2063
+ const updatePosition = throttle((evt) => {
2064
+ const target = getEventTarget(evt);
2065
+ if (!target || isBlocked(target, blockClass, blockSelector, true)) {
2066
+ return;
2067
+ }
2068
+ const id = mirror.getId(target);
2069
+ if (target === doc) {
2070
+ const scrollEl = (doc.scrollingElement || doc.documentElement);
2071
+ scrollCb({
2072
+ id,
2073
+ x: scrollEl.scrollLeft,
2074
+ y: scrollEl.scrollTop,
2075
+ });
2076
+ }
2077
+ else {
2078
+ scrollCb({
2079
+ id,
2080
+ x: target.scrollLeft,
2081
+ y: target.scrollTop,
2082
+ });
2083
+ }
2084
+ }, sampling.scroll || 100);
2085
+ return on('scroll', updatePosition, doc);
2086
+ }
2087
+ function initViewportResizeObserver({ viewportResizeCb, }) {
2088
+ let lastH = -1;
2089
+ let lastW = -1;
2090
+ const updateDimension = throttle(() => {
2091
+ const height = getWindowHeight();
2092
+ const width = getWindowWidth();
2093
+ if (lastH !== height || lastW !== width) {
2094
+ viewportResizeCb({
2095
+ width: Number(width),
2096
+ height: Number(height),
2097
+ });
2098
+ lastH = height;
2099
+ lastW = width;
2100
+ }
2101
+ }, 200);
2102
+ return on('resize', updateDimension, window);
2103
+ }
2104
+ function wrapEventWithUserTriggeredFlag(v, enable) {
2105
+ const value = Object.assign({}, v);
2106
+ if (!enable)
2107
+ delete value.userTriggered;
2108
+ return value;
2109
+ }
2110
+ const INPUT_TAGS = ['INPUT', 'TEXTAREA', 'SELECT'];
2111
+ const lastInputValueMap = new WeakMap();
2112
+ function initInputObserver({ inputCb, doc, mirror, blockClass, blockSelector, ignoreClass, maskInputOptions, maskInputFn, sampling, userTriggeredOnInput, }) {
2113
+ function eventHandler(event) {
2114
+ let target = getEventTarget(event);
2115
+ const userTriggered = event.isTrusted;
2116
+ if (target && target.tagName === 'OPTION')
2117
+ target = target.parentElement;
2118
+ if (!target ||
2119
+ !target.tagName ||
2120
+ INPUT_TAGS.indexOf(target.tagName) < 0 ||
2121
+ isBlocked(target, blockClass, blockSelector, true)) {
2122
+ return;
2123
+ }
2124
+ const type = target.type;
2125
+ if (target.classList.contains(ignoreClass)) {
2126
+ return;
2127
+ }
2128
+ let text = target.value;
2129
+ let isChecked = false;
2130
+ if (type === 'radio' || type === 'checkbox') {
2131
+ isChecked = target.checked;
2132
+ }
2133
+ else if (maskInputOptions[target.tagName.toLowerCase()] ||
2134
+ maskInputOptions[type]) {
2135
+ text = maskInputValue({
2136
+ maskInputOptions,
2137
+ tagName: target.tagName,
2138
+ type,
2139
+ value: text,
2140
+ maskInputFn,
2141
+ });
2142
+ }
2143
+ cbWithDedup(target, wrapEventWithUserTriggeredFlag({ text, isChecked, userTriggered }, userTriggeredOnInput));
2144
+ const name = target.name;
2145
+ if (type === 'radio' && name && isChecked) {
2146
+ doc
2147
+ .querySelectorAll(`input[type="radio"][name="${name}"]`)
2148
+ .forEach((el) => {
2149
+ if (el !== target) {
2150
+ cbWithDedup(el, wrapEventWithUserTriggeredFlag({
2151
+ text: el.value,
2152
+ isChecked: !isChecked,
2153
+ userTriggered: false,
2154
+ }, userTriggeredOnInput));
2155
+ }
2156
+ });
2157
+ }
2158
+ }
2159
+ function cbWithDedup(target, v) {
2160
+ const lastInputValue = lastInputValueMap.get(target);
2161
+ if (!lastInputValue ||
2162
+ lastInputValue.text !== v.text ||
2163
+ lastInputValue.isChecked !== v.isChecked) {
2164
+ lastInputValueMap.set(target, v);
2165
+ const id = mirror.getId(target);
2166
+ inputCb(Object.assign(Object.assign({}, v), { id }));
2167
+ }
2168
+ }
2169
+ const events = sampling.input === 'last' ? ['change'] : ['input', 'change'];
2170
+ const handlers = events.map((eventName) => on(eventName, eventHandler, doc));
2171
+ const currentWindow = doc.defaultView;
2172
+ if (!currentWindow) {
2173
+ return () => {
2174
+ handlers.forEach((h) => h());
2175
+ };
2176
+ }
2177
+ const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype, 'value');
2178
+ const hookProperties = [
2179
+ [currentWindow.HTMLInputElement.prototype, 'value'],
2180
+ [currentWindow.HTMLInputElement.prototype, 'checked'],
2181
+ [currentWindow.HTMLSelectElement.prototype, 'value'],
2182
+ [currentWindow.HTMLTextAreaElement.prototype, 'value'],
2183
+ [currentWindow.HTMLSelectElement.prototype, 'selectedIndex'],
2184
+ [currentWindow.HTMLOptionElement.prototype, 'selected'],
2185
+ ];
2186
+ if (propertyDescriptor && propertyDescriptor.set) {
2187
+ handlers.push(...hookProperties.map((p) => hookSetter(p[0], p[1], {
2188
+ set() {
2189
+ eventHandler({ target: this });
2190
+ },
2191
+ }, false, currentWindow)));
2192
+ }
2193
+ return () => {
2194
+ handlers.forEach((h) => h());
2195
+ };
2196
+ }
2197
+ function getNestedCSSRulePositions(rule) {
2198
+ const positions = [];
2199
+ function recurse(childRule, pos) {
2200
+ if ((isCSSGroupingRuleSupported &&
2201
+ childRule.parentRule instanceof CSSGroupingRule) ||
2202
+ (isCSSMediaRuleSupported &&
2203
+ childRule.parentRule instanceof CSSMediaRule) ||
2204
+ (isCSSSupportsRuleSupported &&
2205
+ childRule.parentRule instanceof CSSSupportsRule) ||
2206
+ (isCSSConditionRuleSupported &&
2207
+ childRule.parentRule instanceof CSSConditionRule)) {
2208
+ const rules = Array.from(childRule.parentRule.cssRules);
2209
+ const index = rules.indexOf(childRule);
2210
+ pos.unshift(index);
2211
+ }
2212
+ else if (childRule.parentStyleSheet) {
2213
+ const rules = Array.from(childRule.parentStyleSheet.cssRules);
2214
+ const index = rules.indexOf(childRule);
2215
+ pos.unshift(index);
2216
+ }
2217
+ return pos;
2218
+ }
2219
+ return recurse(rule, positions);
2220
+ }
2221
+ function getIdAndStyleId(sheet, mirror, styleMirror) {
2222
+ let id, styleId;
2223
+ if (!sheet)
2224
+ return {};
2225
+ if (sheet.ownerNode)
2226
+ id = mirror.getId(sheet.ownerNode);
2227
+ else
2228
+ styleId = styleMirror.getId(sheet);
2229
+ return {
2230
+ styleId,
2231
+ id,
2232
+ };
2233
+ }
2234
+ function initStyleSheetObserver({ styleSheetRuleCb, mirror, stylesheetManager }, { win }) {
2235
+ const insertRule = win.CSSStyleSheet.prototype.insertRule;
2236
+ win.CSSStyleSheet.prototype.insertRule = function (rule, index) {
2237
+ const { id, styleId } = getIdAndStyleId(this, mirror, stylesheetManager.styleMirror);
2238
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
2239
+ styleSheetRuleCb({
2240
+ id,
2241
+ styleId,
2242
+ adds: [{ rule, index }],
2243
+ });
2244
+ }
2245
+ return insertRule.apply(this, [rule, index]);
2246
+ };
2247
+ const deleteRule = win.CSSStyleSheet.prototype.deleteRule;
2248
+ win.CSSStyleSheet.prototype.deleteRule = function (index) {
2249
+ const { id, styleId } = getIdAndStyleId(this, mirror, stylesheetManager.styleMirror);
2250
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
2251
+ styleSheetRuleCb({
2252
+ id,
2253
+ styleId,
2254
+ removes: [{ index }],
2255
+ });
2256
+ }
2257
+ return deleteRule.apply(this, [index]);
2258
+ };
2259
+ let replace;
2260
+ if (win.CSSStyleSheet.prototype.replace) {
2261
+ replace = win.CSSStyleSheet.prototype.replace;
2262
+ win.CSSStyleSheet.prototype.replace = function (text) {
2263
+ const { id, styleId } = getIdAndStyleId(this, mirror, stylesheetManager.styleMirror);
2264
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
2265
+ styleSheetRuleCb({
2266
+ id,
2267
+ styleId,
2268
+ replace: text,
2269
+ });
2270
+ }
2271
+ return replace.apply(this, [text]);
2272
+ };
2273
+ }
2274
+ let replaceSync;
2275
+ if (win.CSSStyleSheet.prototype.replaceSync) {
2276
+ replaceSync = win.CSSStyleSheet.prototype.replaceSync;
2277
+ win.CSSStyleSheet.prototype.replaceSync = function (text) {
2278
+ const { id, styleId } = getIdAndStyleId(this, mirror, stylesheetManager.styleMirror);
2279
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
2280
+ styleSheetRuleCb({
2281
+ id,
2282
+ styleId,
2283
+ replaceSync: text,
2284
+ });
2285
+ }
2286
+ return replaceSync.apply(this, [text]);
2287
+ };
2288
+ }
2289
+ const supportedNestedCSSRuleTypes = {};
2290
+ if (isCSSGroupingRuleSupported) {
2291
+ supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;
2292
+ }
2293
+ else {
2294
+ if (isCSSMediaRuleSupported) {
2295
+ supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;
2296
+ }
2297
+ if (isCSSConditionRuleSupported) {
2298
+ supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;
2299
+ }
2300
+ if (isCSSSupportsRuleSupported) {
2301
+ supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;
2302
+ }
2303
+ }
2304
+ const unmodifiedFunctions = {};
2305
+ Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {
2306
+ unmodifiedFunctions[typeKey] = {
2307
+ insertRule: type.prototype.insertRule,
2308
+ deleteRule: type.prototype.deleteRule,
2309
+ };
2310
+ type.prototype.insertRule = function (rule, index) {
2311
+ const { id, styleId } = getIdAndStyleId(this.parentStyleSheet, mirror, stylesheetManager.styleMirror);
2312
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
2313
+ styleSheetRuleCb({
2314
+ id,
2315
+ styleId,
2316
+ adds: [
2317
+ {
2318
+ rule,
2319
+ index: [
2320
+ ...getNestedCSSRulePositions(this),
2321
+ index || 0,
2322
+ ],
2323
+ },
2324
+ ],
2325
+ });
2326
+ }
2327
+ return unmodifiedFunctions[typeKey].insertRule.apply(this, [rule, index]);
2328
+ };
2329
+ type.prototype.deleteRule = function (index) {
2330
+ const { id, styleId } = getIdAndStyleId(this.parentStyleSheet, mirror, stylesheetManager.styleMirror);
2331
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
2332
+ styleSheetRuleCb({
2333
+ id,
2334
+ styleId,
2335
+ removes: [
2336
+ { index: [...getNestedCSSRulePositions(this), index] },
2337
+ ],
2338
+ });
2339
+ }
2340
+ return unmodifiedFunctions[typeKey].deleteRule.apply(this, [index]);
2341
+ };
2342
+ });
2343
+ return () => {
2344
+ win.CSSStyleSheet.prototype.insertRule = insertRule;
2345
+ win.CSSStyleSheet.prototype.deleteRule = deleteRule;
2346
+ replace && (win.CSSStyleSheet.prototype.replace = replace);
2347
+ replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);
2348
+ Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {
2349
+ type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;
2350
+ type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;
2351
+ });
2352
+ };
2353
+ }
2354
+ function initAdoptedStyleSheetObserver({ mirror, stylesheetManager, }, host) {
2355
+ var _a, _b, _c;
2356
+ let hostId = null;
2357
+ if (host.nodeName === '#document')
2358
+ hostId = mirror.getId(host);
2359
+ else
2360
+ hostId = mirror.getId(host.host);
2361
+ const patchTarget = host.nodeName === '#document'
2362
+ ? (_a = host.defaultView) === null || _a === void 0 ? void 0 : _a.Document
2363
+ : (_c = (_b = host.ownerDocument) === null || _b === void 0 ? void 0 : _b.defaultView) === null || _c === void 0 ? void 0 : _c.ShadowRoot;
2364
+ const originalPropertyDescriptor = Object.getOwnPropertyDescriptor(patchTarget === null || patchTarget === void 0 ? void 0 : patchTarget.prototype, 'adoptedStyleSheets');
2365
+ if (hostId === null ||
2366
+ hostId === -1 ||
2367
+ !patchTarget ||
2368
+ !originalPropertyDescriptor)
2369
+ return () => {
2370
+ };
2371
+ Object.defineProperty(host, 'adoptedStyleSheets', {
2372
+ configurable: originalPropertyDescriptor.configurable,
2373
+ enumerable: originalPropertyDescriptor.enumerable,
2374
+ get() {
2375
+ var _a;
2376
+ return (_a = originalPropertyDescriptor.get) === null || _a === void 0 ? void 0 : _a.call(this);
2377
+ },
2378
+ set(sheets) {
2379
+ var _a;
2380
+ const result = (_a = originalPropertyDescriptor.set) === null || _a === void 0 ? void 0 : _a.call(this, sheets);
2381
+ if (hostId !== null && hostId !== -1) {
2382
+ try {
2383
+ stylesheetManager.adoptStyleSheets(sheets, hostId);
2384
+ }
2385
+ catch (e) {
2386
+ }
2387
+ }
2388
+ return result;
2389
+ },
2390
+ });
2391
+ return () => {
2392
+ Object.defineProperty(host, 'adoptedStyleSheets', {
2393
+ configurable: originalPropertyDescriptor.configurable,
2394
+ enumerable: originalPropertyDescriptor.enumerable,
2395
+ get: originalPropertyDescriptor.get,
2396
+ set: originalPropertyDescriptor.set,
2397
+ });
2398
+ };
2399
+ }
2400
+ function initStyleDeclarationObserver({ styleDeclarationCb, mirror, ignoreCSSAttributes, stylesheetManager, }, { win }) {
2401
+ const setProperty = win.CSSStyleDeclaration.prototype.setProperty;
2402
+ win.CSSStyleDeclaration.prototype.setProperty = function (property, value, priority) {
2403
+ var _a;
2404
+ if (ignoreCSSAttributes.has(property)) {
2405
+ return setProperty.apply(this, [property, value, priority]);
2406
+ }
2407
+ const { id, styleId } = getIdAndStyleId((_a = this.parentRule) === null || _a === void 0 ? void 0 : _a.parentStyleSheet, mirror, stylesheetManager.styleMirror);
2408
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
2409
+ styleDeclarationCb({
2410
+ id,
2411
+ styleId,
2412
+ set: {
2413
+ property,
2414
+ value,
2415
+ priority,
2416
+ },
2417
+ index: getNestedCSSRulePositions(this.parentRule),
2418
+ });
2419
+ }
2420
+ return setProperty.apply(this, [property, value, priority]);
2421
+ };
2422
+ const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;
2423
+ win.CSSStyleDeclaration.prototype.removeProperty = function (property) {
2424
+ var _a;
2425
+ if (ignoreCSSAttributes.has(property)) {
2426
+ return removeProperty.apply(this, [property]);
2427
+ }
2428
+ const { id, styleId } = getIdAndStyleId((_a = this.parentRule) === null || _a === void 0 ? void 0 : _a.parentStyleSheet, mirror, stylesheetManager.styleMirror);
2429
+ if ((id && id !== -1) || (styleId && styleId !== -1)) {
2430
+ styleDeclarationCb({
2431
+ id,
2432
+ styleId,
2433
+ remove: {
2434
+ property,
2435
+ },
2436
+ index: getNestedCSSRulePositions(this.parentRule),
2437
+ });
2438
+ }
2439
+ return removeProperty.apply(this, [property]);
2440
+ };
2441
+ return () => {
2442
+ win.CSSStyleDeclaration.prototype.setProperty = setProperty;
2443
+ win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;
2444
+ };
2445
+ }
2446
+ function initMediaInteractionObserver({ mediaInteractionCb, blockClass, blockSelector, mirror, sampling, }) {
2447
+ const handler = (type) => throttle((event) => {
2448
+ const target = getEventTarget(event);
2449
+ if (!target ||
2450
+ isBlocked(target, blockClass, blockSelector, true)) {
2451
+ return;
2452
+ }
2453
+ const { currentTime, volume, muted, playbackRate, } = target;
2454
+ mediaInteractionCb({
2455
+ type,
2456
+ id: mirror.getId(target),
2457
+ currentTime,
2458
+ volume,
2459
+ muted,
2460
+ playbackRate,
2461
+ });
2462
+ }, sampling.media || 500);
2463
+ const handlers = [
2464
+ on('play', handler(0)),
2465
+ on('pause', handler(1)),
2466
+ on('seeked', handler(2)),
2467
+ on('volumechange', handler(3)),
2468
+ on('ratechange', handler(4)),
2469
+ ];
2470
+ return () => {
2471
+ handlers.forEach((h) => h());
2472
+ };
2473
+ }
2474
+ function initFontObserver({ fontCb, doc }) {
2475
+ const win = doc.defaultView;
2476
+ if (!win) {
2477
+ return () => {
2478
+ };
2479
+ }
2480
+ const handlers = [];
2481
+ const fontMap = new WeakMap();
2482
+ const originalFontFace = win.FontFace;
2483
+ win.FontFace = function FontFace(family, source, descriptors) {
2484
+ const fontFace = new originalFontFace(family, source, descriptors);
2485
+ fontMap.set(fontFace, {
2486
+ family,
2487
+ buffer: typeof source !== 'string',
2488
+ descriptors,
2489
+ fontSource: typeof source === 'string'
2490
+ ? source
2491
+ : JSON.stringify(Array.from(new Uint8Array(source))),
2492
+ });
2493
+ return fontFace;
2494
+ };
2495
+ const restoreHandler = patch(doc.fonts, 'add', function (original) {
2496
+ return function (fontFace) {
2497
+ setTimeout(() => {
2498
+ const p = fontMap.get(fontFace);
2499
+ if (p) {
2500
+ fontCb(p);
2501
+ fontMap.delete(fontFace);
2502
+ }
2503
+ }, 0);
2504
+ return original.apply(this, [fontFace]);
2505
+ };
2506
+ });
2507
+ handlers.push(() => {
2508
+ win.FontFace = originalFontFace;
2509
+ });
2510
+ handlers.push(restoreHandler);
2511
+ return () => {
2512
+ handlers.forEach((h) => h());
2513
+ };
2514
+ }
2515
+ function initSelectionObserver(param) {
2516
+ const { doc, mirror, blockClass, blockSelector, selectionCb } = param;
2517
+ let collapsed = true;
2518
+ const updateSelection = () => {
2519
+ const selection = doc.getSelection();
2520
+ if (!selection || (collapsed && (selection === null || selection === void 0 ? void 0 : selection.isCollapsed)))
2521
+ return;
2522
+ collapsed = selection.isCollapsed || false;
2523
+ const ranges = [];
2524
+ const count = selection.rangeCount || 0;
2525
+ for (let i = 0; i < count; i++) {
2526
+ const range = selection.getRangeAt(i);
2527
+ const { startContainer, startOffset, endContainer, endOffset } = range;
2528
+ const blocked = isBlocked(startContainer, blockClass, blockSelector, true) ||
2529
+ isBlocked(endContainer, blockClass, blockSelector, true);
2530
+ if (blocked)
2531
+ continue;
2532
+ ranges.push({
2533
+ start: mirror.getId(startContainer),
2534
+ startOffset,
2535
+ end: mirror.getId(endContainer),
2536
+ endOffset,
2537
+ });
2538
+ }
2539
+ selectionCb({ ranges });
2540
+ };
2541
+ updateSelection();
2542
+ return on('selectionchange', updateSelection);
2543
+ }
2544
+ function mergeHooks(o, hooks) {
2545
+ const { mutationCb, mousemoveCb, mouseInteractionCb, scrollCb, viewportResizeCb, inputCb, mediaInteractionCb, styleSheetRuleCb, styleDeclarationCb, canvasMutationCb, fontCb, selectionCb, } = o;
2546
+ o.mutationCb = (...p) => {
2547
+ if (hooks.mutation) {
2548
+ hooks.mutation(...p);
2549
+ }
2550
+ mutationCb(...p);
2551
+ };
2552
+ o.mousemoveCb = (...p) => {
2553
+ if (hooks.mousemove) {
2554
+ hooks.mousemove(...p);
2555
+ }
2556
+ mousemoveCb(...p);
2557
+ };
2558
+ o.mouseInteractionCb = (...p) => {
2559
+ if (hooks.mouseInteraction) {
2560
+ hooks.mouseInteraction(...p);
2561
+ }
2562
+ mouseInteractionCb(...p);
2563
+ };
2564
+ o.scrollCb = (...p) => {
2565
+ if (hooks.scroll) {
2566
+ hooks.scroll(...p);
2567
+ }
2568
+ scrollCb(...p);
2569
+ };
2570
+ o.viewportResizeCb = (...p) => {
2571
+ if (hooks.viewportResize) {
2572
+ hooks.viewportResize(...p);
2573
+ }
2574
+ viewportResizeCb(...p);
2575
+ };
2576
+ o.inputCb = (...p) => {
2577
+ if (hooks.input) {
2578
+ hooks.input(...p);
2579
+ }
2580
+ inputCb(...p);
2581
+ };
2582
+ o.mediaInteractionCb = (...p) => {
2583
+ if (hooks.mediaInteaction) {
2584
+ hooks.mediaInteaction(...p);
2585
+ }
2586
+ mediaInteractionCb(...p);
2587
+ };
2588
+ o.styleSheetRuleCb = (...p) => {
2589
+ if (hooks.styleSheetRule) {
2590
+ hooks.styleSheetRule(...p);
2591
+ }
2592
+ styleSheetRuleCb(...p);
2593
+ };
2594
+ o.styleDeclarationCb = (...p) => {
2595
+ if (hooks.styleDeclaration) {
2596
+ hooks.styleDeclaration(...p);
2597
+ }
2598
+ styleDeclarationCb(...p);
2599
+ };
2600
+ o.canvasMutationCb = (...p) => {
2601
+ if (hooks.canvasMutation) {
2602
+ hooks.canvasMutation(...p);
2603
+ }
2604
+ canvasMutationCb(...p);
2605
+ };
2606
+ o.fontCb = (...p) => {
2607
+ if (hooks.font) {
2608
+ hooks.font(...p);
2609
+ }
2610
+ fontCb(...p);
2611
+ };
2612
+ o.selectionCb = (...p) => {
2613
+ if (hooks.selection) {
2614
+ hooks.selection(...p);
2615
+ }
2616
+ selectionCb(...p);
2617
+ };
2618
+ }
2619
+ function initObservers(o, hooks = {}) {
2620
+ const currentWindow = o.doc.defaultView;
2621
+ if (!currentWindow) {
2622
+ return () => {
2623
+ };
2624
+ }
2625
+ mergeHooks(o, hooks);
2626
+ const mutationObserver = initMutationObserver(o, o.doc);
2627
+ const mousemoveHandler = initMoveObserver(o);
2628
+ const mouseInteractionHandler = initMouseInteractionObserver(o);
2629
+ const scrollHandler = initScrollObserver(o);
2630
+ const viewportResizeHandler = initViewportResizeObserver(o);
2631
+ const inputHandler = initInputObserver(o);
2632
+ const mediaInteractionHandler = initMediaInteractionObserver(o);
2633
+ const styleSheetObserver = initStyleSheetObserver(o, { win: currentWindow });
2634
+ const adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o, o.doc);
2635
+ const styleDeclarationObserver = initStyleDeclarationObserver(o, {
2636
+ win: currentWindow,
2637
+ });
2638
+ const fontObserver = o.collectFonts
2639
+ ? initFontObserver(o)
2640
+ : () => {
2641
+ };
2642
+ const selectionObserver = initSelectionObserver(o);
2643
+ const pluginHandlers = [];
2644
+ for (const plugin of o.plugins) {
2645
+ pluginHandlers.push(plugin.observer(plugin.callback, currentWindow, plugin.options));
2646
+ }
2647
+ return () => {
2648
+ mutationBuffers.forEach((b) => b.reset());
2649
+ mutationObserver.disconnect();
2650
+ mousemoveHandler();
2651
+ mouseInteractionHandler();
2652
+ scrollHandler();
2653
+ viewportResizeHandler();
2654
+ inputHandler();
2655
+ mediaInteractionHandler();
2656
+ styleSheetObserver();
2657
+ adoptedStyleSheetObserver();
2658
+ styleDeclarationObserver();
2659
+ fontObserver();
2660
+ selectionObserver();
2661
+ pluginHandlers.forEach((h) => h());
2662
+ };
2663
+ }
2664
+
2665
+ class CrossOriginIframeMirror {
2666
+ constructor(generateIdFn) {
2667
+ this.generateIdFn = generateIdFn;
2668
+ this.iframeIdToRemoteIdMap = new WeakMap();
2669
+ this.iframeRemoteIdToIdMap = new WeakMap();
2670
+ }
2671
+ getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {
2672
+ const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);
2673
+ const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);
2674
+ let id = idToRemoteIdMap.get(remoteId);
2675
+ if (!id) {
2676
+ id = this.generateIdFn();
2677
+ idToRemoteIdMap.set(remoteId, id);
2678
+ remoteIdToIdMap.set(id, remoteId);
2679
+ }
2680
+ return id;
2681
+ }
2682
+ getIds(iframe, remoteId) {
2683
+ const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);
2684
+ const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
2685
+ return remoteId.map((id) => this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap));
2686
+ }
2687
+ getRemoteId(iframe, id, map) {
2688
+ const remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);
2689
+ if (typeof id !== 'number')
2690
+ return id;
2691
+ const remoteId = remoteIdToIdMap.get(id);
2692
+ if (!remoteId)
2693
+ return -1;
2694
+ return remoteId;
2695
+ }
2696
+ getRemoteIds(iframe, ids) {
2697
+ const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
2698
+ return ids.map((id) => this.getRemoteId(iframe, id, remoteIdToIdMap));
2699
+ }
2700
+ reset(iframe) {
2701
+ if (!iframe) {
2702
+ this.iframeIdToRemoteIdMap = new WeakMap();
2703
+ this.iframeRemoteIdToIdMap = new WeakMap();
2704
+ return;
2705
+ }
2706
+ this.iframeIdToRemoteIdMap.delete(iframe);
2707
+ this.iframeRemoteIdToIdMap.delete(iframe);
2708
+ }
2709
+ getIdToRemoteIdMap(iframe) {
2710
+ let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);
2711
+ if (!idToRemoteIdMap) {
2712
+ idToRemoteIdMap = new Map();
2713
+ this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);
2714
+ }
2715
+ return idToRemoteIdMap;
2716
+ }
2717
+ getRemoteIdToIdMap(iframe) {
2718
+ let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);
2719
+ if (!remoteIdToIdMap) {
2720
+ remoteIdToIdMap = new Map();
2721
+ this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);
2722
+ }
2723
+ return remoteIdToIdMap;
2724
+ }
2725
+ }
2726
+
2727
+ class IframeManager {
2728
+ constructor(options) {
2729
+ this.iframes = new WeakMap();
2730
+ this.crossOriginIframeMap = new WeakMap();
2731
+ this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);
2732
+ this.mutationCb = options.mutationCb;
2733
+ this.wrappedEmit = options.wrappedEmit;
2734
+ this.stylesheetManager = options.stylesheetManager;
2735
+ this.recordCrossOriginIframes = options.recordCrossOriginIframes;
2736
+ this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror));
2737
+ this.mirror = options.mirror;
2738
+ if (this.recordCrossOriginIframes) {
2739
+ window.addEventListener('message', this.handleMessage.bind(this));
2740
+ }
2741
+ }
2742
+ addIframe(iframeEl) {
2743
+ this.iframes.set(iframeEl, true);
2744
+ if (iframeEl.contentWindow)
2745
+ this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);
2746
+ }
2747
+ addLoadListener(cb) {
2748
+ this.loadListener = cb;
2749
+ }
2750
+ attachIframe(iframeEl, childSn) {
2751
+ var _a;
2752
+ this.mutationCb({
2753
+ adds: [
2754
+ {
2755
+ parentId: this.mirror.getId(iframeEl),
2756
+ nextId: null,
2757
+ node: childSn,
2758
+ },
2759
+ ],
2760
+ removes: [],
2761
+ texts: [],
2762
+ attributes: [],
2763
+ isAttachIframe: true,
2764
+ });
2765
+ (_a = this.loadListener) === null || _a === void 0 ? void 0 : _a.call(this, iframeEl);
2766
+ if (iframeEl.contentDocument &&
2767
+ iframeEl.contentDocument.adoptedStyleSheets &&
2768
+ iframeEl.contentDocument.adoptedStyleSheets.length > 0)
2769
+ this.stylesheetManager.adoptStyleSheets(iframeEl.contentDocument.adoptedStyleSheets, this.mirror.getId(iframeEl.contentDocument));
2770
+ }
2771
+ handleMessage(message) {
2772
+ if (message.data.type === 'rrweb') {
2773
+ const iframeSourceWindow = message.source;
2774
+ if (!iframeSourceWindow)
2775
+ return;
2776
+ const iframeEl = this.crossOriginIframeMap.get(message.source);
2777
+ if (!iframeEl)
2778
+ return;
2779
+ const transformedEvent = this.transformCrossOriginEvent(iframeEl, message.data.event);
2780
+ if (transformedEvent)
2781
+ this.wrappedEmit(transformedEvent, message.data.isCheckout);
2782
+ }
2783
+ }
2784
+ transformCrossOriginEvent(iframeEl, e) {
2785
+ var _a;
2786
+ switch (e.type) {
2787
+ case EventType.FullSnapshot: {
2788
+ this.crossOriginIframeMirror.reset(iframeEl);
2789
+ this.crossOriginIframeStyleMirror.reset(iframeEl);
2790
+ this.replaceIdOnNode(e.data.node, iframeEl);
2791
+ return {
2792
+ timestamp: e.timestamp,
2793
+ type: EventType.IncrementalSnapshot,
2794
+ data: {
2795
+ source: IncrementalSource.Mutation,
2796
+ adds: [
2797
+ {
2798
+ parentId: this.mirror.getId(iframeEl),
2799
+ nextId: null,
2800
+ node: e.data.node,
2801
+ },
2802
+ ],
2803
+ removes: [],
2804
+ texts: [],
2805
+ attributes: [],
2806
+ isAttachIframe: true,
2807
+ },
2808
+ };
2809
+ }
2810
+ case EventType.Meta:
2811
+ case EventType.Load:
2812
+ case EventType.DomContentLoaded: {
2813
+ return false;
2814
+ }
2815
+ case EventType.Plugin: {
2816
+ return e;
2817
+ }
2818
+ case EventType.Custom: {
2819
+ this.replaceIds(e.data.payload, iframeEl, ['id', 'parentId', 'previousId', 'nextId']);
2820
+ return e;
2821
+ }
2822
+ case EventType.IncrementalSnapshot: {
2823
+ switch (e.data.source) {
2824
+ case IncrementalSource.Mutation: {
2825
+ e.data.adds.forEach((n) => {
2826
+ this.replaceIds(n, iframeEl, [
2827
+ 'parentId',
2828
+ 'nextId',
2829
+ 'previousId',
2830
+ ]);
2831
+ this.replaceIdOnNode(n.node, iframeEl);
2832
+ });
2833
+ e.data.removes.forEach((n) => {
2834
+ this.replaceIds(n, iframeEl, ['parentId', 'id']);
2835
+ });
2836
+ e.data.attributes.forEach((n) => {
2837
+ this.replaceIds(n, iframeEl, ['id']);
2838
+ });
2839
+ e.data.texts.forEach((n) => {
2840
+ this.replaceIds(n, iframeEl, ['id']);
2841
+ });
2842
+ return e;
2843
+ }
2844
+ case IncrementalSource.Drag:
2845
+ case IncrementalSource.TouchMove:
2846
+ case IncrementalSource.MouseMove: {
2847
+ e.data.positions.forEach((p) => {
2848
+ this.replaceIds(p, iframeEl, ['id']);
2849
+ });
2850
+ return e;
2851
+ }
2852
+ case IncrementalSource.ViewportResize: {
2853
+ return false;
2854
+ }
2855
+ case IncrementalSource.MediaInteraction:
2856
+ case IncrementalSource.MouseInteraction:
2857
+ case IncrementalSource.Scroll:
2858
+ case IncrementalSource.CanvasMutation:
2859
+ case IncrementalSource.Input: {
2860
+ this.replaceIds(e.data, iframeEl, ['id']);
2861
+ return e;
2862
+ }
2863
+ case IncrementalSource.StyleSheetRule:
2864
+ case IncrementalSource.StyleDeclaration: {
2865
+ this.replaceIds(e.data, iframeEl, ['id']);
2866
+ this.replaceStyleIds(e.data, iframeEl, ['styleId']);
2867
+ return e;
2868
+ }
2869
+ case IncrementalSource.Font: {
2870
+ return e;
2871
+ }
2872
+ case IncrementalSource.Selection: {
2873
+ e.data.ranges.forEach((range) => {
2874
+ this.replaceIds(range, iframeEl, ['start', 'end']);
2875
+ });
2876
+ return e;
2877
+ }
2878
+ case IncrementalSource.AdoptedStyleSheet: {
2879
+ this.replaceIds(e.data, iframeEl, ['id']);
2880
+ this.replaceStyleIds(e.data, iframeEl, ['styleIds']);
2881
+ (_a = e.data.styles) === null || _a === void 0 ? void 0 : _a.forEach((style) => {
2882
+ this.replaceStyleIds(style, iframeEl, ['styleId']);
2883
+ });
2884
+ return e;
2885
+ }
2886
+ }
2887
+ }
2888
+ }
2889
+ }
2890
+ replace(iframeMirror, obj, iframeEl, keys) {
2891
+ for (const key of keys) {
2892
+ if (!Array.isArray(obj[key]) && typeof obj[key] !== 'number')
2893
+ continue;
2894
+ if (Array.isArray(obj[key])) {
2895
+ obj[key] = iframeMirror.getIds(iframeEl, obj[key]);
2896
+ }
2897
+ else {
2898
+ obj[key] = iframeMirror.getId(iframeEl, obj[key]);
2899
+ }
2900
+ }
2901
+ return obj;
2902
+ }
2903
+ replaceIds(obj, iframeEl, keys) {
2904
+ return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);
2905
+ }
2906
+ replaceStyleIds(obj, iframeEl, keys) {
2907
+ return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);
2908
+ }
2909
+ replaceIdOnNode(node, iframeEl) {
2910
+ this.replaceIds(node, iframeEl, ['id']);
2911
+ if ('childNodes' in node) {
2912
+ node.childNodes.forEach((child) => {
2913
+ this.replaceIdOnNode(child, iframeEl);
2914
+ });
2915
+ }
2916
+ }
2917
+ }
2918
+
2919
+ class ShadowDomManager {
2920
+ constructor(options) {
2921
+ this.shadowDoms = new WeakSet();
2922
+ this.restorePatches = [];
2923
+ this.mutationCb = options.mutationCb;
2924
+ this.scrollCb = options.scrollCb;
2925
+ this.bypassOptions = options.bypassOptions;
2926
+ this.mirror = options.mirror;
2927
+ const manager = this;
2928
+ this.restorePatches.push(patch(Element.prototype, 'attachShadow', function (original) {
2929
+ return function (option) {
2930
+ const shadowRoot = original.call(this, option);
2931
+ if (this.shadowRoot)
2932
+ manager.addShadowRoot(this.shadowRoot, this.ownerDocument);
2933
+ return shadowRoot;
2934
+ };
2935
+ }));
2936
+ }
2937
+ addShadowRoot(shadowRoot, doc) {
2938
+ if (!isNativeShadowDom(shadowRoot))
2939
+ return;
2940
+ if (this.shadowDoms.has(shadowRoot))
2941
+ return;
2942
+ this.shadowDoms.add(shadowRoot);
2943
+ initMutationObserver(Object.assign(Object.assign({}, this.bypassOptions), { doc, mutationCb: this.mutationCb, mirror: this.mirror, shadowDomManager: this }), shadowRoot);
2944
+ initScrollObserver(Object.assign(Object.assign({}, this.bypassOptions), { scrollCb: this.scrollCb, doc: shadowRoot, mirror: this.mirror }));
2945
+ setTimeout(() => {
2946
+ if (shadowRoot.adoptedStyleSheets &&
2947
+ shadowRoot.adoptedStyleSheets.length > 0)
2948
+ this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot.adoptedStyleSheets, this.mirror.getId(shadowRoot.host));
2949
+ initAdoptedStyleSheetObserver({
2950
+ mirror: this.mirror,
2951
+ stylesheetManager: this.bypassOptions.stylesheetManager,
2952
+ }, shadowRoot);
2953
+ }, 0);
2954
+ }
2955
+ observeAttachShadow(iframeElement) {
2956
+ if (iframeElement.contentWindow) {
2957
+ const manager = this;
2958
+ this.restorePatches.push(patch(iframeElement.contentWindow.HTMLElement.prototype, 'attachShadow', function (original) {
2959
+ return function (option) {
2960
+ const shadowRoot = original.call(this, option);
2961
+ if (this.shadowRoot)
2962
+ manager.addShadowRoot(this.shadowRoot, iframeElement.contentDocument);
2963
+ return shadowRoot;
2964
+ };
2965
+ }));
2966
+ }
2967
+ }
2968
+ reset() {
2969
+ this.restorePatches.forEach((restorePatch) => restorePatch());
2970
+ this.shadowDoms = new WeakSet();
2971
+ }
2972
+ }
2973
+
2974
+ /*! *****************************************************************************
2975
+ Copyright (c) Microsoft Corporation.
2976
+
2977
+ Permission to use, copy, modify, and/or distribute this software for any
2978
+ purpose with or without fee is hereby granted.
2979
+
2980
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
2981
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
2982
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
2983
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
2984
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2985
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2986
+ PERFORMANCE OF THIS SOFTWARE.
2987
+ ***************************************************************************** */
2988
+
2989
+ function __rest(s, e) {
2990
+ var t = {};
2991
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
2992
+ t[p] = s[p];
2993
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
2994
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
2995
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
2996
+ t[p[i]] = s[p[i]];
2997
+ }
2998
+ return t;
2999
+ }
3000
+
3001
+ function __awaiter(thisArg, _arguments, P, generator) {
3002
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3003
+ return new (P || (P = Promise))(function (resolve, reject) {
3004
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
3005
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
3006
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
3007
+ step((generator = generator.apply(thisArg, [])).next());
3008
+ });
3009
+ }
3010
+
3011
+ /*
3012
+ * base64-arraybuffer 1.0.1 <https://github.com/niklasvh/base64-arraybuffer>
3013
+ * Copyright (c) 2021 Niklas von Hertzen <https://hertzen.com>
3014
+ * Released under MIT License
3015
+ */
3016
+ var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
3017
+ // Use a lookup table to find the index.
3018
+ var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
3019
+ for (var i = 0; i < chars.length; i++) {
3020
+ lookup[chars.charCodeAt(i)] = i;
3021
+ }
3022
+ var encode = function (arraybuffer) {
3023
+ var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';
3024
+ for (i = 0; i < len; i += 3) {
3025
+ base64 += chars[bytes[i] >> 2];
3026
+ base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
3027
+ base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
3028
+ base64 += chars[bytes[i + 2] & 63];
3029
+ }
3030
+ if (len % 3 === 2) {
3031
+ base64 = base64.substring(0, base64.length - 1) + '=';
3032
+ }
3033
+ else if (len % 3 === 1) {
3034
+ base64 = base64.substring(0, base64.length - 2) + '==';
3035
+ }
3036
+ return base64;
3037
+ };
3038
+
3039
+ const canvasVarMap = new Map();
3040
+ function variableListFor(ctx, ctor) {
3041
+ let contextMap = canvasVarMap.get(ctx);
3042
+ if (!contextMap) {
3043
+ contextMap = new Map();
3044
+ canvasVarMap.set(ctx, contextMap);
3045
+ }
3046
+ if (!contextMap.has(ctor)) {
3047
+ contextMap.set(ctor, []);
3048
+ }
3049
+ return contextMap.get(ctor);
3050
+ }
3051
+ const saveWebGLVar = (value, win, ctx) => {
3052
+ if (!value ||
3053
+ !(isInstanceOfWebGLObject(value, win) || typeof value === 'object'))
3054
+ return;
3055
+ const name = value.constructor.name;
3056
+ const list = variableListFor(ctx, name);
3057
+ let index = list.indexOf(value);
3058
+ if (index === -1) {
3059
+ index = list.length;
3060
+ list.push(value);
3061
+ }
3062
+ return index;
3063
+ };
3064
+ function serializeArg(value, win, ctx) {
3065
+ if (value instanceof Array) {
3066
+ return value.map((arg) => serializeArg(arg, win, ctx));
3067
+ }
3068
+ else if (value === null) {
3069
+ return value;
3070
+ }
3071
+ else if (value instanceof Float32Array ||
3072
+ value instanceof Float64Array ||
3073
+ value instanceof Int32Array ||
3074
+ value instanceof Uint32Array ||
3075
+ value instanceof Uint8Array ||
3076
+ value instanceof Uint16Array ||
3077
+ value instanceof Int16Array ||
3078
+ value instanceof Int8Array ||
3079
+ value instanceof Uint8ClampedArray) {
3080
+ const name = value.constructor.name;
3081
+ return {
3082
+ rr_type: name,
3083
+ args: [Object.values(value)],
3084
+ };
3085
+ }
3086
+ else if (value instanceof ArrayBuffer) {
3087
+ const name = value.constructor.name;
3088
+ const base64 = encode(value);
3089
+ return {
3090
+ rr_type: name,
3091
+ base64,
3092
+ };
3093
+ }
3094
+ else if (value instanceof DataView) {
3095
+ const name = value.constructor.name;
3096
+ return {
3097
+ rr_type: name,
3098
+ args: [
3099
+ serializeArg(value.buffer, win, ctx),
3100
+ value.byteOffset,
3101
+ value.byteLength,
3102
+ ],
3103
+ };
3104
+ }
3105
+ else if (value instanceof HTMLImageElement) {
3106
+ const name = value.constructor.name;
3107
+ const { src } = value;
3108
+ return {
3109
+ rr_type: name,
3110
+ src,
3111
+ };
3112
+ }
3113
+ else if (value instanceof HTMLCanvasElement) {
3114
+ const name = 'HTMLImageElement';
3115
+ const src = value.toDataURL();
3116
+ return {
3117
+ rr_type: name,
3118
+ src,
3119
+ };
3120
+ }
3121
+ else if (value instanceof ImageData) {
3122
+ const name = value.constructor.name;
3123
+ return {
3124
+ rr_type: name,
3125
+ args: [serializeArg(value.data, win, ctx), value.width, value.height],
3126
+ };
3127
+ }
3128
+ else if (isInstanceOfWebGLObject(value, win) || typeof value === 'object') {
3129
+ const name = value.constructor.name;
3130
+ const index = saveWebGLVar(value, win, ctx);
3131
+ return {
3132
+ rr_type: name,
3133
+ index: index,
3134
+ };
3135
+ }
3136
+ return value;
3137
+ }
3138
+ const serializeArgs = (args, win, ctx) => {
3139
+ return [...args].map((arg) => serializeArg(arg, win, ctx));
3140
+ };
3141
+ const isInstanceOfWebGLObject = (value, win) => {
3142
+ const webGLConstructorNames = [
3143
+ 'WebGLActiveInfo',
3144
+ 'WebGLBuffer',
3145
+ 'WebGLFramebuffer',
3146
+ 'WebGLProgram',
3147
+ 'WebGLRenderbuffer',
3148
+ 'WebGLShader',
3149
+ 'WebGLShaderPrecisionFormat',
3150
+ 'WebGLTexture',
3151
+ 'WebGLUniformLocation',
3152
+ 'WebGLVertexArrayObject',
3153
+ 'WebGLVertexArrayObjectOES',
3154
+ ];
3155
+ const supportedWebGLConstructorNames = webGLConstructorNames.filter((name) => typeof win[name] === 'function');
3156
+ return Boolean(supportedWebGLConstructorNames.find((name) => value instanceof win[name]));
3157
+ };
3158
+
3159
+ function initCanvas2DMutationObserver(cb, win, blockClass, blockSelector) {
3160
+ const handlers = [];
3161
+ const props2D = Object.getOwnPropertyNames(win.CanvasRenderingContext2D.prototype);
3162
+ for (const prop of props2D) {
3163
+ try {
3164
+ if (typeof win.CanvasRenderingContext2D.prototype[prop] !== 'function') {
3165
+ continue;
3166
+ }
3167
+ const restoreHandler = patch(win.CanvasRenderingContext2D.prototype, prop, function (original) {
3168
+ return function (...args) {
3169
+ if (!isBlocked(this.canvas, blockClass, blockSelector, true)) {
3170
+ setTimeout(() => {
3171
+ const recordArgs = serializeArgs([...args], win, this);
3172
+ cb(this.canvas, {
3173
+ type: CanvasContext['2D'],
3174
+ property: prop,
3175
+ args: recordArgs,
3176
+ });
3177
+ }, 0);
3178
+ }
3179
+ return original.apply(this, args);
3180
+ };
3181
+ });
3182
+ handlers.push(restoreHandler);
3183
+ }
3184
+ catch (_a) {
3185
+ const hookHandler = hookSetter(win.CanvasRenderingContext2D.prototype, prop, {
3186
+ set(v) {
3187
+ cb(this.canvas, {
3188
+ type: CanvasContext['2D'],
3189
+ property: prop,
3190
+ args: [v],
3191
+ setter: true,
3192
+ });
3193
+ },
3194
+ });
3195
+ handlers.push(hookHandler);
3196
+ }
3197
+ }
3198
+ return () => {
3199
+ handlers.forEach((h) => h());
3200
+ };
3201
+ }
3202
+
3203
+ function initCanvasContextObserver(win, blockClass, blockSelector) {
3204
+ const handlers = [];
3205
+ try {
3206
+ const restoreHandler = patch(win.HTMLCanvasElement.prototype, 'getContext', function (original) {
3207
+ return function (contextType, ...args) {
3208
+ if (!isBlocked(this, blockClass, blockSelector, true)) {
3209
+ if (!('__context' in this))
3210
+ this.__context = contextType;
3211
+ }
3212
+ return original.apply(this, [contextType, ...args]);
3213
+ };
3214
+ });
3215
+ handlers.push(restoreHandler);
3216
+ }
3217
+ catch (_a) {
3218
+ console.error('failed to patch HTMLCanvasElement.prototype.getContext');
3219
+ }
3220
+ return () => {
3221
+ handlers.forEach((h) => h());
3222
+ };
3223
+ }
3224
+
3225
+ function patchGLPrototype(prototype, type, cb, blockClass, blockSelector, mirror, win) {
3226
+ const handlers = [];
3227
+ const props = Object.getOwnPropertyNames(prototype);
3228
+ for (const prop of props) {
3229
+ if ([
3230
+ 'isContextLost',
3231
+ 'canvas',
3232
+ 'drawingBufferWidth',
3233
+ 'drawingBufferHeight',
3234
+ ].includes(prop)) {
3235
+ continue;
3236
+ }
3237
+ try {
3238
+ if (typeof prototype[prop] !== 'function') {
3239
+ continue;
3240
+ }
3241
+ const restoreHandler = patch(prototype, prop, function (original) {
3242
+ return function (...args) {
3243
+ const result = original.apply(this, args);
3244
+ saveWebGLVar(result, win, this);
3245
+ if (!isBlocked(this.canvas, blockClass, blockSelector, true)) {
3246
+ const recordArgs = serializeArgs([...args], win, this);
3247
+ const mutation = {
3248
+ type,
3249
+ property: prop,
3250
+ args: recordArgs,
3251
+ };
3252
+ cb(this.canvas, mutation);
3253
+ }
3254
+ return result;
3255
+ };
3256
+ });
3257
+ handlers.push(restoreHandler);
3258
+ }
3259
+ catch (_a) {
3260
+ const hookHandler = hookSetter(prototype, prop, {
3261
+ set(v) {
3262
+ cb(this.canvas, {
3263
+ type,
3264
+ property: prop,
3265
+ args: [v],
3266
+ setter: true,
3267
+ });
3268
+ },
3269
+ });
3270
+ handlers.push(hookHandler);
3271
+ }
3272
+ }
3273
+ return handlers;
3274
+ }
3275
+ function initCanvasWebGLMutationObserver(cb, win, blockClass, blockSelector, mirror) {
3276
+ const handlers = [];
3277
+ handlers.push(...patchGLPrototype(win.WebGLRenderingContext.prototype, CanvasContext.WebGL, cb, blockClass, blockSelector, mirror, win));
3278
+ if (typeof win.WebGL2RenderingContext !== 'undefined') {
3279
+ handlers.push(...patchGLPrototype(win.WebGL2RenderingContext.prototype, CanvasContext.WebGL2, cb, blockClass, blockSelector, mirror, win));
3280
+ }
3281
+ return () => {
3282
+ handlers.forEach((h) => h());
3283
+ };
3284
+ }
3285
+
3286
+ var WorkerClass = null;
3287
+
3288
+ try {
3289
+ var WorkerThreads =
3290
+ typeof module !== 'undefined' && typeof module.require === 'function' && module.require('worker_threads') ||
3291
+ typeof __non_webpack_require__ === 'function' && __non_webpack_require__('worker_threads') ||
3292
+ typeof require === 'function' && require('worker_threads');
3293
+ WorkerClass = WorkerThreads.Worker;
3294
+ } catch(e) {} // eslint-disable-line
3295
+
3296
+ function decodeBase64$1(base64, enableUnicode) {
3297
+ return Buffer.from(base64, 'base64').toString('utf8');
3298
+ }
3299
+
3300
+ function createBase64WorkerFactory$2(base64, sourcemapArg, enableUnicodeArg) {
3301
+ var source = decodeBase64$1(base64);
3302
+ var start = source.indexOf('\n', 10) + 1;
3303
+ var body = source.substring(start) + ('');
3304
+ return function WorkerFactory(options) {
3305
+ return new WorkerClass(body, Object.assign({}, options, { eval: true }));
3306
+ };
3307
+ }
3308
+
3309
+ function decodeBase64(base64, enableUnicode) {
3310
+ var binaryString = atob(base64);
3311
+ return binaryString;
3312
+ }
3313
+
3314
+ function createURL(base64, sourcemapArg, enableUnicodeArg) {
3315
+ var source = decodeBase64(base64);
3316
+ var start = source.indexOf('\n', 10) + 1;
3317
+ var body = source.substring(start) + ('');
3318
+ var blob = new Blob([body], { type: 'application/javascript' });
3319
+ return URL.createObjectURL(blob);
3320
+ }
3321
+
3322
+ function createBase64WorkerFactory$1(base64, sourcemapArg, enableUnicodeArg) {
3323
+ var url;
3324
+ return function WorkerFactory(options) {
3325
+ url = url || createURL(base64);
3326
+ return new Worker(url, options);
3327
+ };
3328
+ }
3329
+
3330
+ var kIsNodeJS = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';
3331
+
3332
+ function isNodeJS() {
3333
+ return kIsNodeJS;
3334
+ }
3335
+
3336
+ function createBase64WorkerFactory(base64, sourcemapArg, enableUnicodeArg) {
3337
+ if (isNodeJS()) {
3338
+ return createBase64WorkerFactory$2(base64);
3339
+ }
3340
+ return createBase64WorkerFactory$1(base64);
3341
+ }
3342
+
3343
+ var WorkerFactory = createBase64WorkerFactory('Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwooZnVuY3Rpb24gKCkgewogICAgJ3VzZSBzdHJpY3QnOwoKICAgIC8qISAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKg0KICAgIENvcHlyaWdodCAoYykgTWljcm9zb2Z0IENvcnBvcmF0aW9uLg0KDQogICAgUGVybWlzc2lvbiB0byB1c2UsIGNvcHksIG1vZGlmeSwgYW5kL29yIGRpc3RyaWJ1dGUgdGhpcyBzb2Z0d2FyZSBmb3IgYW55DQogICAgcHVycG9zZSB3aXRoIG9yIHdpdGhvdXQgZmVlIGlzIGhlcmVieSBncmFudGVkLg0KDQogICAgVEhFIFNPRlRXQVJFIElTIFBST1ZJREVEICJBUyBJUyIgQU5EIFRIRSBBVVRIT1IgRElTQ0xBSU1TIEFMTCBXQVJSQU5USUVTIFdJVEgNCiAgICBSRUdBUkQgVE8gVEhJUyBTT0ZUV0FSRSBJTkNMVURJTkcgQUxMIElNUExJRUQgV0FSUkFOVElFUyBPRiBNRVJDSEFOVEFCSUxJVFkNCiAgICBBTkQgRklUTkVTUy4gSU4gTk8gRVZFTlQgU0hBTEwgVEhFIEFVVEhPUiBCRSBMSUFCTEUgRk9SIEFOWSBTUEVDSUFMLCBESVJFQ1QsDQogICAgSU5ESVJFQ1QsIE9SIENPTlNFUVVFTlRJQUwgREFNQUdFUyBPUiBBTlkgREFNQUdFUyBXSEFUU09FVkVSIFJFU1VMVElORyBGUk9NDQogICAgTE9TUyBPRiBVU0UsIERBVEEgT1IgUFJPRklUUywgV0hFVEhFUiBJTiBBTiBBQ1RJT04gT0YgQ09OVFJBQ1QsIE5FR0xJR0VOQ0UgT1INCiAgICBPVEhFUiBUT1JUSU9VUyBBQ1RJT04sIEFSSVNJTkcgT1VUIE9GIE9SIElOIENPTk5FQ1RJT04gV0lUSCBUSEUgVVNFIE9SDQogICAgUEVSRk9STUFOQ0UgT0YgVEhJUyBTT0ZUV0FSRS4NCiAgICAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKiAqLw0KDQogICAgZnVuY3Rpb24gX19hd2FpdGVyKHRoaXNBcmcsIF9hcmd1bWVudHMsIFAsIGdlbmVyYXRvcikgew0KICAgICAgICBmdW5jdGlvbiBhZG9wdCh2YWx1ZSkgeyByZXR1cm4gdmFsdWUgaW5zdGFuY2VvZiBQID8gdmFsdWUgOiBuZXcgUChmdW5jdGlvbiAocmVzb2x2ZSkgeyByZXNvbHZlKHZhbHVlKTsgfSk7IH0NCiAgICAgICAgcmV0dXJuIG5ldyAoUCB8fCAoUCA9IFByb21pc2UpKShmdW5jdGlvbiAocmVzb2x2ZSwgcmVqZWN0KSB7DQogICAgICAgICAgICBmdW5jdGlvbiBmdWxmaWxsZWQodmFsdWUpIHsgdHJ5IHsgc3RlcChnZW5lcmF0b3IubmV4dCh2YWx1ZSkpOyB9IGNhdGNoIChlKSB7IHJlamVjdChlKTsgfSB9DQogICAgICAgICAgICBmdW5jdGlvbiByZWplY3RlZCh2YWx1ZSkgeyB0cnkgeyBzdGVwKGdlbmVyYXRvclsidGhyb3ciXSh2YWx1ZSkpOyB9IGNhdGNoIChlKSB7IHJlamVjdChlKTsgfSB9DQogICAgICAgICAgICBmdW5jdGlvbiBzdGVwKHJlc3VsdCkgeyByZXN1bHQuZG9uZSA/IHJlc29sdmUocmVzdWx0LnZhbHVlKSA6IGFkb3B0KHJlc3VsdC52YWx1ZSkudGhlbihmdWxmaWxsZWQsIHJlamVjdGVkKTsgfQ0KICAgICAgICAgICAgc3RlcCgoZ2VuZXJhdG9yID0gZ2VuZXJhdG9yLmFwcGx5KHRoaXNBcmcsIF9hcmd1bWVudHMgfHwgW10pKS5uZXh0KCkpOw0KICAgICAgICB9KTsNCiAgICB9CgogICAgLyoKICAgICAqIGJhc2U2NC1hcnJheWJ1ZmZlciAxLjAuMSA8aHR0cHM6Ly9naXRodWIuY29tL25pa2xhc3ZoL2Jhc2U2NC1hcnJheWJ1ZmZlcj4KICAgICAqIENvcHlyaWdodCAoYykgMjAyMSBOaWtsYXMgdm9uIEhlcnR6ZW4gPGh0dHBzOi8vaGVydHplbi5jb20+CiAgICAgKiBSZWxlYXNlZCB1bmRlciBNSVQgTGljZW5zZQogICAgICovCiAgICB2YXIgY2hhcnMgPSAnQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyc7CiAgICAvLyBVc2UgYSBsb29rdXAgdGFibGUgdG8gZmluZCB0aGUgaW5kZXguCiAgICB2YXIgbG9va3VwID0gdHlwZW9mIFVpbnQ4QXJyYXkgPT09ICd1bmRlZmluZWQnID8gW10gOiBuZXcgVWludDhBcnJheSgyNTYpOwogICAgZm9yICh2YXIgaSA9IDA7IGkgPCBjaGFycy5sZW5ndGg7IGkrKykgewogICAgICAgIGxvb2t1cFtjaGFycy5jaGFyQ29kZUF0KGkpXSA9IGk7CiAgICB9CiAgICB2YXIgZW5jb2RlID0gZnVuY3Rpb24gKGFycmF5YnVmZmVyKSB7CiAgICAgICAgdmFyIGJ5dGVzID0gbmV3IFVpbnQ4QXJyYXkoYXJyYXlidWZmZXIpLCBpLCBsZW4gPSBieXRlcy5sZW5ndGgsIGJhc2U2NCA9ICcnOwogICAgICAgIGZvciAoaSA9IDA7IGkgPCBsZW47IGkgKz0gMykgewogICAgICAgICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaV0gPj4gMl07CiAgICAgICAgICAgIGJhc2U2NCArPSBjaGFyc1soKGJ5dGVzW2ldICYgMykgPDwgNCkgfCAoYnl0ZXNbaSArIDFdID4+IDQpXTsKICAgICAgICAgICAgYmFzZTY0ICs9IGNoYXJzWygoYnl0ZXNbaSArIDFdICYgMTUpIDw8IDIpIHwgKGJ5dGVzW2kgKyAyXSA+PiA2KV07CiAgICAgICAgICAgIGJhc2U2NCArPSBjaGFyc1tieXRlc1tpICsgMl0gJiA2M107CiAgICAgICAgfQogICAgICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgICAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgJz0nOwogICAgICAgIH0KICAgICAgICBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgICAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgJz09JzsKICAgICAgICB9CiAgICAgICAgcmV0dXJuIGJhc2U2NDsKICAgIH07CgogICAgY29uc3QgbGFzdEJsb2JNYXAgPSBuZXcgTWFwKCk7DQogICAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gbmV3IE1hcCgpOw0KICAgIGZ1bmN0aW9uIGdldFRyYW5zcGFyZW50QmxvYkZvcih3aWR0aCwgaGVpZ2h0LCBkYXRhVVJMT3B0aW9ucykgew0KICAgICAgICByZXR1cm4gX19hd2FpdGVyKHRoaXMsIHZvaWQgMCwgdm9pZCAwLCBmdW5jdGlvbiogKCkgew0KICAgICAgICAgICAgY29uc3QgaWQgPSBgJHt3aWR0aH0tJHtoZWlnaHR9YDsNCiAgICAgICAgICAgIGlmICgnT2Zmc2NyZWVuQ2FudmFzJyBpbiBnbG9iYWxUaGlzKSB7DQogICAgICAgICAgICAgICAgaWYgKHRyYW5zcGFyZW50QmxvYk1hcC5oYXMoaWQpKQ0KICAgICAgICAgICAgICAgICAgICByZXR1cm4gdHJhbnNwYXJlbnRCbG9iTWFwLmdldChpZCk7DQogICAgICAgICAgICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsNCiAgICAgICAgICAgICAgICBvZmZzY3JlZW4uZ2V0Q29udGV4dCgnMmQnKTsNCiAgICAgICAgICAgICAgICBjb25zdCBibG9iID0geWllbGQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0geWllbGQgYmxvYi5hcnJheUJ1ZmZlcigpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7DQogICAgICAgICAgICAgICAgdHJhbnNwYXJlbnRCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsNCiAgICAgICAgICAgICAgICByZXR1cm4gYmFzZTY0Ow0KICAgICAgICAgICAgfQ0KICAgICAgICAgICAgZWxzZSB7DQogICAgICAgICAgICAgICAgcmV0dXJuICcnOw0KICAgICAgICAgICAgfQ0KICAgICAgICB9KTsNCiAgICB9DQogICAgY29uc3Qgd29ya2VyID0gc2VsZjsNCiAgICB3b3JrZXIub25tZXNzYWdlID0gZnVuY3Rpb24gKGUpIHsNCiAgICAgICAgcmV0dXJuIF9fYXdhaXRlcih0aGlzLCB2b2lkIDAsIHZvaWQgMCwgZnVuY3Rpb24qICgpIHsNCiAgICAgICAgICAgIGlmICgnT2Zmc2NyZWVuQ2FudmFzJyBpbiBnbG9iYWxUaGlzKSB7DQogICAgICAgICAgICAgICAgY29uc3QgeyBpZCwgYml0bWFwLCB3aWR0aCwgaGVpZ2h0LCBkYXRhVVJMT3B0aW9ucyB9ID0gZS5kYXRhOw0KICAgICAgICAgICAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zKTsNCiAgICAgICAgICAgICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOw0KICAgICAgICAgICAgICAgIGNvbnN0IGN0eCA9IG9mZnNjcmVlbi5nZXRDb250ZXh0KCcyZCcpOw0KICAgICAgICAgICAgICAgIGN0eC5kcmF3SW1hZ2UoYml0bWFwLCAwLCAwKTsNCiAgICAgICAgICAgICAgICBiaXRtYXAuY2xvc2UoKTsNCiAgICAgICAgICAgICAgICBjb25zdCBibG9iID0geWllbGQgb2Zmc2NyZWVuLmNvbnZlcnRUb0Jsb2IoZGF0YVVSTE9wdGlvbnMpOw0KICAgICAgICAgICAgICAgIGNvbnN0IHR5cGUgPSBibG9iLnR5cGU7DQogICAgICAgICAgICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSB5aWVsZCBibG9iLmFycmF5QnVmZmVyKCk7DQogICAgICAgICAgICAgICAgY29uc3QgYmFzZTY0ID0gZW5jb2RlKGFycmF5QnVmZmVyKTsNCiAgICAgICAgICAgICAgICBpZiAoIWxhc3RCbG9iTWFwLmhhcyhpZCkgJiYgKHlpZWxkIHRyYW5zcGFyZW50QmFzZTY0KSA9PT0gYmFzZTY0KSB7DQogICAgICAgICAgICAgICAgICAgIGxhc3RCbG9iTWFwLnNldChpZCwgYmFzZTY0KTsNCiAgICAgICAgICAgICAgICAgICAgcmV0dXJuIHdvcmtlci5wb3N0TWVzc2FnZSh7IGlkIH0pOw0KICAgICAgICAgICAgICAgIH0NCiAgICAgICAgICAgICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KQ0KICAgICAgICAgICAgICAgICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7DQogICAgICAgICAgICAgICAgd29ya2VyLnBvc3RNZXNzYWdlKHsNCiAgICAgICAgICAgICAgICAgICAgaWQsDQogICAgICAgICAgICAgICAgICAgIHR5cGUsDQogICAgICAgICAgICAgICAgICAgIGJhc2U2NCwNCiAgICAgICAgICAgICAgICAgICAgd2lkdGgsDQogICAgICAgICAgICAgICAgICAgIGhlaWdodCwNCiAgICAgICAgICAgICAgICB9KTsNCiAgICAgICAgICAgICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7DQogICAgICAgICAgICB9DQogICAgICAgICAgICBlbHNlIHsNCiAgICAgICAgICAgICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsNCiAgICAgICAgICAgIH0NCiAgICAgICAgfSk7DQogICAgfTsKCn0pKCk7Cgo=');
3344
+
3345
+ class CanvasManager {
3346
+ constructor(options) {
3347
+ this.pendingCanvasMutations = new Map();
3348
+ this.rafStamps = { latestId: 0, invokeId: null };
3349
+ this.frozen = false;
3350
+ this.locked = false;
3351
+ this.processMutation = (target, mutation) => {
3352
+ const newFrame = this.rafStamps.invokeId &&
3353
+ this.rafStamps.latestId !== this.rafStamps.invokeId;
3354
+ if (newFrame || !this.rafStamps.invokeId)
3355
+ this.rafStamps.invokeId = this.rafStamps.latestId;
3356
+ if (!this.pendingCanvasMutations.has(target)) {
3357
+ this.pendingCanvasMutations.set(target, []);
3358
+ }
3359
+ this.pendingCanvasMutations.get(target).push(mutation);
3360
+ };
3361
+ const { sampling = 'all', win, blockClass, blockSelector, recordCanvas, dataURLOptions, } = options;
3362
+ this.mutationCb = options.mutationCb;
3363
+ this.mirror = options.mirror;
3364
+ if (recordCanvas && sampling === 'all')
3365
+ this.initCanvasMutationObserver(win, blockClass, blockSelector);
3366
+ if (recordCanvas && typeof sampling === 'number')
3367
+ this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, {
3368
+ dataURLOptions,
3369
+ });
3370
+ }
3371
+ reset() {
3372
+ this.pendingCanvasMutations.clear();
3373
+ this.resetObservers && this.resetObservers();
3374
+ }
3375
+ freeze() {
3376
+ this.frozen = true;
3377
+ }
3378
+ unfreeze() {
3379
+ this.frozen = false;
3380
+ }
3381
+ lock() {
3382
+ this.locked = true;
3383
+ }
3384
+ unlock() {
3385
+ this.locked = false;
3386
+ }
3387
+ initCanvasFPSObserver(fps, win, blockClass, blockSelector, options) {
3388
+ const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector);
3389
+ const snapshotInProgressMap = new Map();
3390
+ const worker = new WorkerFactory();
3391
+ worker.onmessage = (e) => {
3392
+ const { id } = e.data;
3393
+ snapshotInProgressMap.set(id, false);
3394
+ if (!('base64' in e.data))
3395
+ return;
3396
+ const { base64, type, width, height } = e.data;
3397
+ this.mutationCb({
3398
+ id,
3399
+ type: CanvasContext['2D'],
3400
+ commands: [
3401
+ {
3402
+ property: 'clearRect',
3403
+ args: [0, 0, width, height],
3404
+ },
3405
+ {
3406
+ property: 'drawImage',
3407
+ args: [
3408
+ {
3409
+ rr_type: 'ImageBitmap',
3410
+ args: [
3411
+ {
3412
+ rr_type: 'Blob',
3413
+ data: [{ rr_type: 'ArrayBuffer', base64 }],
3414
+ type,
3415
+ },
3416
+ ],
3417
+ },
3418
+ 0,
3419
+ 0,
3420
+ ],
3421
+ },
3422
+ ],
3423
+ });
3424
+ };
3425
+ const timeBetweenSnapshots = 1000 / fps;
3426
+ let lastSnapshotTime = 0;
3427
+ let rafId;
3428
+ const getCanvas = () => {
3429
+ const matchedCanvas = [];
3430
+ win.document.querySelectorAll('canvas').forEach((canvas) => {
3431
+ if (!isBlocked(canvas, blockClass, blockSelector, true)) {
3432
+ matchedCanvas.push(canvas);
3433
+ }
3434
+ });
3435
+ return matchedCanvas;
3436
+ };
3437
+ const takeCanvasSnapshots = (timestamp) => {
3438
+ if (lastSnapshotTime &&
3439
+ timestamp - lastSnapshotTime < timeBetweenSnapshots) {
3440
+ rafId = requestAnimationFrame(takeCanvasSnapshots);
3441
+ return;
3442
+ }
3443
+ lastSnapshotTime = timestamp;
3444
+ getCanvas()
3445
+ .forEach((canvas) => __awaiter(this, void 0, void 0, function* () {
3446
+ var _a;
3447
+ const id = this.mirror.getId(canvas);
3448
+ if (snapshotInProgressMap.get(id))
3449
+ return;
3450
+ snapshotInProgressMap.set(id, true);
3451
+ if (['webgl', 'webgl2'].includes(canvas.__context)) {
3452
+ const context = canvas.getContext(canvas.__context);
3453
+ if (((_a = context === null || context === void 0 ? void 0 : context.getContextAttributes()) === null || _a === void 0 ? void 0 : _a.preserveDrawingBuffer) === false) {
3454
+ context === null || context === void 0 ? void 0 : context.clear(context.COLOR_BUFFER_BIT);
3455
+ }
3456
+ }
3457
+ const bitmap = yield createImageBitmap(canvas);
3458
+ worker.postMessage({
3459
+ id,
3460
+ bitmap,
3461
+ width: canvas.width,
3462
+ height: canvas.height,
3463
+ dataURLOptions: options.dataURLOptions,
3464
+ }, [bitmap]);
3465
+ }));
3466
+ rafId = requestAnimationFrame(takeCanvasSnapshots);
3467
+ };
3468
+ rafId = requestAnimationFrame(takeCanvasSnapshots);
3469
+ this.resetObservers = () => {
3470
+ canvasContextReset();
3471
+ cancelAnimationFrame(rafId);
3472
+ };
3473
+ }
3474
+ initCanvasMutationObserver(win, blockClass, blockSelector) {
3475
+ this.startRAFTimestamping();
3476
+ this.startPendingCanvasMutationFlusher();
3477
+ const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector);
3478
+ const canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector);
3479
+ const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, this.mirror);
3480
+ this.resetObservers = () => {
3481
+ canvasContextReset();
3482
+ canvas2DReset();
3483
+ canvasWebGL1and2Reset();
3484
+ };
3485
+ }
3486
+ startPendingCanvasMutationFlusher() {
3487
+ requestAnimationFrame(() => this.flushPendingCanvasMutations());
3488
+ }
3489
+ startRAFTimestamping() {
3490
+ const setLatestRAFTimestamp = (timestamp) => {
3491
+ this.rafStamps.latestId = timestamp;
3492
+ requestAnimationFrame(setLatestRAFTimestamp);
3493
+ };
3494
+ requestAnimationFrame(setLatestRAFTimestamp);
3495
+ }
3496
+ flushPendingCanvasMutations() {
3497
+ this.pendingCanvasMutations.forEach((values, canvas) => {
3498
+ const id = this.mirror.getId(canvas);
3499
+ this.flushPendingCanvasMutationFor(canvas, id);
3500
+ });
3501
+ requestAnimationFrame(() => this.flushPendingCanvasMutations());
3502
+ }
3503
+ flushPendingCanvasMutationFor(canvas, id) {
3504
+ if (this.frozen || this.locked) {
3505
+ return;
3506
+ }
3507
+ const valuesWithType = this.pendingCanvasMutations.get(canvas);
3508
+ if (!valuesWithType || id === -1)
3509
+ return;
3510
+ const values = valuesWithType.map((value) => {
3511
+ const rest = __rest(value, ["type"]);
3512
+ return rest;
3513
+ });
3514
+ const { type } = valuesWithType[0];
3515
+ this.mutationCb({ id, type, commands: values });
3516
+ this.pendingCanvasMutations.delete(canvas);
3517
+ }
3518
+ }
3519
+
3520
+ class StylesheetManager {
3521
+ constructor(options) {
3522
+ this.trackedLinkElements = new WeakSet();
3523
+ this.styleMirror = new StyleSheetMirror();
3524
+ this.mutationCb = options.mutationCb;
3525
+ this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;
3526
+ }
3527
+ attachLinkElement(linkEl, childSn) {
3528
+ if ('_cssText' in childSn.attributes)
3529
+ this.mutationCb({
3530
+ adds: [],
3531
+ removes: [],
3532
+ texts: [],
3533
+ attributes: [
3534
+ {
3535
+ id: childSn.id,
3536
+ attributes: childSn
3537
+ .attributes,
3538
+ },
3539
+ ],
3540
+ });
3541
+ this.trackLinkElement(linkEl);
3542
+ }
3543
+ trackLinkElement(linkEl) {
3544
+ if (this.trackedLinkElements.has(linkEl))
3545
+ return;
3546
+ this.trackedLinkElements.add(linkEl);
3547
+ this.trackStylesheetInLinkElement(linkEl);
3548
+ }
3549
+ adoptStyleSheets(sheets, hostId) {
3550
+ if (sheets.length === 0)
3551
+ return;
3552
+ const adoptedStyleSheetData = {
3553
+ id: hostId,
3554
+ styleIds: [],
3555
+ };
3556
+ const styles = [];
3557
+ for (const sheet of sheets) {
3558
+ let styleId;
3559
+ if (!this.styleMirror.has(sheet)) {
3560
+ styleId = this.styleMirror.add(sheet);
3561
+ const rules = Array.from(sheet.rules || CSSRule);
3562
+ styles.push({
3563
+ styleId,
3564
+ rules: rules.map((r, index) => {
3565
+ return {
3566
+ rule: getCssRuleString(r),
3567
+ index,
3568
+ };
3569
+ }),
3570
+ });
3571
+ }
3572
+ else
3573
+ styleId = this.styleMirror.getId(sheet);
3574
+ adoptedStyleSheetData.styleIds.push(styleId);
3575
+ }
3576
+ if (styles.length > 0)
3577
+ adoptedStyleSheetData.styles = styles;
3578
+ this.adoptedStyleSheetCb(adoptedStyleSheetData);
3579
+ }
3580
+ reset() {
3581
+ this.styleMirror.reset();
3582
+ this.trackedLinkElements = new WeakSet();
3583
+ }
3584
+ trackStylesheetInLinkElement(linkEl) {
3585
+ }
3586
+ }
3587
+
3588
+ function wrapEvent(e) {
3589
+ return Object.assign(Object.assign({}, e), { timestamp: Date.now() });
3590
+ }
3591
+ let wrappedEmit;
3592
+ let takeFullSnapshot;
3593
+ let canvasManager;
3594
+ let recording = false;
3595
+ const mirror = createMirror();
3596
+ function record(options = {}) {
3597
+ const { emit, checkoutEveryNms, checkoutEveryNth, blockClass = 'rr-block', blockSelector = null, ignoreClass = 'rr-ignore', maskTextClass = 'rr-mask', maskTextSelector = null, inlineStylesheet = true, maskAllInputs, maskInputOptions: _maskInputOptions, slimDOMOptions: _slimDOMOptions, maskInputFn, maskTextFn, hooks, packFn, sampling = {}, dataURLOptions = {}, mousemoveWait, recordCanvas = false, recordCrossOriginIframes = false, userTriggeredOnInput = false, collectFonts = false, inlineImages = false, plugins, keepIframeSrcFn = () => false, ignoreCSSAttributes = new Set([]), } = options;
3598
+ const inEmittingFrame = recordCrossOriginIframes
3599
+ ? window.parent === window
3600
+ : true;
3601
+ let passEmitsToParent = false;
3602
+ if (!inEmittingFrame) {
3603
+ try {
3604
+ window.parent.document;
3605
+ passEmitsToParent = false;
3606
+ }
3607
+ catch (e) {
3608
+ passEmitsToParent = true;
3609
+ }
3610
+ }
3611
+ if (inEmittingFrame && !emit) {
3612
+ throw new Error('emit function is required');
3613
+ }
3614
+ if (mousemoveWait !== undefined && sampling.mousemove === undefined) {
3615
+ sampling.mousemove = mousemoveWait;
3616
+ }
3617
+ mirror.reset();
3618
+ const maskInputOptions = maskAllInputs === true
3619
+ ? {
3620
+ color: true,
3621
+ date: true,
3622
+ 'datetime-local': true,
3623
+ email: true,
3624
+ month: true,
3625
+ number: true,
3626
+ range: true,
3627
+ search: true,
3628
+ tel: true,
3629
+ text: true,
3630
+ time: true,
3631
+ url: true,
3632
+ week: true,
3633
+ textarea: true,
3634
+ select: true,
3635
+ password: true,
3636
+ }
3637
+ : _maskInputOptions !== undefined
3638
+ ? _maskInputOptions
3639
+ : { password: true };
3640
+ const slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === 'all'
3641
+ ? {
3642
+ script: true,
3643
+ comment: true,
3644
+ headFavicon: true,
3645
+ headWhitespace: true,
3646
+ headMetaSocial: true,
3647
+ headMetaRobots: true,
3648
+ headMetaHttpEquiv: true,
3649
+ headMetaVerification: true,
3650
+ headMetaAuthorship: _slimDOMOptions === 'all',
3651
+ headMetaDescKeywords: _slimDOMOptions === 'all',
3652
+ }
3653
+ : _slimDOMOptions
3654
+ ? _slimDOMOptions
3655
+ : {};
3656
+ polyfill();
3657
+ let lastFullSnapshotEvent;
3658
+ let incrementalSnapshotCount = 0;
3659
+ const eventProcessor = (e) => {
3660
+ for (const plugin of plugins || []) {
3661
+ if (plugin.eventProcessor) {
3662
+ e = plugin.eventProcessor(e);
3663
+ }
3664
+ }
3665
+ if (packFn) {
3666
+ e = packFn(e);
3667
+ }
3668
+ return e;
3669
+ };
3670
+ wrappedEmit = (e, isCheckout) => {
3671
+ var _a;
3672
+ if (((_a = mutationBuffers[0]) === null || _a === void 0 ? void 0 : _a.isFrozen()) &&
3673
+ e.type !== EventType.FullSnapshot &&
3674
+ !(e.type === EventType.IncrementalSnapshot &&
3675
+ e.data.source === IncrementalSource.Mutation)) {
3676
+ mutationBuffers.forEach((buf) => buf.unfreeze());
3677
+ }
3678
+ if (inEmittingFrame) {
3679
+ emit === null || emit === void 0 ? void 0 : emit(eventProcessor(e), isCheckout);
3680
+ }
3681
+ else if (passEmitsToParent) {
3682
+ const message = {
3683
+ type: 'rrweb',
3684
+ event: eventProcessor(e),
3685
+ isCheckout,
3686
+ };
3687
+ window.parent.postMessage(message, '*');
3688
+ }
3689
+ if (e.type === EventType.FullSnapshot) {
3690
+ lastFullSnapshotEvent = e;
3691
+ incrementalSnapshotCount = 0;
3692
+ }
3693
+ else if (e.type === EventType.IncrementalSnapshot) {
3694
+ if (e.data.source === IncrementalSource.Mutation &&
3695
+ e.data.isAttachIframe) {
3696
+ return;
3697
+ }
3698
+ incrementalSnapshotCount++;
3699
+ const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;
3700
+ const exceedTime = checkoutEveryNms &&
3701
+ e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;
3702
+ if (exceedCount || exceedTime) {
3703
+ takeFullSnapshot(true);
3704
+ }
3705
+ }
3706
+ };
3707
+ const wrappedMutationEmit = (m) => {
3708
+ wrappedEmit(wrapEvent({
3709
+ type: EventType.IncrementalSnapshot,
3710
+ data: Object.assign({ source: IncrementalSource.Mutation }, m),
3711
+ }));
3712
+ };
3713
+ const wrappedScrollEmit = (p) => wrappedEmit(wrapEvent({
3714
+ type: EventType.IncrementalSnapshot,
3715
+ data: Object.assign({ source: IncrementalSource.Scroll }, p),
3716
+ }));
3717
+ const wrappedCanvasMutationEmit = (p) => wrappedEmit(wrapEvent({
3718
+ type: EventType.IncrementalSnapshot,
3719
+ data: Object.assign({ source: IncrementalSource.CanvasMutation }, p),
3720
+ }));
3721
+ const wrappedAdoptedStyleSheetEmit = (a) => wrappedEmit(wrapEvent({
3722
+ type: EventType.IncrementalSnapshot,
3723
+ data: Object.assign({ source: IncrementalSource.AdoptedStyleSheet }, a),
3724
+ }));
3725
+ const stylesheetManager = new StylesheetManager({
3726
+ mutationCb: wrappedMutationEmit,
3727
+ adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit,
3728
+ });
3729
+ const iframeManager = new IframeManager({
3730
+ mirror,
3731
+ mutationCb: wrappedMutationEmit,
3732
+ stylesheetManager: stylesheetManager,
3733
+ recordCrossOriginIframes,
3734
+ wrappedEmit,
3735
+ });
3736
+ for (const plugin of plugins || []) {
3737
+ if (plugin.getMirror)
3738
+ plugin.getMirror({
3739
+ nodeMirror: mirror,
3740
+ crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,
3741
+ crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror,
3742
+ });
3743
+ }
3744
+ canvasManager = new CanvasManager({
3745
+ recordCanvas,
3746
+ mutationCb: wrappedCanvasMutationEmit,
3747
+ win: window,
3748
+ blockClass,
3749
+ blockSelector,
3750
+ mirror,
3751
+ sampling: sampling.canvas,
3752
+ dataURLOptions,
3753
+ });
3754
+ const shadowDomManager = new ShadowDomManager({
3755
+ mutationCb: wrappedMutationEmit,
3756
+ scrollCb: wrappedScrollEmit,
3757
+ bypassOptions: {
3758
+ blockClass,
3759
+ blockSelector,
3760
+ maskTextClass,
3761
+ maskTextSelector,
3762
+ inlineStylesheet,
3763
+ maskInputOptions,
3764
+ dataURLOptions,
3765
+ maskTextFn,
3766
+ maskInputFn,
3767
+ recordCanvas,
3768
+ inlineImages,
3769
+ sampling,
3770
+ slimDOMOptions,
3771
+ iframeManager,
3772
+ stylesheetManager,
3773
+ canvasManager,
3774
+ keepIframeSrcFn,
3775
+ },
3776
+ mirror,
3777
+ });
3778
+ takeFullSnapshot = (isCheckout = false) => {
3779
+ var _a, _b, _c, _d, _e, _f;
3780
+ wrappedEmit(wrapEvent({
3781
+ type: EventType.Meta,
3782
+ data: {
3783
+ href: window.location.href,
3784
+ width: getWindowWidth(),
3785
+ height: getWindowHeight(),
3786
+ },
3787
+ }), isCheckout);
3788
+ stylesheetManager.reset();
3789
+ mutationBuffers.forEach((buf) => buf.lock());
3790
+ const node = snapshot(document, {
3791
+ mirror,
3792
+ blockClass,
3793
+ blockSelector,
3794
+ maskTextClass,
3795
+ maskTextSelector,
3796
+ inlineStylesheet,
3797
+ maskAllInputs: maskInputOptions,
3798
+ maskTextFn,
3799
+ slimDOM: slimDOMOptions,
3800
+ dataURLOptions,
3801
+ recordCanvas,
3802
+ inlineImages,
3803
+ onSerialize: (n) => {
3804
+ if (isSerializedIframe(n, mirror)) {
3805
+ iframeManager.addIframe(n);
3806
+ }
3807
+ if (isSerializedStylesheet(n, mirror)) {
3808
+ stylesheetManager.trackLinkElement(n);
3809
+ }
3810
+ if (hasShadowRoot(n)) {
3811
+ shadowDomManager.addShadowRoot(n.shadowRoot, document);
3812
+ }
3813
+ },
3814
+ onIframeLoad: (iframe, childSn) => {
3815
+ iframeManager.attachIframe(iframe, childSn);
3816
+ shadowDomManager.observeAttachShadow(iframe);
3817
+ },
3818
+ onStylesheetLoad: (linkEl, childSn) => {
3819
+ stylesheetManager.attachLinkElement(linkEl, childSn);
3820
+ },
3821
+ keepIframeSrcFn,
3822
+ });
3823
+ if (!node) {
3824
+ return console.warn('Failed to snapshot the document');
3825
+ }
3826
+ wrappedEmit(wrapEvent({
3827
+ type: EventType.FullSnapshot,
3828
+ data: {
3829
+ node,
3830
+ initialOffset: {
3831
+ left: window.pageXOffset !== undefined
3832
+ ? window.pageXOffset
3833
+ : (document === null || document === void 0 ? void 0 : document.documentElement.scrollLeft) ||
3834
+ ((_b = (_a = document === null || document === void 0 ? void 0 : document.body) === null || _a === void 0 ? void 0 : _a.parentElement) === null || _b === void 0 ? void 0 : _b.scrollLeft) ||
3835
+ ((_c = document === null || document === void 0 ? void 0 : document.body) === null || _c === void 0 ? void 0 : _c.scrollLeft) ||
3836
+ 0,
3837
+ top: window.pageYOffset !== undefined
3838
+ ? window.pageYOffset
3839
+ : (document === null || document === void 0 ? void 0 : document.documentElement.scrollTop) ||
3840
+ ((_e = (_d = document === null || document === void 0 ? void 0 : document.body) === null || _d === void 0 ? void 0 : _d.parentElement) === null || _e === void 0 ? void 0 : _e.scrollTop) ||
3841
+ ((_f = document === null || document === void 0 ? void 0 : document.body) === null || _f === void 0 ? void 0 : _f.scrollTop) ||
3842
+ 0,
3843
+ },
3844
+ },
3845
+ }));
3846
+ mutationBuffers.forEach((buf) => buf.unlock());
3847
+ if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0)
3848
+ stylesheetManager.adoptStyleSheets(document.adoptedStyleSheets, mirror.getId(document));
3849
+ };
3850
+ try {
3851
+ const handlers = [];
3852
+ handlers.push(on('DOMContentLoaded', () => {
3853
+ wrappedEmit(wrapEvent({
3854
+ type: EventType.DomContentLoaded,
3855
+ data: {},
3856
+ }));
3857
+ }));
3858
+ const observe = (doc) => {
3859
+ var _a;
3860
+ return initObservers({
3861
+ mutationCb: wrappedMutationEmit,
3862
+ mousemoveCb: (positions, source) => wrappedEmit(wrapEvent({
3863
+ type: EventType.IncrementalSnapshot,
3864
+ data: {
3865
+ source,
3866
+ positions,
3867
+ },
3868
+ })),
3869
+ mouseInteractionCb: (d) => wrappedEmit(wrapEvent({
3870
+ type: EventType.IncrementalSnapshot,
3871
+ data: Object.assign({ source: IncrementalSource.MouseInteraction }, d),
3872
+ })),
3873
+ scrollCb: wrappedScrollEmit,
3874
+ viewportResizeCb: (d) => wrappedEmit(wrapEvent({
3875
+ type: EventType.IncrementalSnapshot,
3876
+ data: Object.assign({ source: IncrementalSource.ViewportResize }, d),
3877
+ })),
3878
+ inputCb: (v) => wrappedEmit(wrapEvent({
3879
+ type: EventType.IncrementalSnapshot,
3880
+ data: Object.assign({ source: IncrementalSource.Input }, v),
3881
+ })),
3882
+ mediaInteractionCb: (p) => wrappedEmit(wrapEvent({
3883
+ type: EventType.IncrementalSnapshot,
3884
+ data: Object.assign({ source: IncrementalSource.MediaInteraction }, p),
3885
+ })),
3886
+ styleSheetRuleCb: (r) => wrappedEmit(wrapEvent({
3887
+ type: EventType.IncrementalSnapshot,
3888
+ data: Object.assign({ source: IncrementalSource.StyleSheetRule }, r),
3889
+ })),
3890
+ styleDeclarationCb: (r) => wrappedEmit(wrapEvent({
3891
+ type: EventType.IncrementalSnapshot,
3892
+ data: Object.assign({ source: IncrementalSource.StyleDeclaration }, r),
3893
+ })),
3894
+ canvasMutationCb: wrappedCanvasMutationEmit,
3895
+ fontCb: (p) => wrappedEmit(wrapEvent({
3896
+ type: EventType.IncrementalSnapshot,
3897
+ data: Object.assign({ source: IncrementalSource.Font }, p),
3898
+ })),
3899
+ selectionCb: (p) => {
3900
+ wrappedEmit(wrapEvent({
3901
+ type: EventType.IncrementalSnapshot,
3902
+ data: Object.assign({ source: IncrementalSource.Selection }, p),
3903
+ }));
3904
+ },
3905
+ blockClass,
3906
+ ignoreClass,
3907
+ maskTextClass,
3908
+ maskTextSelector,
3909
+ maskInputOptions,
3910
+ inlineStylesheet,
3911
+ sampling,
3912
+ recordCanvas,
3913
+ inlineImages,
3914
+ userTriggeredOnInput,
3915
+ collectFonts,
3916
+ doc,
3917
+ maskInputFn,
3918
+ maskTextFn,
3919
+ keepIframeSrcFn,
3920
+ blockSelector,
3921
+ slimDOMOptions,
3922
+ dataURLOptions,
3923
+ mirror,
3924
+ iframeManager,
3925
+ stylesheetManager,
3926
+ shadowDomManager,
3927
+ canvasManager,
3928
+ ignoreCSSAttributes,
3929
+ plugins: ((_a = plugins === null || plugins === void 0 ? void 0 : plugins.filter((p) => p.observer)) === null || _a === void 0 ? void 0 : _a.map((p) => ({
3930
+ observer: p.observer,
3931
+ options: p.options,
3932
+ callback: (payload) => wrappedEmit(wrapEvent({
3933
+ type: EventType.Plugin,
3934
+ data: {
3935
+ plugin: p.name,
3936
+ payload,
3937
+ },
3938
+ })),
3939
+ }))) || [],
3940
+ }, hooks);
3941
+ };
3942
+ iframeManager.addLoadListener((iframeEl) => {
3943
+ handlers.push(observe(iframeEl.contentDocument));
3944
+ });
3945
+ const init = () => {
3946
+ takeFullSnapshot();
3947
+ handlers.push(observe(document));
3948
+ recording = true;
3949
+ };
3950
+ if (document.readyState === 'interactive' ||
3951
+ document.readyState === 'complete') {
3952
+ init();
3953
+ }
3954
+ else {
3955
+ handlers.push(on('load', () => {
3956
+ wrappedEmit(wrapEvent({
3957
+ type: EventType.Load,
3958
+ data: {},
3959
+ }));
3960
+ init();
3961
+ }, window));
3962
+ }
3963
+ return () => {
3964
+ handlers.forEach((h) => h());
3965
+ recording = false;
3966
+ };
3967
+ }
3968
+ catch (error) {
3969
+ console.warn(error);
3970
+ }
3971
+ }
3972
+ record.addCustomEvent = (tag, payload) => {
3973
+ if (!recording) {
3974
+ throw new Error('please add custom event after start recording');
3975
+ }
3976
+ wrappedEmit(wrapEvent({
3977
+ type: EventType.Custom,
3978
+ data: {
3979
+ tag,
3980
+ payload,
3981
+ },
3982
+ }));
3983
+ };
3984
+ record.freezePage = () => {
3985
+ mutationBuffers.forEach((buf) => buf.freeze());
3986
+ };
3987
+ record.takeFullSnapshot = (isCheckout) => {
3988
+ if (!recording) {
3989
+ throw new Error('please take full snapshot after start recording');
3990
+ }
3991
+ takeFullSnapshot(isCheckout);
3992
+ };
3993
+ record.mirror = mirror;
3994
+
3995
+ const byteToHex = [];
3996
+ for (let i = 0; i < 256; ++i) {
3997
+ byteToHex.push((i + 0x100).toString(16).slice(1));
3998
+ }
3999
+ function unsafeStringify(arr, offset = 0) {
4000
+ return (byteToHex[arr[offset + 0]] +
4001
+ byteToHex[arr[offset + 1]] +
4002
+ byteToHex[arr[offset + 2]] +
4003
+ byteToHex[arr[offset + 3]] +
4004
+ '-' +
4005
+ byteToHex[arr[offset + 4]] +
4006
+ byteToHex[arr[offset + 5]] +
4007
+ '-' +
4008
+ byteToHex[arr[offset + 6]] +
4009
+ byteToHex[arr[offset + 7]] +
4010
+ '-' +
4011
+ byteToHex[arr[offset + 8]] +
4012
+ byteToHex[arr[offset + 9]] +
4013
+ '-' +
4014
+ byteToHex[arr[offset + 10]] +
4015
+ byteToHex[arr[offset + 11]] +
4016
+ byteToHex[arr[offset + 12]] +
4017
+ byteToHex[arr[offset + 13]] +
4018
+ byteToHex[arr[offset + 14]] +
4019
+ byteToHex[arr[offset + 15]]).toLowerCase();
4020
+ }
4021
+
4022
+ let getRandomValues;
4023
+ const rnds8 = new Uint8Array(16);
4024
+ function rng() {
4025
+ if (!getRandomValues) {
4026
+ if (typeof crypto === 'undefined' || !crypto.getRandomValues) {
4027
+ throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
4028
+ }
4029
+ getRandomValues = crypto.getRandomValues.bind(crypto);
4030
+ }
4031
+ return getRandomValues(rnds8);
4032
+ }
4033
+
4034
+ const _state = {};
4035
+ function v1(options, buf, offset) {
4036
+ let bytes;
4037
+ {
4038
+ const now = Date.now();
4039
+ const rnds = rng();
4040
+ updateV1State(_state, now, rnds);
4041
+ bytes = v1Bytes(rnds, _state.msecs, _state.nsecs, _state.clockseq, _state.node, buf, offset);
4042
+ }
4043
+ return buf ?? unsafeStringify(bytes);
4044
+ }
4045
+ function updateV1State(state, now, rnds) {
4046
+ state.msecs ??= -Infinity;
4047
+ state.nsecs ??= 0;
4048
+ if (now === state.msecs) {
4049
+ state.nsecs++;
4050
+ if (state.nsecs >= 10000) {
4051
+ state.node = undefined;
4052
+ state.nsecs = 0;
4053
+ }
4054
+ }
4055
+ else if (now > state.msecs) {
4056
+ state.nsecs = 0;
4057
+ }
4058
+ else if (now < state.msecs) {
4059
+ state.node = undefined;
4060
+ }
4061
+ if (!state.node) {
4062
+ state.node = rnds.slice(10, 16);
4063
+ state.node[0] |= 0x01;
4064
+ state.clockseq = ((rnds[8] << 8) | rnds[9]) & 0x3fff;
4065
+ }
4066
+ state.msecs = now;
4067
+ return state;
4068
+ }
4069
+ function v1Bytes(rnds, msecs, nsecs, clockseq, node, buf, offset = 0) {
4070
+ if (rnds.length < 16) {
4071
+ throw new Error('Random bytes length must be >= 16');
4072
+ }
4073
+ if (!buf) {
4074
+ buf = new Uint8Array(16);
4075
+ offset = 0;
4076
+ }
4077
+ else {
4078
+ if (offset < 0 || offset + 16 > buf.length) {
4079
+ throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
4080
+ }
4081
+ }
4082
+ msecs ??= Date.now();
4083
+ nsecs ??= 0;
4084
+ clockseq ??= ((rnds[8] << 8) | rnds[9]) & 0x3fff;
4085
+ node ??= rnds.slice(10, 16);
4086
+ msecs += 12219292800000;
4087
+ const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
4088
+ buf[offset++] = (tl >>> 24) & 0xff;
4089
+ buf[offset++] = (tl >>> 16) & 0xff;
4090
+ buf[offset++] = (tl >>> 8) & 0xff;
4091
+ buf[offset++] = tl & 0xff;
4092
+ const tmh = ((msecs / 0x100000000) * 10000) & 0xfffffff;
4093
+ buf[offset++] = (tmh >>> 8) & 0xff;
4094
+ buf[offset++] = tmh & 0xff;
4095
+ buf[offset++] = ((tmh >>> 24) & 0xf) | 0x10;
4096
+ buf[offset++] = (tmh >>> 16) & 0xff;
4097
+ buf[offset++] = (clockseq >>> 8) | 0x80;
4098
+ buf[offset++] = clockseq & 0xff;
4099
+ for (let n = 0; n < 6; ++n) {
4100
+ buf[offset++] = node[n];
4101
+ }
4102
+ return buf;
4103
+ }
4104
+
4105
+ var INGESTION_URL = process.env.HUMAN_BEHAVIOR_INGESTION_URL || "http://localhost:9000"; // for development
4106
+ var MAX_CHUNK_SIZE_BYTES = 1024 * 1024 * 10; // 10MB chunk size
4107
+ function isChunkSizeExceeded(currentChunk, newEvent, sessionId) {
4108
+ var nextChunkSize = new TextEncoder().encode(JSON.stringify({
4109
+ sessionId: sessionId,
4110
+ events: __spreadArray(__spreadArray([], currentChunk, true), [newEvent], false)
4111
+ })).length;
4112
+ return nextChunkSize > MAX_CHUNK_SIZE_BYTES;
4113
+ }
4114
+ function validateSingleEventSize(event, sessionId) {
4115
+ var singleEventSize = new TextEncoder().encode(JSON.stringify({
4116
+ sessionId: sessionId,
4117
+ events: [event]
4118
+ })).length;
4119
+ if (singleEventSize > MAX_CHUNK_SIZE_BYTES) {
4120
+ throw new Error("Single event size (".concat(singleEventSize, " bytes) exceeds maximum chunk size (").concat(MAX_CHUNK_SIZE_BYTES, " bytes)"));
4121
+ }
4122
+ }
4123
+ var HumanBehaviorAPI = /** @class */ (function () {
4124
+ function HumanBehaviorAPI(_a) {
4125
+ var apiKey = _a.apiKey;
4126
+ this.apiKey = apiKey;
4127
+ this.baseUrl = INGESTION_URL;
4128
+ }
4129
+ HumanBehaviorAPI.prototype.init = function (sessionId, userId) {
4130
+ return __awaiter$1(this, void 0, void 0, function () {
4131
+ var response, responseJson;
4132
+ return __generator(this, function (_a) {
4133
+ switch (_a.label) {
4134
+ case 0: return [4 /*yield*/, fetch("".concat(this.baseUrl, "/api/ingestion/init"), {
4135
+ method: 'POST',
4136
+ headers: {
4137
+ 'Content-Type': 'application/json',
4138
+ 'Authorization': "Bearer ".concat(this.apiKey)
4139
+ },
4140
+ body: JSON.stringify({
4141
+ sessionId: sessionId,
4142
+ endUserId: userId
4143
+ })
4144
+ })];
4145
+ case 1:
4146
+ response = _a.sent();
4147
+ if (!response.ok) {
4148
+ throw new Error("Failed to initialize ingestion: ".concat(response.statusText));
4149
+ }
4150
+ return [4 /*yield*/, response.json()];
4151
+ case 2:
4152
+ responseJson = _a.sent();
4153
+ return [2 /*return*/, {
4154
+ sessionId: responseJson.sessionId,
4155
+ endUserId: responseJson.endUserId
4156
+ }];
4157
+ }
4158
+ });
4159
+ });
4160
+ };
4161
+ HumanBehaviorAPI.prototype.sendEvents = function (events, sessionId, userId) {
4162
+ return __awaiter$1(this, void 0, void 0, function () {
4163
+ var response;
4164
+ return __generator(this, function (_a) {
4165
+ switch (_a.label) {
4166
+ case 0: return [4 /*yield*/, fetch("".concat(this.baseUrl, "/api/ingestion/events"), {
4167
+ method: 'POST',
4168
+ headers: {
4169
+ 'Content-Type': 'application/json',
4170
+ 'Authorization': "Bearer ".concat(this.apiKey)
4171
+ },
4172
+ body: JSON.stringify({
4173
+ sessionId: sessionId,
4174
+ events: events,
4175
+ endUserId: userId
4176
+ })
4177
+ })];
4178
+ case 1:
4179
+ response = _a.sent();
4180
+ if (!response.ok) {
4181
+ throw new Error("Failed to send events: ".concat(response.statusText));
4182
+ }
4183
+ return [2 /*return*/];
4184
+ }
4185
+ });
4186
+ });
4187
+ };
4188
+ HumanBehaviorAPI.prototype.sendEventsChunked = function (events, sessionId) {
4189
+ return __awaiter$1(this, void 0, void 0, function () {
4190
+ var results, currentChunk, _i, events_1, event_1, response, _a, _b, response, _c, _d, error_1;
4191
+ return __generator(this, function (_e) {
4192
+ switch (_e.label) {
4193
+ case 0:
4194
+ _e.trys.push([0, 11, , 12]);
4195
+ results = [];
4196
+ currentChunk = [];
4197
+ _i = 0, events_1 = events;
4198
+ _e.label = 1;
4199
+ case 1:
4200
+ if (!(_i < events_1.length)) return [3 /*break*/, 7];
4201
+ event_1 = events_1[_i];
4202
+ if (!isChunkSizeExceeded(currentChunk, event_1, sessionId)) return [3 /*break*/, 5];
4203
+ if (!(currentChunk.length > 0)) return [3 /*break*/, 4];
4204
+ return [4 /*yield*/, fetch("".concat(this.baseUrl, "/api/ingestion/events"), {
4205
+ method: 'POST',
4206
+ headers: {
4207
+ 'Content-Type': 'application/json',
4208
+ 'Authorization': "Bearer ".concat(this.apiKey)
4209
+ },
4210
+ body: JSON.stringify({
4211
+ sessionId: sessionId,
4212
+ events: currentChunk
4213
+ })
4214
+ })];
4215
+ case 2:
4216
+ response = _e.sent();
4217
+ if (!response.ok) {
4218
+ throw new Error("Failed to send events: ".concat(response.statusText));
4219
+ }
4220
+ _b = (_a = results).push;
4221
+ return [4 /*yield*/, response.json()];
4222
+ case 3:
4223
+ _b.apply(_a, [_e.sent()]);
4224
+ currentChunk = [];
4225
+ _e.label = 4;
4226
+ case 4:
4227
+ // Validate single event size
4228
+ validateSingleEventSize(event_1, sessionId);
4229
+ // Start new chunk with this event
4230
+ currentChunk = [event_1];
4231
+ return [3 /*break*/, 6];
4232
+ case 5:
4233
+ // Add event to current chunk
4234
+ currentChunk.push(event_1);
4235
+ _e.label = 6;
4236
+ case 6:
4237
+ _i++;
4238
+ return [3 /*break*/, 1];
4239
+ case 7:
4240
+ if (!(currentChunk.length > 0)) return [3 /*break*/, 10];
4241
+ return [4 /*yield*/, fetch("".concat(this.baseUrl, "/api/ingestion/events"), {
4242
+ method: 'POST',
4243
+ headers: {
4244
+ 'Content-Type': 'application/json',
4245
+ 'Authorization': "Bearer ".concat(this.apiKey)
4246
+ },
4247
+ body: JSON.stringify({
4248
+ sessionId: sessionId,
4249
+ events: currentChunk
4250
+ })
4251
+ })];
4252
+ case 8:
4253
+ response = _e.sent();
4254
+ if (!response.ok) {
4255
+ throw new Error("Failed to send events: ".concat(response.statusText));
4256
+ }
4257
+ _d = (_c = results).push;
4258
+ return [4 /*yield*/, response.json()];
4259
+ case 9:
4260
+ _d.apply(_c, [_e.sent()]);
4261
+ _e.label = 10;
4262
+ case 10: return [2 /*return*/, results.flat()];
4263
+ case 11:
4264
+ error_1 = _e.sent();
4265
+ console.error('Error sending events:', error_1);
4266
+ throw error_1;
4267
+ case 12: return [2 /*return*/];
4268
+ }
4269
+ });
4270
+ });
4271
+ };
4272
+ HumanBehaviorAPI.prototype.sendUserData = function (userId, userData, sessionId) {
4273
+ return __awaiter$1(this, void 0, void 0, function () {
4274
+ var response, error_2;
4275
+ return __generator(this, function (_a) {
4276
+ switch (_a.label) {
4277
+ case 0:
4278
+ _a.trys.push([0, 3, , 4]);
4279
+ return [4 /*yield*/, fetch("".concat(this.baseUrl, "/api/ingestion/user"), {
4280
+ method: 'POST',
4281
+ headers: {
4282
+ 'Content-Type': 'application/json',
4283
+ 'Authorization': "Bearer ".concat(this.apiKey)
4284
+ },
4285
+ body: JSON.stringify({
4286
+ userId: userId,
4287
+ userAttributes: userData,
4288
+ sessionId: sessionId
4289
+ })
4290
+ })];
4291
+ case 1:
4292
+ response = _a.sent();
4293
+ if (!response.ok) {
4294
+ throw new Error("Failed to send user data: ".concat(response.statusText, " with API key: ").concat(this.apiKey));
4295
+ }
4296
+ return [4 /*yield*/, response.json()];
4297
+ case 2: return [2 /*return*/, _a.sent()];
4298
+ case 3:
4299
+ error_2 = _a.sent();
4300
+ console.error('Error sending user data:', error_2);
4301
+ throw error_2;
4302
+ case 4: return [2 /*return*/];
4303
+ }
4304
+ });
4305
+ });
4306
+ };
4307
+ HumanBehaviorAPI.prototype.sendSessionComplete = function (sessionId) {
4308
+ return __awaiter$1(this, void 0, void 0, function () {
4309
+ var response;
4310
+ return __generator(this, function (_a) {
4311
+ switch (_a.label) {
4312
+ case 0: return [4 /*yield*/, fetch("".concat(this.baseUrl, "/api/ingestion/sessionComplete"), {
4313
+ method: 'POST',
4314
+ headers: {
4315
+ 'Content-Type': 'application/json',
4316
+ 'Authorization': "Bearer ".concat(this.apiKey)
4317
+ },
4318
+ body: JSON.stringify({ sessionId: sessionId })
4319
+ })];
4320
+ case 1:
4321
+ response = _a.sent();
4322
+ if (!response.ok) {
4323
+ throw new Error("Failed to send session complete: ".concat(response.statusText));
4324
+ }
4325
+ return [2 /*return*/];
4326
+ }
4327
+ });
4328
+ });
4329
+ };
4330
+ HumanBehaviorAPI.prototype.sendCustomEvent = function (eventName, eventProperties, sessionId) {
4331
+ return __awaiter$1(this, void 0, void 0, function () {
4332
+ var maxRetries, retryCount, response, error_3;
4333
+ return __generator(this, function (_a) {
4334
+ switch (_a.label) {
4335
+ case 0:
4336
+ maxRetries = 3;
4337
+ retryCount = 0;
4338
+ _a.label = 1;
4339
+ case 1:
4340
+ if (!(retryCount < maxRetries)) return [3 /*break*/, 8];
4341
+ _a.label = 2;
4342
+ case 2:
4343
+ _a.trys.push([2, 5, , 7]);
4344
+ return [4 /*yield*/, fetch("".concat(this.baseUrl, "/api/ingestion/customEvent"), {
4345
+ method: 'POST',
4346
+ headers: {
4347
+ 'Content-Type': 'application/json',
4348
+ 'Authorization': "Bearer ".concat(this.apiKey)
4349
+ },
4350
+ body: JSON.stringify({
4351
+ name: eventName,
4352
+ properties: eventProperties,
4353
+ sessionId: sessionId,
4354
+ timestamp: new Date().toISOString()
4355
+ })
4356
+ })];
4357
+ case 3:
4358
+ response = _a.sent();
4359
+ if (!response.ok) {
4360
+ throw new Error("Failed to send custom event: ".concat(response.statusText));
4361
+ }
4362
+ return [4 /*yield*/, response.json()];
4363
+ case 4: return [2 /*return*/, _a.sent()];
4364
+ case 5:
4365
+ error_3 = _a.sent();
4366
+ retryCount++;
4367
+ if (retryCount === maxRetries) {
4368
+ console.error('Error sending custom event after max retries:', error_3);
4369
+ throw error_3;
4370
+ }
4371
+ // Exponential backoff
4372
+ return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, Math.pow(2, retryCount) * 1000); })];
4373
+ case 6:
4374
+ // Exponential backoff
4375
+ _a.sent();
4376
+ return [3 /*break*/, 7];
4377
+ case 7: return [3 /*break*/, 1];
4378
+ case 8: return [2 /*return*/];
4379
+ }
4380
+ });
4381
+ });
4382
+ };
4383
+ HumanBehaviorAPI.prototype.sendCustomEvents = function (events, sessionId) {
4384
+ return __awaiter$1(this, void 0, void 0, function () {
4385
+ var maxRetries, retryCount, response, error_4;
4386
+ return __generator(this, function (_a) {
4387
+ switch (_a.label) {
4388
+ case 0:
4389
+ maxRetries = 3;
4390
+ retryCount = 0;
4391
+ _a.label = 1;
4392
+ case 1:
4393
+ if (!(retryCount < maxRetries)) return [3 /*break*/, 8];
4394
+ _a.label = 2;
4395
+ case 2:
4396
+ _a.trys.push([2, 5, , 7]);
4397
+ return [4 /*yield*/, fetch("".concat(this.baseUrl, "/api/ingestion/customEvent/batch"), {
4398
+ method: 'POST',
4399
+ headers: {
4400
+ 'Content-Type': 'application/json',
4401
+ 'Authorization': "Bearer ".concat(this.apiKey)
4402
+ },
4403
+ body: JSON.stringify({
4404
+ events: events.map(function (event) { return (__assign(__assign({}, event), { sessionId: sessionId })); })
4405
+ })
4406
+ })];
4407
+ case 3:
4408
+ response = _a.sent();
4409
+ if (!response.ok) {
4410
+ throw new Error("Failed to send custom events: ".concat(response.statusText));
4411
+ }
4412
+ return [4 /*yield*/, response.json()];
4413
+ case 4: return [2 /*return*/, _a.sent()];
4414
+ case 5:
4415
+ error_4 = _a.sent();
4416
+ retryCount++;
4417
+ if (retryCount === maxRetries) {
4418
+ console.error('Error sending custom events after max retries:', error_4);
4419
+ throw error_4;
4420
+ }
4421
+ // Exponential backoff
4422
+ return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, Math.pow(2, retryCount) * 1000); })];
4423
+ case 6:
4424
+ // Exponential backoff
4425
+ _a.sent();
4426
+ return [3 /*break*/, 7];
4427
+ case 7: return [3 /*break*/, 1];
4428
+ case 8: return [2 /*return*/];
4429
+ }
4430
+ });
4431
+ });
4432
+ };
4433
+ HumanBehaviorAPI.prototype.sendBeaconEvents = function (events, sessionId, isSessionComplete) {
4434
+ if (isSessionComplete === void 0) { isSessionComplete = false; }
4435
+ var data = new URLSearchParams();
4436
+ data.append('events', encodeURIComponent(JSON.stringify(events)));
4437
+ data.append('sessionId', encodeURIComponent(sessionId));
4438
+ data.append('timestamp', encodeURIComponent(Date.now().toString()));
4439
+ data.append('apiKey', encodeURIComponent(this.apiKey));
4440
+ if (isSessionComplete) {
4441
+ console.log('Session complete beacon sending');
4442
+ localStorage.setItem('koalaware_session_complete', Date.now().toString());
4443
+ data.append('sessionComplete', encodeURIComponent('true'));
4444
+ }
4445
+ navigator.sendBeacon("".concat(this.baseUrl, "/api/ingestion/events"), data);
4446
+ // KoalawareTracker.logToStorage(`Sending events beacon: ${this.baseUrl}/api/ingestion/events`);
4447
+ // KoalawareTracker.logToStorage(`Events beacon success: ${success}`);
4448
+ };
4449
+ HumanBehaviorAPI.prototype.sendBeaconSessionComplete = function (sessionId) {
4450
+ var data = new URLSearchParams();
4451
+ data.append('sessionId', sessionId);
4452
+ data.append('apiKey', this.apiKey);
4453
+ data.append('sessionComplete', 'true');
4454
+ navigator.sendBeacon("".concat(this.baseUrl, "/api/ingestion/sessionComplete"), data);
4455
+ // KoalawareTracker.logToStorage(`Sending completion beacon: ${this.baseUrl}/api/ingestion/sessionComplete`);
4456
+ // KoalawareTracker.logToStorage(`Complete beacon success: ${success}`);
4457
+ };
4458
+ HumanBehaviorAPI.prototype.sendBeaconCustomEvent = function (eventName, eventProperties, sessionId) {
4459
+ var data = new URLSearchParams();
4460
+ data.append('name', encodeURIComponent(eventName));
4461
+ data.append('properties', encodeURIComponent(JSON.stringify(eventProperties)));
4462
+ data.append('sessionId', encodeURIComponent(sessionId));
4463
+ data.append('timestamp', encodeURIComponent(new Date().toISOString()));
4464
+ data.append('apiKey', encodeURIComponent(this.apiKey));
4465
+ return navigator.sendBeacon("".concat(this.baseUrl, "/api/ingestion/customEvent"), data);
4466
+ };
4467
+ HumanBehaviorAPI.prototype.sendBeaconCustomEvents = function (events, sessionId) {
4468
+ var data = new URLSearchParams();
4469
+ data.append('events', encodeURIComponent(JSON.stringify(events.map(function (event) { return (__assign(__assign({}, event), { sessionId: sessionId })); }))));
4470
+ data.append('apiKey', encodeURIComponent(this.apiKey));
4471
+ return navigator.sendBeacon("".concat(this.baseUrl, "/api/ingestion/customEvent/batch"), data);
4472
+ };
4473
+ return HumanBehaviorAPI;
4474
+ }());
4475
+
4476
+ // Check if we're in a browser environment
4477
+ var isBrowser = typeof window !== 'undefined';
4478
+ var HumanBehaviorTracker = /** @class */ (function () {
4479
+ function HumanBehaviorTracker(apiKey) {
4480
+ this.eventIngestionQueue = [];
4481
+ this.queueSizeBytes = 0;
4482
+ this.rejectedEvents = [];
4483
+ this.isProcessingRejectedEvents = false;
4484
+ this.userProperties = {};
4485
+ this.isProcessing = false;
4486
+ this.flushInterval = null;
4487
+ this.FLUSH_INTERVAL_MS = 5000; // Flush every 5 seconds
4488
+ this.endUserId = null;
4489
+ this.initialized = false;
4490
+ this.initializationPromise = null;
4491
+ this.api = new HumanBehaviorAPI({
4492
+ apiKey: apiKey,
4493
+ });
4494
+ this.apiKey = apiKey;
4495
+ // Check for existing session ID and last activity time in localStorage
4496
+ var existingSessionId = isBrowser ? localStorage.getItem('human_behavior_session_id') : null;
4497
+ var lastActivity = isBrowser ? localStorage.getItem('human_behavior_last_activity') : null;
4498
+ // If we have a last activity time, check if it's within 30 minutes
4499
+ var thirtyMinutesAgo = Date.now() - (30 * 60 * 1000);
4500
+ var shouldUseExistingSession = lastActivity && parseInt(lastActivity) > thirtyMinutesAgo;
4501
+ this.sessionId = (existingSessionId && shouldUseExistingSession) ? existingSessionId : v1();
4502
+ // Store the session ID if it's new
4503
+ if ((!existingSessionId || !shouldUseExistingSession) && isBrowser) {
4504
+ localStorage.setItem('human_behavior_session_id', this.sessionId);
4505
+ }
4506
+ // Start initialization immediately
4507
+ this.initializationPromise = this.init();
4508
+ }
4509
+ HumanBehaviorTracker.prototype.init = function () {
4510
+ return __awaiter$1(this, void 0, void 0, function () {
4511
+ var userId, _a, sessionId, endUserId, error_1;
4512
+ return __generator(this, function (_b) {
4513
+ switch (_b.label) {
4514
+ case 0:
4515
+ _b.trys.push([0, 2, , 3]);
4516
+ userId = this.getCookie("human_behavior_end_user_id_".concat(this.apiKey));
4517
+ return [4 /*yield*/, this.api.init(this.sessionId, userId)];
4518
+ case 1:
4519
+ _a = _b.sent(), sessionId = _a.sessionId, endUserId = _a.endUserId;
4520
+ this.sessionId = sessionId;
4521
+ this.endUserId = endUserId;
4522
+ this.setCookie("human_behavior_end_user_id_".concat(this.apiKey), endUserId, 365);
4523
+ // Only setup browser-specific handlers when in browser environment
4524
+ if (isBrowser) {
4525
+ this.setupPageUnloadHandler();
4526
+ this.start();
4527
+ this.processRejectedEvents();
4528
+ }
4529
+ else {
4530
+ console.warn('HumanBehaviorTracker initialized in a non-browser environment. Session tracking is disabled.');
4531
+ }
4532
+ this.initialized = true;
4533
+ console.log('HumanBehaviorTracker initialized');
4534
+ return [3 /*break*/, 3];
4535
+ case 2:
4536
+ error_1 = _b.sent();
4537
+ console.error('Failed to initialize HumanBehaviorTracker:', error_1);
4538
+ throw error_1;
4539
+ case 3: return [2 /*return*/];
4540
+ }
4541
+ });
4542
+ });
4543
+ };
4544
+ HumanBehaviorTracker.prototype.ensureInitialized = function () {
4545
+ return __awaiter$1(this, void 0, void 0, function () {
4546
+ return __generator(this, function (_a) {
4547
+ switch (_a.label) {
4548
+ case 0:
4549
+ if (!this.initializationPromise) {
4550
+ throw new Error('HumanBehaviorTracker initialization failed');
4551
+ }
4552
+ return [4 /*yield*/, this.initializationPromise];
4553
+ case 1:
4554
+ _a.sent();
4555
+ return [2 /*return*/];
4556
+ }
4557
+ });
4558
+ });
4559
+ };
4560
+ HumanBehaviorTracker.logToStorage = function (message) {
4561
+ try {
4562
+ var logs = JSON.parse(localStorage.getItem('human_behavior_logs') || '[]');
4563
+ logs.push("".concat(new Date().toISOString(), ": ").concat(message));
4564
+ localStorage.setItem('human_behavior_logs', JSON.stringify(logs));
4565
+ }
4566
+ catch (e) {
4567
+ console.error('Failed to log to storage:', e);
4568
+ }
4569
+ };
4570
+ HumanBehaviorTracker.prototype.setupPageUnloadHandler = function () {
4571
+ var _this = this;
4572
+ if (!isBrowser)
4573
+ return;
4574
+ console.log('Setting up page unload handler');
4575
+ // Handle visibility changes for sending events
4576
+ window.addEventListener('visibilitychange', function () {
4577
+ // Only send events when page becomes hidden
4578
+ if (document.visibilityState === 'hidden') {
4579
+ console.log('Page hidden - sending pending events');
4580
+ _this.api.sendBeaconEvents(_this.eventIngestionQueue, _this.sessionId);
4581
+ }
4582
+ });
4583
+ // Handle actual page unload/close
4584
+ window.addEventListener('beforeunload', function () {
4585
+ // Update last activity time
4586
+ localStorage.setItem('human_behavior_last_activity', Date.now().toString());
4587
+ // Send final events
4588
+ _this.api.sendBeaconEvents(_this.eventIngestionQueue, _this.sessionId);
4589
+ });
4590
+ // Update activity timestamp periodically
4591
+ setInterval(function () {
4592
+ localStorage.setItem('human_behavior_last_activity', Date.now().toString());
4593
+ }, 60000); // Update every minute
4594
+ };
4595
+ HumanBehaviorTracker.prototype.viewLogs = function () {
4596
+ try {
4597
+ var logs = JSON.parse(localStorage.getItem('human_behavior_logs') || '[]');
4598
+ console.log('HumanBehavior Logs:', logs);
4599
+ localStorage.removeItem('human_behavior_logs'); // Clear logs after viewing
4600
+ }
4601
+ catch (e) {
4602
+ console.error('Failed to read logs:', e);
4603
+ }
4604
+ };
4605
+ HumanBehaviorTracker.prototype.identifyUser = function (userProperties) {
4606
+ return __awaiter$1(this, void 0, void 0, function () {
4607
+ return __generator(this, function (_a) {
4608
+ switch (_a.label) {
4609
+ case 0: return [4 /*yield*/, this.ensureInitialized()];
4610
+ case 1:
4611
+ _a.sent();
4612
+ this.userProperties = userProperties;
4613
+ return [4 /*yield*/, this.api.sendUserData(this.endUserId, userProperties, this.sessionId)];
4614
+ case 2:
4615
+ _a.sent();
4616
+ return [2 /*return*/];
4617
+ }
4618
+ });
4619
+ });
4620
+ };
4621
+ HumanBehaviorTracker.prototype.customEvent = function (eventName_1) {
4622
+ return __awaiter$1(this, arguments, void 0, function (eventName, eventProperties) {
4623
+ if (eventProperties === void 0) { eventProperties = {}; }
4624
+ return __generator(this, function (_a) {
4625
+ switch (_a.label) {
4626
+ case 0: return [4 /*yield*/, this.ensureInitialized()];
4627
+ case 1:
4628
+ _a.sent();
4629
+ this.api.sendBeaconCustomEvent(eventName, eventProperties, this.sessionId);
4630
+ return [2 /*return*/];
4631
+ }
4632
+ });
4633
+ });
4634
+ };
4635
+ HumanBehaviorTracker.prototype.start = function () {
4636
+ return __awaiter$1(this, void 0, void 0, function () {
4637
+ var _this = this;
4638
+ return __generator(this, function (_a) {
4639
+ switch (_a.label) {
4640
+ case 0: return [4 /*yield*/, this.ensureInitialized()];
4641
+ case 1:
4642
+ _a.sent();
4643
+ if (!isBrowser)
4644
+ return [2 /*return*/];
4645
+ // Start periodic flushing
4646
+ this.flushInterval = window.setInterval(function () {
4647
+ _this.flush();
4648
+ }, this.FLUSH_INTERVAL_MS);
4649
+ // Start recording
4650
+ record({
4651
+ emit: function (event) {
4652
+ _this.addEvent(event);
4653
+ },
4654
+ });
4655
+ return [2 /*return*/];
4656
+ }
4657
+ });
4658
+ });
4659
+ };
4660
+ HumanBehaviorTracker.prototype.stop = function () {
4661
+ return __awaiter$1(this, void 0, void 0, function () {
4662
+ return __generator(this, function (_a) {
4663
+ switch (_a.label) {
4664
+ case 0: return [4 /*yield*/, this.ensureInitialized()];
4665
+ case 1:
4666
+ _a.sent();
4667
+ if (!isBrowser)
4668
+ return [2 /*return*/];
4669
+ if (this.flushInterval) {
4670
+ clearInterval(this.flushInterval);
4671
+ this.flushInterval = null;
4672
+ }
4673
+ return [2 /*return*/];
4674
+ }
4675
+ });
4676
+ });
4677
+ };
4678
+ HumanBehaviorTracker.prototype.addEvent = function (event) {
4679
+ return __awaiter$1(this, void 0, void 0, function () {
4680
+ var eventSize;
4681
+ return __generator(this, function (_a) {
4682
+ switch (_a.label) {
4683
+ case 0: return [4 /*yield*/, this.ensureInitialized()];
4684
+ case 1:
4685
+ _a.sent();
4686
+ eventSize = new TextEncoder().encode(JSON.stringify(event)).length;
4687
+ this.eventIngestionQueue.push(event);
4688
+ this.queueSizeBytes += eventSize;
4689
+ return [2 /*return*/];
4690
+ }
4691
+ });
4692
+ });
4693
+ };
4694
+ HumanBehaviorTracker.prototype.processRejectedEvents = function () {
4695
+ return __awaiter$1(this, void 0, void 0, function () {
4696
+ var newSessionId;
4697
+ return __generator(this, function (_a) {
4698
+ if (this.isProcessingRejectedEvents || this.rejectedEvents.length === 0)
4699
+ return [2 /*return*/];
4700
+ this.isProcessingRejectedEvents = true;
4701
+ try {
4702
+ newSessionId = v1();
4703
+ if (isBrowser) {
4704
+ localStorage.setItem('human_behavior_session_id', newSessionId);
4705
+ }
4706
+ // Try to send rejected events with new session ID using beacon
4707
+ // sendBeacon returns true if the request was queued successfully
4708
+ this.api.sendBeaconEvents(this.rejectedEvents, newSessionId);
4709
+ // Clear rejected events and update session ID
4710
+ // Note: We can't verify if the beacon data was actually sent,
4711
+ // but we clear the events to prevent duplicate sending attempts
4712
+ this.rejectedEvents = [];
4713
+ this.sessionId = newSessionId;
4714
+ }
4715
+ catch (error) {
4716
+ console.error('Failed to process rejected events:', error);
4717
+ }
4718
+ finally {
4719
+ this.isProcessingRejectedEvents = false;
4720
+ }
4721
+ return [2 /*return*/];
4722
+ });
4723
+ });
4724
+ };
4725
+ HumanBehaviorTracker.prototype.flush = function () {
4726
+ return __awaiter$1(this, void 0, void 0, function () {
4727
+ var eventsToProcess, error_2;
4728
+ var _a;
4729
+ var _b;
4730
+ return __generator(this, function (_c) {
4731
+ switch (_c.label) {
4732
+ case 0:
4733
+ // Prevent concurrent flushes
4734
+ if (this.isProcessing || !this.initialized) {
4735
+ return [2 /*return*/];
4736
+ }
4737
+ this.isProcessing = true;
4738
+ _c.label = 1;
4739
+ case 1:
4740
+ _c.trys.push([1, , 6, 7]);
4741
+ eventsToProcess = this.eventIngestionQueue;
4742
+ this.eventIngestionQueue = [];
4743
+ this.queueSizeBytes = 0;
4744
+ if (!(eventsToProcess.length > 0)) return [3 /*break*/, 5];
4745
+ console.log('Flushing events:', eventsToProcess);
4746
+ _c.label = 2;
4747
+ case 2:
4748
+ _c.trys.push([2, 4, , 5]);
4749
+ return [4 /*yield*/, this.api.sendEvents(eventsToProcess, this.sessionId, this.endUserId)];
4750
+ case 3:
4751
+ _c.sent();
4752
+ return [3 /*break*/, 5];
4753
+ case 4:
4754
+ error_2 = _c.sent();
4755
+ // If we get a 400 error, store events for retry
4756
+ if ((_b = error_2.message) === null || _b === void 0 ? void 0 : _b.includes('ERROR: Session already completed')) {
4757
+ console.log('Session expired, storing events for retry');
4758
+ (_a = this.rejectedEvents).push.apply(_a, eventsToProcess);
4759
+ this.processRejectedEvents();
4760
+ }
4761
+ else {
4762
+ throw error_2;
4763
+ }
4764
+ return [3 /*break*/, 5];
4765
+ case 5: return [3 /*break*/, 7];
4766
+ case 6:
4767
+ this.isProcessing = false;
4768
+ return [7 /*endfinally*/];
4769
+ case 7: return [2 /*return*/];
4770
+ }
4771
+ });
4772
+ });
4773
+ };
4774
+ // Add helper methods for cookie management
4775
+ HumanBehaviorTracker.prototype.setCookie = function (name, value, daysToExpire) {
4776
+ if (!isBrowser)
4777
+ return;
4778
+ var date = new Date();
4779
+ date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
4780
+ var expires = "expires=".concat(date.toUTCString());
4781
+ document.cookie = "".concat(name, "=").concat(value, ";").concat(expires, ";path=/;SameSite=Lax");
4782
+ };
4783
+ HumanBehaviorTracker.prototype.getCookie = function (name) {
4784
+ if (!isBrowser)
4785
+ return null;
4786
+ var nameEQ = name + "=";
4787
+ var ca = document.cookie.split(';');
4788
+ for (var i = 0; i < ca.length; i++) {
4789
+ var c = ca[i];
4790
+ while (c.charAt(0) === ' ')
4791
+ c = c.substring(1, c.length);
4792
+ if (c.indexOf(nameEQ) === 0)
4793
+ return c.substring(nameEQ.length, c.length);
4794
+ }
4795
+ return null;
4796
+ };
4797
+ return HumanBehaviorTracker;
4798
+ }());
4799
+ // Only expose to window object in browser environments
4800
+ if (isBrowser) {
4801
+ window.HumanBehaviorTracker = HumanBehaviorTracker;
4802
+ }
4803
+
4804
+ exports.HumanBehaviorAPI = HumanBehaviorAPI;
4805
+ exports.HumanBehaviorTracker = HumanBehaviorTracker;
4806
+ exports.MAX_CHUNK_SIZE_BYTES = MAX_CHUNK_SIZE_BYTES;
4807
+ exports.default = HumanBehaviorTracker;
4808
+ exports.isChunkSizeExceeded = isChunkSizeExceeded;
4809
+ exports.validateSingleEventSize = validateSingleEventSize;
4810
+ //# sourceMappingURL=index.js.map