@screeb/rrweb 1.0.21 → 2.1.6-screeb.2

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