@screeb/rrweb 1.0.21 → 2.1.6-screeb.1

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