{
  "version": 3,
  "sources": ["../../types/dist/types.js", "../../utils/dist/utils.js", "../../rrweb-snapshot/src/utils.ts", "../../rrweb-snapshot/src/snapshot.ts", "../../rrdom/src/document.ts", "../../rrweb/src/utils.ts", "../../rrweb/src/record/mutation.ts", "../../rrweb/src/record/error-handler.ts", "../../rrweb/src/record/observer.ts", "../../rrweb/src/record/cross-origin-iframe-mirror.ts", "../../rrweb/src/record/iframe-manager.ts", "../../rrweb/src/record/shadow-dom-manager.ts", "../../../node_modules/base64-arraybuffer/dist/base64-arraybuffer.es5.js", "../../rrweb/src/record/observers/canvas/serialize-args.ts", "../../rrweb/src/record/observers/canvas/2d.ts", "../../rrweb/src/record/observers/canvas/canvas.ts", "../../rrweb/src/record/observers/canvas/webgl.ts", "../../rrweb/src/record/observers/canvas/canvas-manager.ts", "../../rrweb/src/record/stylesheet-manager.ts", "../../rrweb/src/record/processed-node-manager.ts", "../../rrweb/src/record/index.ts"],
  "sourcesContent": ["// src/index.ts\nvar EventType = /* @__PURE__ */ function(EventType) {\n\tEventType[EventType[\"DomContentLoaded\"] = 0] = \"DomContentLoaded\";\n\tEventType[EventType[\"Load\"] = 1] = \"Load\";\n\tEventType[EventType[\"FullSnapshot\"] = 2] = \"FullSnapshot\";\n\tEventType[EventType[\"IncrementalSnapshot\"] = 3] = \"IncrementalSnapshot\";\n\tEventType[EventType[\"Meta\"] = 4] = \"Meta\";\n\tEventType[EventType[\"Custom\"] = 5] = \"Custom\";\n\tEventType[EventType[\"Plugin\"] = 6] = \"Plugin\";\n\tEventType[EventType[\"Asset\"] = 7] = \"Asset\";\n\tEventType[EventType[\"Annotation\"] = 8] = \"Annotation\";\n\treturn EventType;\n}({});\nvar IncrementalSource = /* @__PURE__ */ function(IncrementalSource) {\n\tIncrementalSource[IncrementalSource[\"Mutation\"] = 0] = \"Mutation\";\n\tIncrementalSource[IncrementalSource[\"MouseMove\"] = 1] = \"MouseMove\";\n\tIncrementalSource[IncrementalSource[\"MouseInteraction\"] = 2] = \"MouseInteraction\";\n\tIncrementalSource[IncrementalSource[\"Scroll\"] = 3] = \"Scroll\";\n\tIncrementalSource[IncrementalSource[\"ViewportResize\"] = 4] = \"ViewportResize\";\n\tIncrementalSource[IncrementalSource[\"Input\"] = 5] = \"Input\";\n\tIncrementalSource[IncrementalSource[\"TouchMove\"] = 6] = \"TouchMove\";\n\tIncrementalSource[IncrementalSource[\"MediaInteraction\"] = 7] = \"MediaInteraction\";\n\tIncrementalSource[IncrementalSource[\"StyleSheetRule\"] = 8] = \"StyleSheetRule\";\n\tIncrementalSource[IncrementalSource[\"CanvasMutation\"] = 9] = \"CanvasMutation\";\n\tIncrementalSource[IncrementalSource[\"Font\"] = 10] = \"Font\";\n\tIncrementalSource[IncrementalSource[\"Log\"] = 11] = \"Log\";\n\tIncrementalSource[IncrementalSource[\"Drag\"] = 12] = \"Drag\";\n\tIncrementalSource[IncrementalSource[\"StyleDeclaration\"] = 13] = \"StyleDeclaration\";\n\tIncrementalSource[IncrementalSource[\"Selection\"] = 14] = \"Selection\";\n\tIncrementalSource[IncrementalSource[\"AdoptedStyleSheet\"] = 15] = \"AdoptedStyleSheet\";\n\tIncrementalSource[IncrementalSource[\"CustomElement\"] = 16] = \"CustomElement\";\n\treturn IncrementalSource;\n}({});\nvar MouseInteractions = /* @__PURE__ */ function(MouseInteractions) {\n\tMouseInteractions[MouseInteractions[\"MouseUp\"] = 0] = \"MouseUp\";\n\tMouseInteractions[MouseInteractions[\"MouseDown\"] = 1] = \"MouseDown\";\n\tMouseInteractions[MouseInteractions[\"Click\"] = 2] = \"Click\";\n\tMouseInteractions[MouseInteractions[\"ContextMenu\"] = 3] = \"ContextMenu\";\n\tMouseInteractions[MouseInteractions[\"DblClick\"] = 4] = \"DblClick\";\n\tMouseInteractions[MouseInteractions[\"Focus\"] = 5] = \"Focus\";\n\tMouseInteractions[MouseInteractions[\"Blur\"] = 6] = \"Blur\";\n\tMouseInteractions[MouseInteractions[\"TouchStart\"] = 7] = \"TouchStart\";\n\tMouseInteractions[MouseInteractions[\"TouchMove_Departed\"] = 8] = \"TouchMove_Departed\";\n\tMouseInteractions[MouseInteractions[\"TouchEnd\"] = 9] = \"TouchEnd\";\n\tMouseInteractions[MouseInteractions[\"TouchCancel\"] = 10] = \"TouchCancel\";\n\treturn MouseInteractions;\n}({});\nvar PointerTypes = /* @__PURE__ */ function(PointerTypes) {\n\tPointerTypes[PointerTypes[\"Mouse\"] = 0] = \"Mouse\";\n\tPointerTypes[PointerTypes[\"Pen\"] = 1] = \"Pen\";\n\tPointerTypes[PointerTypes[\"Touch\"] = 2] = \"Touch\";\n\treturn PointerTypes;\n}({});\nvar CanvasContext = /* @__PURE__ */ function(CanvasContext) {\n\tCanvasContext[CanvasContext[\"2D\"] = 0] = \"2D\";\n\tCanvasContext[CanvasContext[\"WebGL\"] = 1] = \"WebGL\";\n\tCanvasContext[CanvasContext[\"WebGL2\"] = 2] = \"WebGL2\";\n\treturn CanvasContext;\n}({});\nvar MediaInteractions = /* @__PURE__ */ function(MediaInteractions) {\n\tMediaInteractions[MediaInteractions[\"Play\"] = 0] = \"Play\";\n\tMediaInteractions[MediaInteractions[\"Pause\"] = 1] = \"Pause\";\n\tMediaInteractions[MediaInteractions[\"Seeked\"] = 2] = \"Seeked\";\n\tMediaInteractions[MediaInteractions[\"VolumeChange\"] = 3] = \"VolumeChange\";\n\tMediaInteractions[MediaInteractions[\"RateChange\"] = 4] = \"RateChange\";\n\treturn MediaInteractions;\n}({});\nvar ReplayerEvents = /* @__PURE__ */ function(ReplayerEvents) {\n\tReplayerEvents[\"Start\"] = \"start\";\n\tReplayerEvents[\"Pause\"] = \"pause\";\n\t/**\n\t* @deprecated use Play instead\n\t*/\n\tReplayerEvents[\"Resume\"] = \"resume\";\n\tReplayerEvents[\"Resize\"] = \"resize\";\n\tReplayerEvents[\"Finish\"] = \"finish\";\n\tReplayerEvents[\"FullsnapshotRebuilded\"] = \"fullsnapshot-rebuilded\";\n\tReplayerEvents[\"LoadStylesheetStart\"] = \"load-stylesheet-start\";\n\tReplayerEvents[\"LoadStylesheetEnd\"] = \"load-stylesheet-end\";\n\tReplayerEvents[\"SkipStart\"] = \"skip-start\";\n\tReplayerEvents[\"SkipEnd\"] = \"skip-end\";\n\tReplayerEvents[\"MouseInteraction\"] = \"mouse-interaction\";\n\tReplayerEvents[\"EventCast\"] = \"event-cast\";\n\tReplayerEvents[\"CustomEvent\"] = \"custom-event\";\n\tReplayerEvents[\"Annotation\"] = \"annotation\";\n\tReplayerEvents[\"Flush\"] = \"flush\";\n\tReplayerEvents[\"StateChange\"] = \"state-change\";\n\tReplayerEvents[\"PlayBack\"] = \"play-back\";\n\tReplayerEvents[\"Destroy\"] = \"destroy\";\n\treturn ReplayerEvents;\n}({});\nvar NodeType = /* @__PURE__ */ function(NodeType) {\n\tNodeType[NodeType[\"Document\"] = 0] = \"Document\";\n\tNodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\n\tNodeType[NodeType[\"Element\"] = 2] = \"Element\";\n\tNodeType[NodeType[\"Text\"] = 3] = \"Text\";\n\tNodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\n\tNodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\n\treturn NodeType;\n}({});\nexport { CanvasContext, EventType, IncrementalSource, MediaInteractions, MouseInteractions, NodeType, PointerTypes, ReplayerEvents };\n\n//# sourceMappingURL=types.js.map", "// src/index.ts\nvar testableAccessors = {\n\tNode: [\n\t\t\"childNodes\",\n\t\t\"parentNode\",\n\t\t\"parentElement\",\n\t\t\"textContent\",\n\t\t\"ownerDocument\",\n\t\t\"firstChild\",\n\t\t\"lastChild\",\n\t\t\"nextSibling\",\n\t\t\"previousSibling\"\n\t],\n\tShadowRoot: [\"host\", \"styleSheets\"],\n\tElement: [\n\t\t\"shadowRoot\",\n\t\t\"querySelector\",\n\t\t\"querySelectorAll\"\n\t],\n\tMutationObserver: []\n};\nvar testableMethods = {\n\tNode: [\"contains\", \"getRootNode\"],\n\tShadowRoot: [\"getSelection\"],\n\tElement: [],\n\tMutationObserver: [\"constructor\"]\n};\nvar untaintedBasePrototype = {};\nvar untaintedBaseIframeCleanup = {};\nvar mutationObserverUsers = 0;\nfunction angularZoneUnpatchedAlternative(key) {\n\tconst angularUnpatchedVersionSymbol = globalThis?.Zone?.__symbol__?.(key);\n\tif (angularUnpatchedVersionSymbol && globalThis[angularUnpatchedVersionSymbol]) return globalThis[angularUnpatchedVersionSymbol];\n\telse return;\n}\nfunction getUntaintedPrototype(key) {\n\tif (untaintedBasePrototype[key]) return untaintedBasePrototype[key];\n\tconst defaultObj = angularZoneUnpatchedAlternative(key) || globalThis[key];\n\tconst defaultPrototype = defaultObj.prototype;\n\tconst accessorNames = key in testableAccessors ? testableAccessors[key] : void 0;\n\tconst isUntaintedAccessors = Boolean(accessorNames && accessorNames.every((accessor) => Boolean(Object.getOwnPropertyDescriptor(defaultPrototype, accessor)?.get?.toString().includes(\"[native code]\"))));\n\tconst methodNames = key in testableMethods ? testableMethods[key] : void 0;\n\tconst isUntaintedMethods = Boolean(methodNames && methodNames.every((method) => typeof defaultPrototype[method] === \"function\" && defaultPrototype[method]?.toString().includes(\"[native code]\")));\n\tif (isUntaintedAccessors && isUntaintedMethods) {\n\t\tuntaintedBasePrototype[key] = defaultObj.prototype;\n\t\treturn defaultObj.prototype;\n\t}\n\ttry {\n\t\tconst iframeEl = document.createElement(\"iframe\");\n\t\tiframeEl.style.display = \"none\";\n\t\tdocument.body.appendChild(iframeEl);\n\t\tconst win = iframeEl.contentWindow;\n\t\tif (!win) return defaultObj.prototype;\n\t\tconst untaintedObject = win[key].prototype;\n\t\tif (!untaintedObject) {\n\t\t\tiframeEl.remove();\n\t\t\treturn defaultPrototype;\n\t\t}\n\t\tconst ua = navigator.userAgent;\n\t\tif (ua.includes(\"Safari\") && !ua.includes(\"Chrome\")) {\n\t\t\tiframeEl.classList.add(\"rr-block\");\n\t\t\tiframeEl.setAttribute(\"__rrwebUntaintedMutationObserver\", \"\");\n\t\t\tuntaintedBaseIframeCleanup[key] = () => iframeEl.remove();\n\t\t} else iframeEl.remove();\n\t\treturn untaintedBasePrototype[key] = untaintedObject;\n\t} catch {\n\t\treturn defaultPrototype;\n\t}\n}\nvar untaintedAccessorCache = {};\nfunction getUntaintedAccessor(key, instance, accessor) {\n\tconst cached = untaintedAccessorCache[key]?.[accessor];\n\tif (cached) return cached.call(instance);\n\tconst untaintedPrototype = getUntaintedPrototype(key);\n\tconst untaintedAccessor = Object.getOwnPropertyDescriptor(untaintedPrototype, accessor)?.get;\n\tif (!untaintedAccessor) return instance[accessor];\n\t(untaintedAccessorCache[key] ||= {})[accessor] = untaintedAccessor;\n\treturn untaintedAccessor.call(instance);\n}\nvar untaintedMethodCache = {};\nfunction getUntaintedMethod(key, instance, method) {\n\tconst cacheKey = `${key}.${String(method)}`;\n\tif (untaintedMethodCache[cacheKey]) return untaintedMethodCache[cacheKey].bind(instance);\n\tconst untaintedMethod = getUntaintedPrototype(key)[method];\n\tif (typeof untaintedMethod !== \"function\") return instance[method];\n\tuntaintedMethodCache[cacheKey] = untaintedMethod;\n\treturn untaintedMethod.bind(instance);\n}\nfunction ownerDocument(n) {\n\treturn getUntaintedAccessor(\"Node\", n, \"ownerDocument\");\n}\nfunction childNodes(n) {\n\treturn getUntaintedAccessor(\"Node\", n, \"childNodes\");\n}\nfunction parentNode(n) {\n\treturn getUntaintedAccessor(\"Node\", n, \"parentNode\");\n}\nfunction parentElement(n) {\n\treturn getUntaintedAccessor(\"Node\", n, \"parentElement\");\n}\nfunction textContent(n) {\n\treturn getUntaintedAccessor(\"Node\", n, \"textContent\");\n}\nfunction firstChild(n) {\n\treturn getUntaintedAccessor(\"Node\", n, \"firstChild\");\n}\nfunction lastChild(n) {\n\treturn getUntaintedAccessor(\"Node\", n, \"lastChild\");\n}\nfunction nextSibling(n) {\n\treturn getUntaintedAccessor(\"Node\", n, \"nextSibling\");\n}\nfunction previousSibling(n) {\n\treturn getUntaintedAccessor(\"Node\", n, \"previousSibling\");\n}\nfunction contains(n, other) {\n\treturn getUntaintedMethod(\"Node\", n, \"contains\")(other);\n}\nfunction getRootNode(n) {\n\treturn getUntaintedMethod(\"Node\", n, \"getRootNode\")();\n}\nfunction host(n) {\n\tif (!n || !(\"host\" in n)) return null;\n\treturn getUntaintedAccessor(\"ShadowRoot\", n, \"host\");\n}\nfunction styleSheets(n) {\n\treturn n.styleSheets;\n}\nfunction shadowRoot(n) {\n\tif (!n || !(\"shadowRoot\" in n)) return null;\n\treturn getUntaintedAccessor(\"Element\", n, \"shadowRoot\");\n}\nfunction querySelector(n, selectors) {\n\treturn getUntaintedAccessor(\"Element\", n, \"querySelector\")(selectors);\n}\nfunction querySelectorAll(n, selectors) {\n\treturn getUntaintedAccessor(\"Element\", n, \"querySelectorAll\")(selectors);\n}\nfunction mutationObserverCtor() {\n\tconst prototype = getUntaintedPrototype(\"MutationObserver\");\n\tmutationObserverUsers++;\n\tlet stopCalled = false;\n\treturn [prototype.constructor, () => {\n\t\tif (stopCalled) return;\n\t\tstopCalled = true;\n\t\tif (--mutationObserverUsers !== 0) return;\n\t\tconst cleanup = untaintedBaseIframeCleanup[\"MutationObserver\"];\n\t\tif (!cleanup) return;\n\t\ttry {\n\t\t\tcleanup();\n\t\t} finally {\n\t\t\tdelete untaintedBasePrototype[\"MutationObserver\"];\n\t\t\tdelete untaintedBaseIframeCleanup[\"MutationObserver\"];\n\t\t}\n\t}];\n}\nvar nowTimestamp = Date.now;\nif (!/*@__PURE__*/ /[1-9][0-9]{12}/.test(Date.now().toString())) nowTimestamp = () => (/* @__PURE__ */ new Date()).getTime();\nfunction patch(source, name, replacement) {\n\ttry {\n\t\tif (!(name in source)) return () => {};\n\t\tconst original = source[name];\n\t\tconst wrapped = replacement(original);\n\t\tif (typeof wrapped === \"function\") {\n\t\t\twrapped.prototype = wrapped.prototype || {};\n\t\t\tObject.defineProperties(wrapped, { __rrweb_original__: {\n\t\t\t\tenumerable: false,\n\t\t\t\tvalue: original\n\t\t\t} });\n\t\t}\n\t\tsource[name] = wrapped;\n\t\treturn () => {\n\t\t\tsource[name] = original;\n\t\t};\n\t} catch {\n\t\treturn () => {};\n\t}\n}\nvar src_default = {\n\townerDocument,\n\tchildNodes,\n\tparentNode,\n\tparentElement,\n\ttextContent,\n\tfirstChild,\n\tlastChild,\n\tnextSibling,\n\tpreviousSibling,\n\tcontains,\n\tgetRootNode,\n\thost,\n\tstyleSheets,\n\tshadowRoot,\n\tquerySelector,\n\tquerySelectorAll,\n\tnowTimestamp,\n\tmutationObserverCtor,\n\tpatch\n};\nexport { childNodes, contains, src_default as default, firstChild, getRootNode, getUntaintedAccessor, getUntaintedMethod, getUntaintedPrototype, host, lastChild, mutationObserverCtor, nextSibling, nowTimestamp, ownerDocument, parentElement, parentNode, patch, previousSibling, querySelector, querySelectorAll, shadowRoot, styleSheets, textContent };\n\n//# sourceMappingURL=utils.js.map", "/**\n * Legacy shared utility module.\n *\n * This file currently contains helpers used by both snapshot and rebuild paths\n * and is also part of the public API surface, re-exported from index.ts.\n *\n * Migration intent:\n * - snapshot.ts should consume snapshot-domain helpers via snapshot-utils.ts\n * - rebuild.ts should consume rebuild-domain helpers via rebuild-utils.ts\n * - when safe, split internals into snapshot-only / rebuild-only / shared\n *   modules while keeping this module as a compatibility shim for external users\n */\nimport type {\n  idNodeMap,\n  MaskInputFn,\n  MaskInputOptions,\n  nodeMetaMap,\n} from './types';\n\nimport { NodeType } from '@rrweb/types';\nimport type {\n  IMirror,\n  serializedNodeWithId,\n  serializedNode,\n  documentNode,\n  documentTypeNode,\n  textNode,\n  elementNode,\n} from '@rrweb/types';\nimport dom from '@rrweb/utils';\n\nexport function isElement(n: Node): n is Element {\n  return n.nodeType === n.ELEMENT_NODE;\n}\n\nexport function isShadowRoot(n: Node): n is ShadowRoot {\n  const hostEl: Element | null =\n    // anchor and textarea elements also have a `host` property\n    // but only shadow roots have a `mode` property\n    (n && 'host' in n && 'mode' in n && dom.host(n as ShadowRoot)) || null;\n  return Boolean(\n    hostEl && 'shadowRoot' in hostEl && dom.shadowRoot(hostEl) === n,\n  );\n}\n\n/**\n * To fix the issue https://github.com/rrweb-io/rrweb/issues/933.\n * Some websites use polyfilled shadow dom and this function is used to detect this situation.\n */\nexport function isNativeShadowDom(shadowRoot: ShadowRoot): boolean {\n  return Object.prototype.toString.call(shadowRoot) === '[object ShadowRoot]';\n}\n\n/**\n * Browsers sometimes destructively modify the css rules they receive.\n * This function tries to rectify the modifications the browser made to make it more cross platform compatible.\n * @param cssText - output of `CSSStyleRule.cssText`\n * @returns `cssText` with browser inconsistencies fixed.\n */\nfunction fixBrowserCompatibilityIssuesInCSS(cssText: string): string {\n  /**\n   * Chrome outputs `-webkit-background-clip` as `background-clip` in `CSSStyleRule.cssText`.\n   * But then Chrome ignores `background-clip` as css input.\n   * Re-introduce `-webkit-background-clip` to fix this issue.\n   */\n  if (\n    cssText.includes(' background-clip: text;') &&\n    !cssText.includes(' -webkit-background-clip: text;')\n  ) {\n    cssText = cssText.replace(\n      /\\sbackground-clip:\\s*text;/g,\n      ' -webkit-background-clip: text; background-clip: text;',\n    );\n  }\n  return cssText;\n}\n\n// Remove this declaration once typescript has added `CSSImportRule.supportsText` to the lib.\ndeclare interface CSSImportRule extends CSSRule {\n  readonly href: string;\n  readonly layerName: string | null;\n  readonly media: MediaList;\n  readonly styleSheet: CSSStyleSheet;\n  /**\n   * experimental API, currently only supported in firefox\n   * https://developer.mozilla.org/en-US/docs/Web/API/CSSImportRule/supportsText\n   */\n  readonly supportsText?: string | null;\n}\n\n/**\n * Browsers sometimes incorrectly escape `@import` on `.cssText` statements.\n * This function tries to correct the escaping.\n * more info: https://bugs.chromium.org/p/chromium/issues/detail?id=1472259\n * @param cssImportRule\n * @returns `cssText` with browser inconsistencies fixed, or null if not applicable.\n */\nexport function escapeImportStatement(rule: CSSImportRule): string {\n  const { cssText } = rule;\n  if (cssText.split('\"').length < 3) return cssText;\n\n  const statement = ['@import', `url(${JSON.stringify(rule.href)})`];\n  if (rule.layerName === '') {\n    statement.push(`layer`);\n  } else if (rule.layerName) {\n    statement.push(`layer(${rule.layerName})`);\n  }\n  if (rule.supportsText) {\n    statement.push(`supports(${rule.supportsText})`);\n  }\n  if (rule.media.length) {\n    statement.push(rule.media.mediaText);\n  }\n  return statement.join(' ') + ';';\n}\n\n/*\n * serialize the css rules from the .sheet property\n * for <link rel=\"stylesheet\"> elements, this is the only way of getting the rules without a FETCH\n * for <style> elements, this is less preferable to looking at childNodes[0].textContent\n * (which will include vendor prefixed rules which may not be used or visible to the recorded browser,\n * but which might be needed by the replayer browser)\n * however, at snapshot time, we don't know whether the style element has suffered\n * any programmatic manipulation prior to the snapshot, in which case the .sheet would be more up to date\n */\nexport function stringifyStylesheet(s: CSSStyleSheet): string | null {\n  try {\n    const rules = s.rules || s.cssRules;\n    if (!rules) {\n      return null;\n    }\n    let sheetHref = s.href;\n    if (!sheetHref && s.ownerNode) {\n      // an inline <style> element\n      sheetHref = s.ownerNode.baseURI;\n    }\n    const stringifiedRules = Array.from(rules, (rule: CSSRule) =>\n      stringifyRule(rule, sheetHref),\n    ).join('');\n    return fixBrowserCompatibilityIssuesInCSS(stringifiedRules);\n  } catch (error) {\n    return null;\n  }\n}\n\nexport function stringifyRule(rule: CSSRule, sheetHref: string | null): string {\n  if (isCSSImportRule(rule)) {\n    let importStringified;\n    try {\n      importStringified =\n        // for same-origin stylesheets,\n        // we can access the imported stylesheet rules directly\n        stringifyStylesheet(rule.styleSheet) ||\n        // work around browser issues with the raw string `@import url(...)` statement\n        escapeImportStatement(rule);\n    } catch (error) {\n      importStringified = rule.cssText;\n    }\n    if (rule.styleSheet.href) {\n      // url()s within the imported stylesheet are relative to _that_ sheet's href\n      return absolutifyURLs(importStringified, rule.styleSheet.href);\n    }\n    return importStringified;\n  } else {\n    let ruleStringified = rule.cssText;\n    if (isCSSStyleRule(rule) && rule.selectorText.includes(':')) {\n      // Safari does not escape selectors with : properly\n      // see https://bugs.webkit.org/show_bug.cgi?id=184604\n      ruleStringified = fixSafariColons(ruleStringified);\n    }\n    if (sheetHref) {\n      return absolutifyURLs(ruleStringified, sheetHref);\n    }\n    return ruleStringified;\n  }\n}\n\nexport function fixSafariColons(cssStringified: string): string {\n  // Replace e.g. [aa:bb] with [aa\\\\:bb]\n  const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\n  return cssStringified.replace(regex, '$1\\\\$2');\n}\n\nexport function isCSSImportRule(rule: CSSRule): rule is CSSImportRule {\n  return 'styleSheet' in rule;\n}\n\nexport function isCSSStyleRule(rule: CSSRule): rule is CSSStyleRule {\n  return 'selectorText' in rule;\n}\n\nexport class Mirror implements IMirror<Node> {\n  private idNodeMap: idNodeMap = new Map();\n  private nodeMetaMap: nodeMetaMap = new WeakMap();\n\n  getId(n: Node | undefined | null): number {\n    if (!n) return -1;\n\n    const id = this.getMeta(n)?.id;\n\n    // if n is not a serialized Node, use -1 as its id.\n    return id ?? -1;\n  }\n\n  getNode(id: number): Node | null {\n    return this.idNodeMap.get(id) || null;\n  }\n\n  getIds(): number[] {\n    return Array.from(this.idNodeMap.keys());\n  }\n\n  getMeta(n: Node): serializedNodeWithId | null {\n    return this.nodeMetaMap.get(n) || null;\n  }\n\n  // removes the node from idNodeMap\n  // doesn't remove the node from nodeMetaMap\n  removeNodeFromMap(n: Node) {\n    const id = this.getId(n);\n    this.idNodeMap.delete(id);\n\n    if (n.childNodes) {\n      n.childNodes.forEach((childNode) =>\n        this.removeNodeFromMap(childNode as unknown as Node),\n      );\n    }\n\n    const shadowRoot = dom.shadowRoot(n);\n    if (shadowRoot) {\n      this.removeNodeFromMap(shadowRoot);\n    }\n  }\n  has(id: number): boolean {\n    return this.idNodeMap.has(id);\n  }\n\n  hasNode(node: Node): boolean {\n    return this.nodeMetaMap.has(node);\n  }\n\n  add(n: Node, meta: serializedNodeWithId) {\n    const id = meta.id;\n    this.idNodeMap.set(id, n);\n    this.nodeMetaMap.set(n, meta);\n  }\n\n  replace(id: number, n: Node) {\n    const oldNode = this.getNode(id);\n    if (oldNode) {\n      const meta = this.nodeMetaMap.get(oldNode);\n      if (meta) this.nodeMetaMap.set(n, meta);\n    }\n    this.idNodeMap.set(id, n);\n  }\n\n  reset() {\n    this.idNodeMap = new Map();\n    this.nodeMetaMap = new WeakMap();\n  }\n}\n\nexport function createMirror(): Mirror {\n  return new Mirror();\n}\n\nexport function maskInputValue({\n  element,\n  maskInputOptions,\n  tagName,\n  type,\n  value,\n  maskInputFn,\n}: {\n  element: HTMLElement;\n  maskInputOptions: MaskInputOptions;\n  tagName: string;\n  type: string | null;\n  value: string | null;\n  maskInputFn?: MaskInputFn;\n}): string {\n  let text = value || '';\n  const actualType = type && toLowerCase(type);\n\n  if (\n    maskInputOptions[tagName.toLowerCase() as keyof MaskInputOptions] ||\n    (actualType && maskInputOptions[actualType as keyof MaskInputOptions])\n  ) {\n    if (maskInputFn) {\n      text = maskInputFn(text, element);\n    } else {\n      text = '*'.repeat(text.length);\n    }\n  }\n  return text;\n}\n\nexport function toLowerCase<T extends string>(str: T): Lowercase<T> {\n  return str.toLowerCase() as unknown as Lowercase<T>;\n}\n\nconst ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';\ntype PatchedGetImageData = {\n  [ORIGINAL_ATTRIBUTE_NAME]: CanvasImageData['getImageData'];\n} & CanvasImageData['getImageData'];\n\nexport function is2DCanvasBlank(canvas: HTMLCanvasElement): boolean {\n  const ctx = canvas.getContext('2d');\n  if (!ctx) return true;\n\n  const chunkSize = 50;\n\n  // get chunks of the canvas and check if it is blank\n  for (let x = 0; x < canvas.width; x += chunkSize) {\n    for (let y = 0; y < canvas.height; y += chunkSize) {\n      // eslint-disable-next-line @typescript-eslint/unbound-method\n      const getImageData = ctx.getImageData as PatchedGetImageData;\n      const originalGetImageData =\n        ORIGINAL_ATTRIBUTE_NAME in getImageData\n          ? getImageData[ORIGINAL_ATTRIBUTE_NAME]\n          : getImageData;\n      // by getting the canvas in chunks we avoid an expensive\n      // `getImageData` call that retrieves everything\n      // even if we can already tell from the first chunk(s) that\n      // the canvas isn't blank\n      const pixelBuffer = new Uint32Array(\n        // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access\n        originalGetImageData.call(\n          ctx,\n          x,\n          y,\n          Math.min(chunkSize, canvas.width - x),\n          Math.min(chunkSize, canvas.height - y),\n        ).data.buffer,\n      );\n      if (pixelBuffer.some((pixel) => pixel !== 0)) return false;\n    }\n  }\n  return true;\n}\n\nexport function isNodeMetaEqual(a: serializedNode, b: serializedNode): boolean {\n  if (!a || !b || a.type !== b.type) return false;\n  if (a.type === NodeType.Document)\n    return a.compatMode === (b as documentNode).compatMode;\n  else if (a.type === NodeType.DocumentType)\n    return (\n      a.name === (b as documentTypeNode).name &&\n      a.publicId === (b as documentTypeNode).publicId &&\n      a.systemId === (b as documentTypeNode).systemId\n    );\n  else if (\n    a.type === NodeType.Comment ||\n    a.type === NodeType.Text ||\n    a.type === NodeType.CDATA\n  )\n    return a.textContent === (b as textNode).textContent;\n  else if (a.type === NodeType.Element)\n    return (\n      a.tagName === (b as elementNode).tagName &&\n      JSON.stringify(a.attributes) ===\n        JSON.stringify((b as elementNode).attributes) &&\n      a.isSVG === (b as elementNode).isSVG &&\n      a.needBlock === (b as elementNode).needBlock\n    );\n  return false;\n}\n\n/**\n * Get the type of an input element.\n * This takes care of the case where a password input is changed to a text input.\n * In this case, we continue to consider this of type password, in order to avoid leaking sensitive data\n * where passwords should be masked.\n */\nexport function getInputType(element: HTMLElement): Lowercase<string> | null {\n  // when omitting the type of input element(e.g. <input />), the type is treated as text\n  const type = (element as HTMLInputElement).type;\n\n  return element.hasAttribute('data-rr-is-password')\n    ? 'password'\n    : type\n    ? // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n      toLowerCase(type)\n    : null;\n}\n\n/**\n * Extracts the file extension from an a path, considering search parameters and fragments.\n * @param path - Path to file\n * @param baseURL - [optional] Base URL of the page, used to resolve relative paths. Defaults to current page URL.\n */\nexport function extractFileExtension(\n  path: string,\n  baseURL?: string,\n): string | null {\n  let url;\n  try {\n    url = new URL(path, baseURL ?? window.location.href);\n  } catch (err) {\n    return null;\n  }\n  const regex = /\\.([0-9a-z]+)(?:$)/i;\n  const match = url.pathname.match(regex);\n  return match?.[1] ?? null;\n}\n\nfunction extractOrigin(url: string): string {\n  let origin = '';\n  if (url.indexOf('//') > -1) {\n    origin = url.split('/').slice(0, 3).join('/');\n  } else {\n    origin = url.split('/')[0];\n  }\n  origin = origin.split('?')[0];\n  return origin;\n}\n\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\nconst URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\\/\\//i;\nconst URL_WWW_MATCH = /^www\\..*/i;\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\nconst BLOB_URI = /^blob:/i;\nexport function absolutifyURLs(cssText: string | null, href: string): string {\n  return (cssText || '').replace(\n    URL_IN_CSS_REF,\n    (\n      origin: string,\n      quote1: string,\n      path1: string,\n      quote2: string,\n      path2: string,\n      path3: string,\n    ) => {\n      const filePath = path1 || path2 || path3;\n      const maybeQuote = quote1 || quote2 || '';\n      if (!filePath) {\n        return origin;\n      }\n      if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {\n        return `url(${maybeQuote}${filePath}${maybeQuote})`;\n      }\n      if (DATA_URI.test(filePath) || BLOB_URI.test(filePath)) {\n        return `url(${maybeQuote}${filePath}${maybeQuote})`;\n      }\n      if (filePath[0] === '#') {\n        // fragment-only urls refer to the current document, not the stylesheet\n        return `url(${maybeQuote}${filePath}${maybeQuote})`;\n      }\n      if (filePath[0] === '/') {\n        return `url(${maybeQuote}${\n          extractOrigin(href) + filePath\n        }${maybeQuote})`;\n      }\n      const filePathNoHash = filePath.split('#')[0];\n      const maybeHash = filePath.substring(filePathNoHash.length);\n      const stack = href.split('#')[0].split('/');\n      const parts = filePathNoHash.split('/');\n      stack.pop();\n      for (const part of parts) {\n        if (part === '.') {\n          continue;\n        } else if (part === '..') {\n          stack.pop();\n        } else {\n          stack.push(part);\n        }\n      }\n      return `url(${maybeQuote}${stack.join('/')}${maybeHash}${maybeQuote})`;\n    },\n  );\n}\n\nconst cssNormalizeBase = '(?:/\\\\*[^*]*\\\\*/)|[\\\\s;]'; // whitespace\nconst cssNormalizeRe = new RegExp(`${cssNormalizeBase}|\\\\b(0)px?`, 'g');\nconst cssNormalizeReNoPx = new RegExp(cssNormalizeBase, 'g');\n\n/**\n * Intention is to normalize by remove spaces, semicolons and CSS comments\n * so that we can compare css as authored vs. output of stringifyStylesheet\n */\nexport function normalizeCssString(\n  cssText: string,\n  /**\n   * _testNoPxNorm: only used as part of the 'substring matching going from many to none'\n   * test case so that it will trigger a failure if the conditions that let to the creation of that test arise again\n   */\n  _testNoPxNorm = false,\n): string {\n  return _testNoPxNorm\n    ? cssText.replace(cssNormalizeReNoPx, '')\n    : cssText.replace(cssNormalizeRe, '$1');\n}\n\n/**\n * Maps the output of stringifyStylesheet to individual text nodes of a <style> element\n * which occurs when javascript is used to append to the style element\n * and may also occur when browsers opt to break up large text nodes\n * performance needs to be considered, see e.g. #1603\n */\nexport function splitCssText(\n  cssText: string,\n  style: HTMLStyleElement,\n  _testNoPxNorm = false,\n): string[] {\n  const childNodes = Array.from(style.childNodes);\n  const splits: string[] = [];\n  let iterCount = 0;\n  if (childNodes.length > 1 && cssText && typeof cssText === 'string') {\n    let cssTextNorm = normalizeCssString(cssText, _testNoPxNorm);\n    const normFactor = cssTextNorm.length / cssText.length;\n    for (let i = 1; i < childNodes.length; i++) {\n      if (\n        childNodes[i].textContent &&\n        typeof childNodes[i].textContent === 'string'\n      ) {\n        const textContentNorm = normalizeCssString(\n          childNodes[i].textContent!,\n          _testNoPxNorm,\n        );\n        const jLimit = 100; // how many iterations for the first part of searching\n        let j = 3;\n        for (; j < textContentNorm.length; j++) {\n          if (\n            // keep consuming css identifiers (to get a decent chunk more quickly)\n            textContentNorm[j].match(/[a-zA-Z0-9]/) ||\n            // substring needs to be unique to this section\n            textContentNorm.indexOf(textContentNorm.substring(0, j), 1) !== -1\n          ) {\n            continue;\n          }\n          break;\n        }\n        for (; j < textContentNorm.length; j++) {\n          let startSubstring = textContentNorm.substring(0, j);\n          // this substring should appears only once in overall text too\n          let cssNormSplits = cssTextNorm.split(startSubstring);\n          let splitNorm = -1;\n          if (cssNormSplits.length === 2) {\n            splitNorm = cssNormSplits[0].length;\n          } else if (\n            cssNormSplits.length > 2 &&\n            cssNormSplits[0] === '' &&\n            childNodes[i - 1].textContent !== ''\n          ) {\n            // this childNode has same starting content as previous\n            splitNorm = cssTextNorm.indexOf(startSubstring, 1);\n          } else if (cssNormSplits.length === 1) {\n            // try to roll back to get multiple matches again\n            startSubstring = startSubstring.substring(\n              0,\n              startSubstring.length - 1,\n            );\n            cssNormSplits = cssTextNorm.split(startSubstring);\n            if (cssNormSplits.length <= 1) {\n              // no split possible\n              splits.push(cssText);\n              return splits;\n            }\n            j = jLimit + 1; // trigger end of search\n          } else if (j === textContentNorm.length - 1) {\n            // we're about to end loop without a split point\n            splitNorm = cssTextNorm.indexOf(startSubstring);\n          }\n          if (cssNormSplits.length >= 2 && j > jLimit) {\n            const prevTextContent = childNodes[i - 1].textContent;\n            if (prevTextContent && typeof prevTextContent === 'string') {\n              // pick the first matching point which respects the previous chunk's approx size\n              const prevMinLength = normalizeCssString(prevTextContent).length;\n              splitNorm = cssTextNorm.indexOf(startSubstring, prevMinLength);\n            }\n            if (splitNorm === -1) {\n              // fall back to pick the first matching point of many\n              splitNorm = cssNormSplits[0].length;\n            }\n          }\n          if (splitNorm !== -1) {\n            // find the split point in the original text\n            let k = Math.floor(splitNorm / normFactor);\n            for (; k > 0 && k < cssText.length; ) {\n              iterCount += 1;\n              if (iterCount > 50 * childNodes.length) {\n                // quit for performance purposes\n                splits.push(cssText);\n                return splits;\n              }\n              const normPart = normalizeCssString(\n                cssText.substring(0, k),\n                _testNoPxNorm,\n              );\n              if (normPart.length === splitNorm) {\n                splits.push(cssText.substring(0, k));\n                cssText = cssText.substring(k);\n                cssTextNorm = cssTextNorm.substring(splitNorm);\n                break;\n              } else if (normPart.length < splitNorm) {\n                k += Math.max(\n                  1,\n                  Math.floor((splitNorm - normPart.length) / normFactor),\n                );\n              } else {\n                k -= Math.max(\n                  1,\n                  Math.floor((normPart.length - splitNorm) * normFactor),\n                );\n              }\n            }\n            break;\n          }\n        }\n      }\n    }\n  }\n  splits.push(cssText); // either the full thing if no splits were found, or the last split\n  return splits;\n}\n\nexport function markCssSplits(\n  cssText: string,\n  style: HTMLStyleElement,\n): string {\n  return splitCssText(cssText, style).join('/* rr_split */');\n}\n", "import type {\n  MaskInputOptions,\n  SlimDOMOptions,\n  MaskTextFn,\n  MaskInputFn,\n  KeepIframeSrcFn,\n  ICanvas,\n  DialogAttributes,\n} from './types';\nimport { NodeType } from '@rrweb/types';\nimport type {\n  serializedNode,\n  serializedNodeWithId,\n  serializedElementNodeWithId,\n  elementNode,\n  attributes,\n  mediaAttributes,\n  DataURLOptions,\n} from '@rrweb/types';\nimport {\n  Mirror,\n  is2DCanvasBlank,\n  isElement,\n  isShadowRoot,\n  maskInputValue,\n  isNativeShadowDom,\n  stringifyStylesheet,\n  getInputType,\n  toLowerCase,\n  extractFileExtension,\n  absolutifyURLs,\n  markCssSplits,\n} from './snapshot-utils';\nimport dom from '@rrweb/utils';\n\nlet _id = 1;\nconst tagNameRegex = new RegExp('[^a-z0-9-_:]');\n\nexport const IGNORED_NODE = -2;\n\nexport function genId(): number {\n  return _id++;\n}\n\nfunction getValidTagName(element: HTMLElement): Lowercase<string> {\n  if (element instanceof HTMLFormElement) {\n    return 'form';\n  }\n\n  const processedTagName = toLowerCase(element.tagName);\n\n  if (tagNameRegex.test(processedTagName)) {\n    // if the tag name is odd and we cannot extract\n    // anything from the string, then we return a\n    // generic div\n    return 'div';\n  }\n\n  return processedTagName;\n}\n\nlet canvasService: HTMLCanvasElement | null;\nlet canvasCtx: CanvasRenderingContext2D | null;\n\n// eslint-disable-next-line no-control-regex\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/; // Don't use \\s, to avoid matching non-breaking space\n// eslint-disable-next-line no-control-regex\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\nfunction getAbsoluteSrcsetString(doc: Document, attributeValue: string) {\n  /*\n    run absoluteToDoc over every url in the srcset\n\n    this is adapted from https://github.com/albell/parse-srcset/\n    without the parsing of the descriptors (we return these as-is)\n    parce-srcset is in turn based on\n    https://html.spec.whatwg.org/multipage/embedded-content.html#parse-a-srcset-attribute\n  */\n  if (attributeValue.trim() === '') {\n    return attributeValue;\n  }\n\n  let pos = 0;\n\n  function collectCharacters(regEx: RegExp) {\n    let chars: string;\n    const match = regEx.exec(attributeValue.substring(pos));\n    if (match) {\n      chars = match[0];\n      pos += chars.length;\n      return chars;\n    }\n    return '';\n  }\n\n  const output = [];\n  // eslint-disable-next-line no-constant-condition\n  while (true) {\n    collectCharacters(SRCSET_COMMAS_OR_SPACES);\n    if (pos >= attributeValue.length) {\n      break;\n    }\n    // don't split on commas within urls\n    let url = collectCharacters(SRCSET_NOT_SPACES);\n    if (url.slice(-1) === ',') {\n      // aside: according to spec more than one comma at the end is a parse error, but we ignore that\n      url = absoluteToDoc(doc, url.substring(0, url.length - 1));\n      // the trailing comma splits the srcset, so the interpretion is that\n      // another url will follow, and the descriptor is empty\n      output.push(url);\n    } else {\n      let descriptorsStr = '';\n      url = absoluteToDoc(doc, url);\n      let inParens = false;\n      // eslint-disable-next-line no-constant-condition\n      while (true) {\n        const c = attributeValue.charAt(pos);\n        if (c === '') {\n          output.push((url + descriptorsStr).trim());\n          break;\n        } else if (!inParens) {\n          if (c === ',') {\n            pos += 1;\n            output.push((url + descriptorsStr).trim());\n            break; // parse the next url\n          } else if (c === '(') {\n            inParens = true;\n          }\n        } else {\n          // in parenthesis; ignore commas\n          // (parenthesis may be supported by future additions to spec)\n          if (c === ')') {\n            inParens = false;\n          }\n        }\n        descriptorsStr += c;\n        pos += 1;\n      }\n    }\n  }\n  return output.join(', ');\n}\n\nconst cachedDocument = new WeakMap<Document, HTMLAnchorElement>();\n\nexport function absoluteToDoc(doc: Document, attributeValue: string): string {\n  if (!attributeValue || attributeValue.trim() === '') {\n    return attributeValue;\n  }\n\n  return getHref(doc, attributeValue);\n}\n\nfunction isSVGElement(el: Element): boolean {\n  return Boolean(el.tagName === 'svg' || (el as SVGElement).ownerSVGElement);\n}\n\nfunction getHref(doc: Document, customHref?: string) {\n  let a = cachedDocument.get(doc);\n  if (!a) {\n    a = doc.createElement('a');\n    cachedDocument.set(doc, a);\n  }\n  if (!customHref) {\n    customHref = '';\n  } else if (customHref.startsWith('blob:') || customHref.startsWith('data:')) {\n    return customHref;\n  }\n  // note: using `new URL` is slower. See #1434 or https://jsbench.me/uqlud17rxo/1\n  a.setAttribute('href', customHref);\n  return a.href;\n}\n\nexport function transformAttribute(\n  doc: Document,\n  tagName: Lowercase<string>,\n  name: Lowercase<string>,\n  value: string | null,\n): string | null {\n  if (!value) {\n    return value;\n  }\n\n  // relative path in attribute\n  if (\n    name === 'src' ||\n    (name === 'href' && !(tagName === 'use' && value[0] === '#'))\n  ) {\n    // href starts with a # is an id pointer for svg\n    return absoluteToDoc(doc, value);\n  } else if (name === 'xlink:href' && value[0] !== '#') {\n    // xlink:href starts with # is an id pointer\n    return absoluteToDoc(doc, value);\n  } else if (name === 'background' && ['table', 'td', 'th'].includes(tagName)) {\n    return absoluteToDoc(doc, value);\n  } else if (name === 'srcset') {\n    return getAbsoluteSrcsetString(doc, value);\n  } else if (name === 'style') {\n    return absolutifyURLs(value, getHref(doc));\n  } else if (tagName === 'object' && name === 'data') {\n    return absoluteToDoc(doc, value);\n  }\n\n  return value;\n}\n\nexport function ignoreAttribute(\n  tagName: Lowercase<string>,\n  name: string,\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  _value: unknown,\n): boolean {\n  return (\n    ['video', 'audio'].includes(tagName) && toLowerCase(name) === 'autoplay'\n  );\n}\n\nexport function _isBlockedElement(\n  element: HTMLElement,\n  blockClass: string | RegExp,\n  blockSelector: string | null,\n): boolean {\n  try {\n    if (typeof blockClass === 'string') {\n      if (element.classList.contains(blockClass)) {\n        return true;\n      }\n    } else {\n      for (let eIndex = element.classList.length; eIndex--; ) {\n        const className = element.classList[eIndex];\n        if (blockClass.test(className)) {\n          return true;\n        }\n      }\n    }\n    if (blockSelector) {\n      return element.matches(blockSelector);\n    }\n  } catch (e) {\n    //\n  }\n\n  return false;\n}\n\nexport function classMatchesRegex(\n  node: Node | null,\n  regex: RegExp,\n  checkAncestors: boolean,\n): boolean {\n  if (!node) return false;\n  if (node.nodeType !== node.ELEMENT_NODE) {\n    if (!checkAncestors) return false;\n    return classMatchesRegex(dom.parentNode(node), regex, checkAncestors);\n  }\n\n  for (let eIndex = (node as HTMLElement).classList.length; eIndex--; ) {\n    const className = (node as HTMLElement).classList[eIndex];\n    if (regex.test(className)) {\n      return true;\n    }\n  }\n  if (!checkAncestors) return false;\n  return classMatchesRegex(dom.parentNode(node), regex, checkAncestors);\n}\n\nexport function needMaskingText(\n  node: Node,\n  maskTextClass: string | RegExp,\n  maskTextSelector: string | null,\n  checkAncestors: boolean,\n): boolean {\n  let el: Element;\n  if (isElement(node)) {\n    el = node;\n    if (!dom.childNodes(el).length) {\n      // optimisation: we can avoid any of the below checks on leaf elements\n      // as masking is applied to child text nodes only\n      return false;\n    }\n  } else if (dom.parentElement(node) === null) {\n    // should warn? maybe a text node isn't attached to a parent node yet?\n    return false;\n  } else {\n    el = dom.parentElement(node)!;\n  }\n  try {\n    if (typeof maskTextClass === 'string') {\n      if (checkAncestors) {\n        if (el.closest(`.${maskTextClass}`)) return true;\n      } else {\n        if (el.classList.contains(maskTextClass)) return true;\n      }\n    } else {\n      if (classMatchesRegex(el, maskTextClass, checkAncestors)) return true;\n    }\n    if (maskTextSelector) {\n      if (checkAncestors) {\n        if (el.closest(maskTextSelector)) return true;\n      } else {\n        if (el.matches(maskTextSelector)) return true;\n      }\n    }\n  } catch (e) {\n    //\n  }\n  return false;\n}\n\n// https://stackoverflow.com/a/36155560\nfunction onceIframeLoaded(\n  iframeEl: HTMLIFrameElement,\n  listener: () => unknown,\n  iframeLoadTimeout: number,\n) {\n  const win = iframeEl.contentWindow;\n  if (!win) {\n    return;\n  }\n  // document is loading\n  let fired = false;\n\n  let readyState: DocumentReadyState;\n  try {\n    readyState = win.document.readyState;\n  } catch (error) {\n    return;\n  }\n  if (readyState !== 'complete') {\n    const timer = setTimeout(() => {\n      if (!fired) {\n        listener();\n        fired = true;\n      }\n    }, iframeLoadTimeout);\n    iframeEl.addEventListener('load', () => {\n      clearTimeout(timer);\n      fired = true;\n      listener();\n    });\n    return;\n  }\n  // check blank frame for Chrome\n  const blankUrl = 'about:blank';\n  if (\n    win.location.href !== blankUrl ||\n    iframeEl.src === blankUrl ||\n    iframeEl.src === ''\n  ) {\n    // iframe was already loaded, make sure we wait to trigger the listener\n    // till _after_ the mutation that found this iframe has had time to process\n    setTimeout(listener, 0);\n\n    return iframeEl.addEventListener('load', listener); // keep listing for future loads\n  }\n  // use default listener\n  iframeEl.addEventListener('load', listener);\n}\n\nfunction onceStylesheetLoaded(\n  link: HTMLLinkElement,\n  listener: () => unknown,\n  styleSheetLoadTimeout: number,\n) {\n  let fired = false;\n  let styleSheetLoaded: StyleSheet | null;\n  try {\n    styleSheetLoaded = link.sheet;\n  } catch (error) {\n    return;\n  }\n\n  if (styleSheetLoaded) return;\n\n  const timer = setTimeout(() => {\n    if (!fired) {\n      listener();\n      fired = true;\n    }\n  }, styleSheetLoadTimeout);\n\n  link.addEventListener('load', () => {\n    clearTimeout(timer);\n    fired = true;\n    listener();\n  });\n}\n\nfunction serializeNode(\n  n: Node,\n  options: {\n    doc: Document;\n    mirror: Mirror;\n    blockClass: string | RegExp;\n    blockSelector: string | null;\n    needsMask: boolean;\n    inlineStylesheet: boolean;\n    maskInputOptions: MaskInputOptions;\n    maskTextFn: MaskTextFn | undefined;\n    maskInputFn: MaskInputFn | undefined;\n    dataURLOptions?: DataURLOptions;\n    inlineImages: boolean;\n    recordCanvas: boolean;\n    keepIframeSrcFn: KeepIframeSrcFn;\n    /**\n     * `newlyAddedElement: true` skips scrollTop and scrollLeft check\n     */\n    newlyAddedElement?: boolean;\n    cssCaptured?: boolean;\n  },\n): serializedNode | false {\n  const {\n    doc,\n    mirror,\n    blockClass,\n    blockSelector,\n    needsMask,\n    inlineStylesheet,\n    maskInputOptions = {},\n    maskTextFn,\n    maskInputFn,\n    dataURLOptions = {},\n    inlineImages,\n    recordCanvas,\n    keepIframeSrcFn,\n    newlyAddedElement = false,\n    cssCaptured = false,\n  } = options;\n  // Only record root id when document object is not the base document\n  const rootId = getRootId(doc, mirror);\n  switch (n.nodeType) {\n    case n.DOCUMENT_NODE:\n      if ((n as Document).compatMode !== 'CSS1Compat') {\n        return {\n          type: NodeType.Document,\n          childNodes: [],\n          compatMode: (n as Document).compatMode, // probably \"BackCompat\"\n        };\n      } else {\n        return {\n          type: NodeType.Document,\n          childNodes: [],\n        };\n      }\n    case n.DOCUMENT_TYPE_NODE:\n      return {\n        type: NodeType.DocumentType,\n        name: (n as DocumentType).name,\n        publicId: (n as DocumentType).publicId,\n        systemId: (n as DocumentType).systemId,\n        rootId,\n      };\n    case n.ELEMENT_NODE:\n      return serializeElementNode(n as HTMLElement, {\n        doc,\n        blockClass,\n        blockSelector,\n        inlineStylesheet,\n        maskInputOptions,\n        maskInputFn,\n        dataURLOptions,\n        inlineImages,\n        recordCanvas,\n        keepIframeSrcFn,\n        newlyAddedElement,\n        rootId,\n      });\n    case n.TEXT_NODE:\n      return serializeTextNode(n as Text, {\n        doc,\n        needsMask,\n        maskTextFn,\n        rootId,\n        cssCaptured,\n      });\n    case n.CDATA_SECTION_NODE:\n      return {\n        type: NodeType.CDATA,\n        textContent: '',\n        rootId,\n      };\n    case n.COMMENT_NODE:\n      return {\n        type: NodeType.Comment,\n        textContent: dom.textContent(n as Comment) || '',\n        rootId,\n      };\n    default:\n      return false;\n  }\n}\n\nfunction getRootId(doc: Document, mirror: Mirror): number | undefined {\n  if (!mirror.hasNode(doc)) return undefined;\n  const docId = mirror.getId(doc);\n  return docId === 1 ? undefined : docId;\n}\n\nfunction serializeTextNode(\n  n: Text,\n  options: {\n    doc: Document;\n    needsMask: boolean;\n    maskTextFn: MaskTextFn | undefined;\n    rootId: number | undefined;\n    cssCaptured?: boolean;\n  },\n): serializedNode {\n  const { needsMask, maskTextFn, rootId, cssCaptured } = options;\n  // The parent node may not be a html element which has a tagName attribute.\n  // So just let it be undefined which is ok in this use case.\n  const parent = dom.parentNode(n);\n  const parentTagName = parent && (parent as HTMLElement).tagName;\n  let textContent: string | null = '';\n  const isStyle = parentTagName === 'STYLE' ? true : undefined;\n  const isScript = parentTagName === 'SCRIPT' ? true : undefined;\n  if (isScript) {\n    textContent = 'SCRIPT_PLACEHOLDER';\n  } else if (!cssCaptured) {\n    textContent = dom.textContent(n);\n    if (isStyle && textContent) {\n      // mutation only: we don't need to use stringifyStylesheet\n      // as a <style> text node mutation obliterates any previous\n      // programmatic rule manipulation (.insertRule etc.)\n      // so the current textContent represents the most up to date state\n      textContent = absolutifyURLs(textContent, getHref(options.doc));\n    }\n  }\n  if (!isStyle && !isScript && textContent && needsMask) {\n    textContent = maskTextFn\n      ? maskTextFn(textContent, dom.parentElement(n))\n      : textContent.replace(/[\\S]/g, '*');\n  }\n\n  return {\n    type: NodeType.Text,\n    textContent: textContent || '',\n    rootId,\n  };\n}\n\nfunction serializeElementNode(\n  n: HTMLElement,\n  options: {\n    doc: Document;\n    blockClass: string | RegExp;\n    blockSelector: string | null;\n    inlineStylesheet: boolean;\n    maskInputOptions: MaskInputOptions;\n    maskInputFn: MaskInputFn | undefined;\n    dataURLOptions?: DataURLOptions;\n    inlineImages: boolean;\n    recordCanvas: boolean;\n    keepIframeSrcFn: KeepIframeSrcFn;\n    /**\n     * `newlyAddedElement: true` skips scrollTop and scrollLeft check\n     */\n    newlyAddedElement?: boolean;\n    rootId: number | undefined;\n  },\n): serializedNode | false {\n  const {\n    doc,\n    blockClass,\n    blockSelector,\n    inlineStylesheet,\n    maskInputOptions = {},\n    maskInputFn,\n    dataURLOptions = {},\n    inlineImages,\n    recordCanvas,\n    keepIframeSrcFn,\n    newlyAddedElement = false,\n    rootId,\n  } = options;\n  const needBlock = _isBlockedElement(n, blockClass, blockSelector);\n  const tagName = getValidTagName(n);\n  let attributes: attributes = {};\n  const len = n.attributes.length;\n  for (let i = 0; i < len; i++) {\n    const attr = n.attributes[i];\n    if (!ignoreAttribute(tagName, attr.name, attr.value)) {\n      attributes[attr.name] = transformAttribute(\n        doc,\n        tagName,\n        toLowerCase(attr.name),\n        attr.value,\n      );\n    }\n  }\n  // remote css\n  if (tagName === 'link' && inlineStylesheet) {\n    //TODO: maybe replace this `.styleSheets` with original one\n    const stylesheet = Array.from(doc.styleSheets).find((s) => {\n      return s.href === (n as HTMLLinkElement).href;\n    });\n    let cssText: string | null = null;\n    if (stylesheet) {\n      cssText = stringifyStylesheet(stylesheet);\n    }\n    if (cssText) {\n      delete attributes.rel;\n      delete attributes.href;\n      attributes._cssText = cssText;\n    }\n  }\n  if (tagName === 'style' && (n as HTMLStyleElement).sheet) {\n    let cssText = stringifyStylesheet(\n      (n as HTMLStyleElement).sheet as CSSStyleSheet,\n    );\n    if (cssText) {\n      if (n.childNodes.length > 1) {\n        cssText = markCssSplits(cssText, n as HTMLStyleElement);\n      }\n      attributes._cssText = cssText;\n    }\n  }\n  // form fields\n  if (['input', 'textarea', 'select'].includes(tagName)) {\n    const value = (n as HTMLInputElement | HTMLTextAreaElement).value;\n    const checked = (n as HTMLInputElement).checked;\n    if (\n      attributes.type !== 'radio' &&\n      attributes.type !== 'checkbox' &&\n      attributes.type !== 'submit' &&\n      attributes.type !== 'button' &&\n      value\n    ) {\n      attributes.value = maskInputValue({\n        element: n,\n        type: getInputType(n),\n        tagName,\n        value,\n        maskInputOptions,\n        maskInputFn,\n      });\n    } else if (checked) {\n      attributes.checked = checked;\n    }\n  }\n  if (tagName === 'option') {\n    if ((n as HTMLOptionElement).selected && !maskInputOptions['select']) {\n      attributes.selected = true;\n    } else {\n      // ignore the html attribute (which corresponds to DOM (n as HTMLOptionElement).defaultSelected)\n      // if it's already been changed\n      delete attributes.selected;\n    }\n  }\n\n  if (tagName === 'dialog' && (n as HTMLDialogElement).open) {\n    // register what type of dialog is this\n    // `modal` or `non-modal`\n    // this is used to trigger `showModal()` or `show()` on replay (outside of rrweb-snapshot, in rrweb)\n    (attributes as DialogAttributes).rr_open_mode = n.matches('dialog:modal')\n      ? 'modal'\n      : 'non-modal';\n  }\n\n  // canvas image data\n  if (tagName === 'canvas' && recordCanvas) {\n    if ((n as ICanvas).__context === '2d') {\n      // only record this on 2d canvas\n      if (!is2DCanvasBlank(n as HTMLCanvasElement)) {\n        attributes.rr_dataURL = (n as HTMLCanvasElement).toDataURL(\n          dataURLOptions.type,\n          dataURLOptions.quality,\n        );\n      }\n    } else if (!('__context' in n)) {\n      // context is unknown, better not call getContext to trigger it\n      const canvasDataURL = (n as HTMLCanvasElement).toDataURL(\n        dataURLOptions.type,\n        dataURLOptions.quality,\n      );\n\n      // create blank canvas of same dimensions\n      const blankCanvas = doc.createElement('canvas');\n      blankCanvas.width = (n as HTMLCanvasElement).width;\n      blankCanvas.height = (n as HTMLCanvasElement).height;\n      const blankCanvasDataURL = blankCanvas.toDataURL(\n        dataURLOptions.type,\n        dataURLOptions.quality,\n      );\n\n      // no need to save dataURL if it's the same as blank canvas\n      if (canvasDataURL !== blankCanvasDataURL) {\n        attributes.rr_dataURL = canvasDataURL;\n      }\n    }\n  }\n  // save image offline\n  if (tagName === 'img' && inlineImages) {\n    if (!canvasService) {\n      canvasService = doc.createElement('canvas');\n      canvasCtx = canvasService.getContext('2d');\n    }\n    const image = n as HTMLImageElement;\n    const imageSrc: string =\n      image.currentSrc || image.getAttribute('src') || '<unknown-src>';\n    const priorCrossOrigin = image.crossOrigin;\n    const recordInlineImage = () => {\n      image.removeEventListener('load', recordInlineImage);\n      try {\n        canvasService!.width = image.naturalWidth;\n        canvasService!.height = image.naturalHeight;\n        canvasCtx!.drawImage(image, 0, 0);\n        attributes.rr_dataURL = canvasService!.toDataURL(\n          dataURLOptions.type,\n          dataURLOptions.quality,\n        );\n      } catch (err) {\n        if (image.crossOrigin !== 'anonymous') {\n          image.crossOrigin = 'anonymous';\n          if (image.complete && image.naturalWidth !== 0)\n            recordInlineImage(); // too early due to image reload\n          else image.addEventListener('load', recordInlineImage);\n          return;\n        } else {\n          console.warn(\n            `Cannot inline img src=${imageSrc}! Error: ${err as string}`,\n          );\n        }\n      }\n      if (image.crossOrigin === 'anonymous') {\n        priorCrossOrigin\n          ? (attributes.crossOrigin = priorCrossOrigin)\n          : image.removeAttribute('crossorigin');\n      }\n    };\n    // The image content may not have finished loading yet.\n    if (image.complete && image.naturalWidth !== 0) recordInlineImage();\n    else image.addEventListener('load', recordInlineImage);\n  }\n  // media elements\n  if (['audio', 'video'].includes(tagName)) {\n    const mediaAttributes = attributes as mediaAttributes;\n    mediaAttributes.rr_mediaState = (n as HTMLMediaElement).paused\n      ? 'paused'\n      : 'played';\n    mediaAttributes.rr_mediaCurrentTime = (n as HTMLMediaElement).currentTime;\n    mediaAttributes.rr_mediaPlaybackRate = (n as HTMLMediaElement).playbackRate;\n    mediaAttributes.rr_mediaMuted = (n as HTMLMediaElement).muted;\n    mediaAttributes.rr_mediaLoop = (n as HTMLMediaElement).loop;\n    mediaAttributes.rr_mediaVolume = (n as HTMLMediaElement).volume;\n  }\n  // Scroll\n  if (!newlyAddedElement) {\n    // `scrollTop` and `scrollLeft` are expensive calls because they trigger reflow.\n    // Since `scrollTop` & `scrollLeft` are always 0 when an element is added to the DOM.\n    // And scrolls also get picked up by rrweb's ScrollObserver\n    // So we can safely skip the `scrollTop/Left` calls for newly added elements\n    if (n.scrollLeft) {\n      attributes.rr_scrollLeft = n.scrollLeft;\n    }\n    if (n.scrollTop) {\n      attributes.rr_scrollTop = n.scrollTop;\n    }\n  }\n  // block element\n  if (needBlock) {\n    const { width, height } = n.getBoundingClientRect();\n    attributes = {\n      class: attributes.class,\n      rr_width: `${width}px`,\n      rr_height: `${height}px`,\n    };\n  }\n  // iframe\n  if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src as string)) {\n    if (!(n as HTMLIFrameElement).contentDocument) {\n      // we can't record it directly as we can't see into it\n      // preserve the src attribute so a decision can be taken at replay time\n      attributes.rr_src = attributes.src;\n    }\n    delete attributes.src; // prevent auto loading\n  }\n\n  let isCustomElement: true | undefined;\n  try {\n    if (customElements.get(tagName)) isCustomElement = true;\n  } catch (e) {\n    // In case old browsers don't support customElements\n  }\n\n  return {\n    type: NodeType.Element,\n    tagName,\n    attributes,\n    childNodes: [],\n    isSVG: isSVGElement(n as Element) || undefined,\n    needBlock,\n    rootId,\n    isCustom: isCustomElement,\n  };\n}\n\nfunction lowerIfExists(\n  maybeAttr: string | number | boolean | undefined | null,\n): string {\n  if (maybeAttr === undefined || maybeAttr === null) {\n    return '';\n  } else {\n    return (maybeAttr as string).toLowerCase();\n  }\n}\n\nexport function slimDOMDefaults(\n  _slimDOMOptions: SlimDOMOptions | 'all' | true | false | undefined,\n) {\n  if (_slimDOMOptions === true || _slimDOMOptions === 'all') {\n    // if true: set of sensible options that should not throw away any information\n    return {\n      script: true,\n      comment: true,\n      headFavicon: true,\n      headWhitespace: true,\n      headMetaSocial: true,\n      headMetaRobots: true,\n      headMetaHttpEquiv: true,\n      headMetaVerification: true,\n      // the following are off for slimDOMOptions === true,\n      // as they destroy some (hidden) info:\n      headMetaAuthorship: _slimDOMOptions === 'all',\n      headMetaDescKeywords: _slimDOMOptions === 'all',\n      headTitleMutations: _slimDOMOptions === 'all',\n    };\n  } else if (_slimDOMOptions) {\n    return _slimDOMOptions;\n  }\n  return {};\n}\n\nfunction slimDOMExcluded(\n  sn: serializedNode,\n  slimDOMOptions: SlimDOMOptions,\n): boolean {\n  if (slimDOMOptions.comment && sn.type === NodeType.Comment) {\n    // TODO: convert IE conditional comments to real nodes\n    return true;\n  } else if (sn.type === NodeType.Element) {\n    if (\n      slimDOMOptions.script &&\n      // script tag\n      (sn.tagName === 'script' ||\n        // (module)preload link\n        (sn.tagName === 'link' &&\n          ((sn.attributes.rel === 'preload' && sn.attributes.as === 'script') ||\n            sn.attributes.rel === 'modulepreload')) ||\n        // prefetch link\n        (sn.tagName === 'link' &&\n          sn.attributes.rel === 'prefetch' &&\n          typeof sn.attributes.href === 'string' &&\n          extractFileExtension(sn.attributes.href) === 'js'))\n    ) {\n      return true;\n    } else if (\n      slimDOMOptions.headFavicon &&\n      ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||\n        (sn.tagName === 'meta' &&\n          (lowerIfExists(sn.attributes.name).match(\n            /^msapplication-tile(image|color)$/,\n          ) ||\n            lowerIfExists(sn.attributes.name) === 'application-name' ||\n            lowerIfExists(sn.attributes.rel) === 'icon' ||\n            lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||\n            lowerIfExists(sn.attributes.rel) === 'shortcut icon')))\n    ) {\n      return true;\n    } else if (sn.tagName === 'meta') {\n      if (\n        slimDOMOptions.headMetaDescKeywords &&\n        lowerIfExists(sn.attributes.name).match(/^description|keywords$/)\n      ) {\n        return true;\n      } else if (\n        slimDOMOptions.headMetaSocial &&\n        (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) || // og = opengraph (facebook)\n          lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||\n          lowerIfExists(sn.attributes.name) === 'pinterest')\n      ) {\n        return true;\n      } else if (\n        slimDOMOptions.headMetaRobots &&\n        (lowerIfExists(sn.attributes.name) === 'robots' ||\n          lowerIfExists(sn.attributes.name) === 'googlebot' ||\n          lowerIfExists(sn.attributes.name) === 'bingbot')\n      ) {\n        return true;\n      } else if (\n        slimDOMOptions.headMetaHttpEquiv &&\n        sn.attributes['http-equiv'] !== undefined\n      ) {\n        // e.g. X-UA-Compatible, Content-Type, Content-Language,\n        // cache-control, X-Translated-By\n        return true;\n      } else if (\n        slimDOMOptions.headMetaAuthorship &&\n        (lowerIfExists(sn.attributes.name) === 'author' ||\n          lowerIfExists(sn.attributes.name) === 'generator' ||\n          lowerIfExists(sn.attributes.name) === 'framework' ||\n          lowerIfExists(sn.attributes.name) === 'publisher' ||\n          lowerIfExists(sn.attributes.name) === 'progid' ||\n          lowerIfExists(sn.attributes.property).match(/^article:/) ||\n          lowerIfExists(sn.attributes.property).match(/^product:/))\n      ) {\n        return true;\n      } else if (\n        slimDOMOptions.headMetaVerification &&\n        (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||\n          lowerIfExists(sn.attributes.name) === 'yandex-verification' ||\n          lowerIfExists(sn.attributes.name) === 'csrf-token' ||\n          lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||\n          lowerIfExists(sn.attributes.name) === 'verify-v1' ||\n          lowerIfExists(sn.attributes.name) === 'verification' ||\n          lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')\n      ) {\n        return true;\n      }\n    }\n  }\n  return false;\n}\n\nexport function serializeNodeWithId(\n  n: Node,\n  options: {\n    doc: Document;\n    mirror: Mirror;\n    blockClass: string | RegExp;\n    blockSelector: string | null;\n    maskTextClass: string | RegExp;\n    maskTextSelector: string | null;\n    skipChild: boolean;\n    inlineStylesheet: boolean;\n    newlyAddedElement?: boolean;\n    maskInputOptions?: MaskInputOptions;\n    needsMask?: boolean;\n    maskTextFn: MaskTextFn | undefined;\n    maskInputFn: MaskInputFn | undefined;\n    slimDOMOptions: SlimDOMOptions;\n    dataURLOptions?: DataURLOptions;\n    keepIframeSrcFn?: KeepIframeSrcFn;\n    inlineImages?: boolean;\n    recordCanvas?: boolean;\n    preserveWhiteSpace?: boolean;\n    onSerialize?: (n: Node) => unknown;\n    onIframeLoad?: (\n      iframeNode: HTMLIFrameElement,\n      node: serializedElementNodeWithId,\n    ) => unknown;\n    iframeLoadTimeout?: number;\n    onStylesheetLoad?: (\n      linkNode: HTMLLinkElement,\n      node: serializedElementNodeWithId,\n    ) => unknown;\n    stylesheetLoadTimeout?: number;\n    cssCaptured?: boolean;\n  },\n): serializedNodeWithId | null {\n  const {\n    doc,\n    mirror,\n    blockClass,\n    blockSelector,\n    maskTextClass,\n    maskTextSelector,\n    skipChild = false,\n    inlineStylesheet = true,\n    maskInputOptions = {},\n    maskTextFn,\n    maskInputFn,\n    slimDOMOptions,\n    dataURLOptions = {},\n    inlineImages = false,\n    recordCanvas = false,\n    onSerialize,\n    onIframeLoad,\n    iframeLoadTimeout = 5000,\n    onStylesheetLoad,\n    stylesheetLoadTimeout = 5000,\n    keepIframeSrcFn = () => false,\n    newlyAddedElement = false,\n    cssCaptured = false,\n  } = options;\n  let { needsMask } = options;\n  let { preserveWhiteSpace = true } = options;\n\n  if (!needsMask) {\n    // perf: if needsMask = true, children won't also need to check\n    const checkAncestors = needsMask === undefined; // if false, we've already checked ancestors\n    needsMask = needMaskingText(\n      n as Element,\n      maskTextClass,\n      maskTextSelector,\n      checkAncestors,\n    );\n  }\n\n  const _serializedNode = serializeNode(n, {\n    doc,\n    mirror,\n    blockClass,\n    blockSelector,\n    needsMask,\n    inlineStylesheet,\n    maskInputOptions,\n    maskTextFn,\n    maskInputFn,\n    dataURLOptions,\n    inlineImages,\n    recordCanvas,\n    keepIframeSrcFn,\n    newlyAddedElement,\n    cssCaptured,\n  });\n  if (!_serializedNode) {\n    // TODO: dev only\n    console.warn(n, 'not serialized');\n    return null;\n  }\n\n  let id: number | undefined;\n  if (mirror.hasNode(n)) {\n    // Reuse the previous id\n    id = mirror.getId(n);\n  } else if (\n    slimDOMExcluded(_serializedNode, slimDOMOptions) ||\n    (!preserveWhiteSpace &&\n      _serializedNode.type === NodeType.Text &&\n      !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, '').length)\n  ) {\n    id = IGNORED_NODE;\n  } else {\n    id = genId();\n  }\n\n  const serializedNode = Object.assign(_serializedNode, { id });\n  // add IGNORED_NODE to mirror to track nextSiblings\n  mirror.add(n, serializedNode);\n\n  if (id === IGNORED_NODE) {\n    return null; // slimDOM\n  }\n\n  if (onSerialize) {\n    onSerialize(n);\n  }\n  let recordChild = !skipChild;\n  if (serializedNode.type === NodeType.Element) {\n    recordChild = recordChild && !serializedNode.needBlock;\n    // this property was not needed in replay side\n    delete serializedNode.needBlock;\n    const shadowRootEl = dom.shadowRoot(n);\n    if (shadowRootEl && isNativeShadowDom(shadowRootEl))\n      serializedNode.isShadowHost = true;\n  }\n  if (\n    (serializedNode.type === NodeType.Document ||\n      serializedNode.type === NodeType.Element) &&\n    recordChild\n  ) {\n    if (\n      slimDOMOptions.headWhitespace &&\n      serializedNode.type === NodeType.Element &&\n      serializedNode.tagName === 'head'\n      // would impede performance: || getComputedStyle(n)['white-space'] === 'normal'\n    ) {\n      preserveWhiteSpace = false;\n    }\n    const bypassOptions = {\n      doc,\n      mirror,\n      blockClass,\n      blockSelector,\n      needsMask,\n      maskTextClass,\n      maskTextSelector,\n      skipChild,\n      inlineStylesheet,\n      maskInputOptions,\n      maskTextFn,\n      maskInputFn,\n      slimDOMOptions,\n      dataURLOptions,\n      inlineImages,\n      recordCanvas,\n      preserveWhiteSpace,\n      onSerialize,\n      onIframeLoad,\n      iframeLoadTimeout,\n      onStylesheetLoad,\n      stylesheetLoadTimeout,\n      keepIframeSrcFn,\n      cssCaptured: false,\n    };\n\n    if (\n      serializedNode.type === NodeType.Element &&\n      serializedNode.tagName === 'textarea' &&\n      (serializedNode as elementNode).attributes.value !== undefined\n    ) {\n      // value parameter in DOM reflects the correct value, so ignore childNode\n    } else {\n      if (\n        serializedNode.type === NodeType.Element &&\n        (serializedNode as elementNode).attributes._cssText !== undefined &&\n        typeof serializedNode.attributes._cssText === 'string'\n      ) {\n        bypassOptions.cssCaptured = true;\n      }\n      for (const childN of Array.from(dom.childNodes(n))) {\n        const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n        if (serializedChildNode) {\n          serializedNode.childNodes.push(serializedChildNode);\n        }\n      }\n    }\n\n    let shadowRootEl: ShadowRoot | null = null;\n    if (isElement(n) && (shadowRootEl = dom.shadowRoot(n))) {\n      for (const childN of Array.from(dom.childNodes(shadowRootEl))) {\n        const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n        if (serializedChildNode) {\n          isNativeShadowDom(shadowRootEl) &&\n            (serializedChildNode.isShadow = true);\n          serializedNode.childNodes.push(serializedChildNode);\n        }\n      }\n    }\n  }\n\n  const parent = dom.parentNode(n);\n  if (parent && isShadowRoot(parent) && isNativeShadowDom(parent)) {\n    serializedNode.isShadow = true;\n  }\n\n  if (\n    serializedNode.type === NodeType.Element &&\n    serializedNode.tagName === 'iframe' &&\n    !_isBlockedElement(n as HTMLElement, blockClass, blockSelector)\n  ) {\n    onceIframeLoaded(\n      n as HTMLIFrameElement,\n      () => {\n        const iframeDoc = (n as HTMLIFrameElement).contentDocument;\n        if (iframeDoc && onIframeLoad) {\n          const serializedIframeNode = serializeNodeWithId(iframeDoc, {\n            doc: iframeDoc,\n            mirror,\n            blockClass,\n            blockSelector,\n            needsMask,\n            maskTextClass,\n            maskTextSelector,\n            skipChild: false,\n            inlineStylesheet,\n            maskInputOptions,\n            maskTextFn,\n            maskInputFn,\n            slimDOMOptions,\n            dataURLOptions,\n            inlineImages,\n            recordCanvas,\n            preserveWhiteSpace,\n            onSerialize,\n            onIframeLoad,\n            iframeLoadTimeout,\n            onStylesheetLoad,\n            stylesheetLoadTimeout,\n            keepIframeSrcFn,\n          });\n\n          if (serializedIframeNode) {\n            onIframeLoad(\n              n as HTMLIFrameElement,\n              serializedIframeNode as serializedElementNodeWithId,\n            );\n          }\n        }\n      },\n      iframeLoadTimeout,\n    );\n  }\n\n  // <link rel=stylesheet href=...>\n  if (\n    serializedNode.type === NodeType.Element &&\n    serializedNode.tagName === 'link' &&\n    typeof serializedNode.attributes.rel === 'string' &&\n    (serializedNode.attributes.rel === 'stylesheet' ||\n      (serializedNode.attributes.rel === 'preload' &&\n        typeof serializedNode.attributes.href === 'string' &&\n        extractFileExtension(serializedNode.attributes.href) === 'css'))\n  ) {\n    onceStylesheetLoaded(\n      n as HTMLLinkElement,\n      () => {\n        if (onStylesheetLoad) {\n          const serializedLinkNode = serializeNodeWithId(n, {\n            doc,\n            mirror,\n            blockClass,\n            blockSelector,\n            needsMask,\n            maskTextClass,\n            maskTextSelector,\n            skipChild: false,\n            inlineStylesheet,\n            maskInputOptions,\n            maskTextFn,\n            maskInputFn,\n            slimDOMOptions,\n            dataURLOptions,\n            inlineImages,\n            recordCanvas,\n            preserveWhiteSpace,\n            onSerialize,\n            onIframeLoad,\n            iframeLoadTimeout,\n            onStylesheetLoad,\n            stylesheetLoadTimeout,\n            keepIframeSrcFn,\n          });\n\n          if (serializedLinkNode) {\n            onStylesheetLoad(\n              n as HTMLLinkElement,\n              serializedLinkNode as serializedElementNodeWithId,\n            );\n          }\n        }\n      },\n      stylesheetLoadTimeout,\n    );\n  }\n\n  return serializedNode;\n}\n\nfunction snapshot(\n  n: Document,\n  options?: {\n    mirror?: Mirror;\n    blockClass?: string | RegExp;\n    blockSelector?: string | null;\n    maskTextClass?: string | RegExp;\n    maskTextSelector?: string | null;\n    inlineStylesheet?: boolean;\n    maskAllInputs?: boolean | MaskInputOptions;\n    maskTextFn?: MaskTextFn;\n    maskInputFn?: MaskInputFn;\n    slimDOM?: 'all' | boolean | SlimDOMOptions;\n    dataURLOptions?: DataURLOptions;\n    inlineImages?: boolean;\n    recordCanvas?: boolean;\n    preserveWhiteSpace?: boolean;\n    onSerialize?: (n: Node) => unknown;\n    onIframeLoad?: (\n      iframeNode: HTMLIFrameElement,\n      node: serializedElementNodeWithId,\n    ) => unknown;\n    iframeLoadTimeout?: number;\n    onStylesheetLoad?: (\n      linkNode: HTMLLinkElement,\n      node: serializedElementNodeWithId,\n    ) => unknown;\n    stylesheetLoadTimeout?: number;\n    keepIframeSrcFn?: KeepIframeSrcFn;\n  },\n): serializedNodeWithId | null {\n  const {\n    mirror = new Mirror(),\n    blockClass = 'rr-block',\n    blockSelector = null,\n    maskTextClass = 'rr-mask',\n    maskTextSelector = null,\n    inlineStylesheet = true,\n    inlineImages = false,\n    recordCanvas = false,\n    maskAllInputs = false,\n    maskTextFn,\n    maskInputFn,\n    slimDOM = false,\n    dataURLOptions,\n    preserveWhiteSpace,\n    onSerialize,\n    onIframeLoad,\n    iframeLoadTimeout,\n    onStylesheetLoad,\n    stylesheetLoadTimeout,\n    keepIframeSrcFn = () => false,\n  } = options || {};\n  const maskInputOptions: MaskInputOptions =\n    maskAllInputs === true\n      ? {\n          color: true,\n          date: true,\n          'datetime-local': true,\n          email: true,\n          month: true,\n          number: true,\n          range: true,\n          search: true,\n          tel: true,\n          text: true,\n          time: true,\n          url: true,\n          week: true,\n          textarea: true,\n          select: true,\n          password: true,\n        }\n      : maskAllInputs === false\n      ? {\n          password: true,\n        }\n      : maskAllInputs;\n  const slimDOMOptions = slimDOMDefaults(slimDOM);\n\n  return serializeNodeWithId(n, {\n    doc: n,\n    mirror,\n    blockClass,\n    blockSelector,\n    maskTextClass,\n    maskTextSelector,\n    skipChild: false,\n    inlineStylesheet,\n    maskInputOptions,\n    maskTextFn,\n    maskInputFn,\n    slimDOMOptions,\n    dataURLOptions,\n    inlineImages,\n    recordCanvas,\n    preserveWhiteSpace,\n    onSerialize,\n    onIframeLoad,\n    iframeLoadTimeout,\n    onStylesheetLoad,\n    stylesheetLoadTimeout,\n    keepIframeSrcFn,\n    newlyAddedElement: false,\n  });\n}\n\nexport function visitSnapshot(\n  node: serializedNodeWithId,\n  onVisit: (node: serializedNodeWithId) => unknown,\n) {\n  function walk(current: serializedNodeWithId) {\n    onVisit(current);\n    if (\n      current.type === NodeType.Document ||\n      current.type === NodeType.Element\n    ) {\n      current.childNodes.forEach(walk);\n    }\n  }\n\n  walk(node);\n}\n\nexport function cleanupSnapshot() {\n  // allow a new recording to start numbering nodes from scratch\n  _id = 1;\n}\n\nexport default snapshot;\n", "import { NodeType as RRNodeType } from '@rrweb/types';\nimport { parseCSSText, camelize, toCSSText } from './style';\nexport interface IRRNode {\n  parentElement: IRRNode | null;\n  parentNode: IRRNode | null;\n  ownerDocument: IRRDocument;\n  readonly childNodes: IRRNode[];\n  readonly ELEMENT_NODE: number;\n  readonly TEXT_NODE: number;\n  // corresponding nodeType value of standard HTML Node\n  readonly nodeType: number;\n  readonly nodeName: string; // https://dom.spec.whatwg.org/#dom-node-nodename\n  readonly RRNodeType: RRNodeType;\n\n  firstChild: IRRNode | null;\n\n  lastChild: IRRNode | null;\n\n  previousSibling: IRRNode | null;\n\n  nextSibling: IRRNode | null;\n\n  // If the node is a document or a doctype, textContent returns null.\n  textContent: string | null;\n\n  contains(node: IRRNode): boolean;\n\n  appendChild(newChild: IRRNode): IRRNode;\n\n  insertBefore(newChild: IRRNode, refChild: IRRNode | null): IRRNode;\n\n  removeChild(node: IRRNode): IRRNode;\n\n  toString(): string;\n}\nexport interface IRRDocument extends IRRNode {\n  documentElement: IRRElement | null;\n\n  body: IRRElement | null;\n\n  head: IRRElement | null;\n\n  implementation: IRRDocument;\n\n  firstElementChild: IRRElement | null;\n\n  readonly nodeName: '#document';\n\n  compatMode: 'BackCompat' | 'CSS1Compat';\n\n  createDocument(\n    _namespace: string | null,\n    _qualifiedName: string | null,\n    _doctype?: DocumentType | null,\n  ): IRRDocument;\n\n  createDocumentType(\n    qualifiedName: string,\n    publicId: string,\n    systemId: string,\n  ): IRRDocumentType;\n\n  createElement(tagName: string): IRRElement;\n\n  createElementNS(_namespaceURI: string, qualifiedName: string): IRRElement;\n\n  createTextNode(data: string): IRRText;\n\n  createComment(data: string): IRRComment;\n\n  createCDATASection(data: string): IRRCDATASection;\n\n  open(): void;\n\n  close(): void;\n\n  write(content: string): void;\n}\nexport interface IRRElement extends IRRNode {\n  tagName: string;\n  attributes: Record<string, string>;\n  shadowRoot: IRRElement | null;\n  scrollLeft?: number;\n  scrollTop?: number;\n  id: string;\n  className: string;\n  classList: ClassList;\n  style: CSSStyleDeclaration;\n\n  attachShadow(init: ShadowRootInit): IRRElement;\n\n  getAttribute(name: string): string | null;\n\n  setAttribute(name: string, attribute: string): void;\n\n  setAttributeNS(\n    namespace: string | null,\n    qualifiedName: string,\n    value: string,\n  ): void;\n\n  removeAttribute(name: string): void;\n\n  dispatchEvent(event: Event): boolean;\n}\nexport interface IRRDocumentType extends IRRNode {\n  readonly name: string;\n  readonly publicId: string;\n  readonly systemId: string;\n}\nexport interface IRRText extends IRRNode {\n  readonly nodeName: '#text';\n  data: string;\n}\nexport interface IRRComment extends IRRNode {\n  readonly nodeName: '#comment';\n  data: string;\n}\nexport interface IRRCDATASection extends IRRNode {\n  readonly nodeName: '#cdata-section';\n  data: string;\n}\n\n/**\n * This is designed as an abstract class so it should never be instantiated.\n */\nexport abstract class BaseRRNode implements IRRNode {\n  public parentElement: IRRNode | null = null;\n  public parentNode: IRRNode | null = null;\n  public ownerDocument!: IRRDocument;\n  public firstChild: IRRNode | null = null;\n  public lastChild: IRRNode | null = null;\n  public previousSibling: IRRNode | null = null;\n  public nextSibling: IRRNode | null = null;\n\n  public abstract textContent: string | null;\n\n  public readonly ELEMENT_NODE: number = NodeType.ELEMENT_NODE;\n  public readonly TEXT_NODE: number = NodeType.TEXT_NODE;\n  // corresponding nodeType value of standard HTML Node\n  public readonly nodeType!: number;\n  public readonly nodeName!: string;\n  public readonly RRNodeType!: RRNodeType;\n\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any\n  constructor(..._args: any[]) {\n    //\n  }\n\n  public get childNodes(): IRRNode[] {\n    const childNodes: IRRNode[] = [];\n    let childIterator: IRRNode | null = this.firstChild;\n    while (childIterator) {\n      childNodes.push(childIterator);\n      childIterator = childIterator.nextSibling;\n    }\n    return childNodes;\n  }\n\n  public contains(node: IRRNode) {\n    if (!(node instanceof BaseRRNode)) return false;\n    else if (node.ownerDocument !== this.ownerDocument) return false;\n    else if (node === this) return true;\n\n    while (node.parentNode) {\n      if (node.parentNode === this) return true;\n      node = node.parentNode;\n    }\n    return false;\n  }\n\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  public appendChild(_newChild: IRRNode): IRRNode {\n    throw new Error(\n      `RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.`,\n    );\n  }\n\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  public insertBefore(_newChild: IRRNode, _refChild: IRRNode | null): IRRNode {\n    throw new Error(\n      `RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.`,\n    );\n  }\n\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  public removeChild(_node: IRRNode): IRRNode {\n    throw new Error(\n      `RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.`,\n    );\n  }\n\n  public toString(): string {\n    return 'RRNode';\n  }\n}\n\nexport class BaseRRDocument extends BaseRRNode implements IRRDocument {\n  public readonly nodeType: number = NodeType.DOCUMENT_NODE;\n  public readonly nodeName = '#document' as const;\n  public readonly compatMode: 'BackCompat' | 'CSS1Compat' = 'CSS1Compat';\n  public readonly RRNodeType = RRNodeType.Document;\n  public textContent: string | null = null;\n\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  constructor(...args: any[]) {\n    super(args);\n    this.ownerDocument = this;\n  }\n\n  public get documentElement(): IRRElement | null {\n    return (\n      (this.childNodes.find(\n        (node) =>\n          node.RRNodeType === RRNodeType.Element &&\n          (node as IRRElement).tagName === 'HTML',\n      ) as IRRElement) || null\n    );\n  }\n\n  public get body(): IRRElement | null {\n    return (\n      (this.documentElement?.childNodes.find(\n        (node) =>\n          node.RRNodeType === RRNodeType.Element &&\n          (node as IRRElement).tagName === 'BODY',\n      ) as IRRElement) || null\n    );\n  }\n\n  public get head(): IRRElement | null {\n    return (\n      (this.documentElement?.childNodes.find(\n        (node) =>\n          node.RRNodeType === RRNodeType.Element &&\n          (node as IRRElement).tagName === 'HEAD',\n      ) as IRRElement) || null\n    );\n  }\n\n  public get implementation(): IRRDocument {\n    return this;\n  }\n\n  public get firstElementChild(): IRRElement | null {\n    return this.documentElement;\n  }\n\n  public appendChild(newChild: IRRNode): IRRNode {\n    const nodeType = newChild.RRNodeType;\n    if (\n      nodeType === RRNodeType.Element ||\n      nodeType === RRNodeType.DocumentType\n    ) {\n      if (this.childNodes.some((s) => s.RRNodeType === nodeType)) {\n        throw new Error(\n          `RRDomException: Failed to execute 'appendChild' on 'RRNode': Only one ${\n            nodeType === RRNodeType.Element ? 'RRElement' : 'RRDoctype'\n          } on RRDocument allowed.`,\n        );\n      }\n    }\n\n    const child = appendChild(this, newChild);\n    child.parentElement = null;\n    return child;\n  }\n\n  public insertBefore(newChild: IRRNode, refChild: IRRNode | null): IRRNode {\n    const nodeType = newChild.RRNodeType;\n    if (\n      nodeType === RRNodeType.Element ||\n      nodeType === RRNodeType.DocumentType\n    ) {\n      if (this.childNodes.some((s) => s.RRNodeType === nodeType)) {\n        throw new Error(\n          `RRDomException: Failed to execute 'insertBefore' on 'RRNode': Only one ${\n            nodeType === RRNodeType.Element ? 'RRElement' : 'RRDoctype'\n          } on RRDocument allowed.`,\n        );\n      }\n    }\n\n    const child = insertBefore(this, newChild, refChild);\n    child.parentElement = null;\n    return child;\n  }\n\n  public removeChild(node: IRRNode): IRRNode {\n    return removeChild(this, node);\n  }\n\n  public open() {\n    this.firstChild = null;\n    this.lastChild = null;\n  }\n\n  public close() {\n    //\n  }\n\n  /**\n   * Adhoc implementation for setting xhtml namespace in rebuilt.ts (rrweb-snapshot).\n   * There are two lines used this function:\n   * 1. doc.write('\\<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"\"\\>')\n   * 2. doc.write('\\<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"\"\\>')\n   */\n  public write(content: string) {\n    let publicId;\n    if (\n      content ===\n      '<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"\">'\n    )\n      publicId = '-//W3C//DTD XHTML 1.0 Transitional//EN';\n    else if (\n      content ===\n      '<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"\">'\n    )\n      publicId = '-//W3C//DTD HTML 4.0 Transitional//EN';\n    if (publicId) {\n      const doctype = this.createDocumentType('html', publicId, '');\n      this.open();\n      this.appendChild(doctype);\n    }\n  }\n\n  createDocument(\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    _namespace: string | null,\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    _qualifiedName: string | null,\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    _doctype?: DocumentType | null,\n  ): IRRDocument {\n    return new BaseRRDocument();\n  }\n\n  createDocumentType(\n    qualifiedName: string,\n    publicId: string,\n    systemId: string,\n  ): IRRDocumentType {\n    const doctype = new BaseRRDocumentType(qualifiedName, publicId, systemId);\n    doctype.ownerDocument = this;\n    return doctype;\n  }\n\n  createElement(tagName: string): IRRElement {\n    const element = new BaseRRElement(tagName);\n    element.ownerDocument = this;\n    return element;\n  }\n\n  createElementNS(_namespaceURI: string, qualifiedName: string): IRRElement {\n    return this.createElement(qualifiedName);\n  }\n\n  createTextNode(data: string): IRRText {\n    const text = new BaseRRText(data);\n    text.ownerDocument = this;\n    return text;\n  }\n\n  createComment(data: string): IRRComment {\n    const comment = new BaseRRComment(data);\n    comment.ownerDocument = this;\n    return comment;\n  }\n\n  createCDATASection(data: string): IRRCDATASection {\n    const CDATASection = new BaseRRCDATASection(data);\n    CDATASection.ownerDocument = this;\n    return CDATASection;\n  }\n\n  toString() {\n    return 'RRDocument';\n  }\n}\n\nexport class BaseRRDocumentType extends BaseRRNode implements IRRDocumentType {\n  public readonly nodeType: number = NodeType.DOCUMENT_TYPE_NODE;\n  public readonly RRNodeType = RRNodeType.DocumentType;\n  declare readonly nodeName: string;\n  public readonly name: string;\n  public readonly publicId: string;\n  public readonly systemId: string;\n  public textContent: string | null = null;\n\n  constructor(qualifiedName: string, publicId: string, systemId: string) {\n    super();\n    this.name = qualifiedName;\n    this.publicId = publicId;\n    this.systemId = systemId;\n    this.nodeName = qualifiedName;\n  }\n\n  toString() {\n    return 'RRDocumentType';\n  }\n}\n\nexport class BaseRRElement extends BaseRRNode implements IRRElement {\n  public readonly nodeType: number = NodeType.ELEMENT_NODE;\n  public readonly RRNodeType = RRNodeType.Element;\n  declare readonly nodeName: string;\n  public tagName: string;\n  public attributes: Record<string, string> = {};\n  public shadowRoot: IRRElement | null = null;\n  public scrollLeft?: number;\n  public scrollTop?: number;\n\n  constructor(tagName: string) {\n    super();\n    this.tagName = tagName.toUpperCase();\n    this.nodeName = tagName.toUpperCase();\n  }\n\n  public get textContent(): string {\n    let result = '';\n    this.childNodes.forEach((node) => (result += node.textContent));\n    return result;\n  }\n\n  public set textContent(textContent: string) {\n    this.firstChild = null;\n    this.lastChild = null;\n    this.appendChild(this.ownerDocument.createTextNode(textContent));\n  }\n\n  public get classList(): ClassList {\n    return new ClassList(\n      this.attributes.class as string | undefined,\n      (newClassName) => {\n        this.attributes.class = newClassName;\n      },\n    );\n  }\n\n  public get id() {\n    return this.attributes.id || '';\n  }\n\n  public get className() {\n    return this.attributes.class || '';\n  }\n\n  public get style() {\n    const style = (\n      this.attributes.style ? parseCSSText(this.attributes.style) : {}\n    ) as CSSStyleDeclaration;\n    const hyphenateRE = /\\B([A-Z])/g;\n    style.setProperty = (\n      name: string,\n      value: string | null,\n      priority?: string | null,\n    ) => {\n      if (hyphenateRE.test(name)) return;\n      const normalizedName = camelize(name);\n      if (!value) delete style[normalizedName];\n      else style[normalizedName] = value;\n      if (priority === 'important') style[normalizedName] += ' !important';\n      this.attributes.style = toCSSText(style);\n    };\n    style.removeProperty = (name: string) => {\n      if (hyphenateRE.test(name)) return '';\n      const normalizedName = camelize(name);\n      const value = style[normalizedName] || '';\n      delete style[normalizedName];\n      this.attributes.style = toCSSText(style);\n      return value;\n    };\n    return style;\n  }\n\n  public getAttribute(name: string): string | null {\n    if (this.attributes[name] === undefined) return null;\n    return this.attributes[name];\n  }\n\n  public setAttribute(name: string, attribute: string) {\n    this.attributes[name] = attribute;\n  }\n\n  public setAttributeNS(\n    _namespace: string | null,\n    qualifiedName: string,\n    value: string,\n  ): void {\n    this.setAttribute(qualifiedName, value);\n  }\n\n  public removeAttribute(name: string) {\n    delete this.attributes[name];\n  }\n\n  public appendChild(newChild: IRRNode): IRRNode {\n    return appendChild(this, newChild);\n  }\n\n  public insertBefore(newChild: IRRNode, refChild: IRRNode | null): IRRNode {\n    return insertBefore(this, newChild, refChild);\n  }\n\n  public removeChild(node: IRRNode): IRRNode {\n    return removeChild(this, node);\n  }\n\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  public attachShadow(_init: ShadowRootInit): IRRElement {\n    const shadowRoot = this.ownerDocument.createElement('SHADOWROOT');\n    this.shadowRoot = shadowRoot;\n    return shadowRoot;\n  }\n\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  public dispatchEvent(_event: Event) {\n    return true;\n  }\n\n  toString() {\n    let attributeString = '';\n    for (const attribute in this.attributes) {\n      attributeString += `${attribute}=\"${this.attributes[attribute]}\" `;\n    }\n    return `${this.tagName} ${attributeString}`;\n  }\n}\n\nexport class BaseRRMediaElement extends BaseRRElement {\n  public currentTime?: number;\n  public volume?: number;\n  public paused?: boolean;\n  public muted?: boolean;\n  public playbackRate?: number;\n  public loop?: boolean;\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  attachShadow(_init: ShadowRootInit): IRRElement {\n    throw new Error(\n      `RRDomException: Failed to execute 'attachShadow' on 'RRElement': This RRElement does not support attachShadow`,\n    );\n  }\n  public play() {\n    this.paused = false;\n  }\n  public pause() {\n    this.paused = true;\n  }\n}\n\nexport class BaseRRDialogElement extends BaseRRElement {\n  public readonly tagName = 'DIALOG' as const;\n  public readonly nodeName = 'DIALOG' as const;\n\n  get isModal() {\n    return this.getAttribute('rr_open_mode') === 'modal';\n  }\n  get open() {\n    return this.getAttribute('open') !== null;\n  }\n  public close() {\n    this.removeAttribute('open');\n    this.removeAttribute('rr_open_mode');\n  }\n  public show() {\n    this.setAttribute('open', '');\n    this.setAttribute('rr_open_mode', 'non-modal');\n  }\n  public showModal() {\n    this.setAttribute('open', '');\n    this.setAttribute('rr_open_mode', 'modal');\n  }\n}\n\nexport class BaseRRText extends BaseRRNode implements IRRText {\n  public readonly nodeType: number = NodeType.TEXT_NODE;\n  public readonly nodeName = '#text' as const;\n  public readonly RRNodeType = RRNodeType.Text;\n  public data: string;\n\n  constructor(data: string) {\n    super();\n    this.data = data;\n  }\n\n  public get textContent(): string {\n    return this.data;\n  }\n\n  public set textContent(textContent: string) {\n    this.data = textContent;\n  }\n\n  toString() {\n    return `RRText text=${JSON.stringify(this.data)}`;\n  }\n}\n\nexport class BaseRRComment extends BaseRRNode implements IRRComment {\n  public readonly nodeType: number = NodeType.COMMENT_NODE;\n  public readonly nodeName = '#comment' as const;\n  public readonly RRNodeType = RRNodeType.Comment;\n  public data: string;\n\n  constructor(data: string) {\n    super();\n    this.data = data;\n  }\n\n  public get textContent(): string {\n    return this.data;\n  }\n\n  public set textContent(textContent: string) {\n    this.data = textContent;\n  }\n\n  toString() {\n    return `RRComment text=${JSON.stringify(this.data)}`;\n  }\n}\n\nexport class BaseRRCDATASection extends BaseRRNode implements IRRCDATASection {\n  public readonly nodeName = '#cdata-section' as const;\n  public readonly nodeType: number = NodeType.CDATA_SECTION_NODE;\n  public readonly RRNodeType = RRNodeType.CDATA;\n  public data: string;\n\n  constructor(data: string) {\n    super();\n    this.data = data;\n  }\n\n  public get textContent(): string {\n    return this.data;\n  }\n\n  public set textContent(textContent: string) {\n    this.data = textContent;\n  }\n\n  toString() {\n    return `RRCDATASection data=${JSON.stringify(this.data)}`;\n  }\n}\n\nexport class ClassList {\n  private onChange: ((newClassText: string) => void) | undefined;\n  classes: string[] = [];\n\n  constructor(\n    classText?: string,\n    onChange?: ((newClassText: string) => void) | undefined,\n  ) {\n    if (classText) {\n      const classes = classText.trim().split(/\\s+/);\n      this.classes.push(...classes);\n    }\n    this.onChange = onChange;\n  }\n\n  add = (...classNames: string[]) => {\n    for (const item of classNames) {\n      const className = String(item);\n      if (this.classes.indexOf(className) >= 0) continue;\n      this.classes.push(className);\n    }\n    this.onChange && this.onChange(this.classes.join(' '));\n  };\n\n  remove = (...classNames: string[]) => {\n    this.classes = this.classes.filter(\n      (item) => classNames.indexOf(item) === -1,\n    );\n    this.onChange && this.onChange(this.classes.join(' '));\n  };\n}\n\nexport type CSSStyleDeclaration = Record<string, string> & {\n  setProperty: (\n    name: string,\n    value: string | null,\n    priority?: string | null,\n  ) => void;\n  removeProperty: (name: string) => string;\n};\n\nfunction appendChild(parent: IRRNode, newChild: IRRNode) {\n  if (newChild.parentNode) newChild.parentNode.removeChild(newChild);\n\n  if (parent.lastChild) {\n    parent.lastChild.nextSibling = newChild;\n    newChild.previousSibling = parent.lastChild;\n  } else {\n    parent.firstChild = newChild;\n    newChild.previousSibling = null;\n  }\n  parent.lastChild = newChild;\n  newChild.nextSibling = null;\n  newChild.parentNode = parent;\n  newChild.parentElement = parent;\n  newChild.ownerDocument = parent.ownerDocument;\n  return newChild;\n}\n\nfunction insertBefore(\n  parent: IRRNode,\n  newChild: IRRNode,\n  refChild: IRRNode | null,\n) {\n  if (!refChild) return appendChild(parent, newChild);\n\n  if (refChild.parentNode !== parent)\n    throw new Error(\n      \"Failed to execute 'insertBefore' on 'RRNode': The RRNode before which the new node is to be inserted is not a child of this RRNode.\",\n    );\n\n  if (newChild === refChild) return newChild;\n  if (newChild.parentNode) newChild.parentNode.removeChild(newChild);\n\n  newChild.previousSibling = refChild.previousSibling;\n  refChild.previousSibling = newChild;\n  newChild.nextSibling = refChild;\n\n  if (newChild.previousSibling) newChild.previousSibling.nextSibling = newChild;\n  else parent.firstChild = newChild;\n\n  newChild.parentElement = parent;\n  newChild.parentNode = parent;\n  newChild.ownerDocument = parent.ownerDocument;\n  return newChild;\n}\n\nfunction removeChild(parent: IRRNode, child: IRRNode) {\n  if (child.parentNode !== parent)\n    throw new Error(\n      \"Failed to execute 'removeChild' on 'RRNode': The RRNode to be removed is not a child of this RRNode.\",\n    );\n  if (child.previousSibling)\n    child.previousSibling.nextSibling = child.nextSibling;\n  else parent.firstChild = child.nextSibling;\n  if (child.nextSibling)\n    child.nextSibling.previousSibling = child.previousSibling;\n  else parent.lastChild = child.previousSibling;\n  child.previousSibling = null;\n  child.nextSibling = null;\n  child.parentElement = null;\n  child.parentNode = null;\n  return child;\n}\n\n// Enumerate nodeType value of standard HTML Node.\nexport enum NodeType {\n  PLACEHOLDER, // This isn't a node type. Enum type value starts from zero but NodeType value starts from 1.\n  ELEMENT_NODE,\n  ATTRIBUTE_NODE,\n  TEXT_NODE,\n  CDATA_SECTION_NODE,\n  ENTITY_REFERENCE_NODE,\n  ENTITY_NODE,\n  PROCESSING_INSTRUCTION_NODE,\n  COMMENT_NODE,\n  DOCUMENT_NODE,\n  DOCUMENT_TYPE_NODE,\n  DOCUMENT_FRAGMENT_NODE,\n}\n", "import type {\n  throttleOptions,\n  listenerHandler,\n  hookResetter,\n  blockClass,\n  addedNodeMutation,\n  DocumentDimension,\n  IWindow,\n  DeprecatedMirror,\n  textMutation,\n  IMirror,\n} from '@rrweb/types';\nimport type { Mirror, SlimDOMOptions } from 'rrweb-snapshot';\nimport { isShadowRoot, IGNORED_NODE, classMatchesRegex } from 'rrweb-snapshot';\nimport { RRNode, RRIFrameElement, BaseRRNode } from 'rrdom';\nimport dom from '@rrweb/utils';\nexport { nowTimestamp } from '@rrweb/utils';\n\nexport function on(\n  type: string,\n  fn: EventListenerOrEventListenerObject,\n  target: Document | IWindow = document,\n): listenerHandler {\n  const options = { capture: true, passive: true };\n  target.addEventListener(type, fn, options);\n  return () => target.removeEventListener(type, fn, options);\n}\n\n// https://github.com/rrweb-io/rrweb/pull/407\nconst DEPARTED_MIRROR_ACCESS_WARNING =\n  'Please stop import mirror directly. Instead of that,' +\n  '\\r\\n' +\n  'now you can use replayer.getMirror() to access the mirror instance of a replayer,' +\n  '\\r\\n' +\n  'or you can use record.mirror to access the mirror instance during recording.';\n/** @deprecated */\nexport let _mirror: DeprecatedMirror = {\n  map: {},\n  getId() {\n    console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n    return -1;\n  },\n  getNode() {\n    console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n    return null;\n  },\n  removeNodeFromMap() {\n    console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n  },\n  has() {\n    console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n    return false;\n  },\n  reset() {\n    console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n  },\n};\nif (typeof window !== 'undefined' && window.Proxy && window.Reflect) {\n  _mirror = new Proxy(_mirror, {\n    get(target, prop, receiver) {\n      if (prop === 'map') {\n        console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n      }\n      // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n      return Reflect.get(target, prop, receiver);\n    },\n  });\n}\n\n// copy from underscore and modified\nexport function throttle<T>(\n  func: (arg: T) => void,\n  wait: number,\n  options: throttleOptions = {},\n) {\n  let timeout: ReturnType<typeof setTimeout> | null = null;\n  let previous = 0;\n  return function (...args: T[]) {\n    const now = Date.now();\n    if (!previous && options.leading === false) {\n      previous = now;\n    }\n    const remaining = wait - (now - previous);\n    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-this-alias\n    const context = this;\n    if (remaining <= 0 || remaining > wait) {\n      if (timeout) {\n        clearTimeout(timeout);\n        timeout = null;\n      }\n      previous = now;\n      func.apply(context, args);\n    } else if (!timeout && options.trailing !== false) {\n      timeout = setTimeout(() => {\n        previous = options.leading === false ? 0 : Date.now();\n        timeout = null;\n        func.apply(context, args);\n      }, remaining);\n    }\n  };\n}\n\nexport function hookSetter<T>(\n  target: T,\n  key: string | number | symbol,\n  d: PropertyDescriptor,\n  isRevoked?: boolean,\n  win = window,\n): hookResetter {\n  const original = win.Object.getOwnPropertyDescriptor(target, key);\n  win.Object.defineProperty(\n    target,\n    key,\n    isRevoked\n      ? d\n      : {\n          set(value) {\n            // put hooked setter into event loop to avoid of set latency\n            setTimeout(() => {\n              d.set!.call(this, value);\n            }, 0);\n            if (original && original.set) {\n              original.set.call(this, value);\n            }\n          },\n        },\n  );\n  return () => hookSetter(target, key, original || {}, true);\n}\n\nexport function getWindowScroll(win: Window) {\n  const doc = win.document;\n  return {\n    left: doc.scrollingElement\n      ? doc.scrollingElement.scrollLeft\n      : win.pageXOffset !== undefined\n      ? win.pageXOffset\n      : doc.documentElement.scrollLeft ||\n        (doc?.body && dom.parentElement(doc.body)?.scrollLeft) ||\n        doc?.body?.scrollLeft ||\n        0,\n    top: doc.scrollingElement\n      ? doc.scrollingElement.scrollTop\n      : win.pageYOffset !== undefined\n      ? win.pageYOffset\n      : doc?.documentElement.scrollTop ||\n        (doc?.body && dom.parentElement(doc.body)?.scrollTop) ||\n        doc?.body?.scrollTop ||\n        0,\n  };\n}\n\nexport function getWindowHeight(): number {\n  return (\n    window.innerHeight ||\n    (document.documentElement && document.documentElement.clientHeight) ||\n    (document.body && document.body.clientHeight)\n  );\n}\n\nexport function getWindowWidth(): number {\n  return (\n    window.innerWidth ||\n    (document.documentElement && document.documentElement.clientWidth) ||\n    (document.body && document.body.clientWidth)\n  );\n}\n\n/**\n * Returns the given node as an HTMLElement if it is one, otherwise the parent node as an HTMLElement\n * @param node - node to check\n * @returns HTMLElement or null\n */\n\nexport function closestElementOfNode(node: Node | null): HTMLElement | null {\n  if (!node) {\n    return null;\n  }\n  const el: HTMLElement | null =\n    node.nodeType === node.ELEMENT_NODE\n      ? (node as HTMLElement)\n      : dom.parentElement(node);\n  return el;\n}\n\n/**\n * Checks if the given element set to be blocked by rrweb\n * @param node - node to check\n * @param blockClass - class name to check\n * @param blockSelector - css selectors to check\n * @param checkAncestors - whether to search through parent nodes for the block class\n * @returns true/false if the node was blocked or not\n */\nexport function isBlocked(\n  node: Node | null,\n  blockClass: blockClass,\n  blockSelector: string | null,\n  checkAncestors: boolean,\n): boolean {\n  if (!node) {\n    return false;\n  }\n  const el = closestElementOfNode(node);\n\n  if (!el) {\n    return false;\n  }\n\n  try {\n    if (typeof blockClass === 'string') {\n      if (el.classList.contains(blockClass)) return true;\n      if (checkAncestors && el.closest('.' + blockClass) !== null) return true;\n    } else {\n      if (classMatchesRegex(el, blockClass, checkAncestors)) return true;\n    }\n  } catch (e) {\n    // e\n  }\n  if (blockSelector) {\n    if (el.matches(blockSelector)) return true;\n    if (checkAncestors && el.closest(blockSelector) !== null) return true;\n  }\n  return false;\n}\n\nexport function isSerialized(n: Node, mirror: Mirror): boolean {\n  return mirror.getId(n) !== -1;\n}\n\nexport function isIgnored(\n  n: Node,\n  mirror: Mirror,\n  slimDOMOptions: SlimDOMOptions,\n): boolean {\n  if ((n as Element).tagName === 'TITLE' && slimDOMOptions.headTitleMutations) {\n    // we do this check here but not in rrweb-snapshot\n    // to block mutations/animations on the title.\n    // the headTitleMutations option isn't intended to block recording of the initial value\n    return true;\n  }\n  // The main part of the slimDOM check happens in\n  // rrweb-snapshot::serializeNodeWithId\n  return mirror.getId(n) === IGNORED_NODE;\n}\n\nexport function isAncestorRemoved(target: Node, mirror: Mirror): boolean {\n  if (isShadowRoot(target)) {\n    return false;\n  }\n  const id = mirror.getId(target);\n  if (!mirror.has(id)) {\n    return true;\n  }\n  const parent = dom.parentNode(target);\n  if (parent && parent.nodeType === target.DOCUMENT_NODE) {\n    return false;\n  }\n  // if the root is not document, it means the node is not in the DOM tree anymore\n  if (!parent) {\n    return true;\n  }\n  return isAncestorRemoved(parent, mirror);\n}\n\nexport function legacy_isTouchEvent(\n  event: MouseEvent | TouchEvent | PointerEvent,\n): event is TouchEvent {\n  return Boolean((event as TouchEvent).changedTouches);\n}\n\nexport function polyfill(win = window) {\n  if ('NodeList' in win && !win.NodeList.prototype.forEach) {\n    // eslint-disable-next-line @typescript-eslint/unbound-method\n    win.NodeList.prototype.forEach = Array.prototype\n      .forEach as unknown as NodeList['forEach'];\n  }\n\n  if ('DOMTokenList' in win && !win.DOMTokenList.prototype.forEach) {\n    // eslint-disable-next-line @typescript-eslint/unbound-method\n    win.DOMTokenList.prototype.forEach = Array.prototype\n      .forEach as unknown as DOMTokenList['forEach'];\n  }\n}\n\ntype ResolveTree = {\n  value: addedNodeMutation;\n  children: ResolveTree[];\n  parent: ResolveTree | null;\n};\n\nexport function queueToResolveTrees(queue: addedNodeMutation[]): ResolveTree[] {\n  const queueNodeMap: Record<number, ResolveTree> = {};\n  const putIntoMap = (\n    m: addedNodeMutation,\n    parent: ResolveTree | null,\n  ): ResolveTree => {\n    const nodeInTree: ResolveTree = {\n      value: m,\n      parent,\n      children: [],\n    };\n    queueNodeMap[m.node.id] = nodeInTree;\n    return nodeInTree;\n  };\n\n  const queueNodeTrees: ResolveTree[] = [];\n  for (const mutation of queue) {\n    const { nextId, parentId } = mutation;\n    if (nextId && nextId in queueNodeMap) {\n      const nextInTree = queueNodeMap[nextId];\n      if (nextInTree.parent) {\n        const idx = nextInTree.parent.children.indexOf(nextInTree);\n        nextInTree.parent.children.splice(\n          idx,\n          0,\n          putIntoMap(mutation, nextInTree.parent),\n        );\n      } else {\n        const idx = queueNodeTrees.indexOf(nextInTree);\n        queueNodeTrees.splice(idx, 0, putIntoMap(mutation, null));\n      }\n      continue;\n    }\n    if (parentId in queueNodeMap) {\n      const parentInTree = queueNodeMap[parentId];\n      parentInTree.children.push(putIntoMap(mutation, parentInTree));\n      continue;\n    }\n    queueNodeTrees.push(putIntoMap(mutation, null));\n  }\n\n  return queueNodeTrees;\n}\n\nexport function iterateResolveTree(\n  tree: ResolveTree,\n  cb: (mutation: addedNodeMutation) => unknown,\n) {\n  cb(tree.value);\n  /**\n   * The resolve tree was designed to reflect the DOM layout,\n   * but we need append next sibling first, so we do a reverse\n   * loop here.\n   */\n  for (let i = tree.children.length - 1; i >= 0; i--) {\n    iterateResolveTree(tree.children[i], cb);\n  }\n}\n\nexport type AppendedIframe = {\n  mutationInQueue: addedNodeMutation;\n  builtNode: HTMLIFrameElement | RRIFrameElement;\n};\n\nexport function isSerializedIframe<TNode extends Node | RRNode>(\n  n: TNode,\n  mirror: IMirror<TNode>,\n): boolean {\n  return Boolean(n.nodeName === 'IFRAME' && mirror.getMeta(n));\n}\n\nexport function isSerializedStylesheet<TNode extends Node | RRNode>(\n  n: TNode,\n  mirror: IMirror<TNode>,\n): boolean {\n  return Boolean(\n    n.nodeName === 'LINK' &&\n      n.nodeType === n.ELEMENT_NODE &&\n      (n as HTMLElement).getAttribute &&\n      (n as HTMLElement).getAttribute('rel') === 'stylesheet' &&\n      mirror.getMeta(n),\n  );\n}\n\nexport function getBaseDimension(\n  node: Node,\n  rootIframe: Node,\n): DocumentDimension {\n  const frameElement = node.ownerDocument?.defaultView?.frameElement;\n  if (!frameElement || frameElement === rootIframe) {\n    return {\n      x: 0,\n      y: 0,\n      relativeScale: 1,\n      absoluteScale: 1,\n    };\n  }\n\n  const frameDimension = frameElement.getBoundingClientRect();\n  const frameBaseDimension = getBaseDimension(frameElement, rootIframe);\n  // the iframe element may have a scale transform\n  const relativeScale = frameDimension.height / frameElement.clientHeight;\n  return {\n    x:\n      frameDimension.x * frameBaseDimension.relativeScale +\n      frameBaseDimension.x,\n    y:\n      frameDimension.y * frameBaseDimension.relativeScale +\n      frameBaseDimension.y,\n    relativeScale,\n    absoluteScale: frameBaseDimension.absoluteScale * relativeScale,\n  };\n}\n\nexport function hasShadowRoot<T extends Node | RRNode>(\n  n: T,\n): n is T & { shadowRoot: ShadowRoot } {\n  if (!n) return false;\n  if (n instanceof BaseRRNode && 'shadowRoot' in n) {\n    return Boolean(n.shadowRoot);\n  }\n  return Boolean(dom.shadowRoot(n as unknown as Element));\n}\n\n/**\n * Traverses a CSSRuleList to find a nested rule at the given position.\n *\n * Returns null instead of throwing if the rule doesn't exist. This is important\n * because during replay:\n * - StyleDeclaration events may reference rules added dynamically that don't\n *   exist yet due to timing/ordering issues\n * - StyleSheetRule events that create rules may not have been processed yet\n * - Constructed/adopted stylesheets may not be fully synchronized\n *\n * @param rules - The CSSRuleList to traverse\n * @param position - Array of indices, e.g., [0, 1, 0] for rules[0].cssRules[1].cssRules[0]\n * @returns The nested rule, or null if not found\n */\nexport function getNestedRule(\n  rules: CSSRuleList,\n  position: number[],\n): CSSGroupingRule | null {\n  const rule = rules?.[position[0]] as CSSGroupingRule | null;\n  if (!rule) {\n    return null;\n  }\n  if (position.length === 1) {\n    return rule;\n  } else {\n    return getNestedRule(rule.cssRules, position.slice(1));\n  }\n}\n\nexport function getPositionsAndIndex(nestedIndex: number[]) {\n  const positions = [...nestedIndex];\n  const index = positions.pop();\n  return { positions, index };\n}\n\n/**\n * Returns the latest mutation in the queue for each node.\n * @param mutations - mutations The text mutations to filter.\n * @returns The filtered text mutations.\n */\nexport function uniqueTextMutations(mutations: textMutation[]): textMutation[] {\n  const idSet = new Set<number>();\n  const uniqueMutations: textMutation[] = [];\n\n  for (let i = mutations.length; i--; ) {\n    const mutation = mutations[i];\n    if (!idSet.has(mutation.id)) {\n      uniqueMutations.push(mutation);\n      idSet.add(mutation.id);\n    }\n  }\n\n  return uniqueMutations;\n}\n\nexport class StyleSheetMirror {\n  private id = 1;\n  private styleIDMap = new WeakMap<CSSStyleSheet, number>();\n  private idStyleMap = new Map<number, CSSStyleSheet>();\n\n  getId(stylesheet: CSSStyleSheet): number {\n    return this.styleIDMap.get(stylesheet) ?? -1;\n  }\n\n  has(stylesheet: CSSStyleSheet): boolean {\n    return this.styleIDMap.has(stylesheet);\n  }\n\n  /**\n   * @returns If the stylesheet is in the mirror, returns the id of the stylesheet. If not, return the new assigned id.\n   */\n  add(stylesheet: CSSStyleSheet, id?: number): number {\n    if (this.has(stylesheet)) return this.getId(stylesheet);\n    let newId: number;\n    if (id === undefined) {\n      newId = this.id++;\n    } else newId = id;\n    this.styleIDMap.set(stylesheet, newId);\n    this.idStyleMap.set(newId, stylesheet);\n    return newId;\n  }\n\n  getStyle(id: number): CSSStyleSheet | null {\n    return this.idStyleMap.get(id) || null;\n  }\n\n  reset(): void {\n    this.styleIDMap = new WeakMap();\n    this.idStyleMap = new Map();\n    this.id = 1;\n  }\n\n  generateId(): number {\n    return this.id++;\n  }\n}\n\n/**\n * Get the direct shadow host of a node in shadow dom. Returns null if it is not in a shadow dom.\n */\nexport function getShadowHost(n: Node): Element | null {\n  let shadowHost: Element | null = null;\n  if (\n    'getRootNode' in n &&\n    dom.getRootNode(n)?.nodeType === Node.DOCUMENT_FRAGMENT_NODE &&\n    dom.host(dom.getRootNode(n) as ShadowRoot)\n  )\n    shadowHost = dom.host(dom.getRootNode(n) as ShadowRoot);\n  return shadowHost;\n}\n\n/**\n * Get the root shadow host of a node in nested shadow doms. Returns the node itself if it is not in a shadow dom.\n */\nexport function getRootShadowHost(n: Node): Node {\n  let rootShadowHost: Node = n;\n\n  let shadowHost: Element | null;\n  // If n is in a nested shadow dom.\n  while ((shadowHost = getShadowHost(rootShadowHost)))\n    rootShadowHost = shadowHost;\n\n  return rootShadowHost;\n}\n\nexport function shadowHostInDom(n: Node): boolean {\n  const doc = dom.ownerDocument(n);\n  if (!doc) return false;\n  const shadowHost = getRootShadowHost(n);\n  return dom.contains(doc, shadowHost);\n}\n\nexport function inDom(n: Node): boolean {\n  const doc = dom.ownerDocument(n);\n  if (!doc) return false;\n  return dom.contains(doc, n) || shadowHostInDom(n);\n}\n", "import {\n  serializeNodeWithId,\n  transformAttribute,\n  IGNORED_NODE,\n  ignoreAttribute,\n  isShadowRoot,\n  needMaskingText,\n  maskInputValue,\n  isNativeShadowDom,\n  getInputType,\n  toLowerCase,\n} from 'rrweb-snapshot';\nimport type { observerParam, MutationBufferParam } from '../types';\nimport type {\n  mutationRecord,\n  textCursor,\n  attributeCursor,\n  removedNodeMutation,\n  addedNodeMutation,\n} from '@rrweb/types';\nimport {\n  isBlocked,\n  isAncestorRemoved,\n  isIgnored,\n  isSerialized,\n  hasShadowRoot,\n  isSerializedIframe,\n  isSerializedStylesheet,\n  inDom,\n  getShadowHost,\n  closestElementOfNode,\n} from '../utils';\nimport dom from '@rrweb/utils';\n\nconst moveKey = (id: number, parentId: number) => `${id}@${parentId}`;\n\n/**\n * controls behaviour of a MutationObserver\n */\nexport default class MutationBuffer {\n  private frozen = false;\n  private locked = false;\n\n  private texts: textCursor[] = [];\n  private attributes: attributeCursor[] = [];\n  private attributeMap = new WeakMap<Node, attributeCursor>();\n  private removes: removedNodeMutation[] = [];\n  private mapRemoves: Node[] = [];\n\n  private movedMap: Record<string, true> = {};\n\n  /**\n   * the browser MutationObserver emits multiple mutations after\n   * a delay for performance reasons, making tracing added nodes hard\n   * in our `processMutations` callback function.\n   * For example, if we append an element el_1 into body, and then append\n   * another element el_2 into el_1, these two mutations may be passed to the\n   * callback function together when the two operations were done.\n   * Generally we need to trace child nodes of newly added nodes, but in this\n   * case if we count el_2 as el_1's child node in the first mutation record,\n   * then we will count el_2 again in the second mutation record which was\n   * duplicated.\n   * To avoid of duplicate counting added nodes, we use a Set to store\n   * added nodes and its child nodes during iterate mutation records. Then\n   * collect added nodes from the Set which have no duplicate copy. But\n   * this also causes newly added nodes will not be serialized with id ASAP,\n   * which means all the id related calculation should be lazy too.\n   */\n  private addedSet = new Set<Node>();\n  private movedSet = new Set<Node>();\n  private droppedSet = new Set<Node>();\n  private removesSubTreeCache = new Set<Node>();\n\n  private mutationCb: observerParam['mutationCb'];\n  private blockClass: observerParam['blockClass'];\n  private blockSelector: observerParam['blockSelector'];\n  private maskTextClass: observerParam['maskTextClass'];\n  private maskTextSelector: observerParam['maskTextSelector'];\n  private inlineStylesheet: observerParam['inlineStylesheet'];\n  private maskInputOptions: observerParam['maskInputOptions'];\n  private maskTextFn: observerParam['maskTextFn'];\n  private maskInputFn: observerParam['maskInputFn'];\n  private keepIframeSrcFn: observerParam['keepIframeSrcFn'];\n  private recordCanvas: observerParam['recordCanvas'];\n  private inlineImages: observerParam['inlineImages'];\n  private slimDOMOptions: observerParam['slimDOMOptions'];\n  private dataURLOptions: observerParam['dataURLOptions'];\n  private doc: observerParam['doc'];\n  private mirror: observerParam['mirror'];\n\n  // managers: convenience references to per-recording singletons\n  private iframeManager: observerParam['iframeManager'];\n  private stylesheetManager: observerParam['stylesheetManager'];\n  private shadowDomManager: observerParam['shadowDomManager'];\n  private processedNodeManager: observerParam['processedNodeManager'];\n\n  private unattachedDoc: HTMLDocument;\n\n  public init(options: MutationBufferParam) {\n    (\n      [\n        'mutationCb',\n        'blockClass',\n        'blockSelector',\n        'maskTextClass',\n        'maskTextSelector',\n        'inlineStylesheet',\n        'maskInputOptions',\n        'maskTextFn',\n        'maskInputFn',\n        'keepIframeSrcFn',\n        'recordCanvas',\n        'inlineImages',\n        'slimDOMOptions',\n        'dataURLOptions',\n        'doc',\n        'mirror',\n        'iframeManager',\n        'stylesheetManager',\n        'shadowDomManager',\n        'processedNodeManager',\n      ] as const\n    ).forEach((key) => {\n      // just a type trick, the runtime result is correct\n      this[key] = options[key] as never;\n    });\n  }\n\n  public freeze() {\n    this.frozen = true;\n  }\n\n  public unfreeze() {\n    this.frozen = false;\n    this.emit();\n  }\n\n  public isFrozen() {\n    return this.frozen;\n  }\n\n  public lock() {\n    this.locked = true;\n  }\n\n  public unlock() {\n    this.locked = false;\n    this.emit();\n  }\n\n  public processMutations = (mutations: mutationRecord[]) => {\n    mutations.forEach(this.processMutation); // adds mutations to the buffer\n    this.emit(); // clears buffer if not locked/frozen\n  };\n\n  public emit = () => {\n    if (this.frozen || this.locked) {\n      return;\n    }\n\n    // delay any modification of the mirror until this function\n    // so that the mirror for takeFullSnapshot doesn't get mutated while it's event is being processed\n\n    const adds: addedNodeMutation[] = [];\n    const addedIds = new Set<number>();\n\n    while (this.mapRemoves.length) {\n      this.mirror.removeNodeFromMap(this.mapRemoves.shift()!);\n    }\n\n    for (const n of this.movedSet) {\n      const parentNode = dom.parentNode(n);\n      if (\n        this.removesSubTreeCache.has(parentNode as Node) &&\n        !this.movedSet.has(parentNode as Node)\n      ) {\n        continue;\n      }\n      this.addedSet.add(n);\n    }\n\n    let n: Node | null = null;\n    let parentNode: Node | null = null;\n    let parentId = -1;\n    let nextSibling: Node | null = null;\n    let ancestorBad = false;\n    const missingParents = new Set<Node>();\n    const iter = this.addedSet.values();\n    let curr = iter.next();\n    while (this.addedSet.size) {\n      if (n !== null && this.addedSet.has(dom.previousSibling(n) as Node)) {\n        // reuse parentNode, parentId, ancestorBad\n        nextSibling = n; // n is a good next sibling\n        n = dom.previousSibling(n) as Node;\n      } else {\n        if (!this.addedSet.has(curr.value as Node)) {\n          // having the `iter` here rather than picking directly from this.addedSet\n          // ensures we don't get caught re-traversing 'tombstones' in the Set\n          // (we reuse curr in multiple iterations until it's ancestors and nextSiblings are serialized)\n          curr = iter.next();\n        }\n        n = curr.value as Node;\n\n        // eslint-disable-next-line no-constant-condition\n        while (true) {\n          parentNode = dom.parentNode(n);\n          if (this.addedSet.has(parentNode as Node)) {\n            // start at top of added tree so as not to serialize children before their parents (parentId requirement)\n            n = parentNode as Node;\n            continue;\n          }\n          break;\n        }\n\n        if (missingParents.has(parentNode as Node)) {\n          parentNode = null;\n        } else if (parentNode) {\n          // we have a new parentNode for a 'row' of DOM children\n          // perf: we reuse these calculations across all child nodes\n\n          if (!inDom(parentNode)) {\n            ancestorBad = true;\n          } else {\n            ancestorBad =\n              isSelfOrAncestorInSet(this.droppedSet, parentNode) ||\n              this.removesSubTreeCache.has(parentNode);\n\n            if (ancestorBad && isSelfOrAncestorInSet(this.movedSet, n)) {\n              // not bad, just moved\n              ancestorBad = false;\n            }\n          }\n\n          if (this.addedSet.has(dom.lastChild(parentNode) as Node)) {\n            // jump instead of crawling nextSibling to nextSibling\n            n = dom.lastChild(parentNode) as Node;\n            nextSibling = null;\n          } else {\n            // eslint-disable-next-line no-constant-condition\n            while (true) {\n              nextSibling = dom.nextSibling(n);\n              if (this.addedSet.has(nextSibling as Node)) {\n                // keep going as we can't serialize a node before it's next sibling (nextId requirement)\n                n = nextSibling as Node;\n                continue;\n              }\n              break;\n            }\n          }\n\n          parentId = isShadowRoot(parentNode)\n            ? this.mirror.getId(getShadowHost(n))\n            : this.mirror.getId(parentNode);\n\n          // If the node is the direct child of a shadow root, we treat the shadow host as its parent node.\n          if (\n            parentId === -1 &&\n            parentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE\n          ) {\n            const shadowHost = dom.host(parentNode as ShadowRoot);\n            parentId = this.mirror.getId(shadowHost);\n          }\n        }\n      }\n\n      this.addedSet.delete(n); // don't re-iterate\n\n      if (!parentNode || parentId === -1) {\n        missingParents.add(n); // ensure any added child nodes can also early-out\n        continue;\n      } else if (ancestorBad) {\n        // it's possible we could unify missingParents and this.droppedSet\n        // but would need to check the subtleties\n        this.droppedSet.add(n);\n        continue;\n      }\n\n      let cssCaptured = false;\n      if (n.nodeType === Node.TEXT_NODE) {\n        const parentTag = (parentNode as Element).tagName;\n        if (parentTag === 'TEXTAREA') {\n          // genTextAreaValueMutation already called via parent\n          continue;\n        } else if (parentTag === 'STYLE' && addedIds.has(parentId)) {\n          // css content will be recorded via parent's _cssText attribute when\n          // mutation adds entire <style> element\n          cssCaptured = true;\n        }\n      }\n\n      let nextId = nextSibling ? this.mirror.getId(nextSibling) : null;\n      while (nextId === IGNORED_NODE) {\n        nextSibling = nextSibling && dom.nextSibling(nextSibling);\n        nextId = nextSibling && this.mirror.getId(nextSibling);\n      }\n      if (nextId === -1) {\n        // sibling not included in addedNodes, but\n        // no id as not yet serialized?\n        console.warn(\n          \"Couldn't record new node. Couldn't find mirror id for nextSibling:\",\n          nextSibling,\n        );\n        n = null; // don't iterate to previousSibling as we haven't successful serialized this node\n        continue;\n      }\n      const sn = serializeNodeWithId(n, {\n        doc: this.doc,\n        mirror: this.mirror,\n        blockClass: this.blockClass,\n        blockSelector: this.blockSelector,\n        maskTextClass: this.maskTextClass,\n        maskTextSelector: this.maskTextSelector,\n        skipChild: true,\n        newlyAddedElement: true,\n        inlineStylesheet: this.inlineStylesheet,\n        maskInputOptions: this.maskInputOptions,\n        maskTextFn: this.maskTextFn,\n        maskInputFn: this.maskInputFn,\n        slimDOMOptions: this.slimDOMOptions,\n        dataURLOptions: this.dataURLOptions,\n        recordCanvas: this.recordCanvas,\n        inlineImages: this.inlineImages,\n        onSerialize: (currentN) => {\n          if (isSerializedIframe(currentN, this.mirror)) {\n            this.iframeManager.addIframe(currentN as HTMLIFrameElement);\n          }\n          if (isSerializedStylesheet(currentN, this.mirror)) {\n            this.stylesheetManager.trackLinkElement(\n              currentN as HTMLLinkElement,\n            );\n          }\n          if (hasShadowRoot(n as Node)) {\n            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n            this.shadowDomManager.addShadowRoot(\n              dom.shadowRoot(n as Node)!,\n              this.doc,\n            );\n          }\n        },\n        onIframeLoad: (iframe, childSn) => {\n          this.iframeManager.attachIframe(iframe, childSn);\n          this.shadowDomManager.observeAttachShadow(iframe);\n        },\n        onStylesheetLoad: (link, childSn) => {\n          this.stylesheetManager.attachLinkElement(link, childSn);\n        },\n        cssCaptured,\n      });\n      if (sn) {\n        adds.push({\n          parentId,\n          nextId,\n          node: sn,\n        });\n        addedIds.add(sn.id);\n      }\n    }\n\n    const payload = {\n      texts: this.texts\n        .map((text) => {\n          const n = text.node;\n          const parent = dom.parentNode(n);\n          if (parent && (parent as Element).tagName === 'TEXTAREA') {\n            // the node is being ignored as it isn't in the mirror, so shift mutation to attributes on parent textarea\n            this.genTextAreaValueMutation(parent as HTMLTextAreaElement);\n          }\n          return {\n            id: this.mirror.getId(n),\n            value: text.value,\n          };\n        })\n        // no need to include them on added elements, as they have just been serialized with up to date attribubtes\n        .filter((text) => !addedIds.has(text.id))\n        // text mutation's id was not in the mirror map means the target node has been removed\n        .filter((text) => this.mirror.has(text.id)),\n      attributes: this.attributes\n        .map((attribute) => {\n          const { attributes } = attribute;\n          if (typeof attributes.style === 'string') {\n            const diffAsStr = JSON.stringify(attribute.styleDiff);\n            const unchangedAsStr = JSON.stringify(attribute._unchangedStyles);\n            // check if the style diff is actually shorter than the regular string based mutation\n            // (which was the whole point of #464 'compact style mutation').\n            if (diffAsStr.length < attributes.style.length) {\n              // also: CSSOM fails badly when var() is present on shorthand properties, so only proceed with\n              // the compact style mutation if these have all been accounted for\n              if (\n                (diffAsStr + unchangedAsStr).split('var(').length ===\n                attributes.style.split('var(').length\n              ) {\n                attributes.style = attribute.styleDiff;\n              }\n            }\n          }\n          return {\n            id: this.mirror.getId(attribute.node),\n            attributes: attributes,\n          };\n        })\n        // no need to include them on added elements, as they have just been serialized with up to date attribubtes\n        .filter((attribute) => !addedIds.has(attribute.id))\n        // attribute mutation's id was not in the mirror map means the target node has been removed\n        .filter((attribute) => this.mirror.has(attribute.id)),\n      removes: this.removes,\n      adds,\n    };\n    // payload may be empty if the mutations happened in some blocked elements\n    if (\n      !payload.texts.length &&\n      !payload.attributes.length &&\n      !payload.removes.length &&\n      !payload.adds.length\n    ) {\n      return;\n    }\n\n    // reset\n    this.texts = [];\n    this.attributes = [];\n    this.attributeMap = new WeakMap<Node, attributeCursor>();\n    this.removes = [];\n    this.addedSet = new Set<Node>();\n    this.movedSet = new Set<Node>();\n    this.droppedSet = new Set<Node>();\n    this.removesSubTreeCache = new Set<Node>();\n    this.movedMap = {};\n\n    this.mutationCb(payload);\n  };\n\n  private genTextAreaValueMutation = (textarea: HTMLTextAreaElement) => {\n    let item = this.attributeMap.get(textarea);\n    if (!item) {\n      item = {\n        node: textarea,\n        attributes: {},\n        styleDiff: {},\n        _unchangedStyles: {},\n      };\n      this.attributes.push(item);\n      this.attributeMap.set(textarea, item);\n    }\n    const value = Array.from(\n      dom.childNodes(textarea),\n      (cn) => dom.textContent(cn) || '',\n    ).join('');\n    item.attributes.value = maskInputValue({\n      element: textarea,\n      maskInputOptions: this.maskInputOptions,\n      tagName: textarea.tagName,\n      type: getInputType(textarea),\n      value,\n      maskInputFn: this.maskInputFn,\n    });\n  };\n\n  private processMutation = (m: mutationRecord) => {\n    if (isIgnored(m.target, this.mirror, this.slimDOMOptions)) {\n      return;\n    }\n    switch (m.type) {\n      case 'characterData': {\n        const value = dom.textContent(m.target);\n\n        if (\n          !isBlocked(m.target, this.blockClass, this.blockSelector, false) &&\n          value !== m.oldValue\n        ) {\n          this.texts.push({\n            value:\n              needMaskingText(\n                m.target,\n                this.maskTextClass,\n                this.maskTextSelector,\n                true, // checkAncestors\n              ) && value\n                ? this.maskTextFn\n                  ? this.maskTextFn(value, closestElementOfNode(m.target))\n                  : value.replace(/[\\S]/g, '*')\n                : value,\n            node: m.target,\n          });\n        }\n        break;\n      }\n      case 'attributes': {\n        const target = m.target as HTMLElement;\n        const tagNameLower = toLowerCase(target.tagName);\n        let attributeName = m.attributeName as string;\n        let value = (m.target as HTMLElement).getAttribute(attributeName);\n\n        if (attributeName === 'value') {\n          const type = getInputType(target);\n\n          value = maskInputValue({\n            element: target,\n            maskInputOptions: this.maskInputOptions,\n            tagName: target.tagName,\n            type,\n            value,\n            maskInputFn: this.maskInputFn,\n          });\n        }\n        if (\n          isBlocked(m.target, this.blockClass, this.blockSelector, false) ||\n          value === m.oldValue\n        ) {\n          return;\n        }\n\n        let item = this.attributeMap.get(m.target);\n        if (\n          tagNameLower === 'iframe' &&\n          attributeName === 'src' &&\n          !this.keepIframeSrcFn(value as string)\n        ) {\n          if (!(target as HTMLIFrameElement).contentDocument) {\n            // we can't record it directly as we can't see into it\n            // preserve the src attribute so a decision can be taken at replay time\n            attributeName = 'rr_src';\n          } else {\n            return;\n          }\n        }\n        if (!item) {\n          item = {\n            node: m.target,\n            attributes: {},\n            styleDiff: {},\n            _unchangedStyles: {},\n          };\n          this.attributes.push(item);\n          this.attributeMap.set(m.target, item);\n        }\n\n        // Keep this property on inputs that used to be password inputs\n        // This is used to ensure we do not unmask value when using e.g. a \"Show password\" type button\n        if (\n          attributeName === 'type' &&\n          tagNameLower === 'input' &&\n          (m.oldValue || '').toLowerCase() === 'password'\n        ) {\n          target.setAttribute('data-rr-is-password', 'true');\n        }\n\n        if (!ignoreAttribute(tagNameLower, attributeName, value)) {\n          // overwrite attribute if the mutations was triggered in same time\n          item.attributes[attributeName] = transformAttribute(\n            this.doc,\n            tagNameLower,\n            toLowerCase(attributeName),\n            value,\n          );\n          if (attributeName === 'style') {\n            if (!this.unattachedDoc) {\n              try {\n                // avoid upsetting original document from a Content Security point of view\n                this.unattachedDoc =\n                  document.implementation.createHTMLDocument();\n              } catch (e) {\n                // fallback to more direct method\n                this.unattachedDoc = this.doc;\n              }\n            }\n            const old = this.unattachedDoc.createElement('span');\n            if (m.oldValue) {\n              old.setAttribute('style', m.oldValue);\n            }\n            for (const pname of Array.from(target.style)) {\n              const newValue = target.style.getPropertyValue(pname);\n              const newPriority = target.style.getPropertyPriority(pname);\n              if (\n                newValue !== old.style.getPropertyValue(pname) ||\n                newPriority !== old.style.getPropertyPriority(pname)\n              ) {\n                if (newPriority === '') {\n                  item.styleDiff[pname] = newValue;\n                } else {\n                  item.styleDiff[pname] = [newValue, newPriority];\n                }\n              } else {\n                // for checking\n                item._unchangedStyles[pname] = [newValue, newPriority];\n              }\n            }\n            for (const pname of Array.from(old.style)) {\n              if (target.style.getPropertyValue(pname) === '') {\n                // \"if not set, returns the empty string\"\n                item.styleDiff[pname] = false; // delete\n              }\n            }\n          } else if (attributeName === 'open' && target.tagName === 'DIALOG') {\n            if (target.matches('dialog:modal')) {\n              item.attributes['rr_open_mode'] = 'modal';\n            } else {\n              item.attributes['rr_open_mode'] = 'non-modal';\n            }\n          }\n        }\n        break;\n      }\n      case 'childList': {\n        /**\n         * Parent is blocked, ignore all child mutations\n         */\n        if (isBlocked(m.target, this.blockClass, this.blockSelector, true))\n          return;\n\n        if ((m.target as Element).tagName === 'TEXTAREA') {\n          // children would be ignored in genAdds as they aren't in the mirror\n          this.genTextAreaValueMutation(m.target as HTMLTextAreaElement);\n          return; // any removedNodes won't have been in mirror either\n        }\n\n        m.addedNodes.forEach((n) => this.genAdds(n, m.target));\n        m.removedNodes.forEach((n) => {\n          if (!inDom(n)) {\n            this.shadowDomManager.removeShadowRootsIn(n);\n          }\n          const nodeId = this.mirror.getId(n);\n          const parentId = isShadowRoot(m.target)\n            ? this.mirror.getId(dom.host(m.target))\n            : this.mirror.getId(m.target);\n          if (\n            isBlocked(m.target, this.blockClass, this.blockSelector, false) ||\n            isIgnored(n, this.mirror, this.slimDOMOptions) ||\n            !isSerialized(n, this.mirror)\n          ) {\n            return;\n          }\n          // removed node has not been serialized yet, just remove it from the Set\n          if (this.addedSet.has(n)) {\n            deepDelete(this.addedSet, n);\n            this.droppedSet.add(n);\n          } else if (this.addedSet.has(m.target) && nodeId === -1) {\n            /**\n             * If target was newly added and removed child node was\n             * not serialized, it means the child node has been removed\n             * before callback fired, so we can ignore it because\n             * newly added node will be serialized without child nodes.\n             * TODO: verify this\n             */\n          } else if (isAncestorRemoved(m.target, this.mirror)) {\n            /**\n             * If parent id was not in the mirror map any more, it\n             * means the parent node has already been removed. So\n             * the node is also removed which we do not need to track\n             * and replay.\n             */\n          } else if (\n            this.movedSet.has(n) &&\n            this.movedMap[moveKey(nodeId, parentId)]\n          ) {\n            deepDelete(this.movedSet, n);\n          } else {\n            this.removes.push({\n              parentId,\n              id: nodeId,\n              isShadow:\n                isShadowRoot(m.target) && isNativeShadowDom(m.target)\n                  ? true\n                  : undefined,\n            });\n            processRemoves(n, this.removesSubTreeCache);\n          }\n          this.mapRemoves.push(n);\n        });\n        break;\n      }\n      default:\n        break;\n    }\n  };\n\n  /**\n   * Make sure you check if `n`'s parent is blocked before calling this function\n   * */\n  private genAdds = (n: Node, target?: Node) => {\n    // this node was already recorded in other buffer, ignore it\n    if (this.processedNodeManager.inOtherBuffer(n, this)) return;\n\n    // if n is added to set, there is no need to travel it and its' children again\n    if (this.addedSet.has(n) || this.movedSet.has(n)) return;\n\n    if (this.mirror.hasNode(n)) {\n      if (isIgnored(n, this.mirror, this.slimDOMOptions)) {\n        return;\n      }\n      this.movedSet.add(n);\n      let targetId: number | null = null;\n      if (target && this.mirror.hasNode(target)) {\n        targetId = this.mirror.getId(target);\n      }\n      if (targetId && targetId !== -1) {\n        this.movedMap[moveKey(this.mirror.getId(n), targetId)] = true;\n      }\n    } else {\n      this.addedSet.add(n);\n      this.droppedSet.delete(n);\n    }\n\n    // if this node is blocked `serializeNode` will turn it into a placeholder element\n    // but we have to remove it's children otherwise they will be added as placeholders too\n    if (!isBlocked(n, this.blockClass, this.blockSelector, false)) {\n      dom.childNodes(n).forEach((childN) => this.genAdds(childN));\n      if (hasShadowRoot(n)) {\n        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n        dom.childNodes(dom.shadowRoot(n)!).forEach((childN) => {\n          this.processedNodeManager.add(childN, this);\n          this.genAdds(childN, n);\n        });\n      }\n    }\n  };\n}\n\n/**\n * Some utils to handle the mutation observer DOM records.\n * It should be more clear to extend the native data structure\n * like Set and Map, but currently Typescript does not support\n * that.\n */\nfunction deepDelete(addsSet: Set<Node>, n: Node) {\n  addsSet.delete(n);\n  dom.childNodes(n).forEach((childN) => deepDelete(addsSet, childN));\n}\n\nfunction processRemoves(n: Node, cache: Set<Node>) {\n  const queue = [n];\n\n  while (queue.length) {\n    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n    const next = queue.pop()!;\n    if (cache.has(next)) continue;\n    cache.add(next);\n    dom.childNodes(next).forEach((n) => queue.push(n));\n  }\n\n  return;\n}\n\nfunction isSelfOrAncestorInSet(set: Set<Node>, n: Node): boolean {\n  if (set.size === 0) return false;\n  return _isSelfOrAncestorInSet(set, n);\n}\n\nfunction _isSelfOrAncestorInSet(set: Set<Node>, n: Node): boolean {\n  if (set.has(n)) {\n    return true;\n  }\n  const parent = dom.parentNode(n);\n  if (!parent) {\n    return false;\n  }\n  return _isSelfOrAncestorInSet(set, parent);\n}\n", "import type { ErrorHandler } from '../types';\n\ntype Callback = (...args: unknown[]) => unknown;\n\nlet errorHandler: ErrorHandler | undefined;\n\nexport function registerErrorHandler(handler: ErrorHandler | undefined) {\n  errorHandler = handler;\n}\n\nexport function unregisterErrorHandler() {\n  errorHandler = undefined;\n}\n\n/**\n * Wrap callbacks in a wrapper that allows to pass errors to a configured `errorHandler` method.\n */\nexport const callbackWrapper = <T extends Callback>(cb: T): T => {\n  if (!errorHandler) {\n    return cb;\n  }\n\n  const rrwebWrapped = ((...rest: unknown[]) => {\n    try {\n      return cb(...rest);\n    } catch (error) {\n      if (errorHandler && errorHandler(error) === true) {\n        return;\n      }\n\n      throw error;\n    }\n  }) as unknown as T;\n\n  return rrwebWrapped;\n};\n", "import {\n  type MaskInputOptions,\n  maskInputValue,\n  Mirror,\n  getInputType,\n  toLowerCase,\n} from 'rrweb-snapshot';\nimport type { FontFaceSet } from 'css-font-loading-module';\nimport {\n  throttle,\n  on,\n  hookSetter,\n  getWindowScroll,\n  getWindowHeight,\n  getWindowWidth,\n  isBlocked,\n  legacy_isTouchEvent,\n  StyleSheetMirror,\n  nowTimestamp,\n} from '../utils';\nimport { patch } from '@rrweb/utils';\nimport type { observerParam, MutationBufferParam } from '../types';\nimport {\n  IncrementalSource,\n  MouseInteractions,\n  PointerTypes,\n  MediaInteractions,\n} from '@rrweb/types';\nimport type {\n  mutationCallBack,\n  mousemoveCallBack,\n  mousePosition,\n  mouseInteractionCallBack,\n  listenerHandler,\n  scrollCallback,\n  styleSheetRuleCallback,\n  viewportResizeCallback,\n  inputValue,\n  inputCallback,\n  hookResetter,\n  hooksParam,\n  Arguments,\n  mediaInteractionCallback,\n  canvasMutationCallback,\n  fontCallback,\n  fontParam,\n  styleDeclarationCallback,\n  IWindow,\n  SelectionRange,\n  selectionCallback,\n  customElementCallback,\n} from '@rrweb/types';\nimport MutationBuffer from './mutation';\nimport { callbackWrapper } from './error-handler';\nimport dom, { mutationObserverCtor } from '@rrweb/utils';\n\n// one principal mutation buffer, but also one per shadowRoot/iframe on the page\nexport const mutationBuffers = new Set<MutationBuffer>();\n\n// Event.path is non-standard and used in some older browsers\ntype NonStandardEvent = Omit<Event, 'composedPath'> & {\n  path: EventTarget[];\n};\n\nfunction getEventTarget(event: Event | NonStandardEvent): EventTarget | null {\n  try {\n    if ('composedPath' in event) {\n      const path = event.composedPath();\n      if (path.length) {\n        return path[0];\n      }\n    } else if ('path' in event && event.path.length) {\n      return event.path[0];\n    }\n  } catch {\n    // fallback to `event.target` below\n  }\n\n  return event && event.target;\n}\n\nexport function initMutationObserver(\n  options: MutationBufferParam,\n  rootEl: Node,\n): listenerHandler {\n  const mutationBuffer = new MutationBuffer();\n  mutationBuffers.add(mutationBuffer);\n  // see mutation.ts for details\n  mutationBuffer.init(options);\n  const [ObserverCtor, releaseObserverConstructor] = mutationObserverCtor();\n  const observer = new (ObserverCtor as new (\n    callback: MutationCallback,\n  ) => MutationObserver)(\n    callbackWrapper(mutationBuffer.processMutations.bind(mutationBuffer)),\n  );\n  observer.observe(rootEl, {\n    attributes: true,\n    attributeOldValue: true,\n    characterData: true,\n    characterDataOldValue: true,\n    childList: true,\n    subtree: true,\n  });\n  const stop = () => {\n    observer.disconnect();\n    mutationBuffers.delete(mutationBuffer);\n    releaseObserverConstructor();\n  };\n  return stop;\n}\n\nfunction initMoveObserver({\n  mousemoveCb,\n  sampling,\n  doc,\n  mirror,\n}: observerParam): listenerHandler {\n  if (sampling.mousemove === false) {\n    return () => {\n      //\n    };\n  }\n\n  const threshold =\n    typeof sampling.mousemove === 'number' ? sampling.mousemove : 50;\n  const callbackThreshold =\n    typeof sampling.mousemoveCallback === 'number'\n      ? sampling.mousemoveCallback\n      : 500;\n\n  let positions: mousePosition[] = [];\n  let timeBaseline: number | null;\n  const wrappedCb = throttle(\n    callbackWrapper(\n      (\n        source:\n          | IncrementalSource.MouseMove\n          | IncrementalSource.TouchMove\n          | IncrementalSource.Drag,\n      ) => {\n        const totalOffset = Date.now() - timeBaseline!;\n        mousemoveCb(\n          positions.map((p) => {\n            p.timeOffset -= totalOffset;\n            return p;\n          }),\n          source,\n        );\n        positions = [];\n        timeBaseline = null;\n      },\n    ),\n    callbackThreshold,\n  );\n  const updatePosition = callbackWrapper(\n    throttle<MouseEvent | TouchEvent | DragEvent>(\n      callbackWrapper((evt) => {\n        const target = getEventTarget(evt);\n        // 'legacy' here as we could switch to https://developer.mozilla.org/en-US/docs/Web/API/Element/pointermove_event\n        const { clientX, clientY } = legacy_isTouchEvent(evt)\n          ? evt.changedTouches[0]\n          : evt;\n        if (!timeBaseline) {\n          timeBaseline = nowTimestamp();\n        }\n        positions.push({\n          x: clientX,\n          y: clientY,\n          id: mirror.getId(target as Node),\n          timeOffset: nowTimestamp() - timeBaseline,\n        });\n        // it is possible DragEvent is undefined even on devices\n        // that support event 'drag'\n        wrappedCb(\n          typeof DragEvent !== 'undefined' && evt instanceof DragEvent\n            ? IncrementalSource.Drag\n            : evt instanceof MouseEvent\n            ? IncrementalSource.MouseMove\n            : IncrementalSource.TouchMove,\n        );\n      }),\n      threshold,\n      {\n        trailing: false,\n      },\n    ),\n  );\n  const handlers = [\n    on('mousemove', updatePosition, doc),\n    on('touchmove', updatePosition, doc),\n    on('drag', updatePosition, doc),\n  ];\n  return callbackWrapper(() => {\n    handlers.forEach((h) => h());\n  });\n}\n\nfunction initMouseInteractionObserver({\n  mouseInteractionCb,\n  doc,\n  mirror,\n  blockClass,\n  blockSelector,\n  sampling,\n}: observerParam): listenerHandler {\n  if (sampling.mouseInteraction === false) {\n    return () => {\n      //\n    };\n  }\n  const disableMap: Record<string, boolean | undefined> =\n    sampling.mouseInteraction === true ||\n    sampling.mouseInteraction === undefined\n      ? {}\n      : sampling.mouseInteraction;\n\n  const handlers: listenerHandler[] = [];\n  let currentPointerType: PointerTypes | null = null;\n  const getHandler = (eventKey: keyof typeof MouseInteractions) => {\n    return (event: MouseEvent | TouchEvent | PointerEvent) => {\n      const target = getEventTarget(event) as Node;\n      if (isBlocked(target, blockClass, blockSelector, true)) {\n        return;\n      }\n      let pointerType: PointerTypes | null = null;\n      let thisEventKey = eventKey;\n      if ('pointerType' in event) {\n        switch (event.pointerType) {\n          case 'mouse':\n            pointerType = PointerTypes.Mouse;\n            break;\n          case 'touch':\n            pointerType = PointerTypes.Touch;\n            break;\n          case 'pen':\n            pointerType = PointerTypes.Pen;\n            break;\n        }\n        if (pointerType === PointerTypes.Touch) {\n          if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) {\n            // we are actually listening on 'pointerdown'\n            thisEventKey = 'TouchStart';\n          } else if (\n            MouseInteractions[eventKey] === MouseInteractions.MouseUp\n          ) {\n            // we are actually listening on 'pointerup'\n            thisEventKey = 'TouchEnd';\n          }\n        } else if (pointerType === PointerTypes.Pen) {\n          // TODO: these will get incorrectly emitted as MouseDown/MouseUp\n        }\n      } else if (legacy_isTouchEvent(event)) {\n        pointerType = PointerTypes.Touch;\n      }\n      if (pointerType !== null) {\n        currentPointerType = pointerType;\n        if (\n          (thisEventKey.startsWith('Touch') &&\n            pointerType === PointerTypes.Touch) ||\n          (thisEventKey.startsWith('Mouse') &&\n            pointerType === PointerTypes.Mouse)\n        ) {\n          // don't output redundant info\n          pointerType = null;\n        }\n      } else if (MouseInteractions[eventKey] === MouseInteractions.Click) {\n        pointerType = currentPointerType;\n        currentPointerType = null; // cleanup as we've used it\n      }\n      const e = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;\n      if (!e) {\n        return;\n      }\n      const id = mirror.getId(target);\n      const { clientX, clientY } = e;\n      callbackWrapper(mouseInteractionCb)({\n        type: MouseInteractions[thisEventKey],\n        id,\n        x: clientX,\n        y: clientY,\n        ...(pointerType !== null && { pointerType }),\n      });\n    };\n  };\n  Object.keys(MouseInteractions)\n    .filter(\n      (key) =>\n        Number.isNaN(Number(key)) &&\n        !key.endsWith('_Departed') &&\n        disableMap[key] !== false,\n    )\n    .forEach((eventKey: keyof typeof MouseInteractions) => {\n      let eventName = toLowerCase(eventKey);\n      const handler = getHandler(eventKey);\n      if (window.PointerEvent) {\n        switch (MouseInteractions[eventKey]) {\n          case MouseInteractions.MouseDown:\n          case MouseInteractions.MouseUp:\n            eventName = eventName.replace(\n              'mouse',\n              'pointer',\n            ) as unknown as typeof eventName;\n            break;\n          case MouseInteractions.TouchStart:\n          case MouseInteractions.TouchEnd:\n            // these are handled by pointerdown/pointerup\n            return;\n        }\n      }\n      handlers.push(on(eventName, handler, doc));\n    });\n  return callbackWrapper(() => {\n    handlers.forEach((h) => h());\n  });\n}\n\nexport function initScrollObserver({\n  scrollCb,\n  doc,\n  mirror,\n  blockClass,\n  blockSelector,\n  sampling,\n}: Pick<\n  observerParam,\n  'scrollCb' | 'doc' | 'mirror' | 'blockClass' | 'blockSelector' | 'sampling'\n>): listenerHandler {\n  const updatePosition = callbackWrapper(\n    throttle<UIEvent>(\n      callbackWrapper((evt) => {\n        const target = getEventTarget(evt);\n        if (\n          !target ||\n          isBlocked(target as Node, blockClass, blockSelector, true)\n        ) {\n          return;\n        }\n        const id = mirror.getId(target as Node);\n        if (target === doc && doc.defaultView) {\n          const scrollLeftTop = getWindowScroll(doc.defaultView);\n          scrollCb({\n            id,\n            x: scrollLeftTop.left,\n            y: scrollLeftTop.top,\n          });\n        } else {\n          scrollCb({\n            id,\n            x: (target as HTMLElement).scrollLeft,\n            y: (target as HTMLElement).scrollTop,\n          });\n        }\n      }),\n      sampling.scroll || 100,\n    ),\n  );\n  return on('scroll', updatePosition, doc);\n}\n\nfunction initViewportResizeObserver(\n  { viewportResizeCb }: observerParam,\n  { win }: { win: IWindow },\n): listenerHandler {\n  let lastH = -1;\n  let lastW = -1;\n  const updateDimension = callbackWrapper(\n    throttle(\n      callbackWrapper(() => {\n        const height = getWindowHeight();\n        const width = getWindowWidth();\n        if (lastH !== height || lastW !== width) {\n          viewportResizeCb({\n            width: Number(width),\n            height: Number(height),\n          });\n          lastH = height;\n          lastW = width;\n        }\n      }),\n      200,\n    ),\n  );\n  return on('resize', updateDimension, win);\n}\n\nexport const INPUT_TAGS = ['INPUT', 'TEXTAREA', 'SELECT'];\nconst lastInputValueMap: WeakMap<EventTarget, inputValue> = new WeakMap();\nfunction initInputObserver({\n  inputCb,\n  doc,\n  mirror,\n  blockClass,\n  blockSelector,\n  ignoreClass,\n  ignoreSelector,\n  maskInputOptions,\n  maskInputFn,\n  sampling,\n  userTriggeredOnInput,\n}: observerParam): listenerHandler {\n  function eventHandler(event: Event) {\n    let target = getEventTarget(event) as HTMLElement | null;\n    const userTriggered = event.isTrusted;\n    const tagName = target && target.tagName;\n\n    /**\n     * If a site changes the value 'selected' of an option element, the value of its parent element, usually a select element, will be changed as well.\n     * We can treat this change as a value change of the select element the current target belongs to.\n     */\n    if (target && tagName === 'OPTION') {\n      target = dom.parentElement(target);\n    }\n    if (\n      !target ||\n      !tagName ||\n      INPUT_TAGS.indexOf(tagName) < 0 ||\n      isBlocked(target as Node, blockClass, blockSelector, true)\n    ) {\n      return;\n    }\n\n    if (\n      target.classList.contains(ignoreClass) ||\n      (ignoreSelector && target.matches(ignoreSelector))\n    ) {\n      return;\n    }\n    let text = (target as HTMLInputElement).value;\n    let isChecked = false;\n    const type: Lowercase<string> = getInputType(target) || '';\n\n    if (type === 'radio' || type === 'checkbox') {\n      isChecked = (target as HTMLInputElement).checked;\n    } else if (\n      maskInputOptions[tagName.toLowerCase() as keyof MaskInputOptions] ||\n      maskInputOptions[type as keyof MaskInputOptions]\n    ) {\n      text = maskInputValue({\n        element: target,\n        maskInputOptions,\n        tagName,\n        type,\n        value: text,\n        maskInputFn,\n      });\n    }\n    cbWithDedup(\n      target,\n      userTriggeredOnInput\n        ? { text, isChecked, userTriggered }\n        : { text, isChecked },\n    );\n    // if a radio was checked\n    // the other radios with the same name attribute will be unchecked.\n    const name: string | undefined = (target as HTMLInputElement).name;\n    if (type === 'radio' && name && isChecked) {\n      doc\n        .querySelectorAll(`input[type=\"radio\"][name=\"${name}\"]`)\n        .forEach((el) => {\n          if (el !== target) {\n            const text = (el as HTMLInputElement).value;\n            cbWithDedup(\n              el,\n              userTriggeredOnInput\n                ? { text, isChecked: !isChecked, userTriggered: false }\n                : { text, isChecked: !isChecked },\n            );\n          }\n        });\n    }\n  }\n  function cbWithDedup(target: EventTarget, v: inputValue) {\n    const lastInputValue = lastInputValueMap.get(target);\n    if (\n      !lastInputValue ||\n      lastInputValue.text !== v.text ||\n      lastInputValue.isChecked !== v.isChecked\n    ) {\n      lastInputValueMap.set(target, v);\n      const id = mirror.getId(target as Node);\n      callbackWrapper(inputCb)({\n        ...v,\n        id,\n      });\n    }\n  }\n  const events = sampling.input === 'last' ? ['change'] : ['input', 'change'];\n  const handlers: Array<listenerHandler | hookResetter> = events.map(\n    (eventName) => on(eventName, callbackWrapper(eventHandler), doc),\n  );\n  const currentWindow = doc.defaultView;\n  if (!currentWindow) {\n    return () => {\n      handlers.forEach((h) => h());\n    };\n  }\n  const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(\n    currentWindow.HTMLInputElement.prototype,\n    'value',\n  );\n  const hookProperties: Array<[HTMLElement, string]> = [\n    [currentWindow.HTMLInputElement.prototype, 'value'],\n    [currentWindow.HTMLInputElement.prototype, 'checked'],\n    [currentWindow.HTMLSelectElement.prototype, 'value'],\n    [currentWindow.HTMLTextAreaElement.prototype, 'value'],\n    // Some UI library use selectedIndex to set select value\n    [currentWindow.HTMLSelectElement.prototype, 'selectedIndex'],\n    [currentWindow.HTMLOptionElement.prototype, 'selected'],\n  ];\n  if (propertyDescriptor && propertyDescriptor.set) {\n    handlers.push(\n      ...hookProperties.map((p) =>\n        hookSetter<HTMLElement>(\n          p[0],\n          p[1],\n          {\n            set() {\n              // mock to a normal event\n              callbackWrapper(eventHandler)({\n                target: this as EventTarget,\n                isTrusted: false, // userTriggered to false as this could well be programmatic\n              } as Event);\n            },\n          },\n          false,\n          currentWindow,\n        ),\n      ),\n    );\n  }\n  return callbackWrapper(() => {\n    handlers.forEach((h) => h());\n  });\n}\n\ntype GroupingCSSRule =\n  | CSSGroupingRule\n  | CSSMediaRule\n  | CSSSupportsRule\n  | CSSConditionRule;\ntype GroupingCSSRuleTypes =\n  | typeof CSSGroupingRule\n  | typeof CSSMediaRule\n  | typeof CSSSupportsRule\n  | typeof CSSConditionRule;\n\nfunction getNestedCSSRulePositions(rule: CSSRule): number[] {\n  const positions: number[] = [];\n  function recurse(childRule: CSSRule, pos: number[]) {\n    if (\n      (hasNestedCSSRule('CSSGroupingRule') &&\n        childRule.parentRule instanceof CSSGroupingRule) ||\n      (hasNestedCSSRule('CSSMediaRule') &&\n        childRule.parentRule instanceof CSSMediaRule) ||\n      (hasNestedCSSRule('CSSSupportsRule') &&\n        childRule.parentRule instanceof CSSSupportsRule) ||\n      (hasNestedCSSRule('CSSConditionRule') &&\n        childRule.parentRule instanceof CSSConditionRule)\n    ) {\n      const rules = Array.from(\n        (childRule.parentRule as GroupingCSSRule).cssRules,\n      );\n      const index = rules.indexOf(childRule);\n      pos.unshift(index);\n      return recurse(childRule.parentRule, pos);\n    } else if (childRule.parentStyleSheet) {\n      const rules = Array.from(childRule.parentStyleSheet.cssRules);\n      const index = rules.indexOf(childRule);\n      pos.unshift(index);\n    }\n    return pos;\n  }\n  return recurse(rule, positions);\n}\n\n/**\n * For StyleSheets in Element, this function retrieves id of its host element.\n * For adopted StyleSheets, this function retrieves its styleId from a styleMirror.\n */\nfunction getIdAndStyleId(\n  sheet: CSSStyleSheet | undefined | null,\n  mirror: Mirror,\n  styleMirror: StyleSheetMirror,\n): {\n  styleId?: number;\n  id?: number;\n} {\n  let id, styleId;\n  if (!sheet) return {};\n  if (sheet.ownerNode) id = mirror.getId(sheet.ownerNode as Node);\n  else styleId = styleMirror.getId(sheet);\n  return {\n    styleId,\n    id,\n  };\n}\n\nfunction initStyleSheetObserver(\n  { styleSheetRuleCb, mirror, stylesheetManager }: observerParam,\n  { win }: { win: IWindow },\n): listenerHandler {\n  if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {\n    // If, for whatever reason, CSSStyleSheet is not available, we skip the observation of stylesheets.\n    return () => {\n      // Do nothing\n    };\n  }\n\n  // eslint-disable-next-line @typescript-eslint/unbound-method\n  const insertRule = win.CSSStyleSheet.prototype.insertRule;\n  win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {\n    apply: callbackWrapper(\n      (\n        target: typeof insertRule,\n        thisArg: CSSStyleSheet,\n        argumentsList: [string, number | undefined],\n      ) => {\n        const [rule, index] = argumentsList;\n\n        const { id, styleId } = getIdAndStyleId(\n          thisArg,\n          mirror,\n          stylesheetManager.styleMirror,\n        );\n\n        if ((id && id !== -1) || (styleId && styleId !== -1)) {\n          styleSheetRuleCb({\n            id,\n            styleId,\n            adds: [{ rule, index }],\n          });\n        }\n        return target.apply(thisArg, argumentsList);\n      },\n    ),\n  });\n\n  // Support for deprecated addRule method\n  win.CSSStyleSheet.prototype.addRule = function (\n    this: CSSStyleSheet,\n    selector: string,\n    styleBlock: string,\n    index: number = this.cssRules.length,\n  ) {\n    const rule = `${selector} { ${styleBlock} }`;\n    return win.CSSStyleSheet.prototype.insertRule.apply(this, [rule, index]);\n  };\n\n  // eslint-disable-next-line @typescript-eslint/unbound-method\n  const deleteRule = win.CSSStyleSheet.prototype.deleteRule;\n  win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {\n    apply: callbackWrapper(\n      (\n        target: typeof deleteRule,\n        thisArg: CSSStyleSheet,\n        argumentsList: [number],\n      ) => {\n        const [index] = argumentsList;\n\n        const { id, styleId } = getIdAndStyleId(\n          thisArg,\n          mirror,\n          stylesheetManager.styleMirror,\n        );\n\n        if ((id && id !== -1) || (styleId && styleId !== -1)) {\n          styleSheetRuleCb({\n            id,\n            styleId,\n            removes: [{ index }],\n          });\n        }\n        return target.apply(thisArg, argumentsList);\n      },\n    ),\n  });\n\n  // Support for deprecated removeRule method\n  win.CSSStyleSheet.prototype.removeRule = function (\n    this: CSSStyleSheet,\n    index: number,\n  ) {\n    return win.CSSStyleSheet.prototype.deleteRule.apply(this, [index]);\n  };\n\n  let replace: (text: string) => Promise<CSSStyleSheet>;\n\n  if (win.CSSStyleSheet.prototype.replace) {\n    // eslint-disable-next-line @typescript-eslint/unbound-method\n    replace = win.CSSStyleSheet.prototype.replace;\n    win.CSSStyleSheet.prototype.replace = new Proxy(replace, {\n      apply: callbackWrapper(\n        (\n          target: typeof replace,\n          thisArg: CSSStyleSheet,\n          argumentsList: [string],\n        ) => {\n          const [text] = argumentsList;\n\n          const { id, styleId } = getIdAndStyleId(\n            thisArg,\n            mirror,\n            stylesheetManager.styleMirror,\n          );\n\n          if ((id && id !== -1) || (styleId && styleId !== -1)) {\n            styleSheetRuleCb({\n              id,\n              styleId,\n              replace: text,\n            });\n          }\n          return target.apply(thisArg, argumentsList);\n        },\n      ),\n    });\n  }\n\n  let replaceSync: (text: string) => void;\n  if (win.CSSStyleSheet.prototype.replaceSync) {\n    // eslint-disable-next-line @typescript-eslint/unbound-method\n    replaceSync = win.CSSStyleSheet.prototype.replaceSync;\n    win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, {\n      apply: callbackWrapper(\n        (\n          target: typeof replaceSync,\n          thisArg: CSSStyleSheet,\n          argumentsList: [string],\n        ) => {\n          const [text] = argumentsList;\n\n          const { id, styleId } = getIdAndStyleId(\n            thisArg,\n            mirror,\n            stylesheetManager.styleMirror,\n          );\n\n          if ((id && id !== -1) || (styleId && styleId !== -1)) {\n            styleSheetRuleCb({\n              id,\n              styleId,\n              replaceSync: text,\n            });\n          }\n          return target.apply(thisArg, argumentsList);\n        },\n      ),\n    });\n  }\n\n  const supportedNestedCSSRuleTypes: {\n    [key: string]: GroupingCSSRuleTypes;\n  } = {};\n  if (canMonkeyPatchNestedCSSRule('CSSGroupingRule')) {\n    supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;\n  } else {\n    // Some browsers (Safari) don't support CSSGroupingRule\n    // https://caniuse.com/?search=cssgroupingrule\n    // fall back to monkey patching classes that would have inherited from CSSGroupingRule\n\n    if (canMonkeyPatchNestedCSSRule('CSSMediaRule')) {\n      supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;\n    }\n    if (canMonkeyPatchNestedCSSRule('CSSConditionRule')) {\n      supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;\n    }\n    if (canMonkeyPatchNestedCSSRule('CSSSupportsRule')) {\n      supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;\n    }\n  }\n\n  const unmodifiedFunctions: {\n    [key: string]: {\n      insertRule: (rule: string, index?: number) => number;\n      deleteRule: (index: number) => void;\n    };\n  } = {};\n\n  Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\n    unmodifiedFunctions[typeKey] = {\n      // eslint-disable-next-line @typescript-eslint/unbound-method\n      insertRule: type.prototype.insertRule,\n      // eslint-disable-next-line @typescript-eslint/unbound-method\n      deleteRule: type.prototype.deleteRule,\n    };\n\n    type.prototype.insertRule = new Proxy(\n      unmodifiedFunctions[typeKey].insertRule,\n      {\n        apply: callbackWrapper(\n          (\n            target: typeof insertRule,\n            thisArg: CSSRule,\n            argumentsList: [string, number | undefined],\n          ) => {\n            const [rule, index] = argumentsList;\n\n            const { id, styleId } = getIdAndStyleId(\n              thisArg.parentStyleSheet,\n              mirror,\n              stylesheetManager.styleMirror,\n            );\n\n            if ((id && id !== -1) || (styleId && styleId !== -1)) {\n              styleSheetRuleCb({\n                id,\n                styleId,\n                adds: [\n                  {\n                    rule,\n                    index: [\n                      ...getNestedCSSRulePositions(thisArg),\n                      index || 0, // defaults to 0\n                    ],\n                  },\n                ],\n              });\n            }\n            return target.apply(thisArg, argumentsList);\n          },\n        ),\n      },\n    );\n\n    type.prototype.deleteRule = new Proxy(\n      unmodifiedFunctions[typeKey].deleteRule,\n      {\n        apply: callbackWrapper(\n          (\n            target: typeof deleteRule,\n            thisArg: CSSRule,\n            argumentsList: [number],\n          ) => {\n            const [index] = argumentsList;\n\n            const { id, styleId } = getIdAndStyleId(\n              thisArg.parentStyleSheet,\n              mirror,\n              stylesheetManager.styleMirror,\n            );\n\n            if ((id && id !== -1) || (styleId && styleId !== -1)) {\n              styleSheetRuleCb({\n                id,\n                styleId,\n                removes: [\n                  { index: [...getNestedCSSRulePositions(thisArg), index] },\n                ],\n              });\n            }\n            return target.apply(thisArg, argumentsList);\n          },\n        ),\n      },\n    );\n  });\n\n  return callbackWrapper(() => {\n    win.CSSStyleSheet.prototype.insertRule = insertRule;\n    win.CSSStyleSheet.prototype.deleteRule = deleteRule;\n    replace && (win.CSSStyleSheet.prototype.replace = replace);\n    replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);\n    Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\n      type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;\n      type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;\n    });\n  });\n}\n\nexport function initAdoptedStyleSheetObserver(\n  {\n    mirror,\n    stylesheetManager,\n  }: Pick<observerParam, 'mirror' | 'stylesheetManager'>,\n  host: Document | ShadowRoot,\n): listenerHandler {\n  let hostId: number | null = null;\n  // host of adoptedStyleSheets is outermost document or IFrame's document\n  if (host.nodeName === '#document') hostId = mirror.getId(host);\n  // The host is a ShadowRoot.\n  else hostId = mirror.getId(dom.host(host as ShadowRoot));\n\n  const patchTarget =\n    host.nodeName === '#document'\n      ? (host as Document).defaultView?.Document\n      : host.ownerDocument?.defaultView?.ShadowRoot;\n  const originalPropertyDescriptor = patchTarget?.prototype\n    ? Object.getOwnPropertyDescriptor(\n        patchTarget?.prototype,\n        'adoptedStyleSheets',\n      )\n    : undefined;\n  if (\n    hostId === null ||\n    hostId === -1 ||\n    !patchTarget ||\n    !originalPropertyDescriptor\n  )\n    return () => {\n      //\n    };\n\n  // Patch adoptedStyleSheets by overriding the original one.\n  Object.defineProperty(host, 'adoptedStyleSheets', {\n    configurable: originalPropertyDescriptor.configurable,\n    enumerable: originalPropertyDescriptor.enumerable,\n    get(): CSSStyleSheet[] {\n      return originalPropertyDescriptor.get?.call(this) as CSSStyleSheet[];\n    },\n    set(sheets: CSSStyleSheet[]) {\n      const result = originalPropertyDescriptor.set?.call(this, sheets);\n      if (hostId !== null && hostId !== -1) {\n        try {\n          stylesheetManager.adoptStyleSheets(sheets, hostId);\n        } catch (e) {\n          // for safety\n        }\n      }\n      return result;\n    },\n  });\n\n  return callbackWrapper(() => {\n    Object.defineProperty(host, 'adoptedStyleSheets', {\n      configurable: originalPropertyDescriptor.configurable,\n      enumerable: originalPropertyDescriptor.enumerable,\n      // eslint-disable-next-line @typescript-eslint/unbound-method\n      get: originalPropertyDescriptor.get,\n      // eslint-disable-next-line @typescript-eslint/unbound-method\n      set: originalPropertyDescriptor.set,\n    });\n  });\n}\n\nfunction initStyleDeclarationObserver(\n  {\n    styleDeclarationCb,\n    mirror,\n    ignoreCSSAttributes,\n    stylesheetManager,\n  }: observerParam,\n  { win }: { win: IWindow },\n): listenerHandler {\n  // eslint-disable-next-line @typescript-eslint/unbound-method\n  const setProperty = win.CSSStyleDeclaration.prototype.setProperty;\n  win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {\n    apply: callbackWrapper(\n      (\n        target: typeof setProperty,\n        thisArg: CSSStyleDeclaration,\n        argumentsList: [string, string, string],\n      ) => {\n        const [property, value, priority] = argumentsList;\n\n        // ignore this mutation if we do not care about this css attribute\n        if (ignoreCSSAttributes.has(property)) {\n          return setProperty.apply(thisArg, [property, value, priority]);\n        }\n        const { id, styleId } = getIdAndStyleId(\n          thisArg.parentRule?.parentStyleSheet,\n          mirror,\n          stylesheetManager.styleMirror,\n        );\n        if ((id && id !== -1) || (styleId && styleId !== -1)) {\n          styleDeclarationCb({\n            id,\n            styleId,\n            set: {\n              property,\n              value,\n              priority,\n            },\n            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n            index: getNestedCSSRulePositions(thisArg.parentRule!),\n          });\n        }\n        return target.apply(thisArg, argumentsList);\n      },\n    ),\n  });\n\n  // eslint-disable-next-line @typescript-eslint/unbound-method\n  const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;\n  win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {\n    apply: callbackWrapper(\n      (\n        target: typeof removeProperty,\n        thisArg: CSSStyleDeclaration,\n        argumentsList: [string],\n      ) => {\n        const [property] = argumentsList;\n\n        // ignore this mutation if we do not care about this css attribute\n        if (ignoreCSSAttributes.has(property)) {\n          return removeProperty.apply(thisArg, [property]);\n        }\n        const { id, styleId } = getIdAndStyleId(\n          thisArg.parentRule?.parentStyleSheet,\n          mirror,\n          stylesheetManager.styleMirror,\n        );\n        if ((id && id !== -1) || (styleId && styleId !== -1)) {\n          styleDeclarationCb({\n            id,\n            styleId,\n            remove: {\n              property,\n            },\n            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n            index: getNestedCSSRulePositions(thisArg.parentRule!),\n          });\n        }\n        return target.apply(thisArg, argumentsList);\n      },\n    ),\n  });\n\n  return callbackWrapper(() => {\n    win.CSSStyleDeclaration.prototype.setProperty = setProperty;\n    win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;\n  });\n}\n\nfunction initMediaInteractionObserver({\n  mediaInteractionCb,\n  blockClass,\n  blockSelector,\n  mirror,\n  sampling,\n  doc,\n}: observerParam): listenerHandler {\n  const handler = callbackWrapper((type: MediaInteractions) =>\n    throttle(\n      callbackWrapper((event: Event) => {\n        const target = getEventTarget(event);\n        if (\n          !target ||\n          !(target instanceof HTMLMediaElement) ||\n          isBlocked(target as Node, blockClass, blockSelector, true)\n        ) {\n          return;\n        }\n        const { currentTime, volume, muted, playbackRate, loop } = target;\n        mediaInteractionCb({\n          type,\n          id: mirror.getId(target as Node),\n          currentTime,\n          volume,\n          muted,\n          playbackRate,\n          loop,\n        });\n      }),\n      sampling.media || 500,\n    ),\n  );\n  const handlers = [\n    on('play', handler(MediaInteractions.Play), doc),\n    on('pause', handler(MediaInteractions.Pause), doc),\n    on('seeked', handler(MediaInteractions.Seeked), doc),\n    on('volumechange', handler(MediaInteractions.VolumeChange), doc),\n    on('ratechange', handler(MediaInteractions.RateChange), doc),\n  ];\n  return callbackWrapper(() => {\n    handlers.forEach((h) => h());\n  });\n}\n\nfunction initFontObserver({ fontCb, doc }: observerParam): listenerHandler {\n  const win = doc.defaultView as IWindow;\n  if (!win) {\n    return () => {\n      //\n    };\n  }\n\n  const handlers: listenerHandler[] = [];\n\n  const fontMap = new WeakMap<FontFace, fontParam>();\n\n  const originalFontFace = win.FontFace;\n  win.FontFace = function FontFace(\n    family: string,\n    source: string | ArrayBufferLike,\n    descriptors?: FontFaceDescriptors,\n  ) {\n    const fontFace = new originalFontFace(family, source, descriptors);\n    fontMap.set(fontFace, {\n      family,\n      buffer: typeof source !== 'string',\n      descriptors,\n      fontSource:\n        typeof source === 'string'\n          ? source\n          : JSON.stringify(Array.from(new Uint8Array(source))),\n    });\n    return fontFace;\n  } as unknown as typeof FontFace;\n\n  const restoreHandler = patch(\n    doc.fonts,\n    'add',\n    function (original: (font: FontFace) => void) {\n      return function (this: FontFaceSet, fontFace: FontFace) {\n        setTimeout(\n          callbackWrapper(() => {\n            const p = fontMap.get(fontFace);\n            if (p) {\n              fontCb(p);\n              fontMap.delete(fontFace);\n            }\n          }),\n          0,\n        );\n        return original.apply(this, [fontFace]);\n      };\n    },\n  );\n\n  handlers.push(() => {\n    win.FontFace = originalFontFace;\n  });\n  handlers.push(restoreHandler);\n\n  return callbackWrapper(() => {\n    handlers.forEach((h) => h());\n  });\n}\n\nfunction initSelectionObserver(param: observerParam): listenerHandler {\n  const { doc, mirror, blockClass, blockSelector, selectionCb } = param;\n  let collapsed = true;\n\n  const updateSelection = callbackWrapper(() => {\n    const selection = doc.getSelection();\n\n    if (!selection || (collapsed && selection?.isCollapsed)) return;\n\n    collapsed = selection.isCollapsed || false;\n\n    const ranges: SelectionRange[] = [];\n    const count = selection.rangeCount || 0;\n\n    for (let i = 0; i < count; i++) {\n      const range = selection.getRangeAt(i);\n\n      const { startContainer, startOffset, endContainer, endOffset } = range;\n\n      const blocked =\n        isBlocked(startContainer, blockClass, blockSelector, true) ||\n        isBlocked(endContainer, blockClass, blockSelector, true);\n\n      if (blocked) continue;\n\n      ranges.push({\n        start: mirror.getId(startContainer),\n        startOffset,\n        end: mirror.getId(endContainer),\n        endOffset,\n      });\n    }\n\n    selectionCb({ ranges });\n  });\n\n  updateSelection();\n\n  return on('selectionchange', updateSelection);\n}\n\nfunction initCustomElementObserver({\n  doc,\n  customElementCb,\n}: observerParam): listenerHandler {\n  const win = doc.defaultView as IWindow;\n  // eslint-disable-next-line @typescript-eslint/no-empty-function\n  if (!win || !win.customElements) return () => {};\n  const restoreHandler = patch(\n    win.customElements,\n    'define',\n    function (\n      original: (\n        name: string,\n        constructor: CustomElementConstructor,\n        options?: ElementDefinitionOptions,\n      ) => void,\n    ) {\n      return function (\n        name: string,\n        constructor: CustomElementConstructor,\n        options?: ElementDefinitionOptions,\n      ) {\n        try {\n          customElementCb({\n            define: {\n              name,\n            },\n          });\n        } catch (e) {\n          console.warn(`Custom element callback failed for ${name}`);\n        }\n        return original.apply(this, [name, constructor, options]);\n      };\n    },\n  );\n  return restoreHandler;\n}\n\nfunction mergeHooks(o: observerParam, hooks: hooksParam) {\n  const {\n    mutationCb,\n    mousemoveCb,\n    mouseInteractionCb,\n    scrollCb,\n    viewportResizeCb,\n    inputCb,\n    mediaInteractionCb,\n    styleSheetRuleCb,\n    styleDeclarationCb,\n    canvasMutationCb,\n    fontCb,\n    selectionCb,\n    customElementCb,\n  } = o;\n  o.mutationCb = (...p: Arguments<mutationCallBack>) => {\n    if (hooks.mutation) {\n      hooks.mutation(...p);\n    }\n    mutationCb(...p);\n  };\n  o.mousemoveCb = (...p: Arguments<mousemoveCallBack>) => {\n    if (hooks.mousemove) {\n      hooks.mousemove(...p);\n    }\n    mousemoveCb(...p);\n  };\n  o.mouseInteractionCb = (...p: Arguments<mouseInteractionCallBack>) => {\n    if (hooks.mouseInteraction) {\n      hooks.mouseInteraction(...p);\n    }\n    mouseInteractionCb(...p);\n  };\n  o.scrollCb = (...p: Arguments<scrollCallback>) => {\n    if (hooks.scroll) {\n      hooks.scroll(...p);\n    }\n    scrollCb(...p);\n  };\n  o.viewportResizeCb = (...p: Arguments<viewportResizeCallback>) => {\n    if (hooks.viewportResize) {\n      hooks.viewportResize(...p);\n    }\n    viewportResizeCb(...p);\n  };\n  o.inputCb = (...p: Arguments<inputCallback>) => {\n    if (hooks.input) {\n      hooks.input(...p);\n    }\n    inputCb(...p);\n  };\n  o.mediaInteractionCb = (...p: Arguments<mediaInteractionCallback>) => {\n    if (hooks.mediaInteaction) {\n      hooks.mediaInteaction(...p);\n    }\n    mediaInteractionCb(...p);\n  };\n  o.styleSheetRuleCb = (...p: Arguments<styleSheetRuleCallback>) => {\n    if (hooks.styleSheetRule) {\n      hooks.styleSheetRule(...p);\n    }\n    styleSheetRuleCb(...p);\n  };\n  o.styleDeclarationCb = (...p: Arguments<styleDeclarationCallback>) => {\n    if (hooks.styleDeclaration) {\n      hooks.styleDeclaration(...p);\n    }\n    styleDeclarationCb(...p);\n  };\n  o.canvasMutationCb = (...p: Arguments<canvasMutationCallback>) => {\n    if (hooks.canvasMutation) {\n      hooks.canvasMutation(...p);\n    }\n    canvasMutationCb(...p);\n  };\n  o.fontCb = (...p: Arguments<fontCallback>) => {\n    if (hooks.font) {\n      hooks.font(...p);\n    }\n    fontCb(...p);\n  };\n  o.selectionCb = (...p: Arguments<selectionCallback>) => {\n    if (hooks.selection) {\n      hooks.selection(...p);\n    }\n    selectionCb(...p);\n  };\n  o.customElementCb = (...c: Arguments<customElementCallback>) => {\n    if (hooks.customElement) {\n      hooks.customElement(...c);\n    }\n    customElementCb(...c);\n  };\n}\n\nexport function initObservers(\n  o: observerParam,\n  hooks: hooksParam = {},\n): listenerHandler {\n  const currentWindow = o.doc.defaultView; // basically document.window\n  if (!currentWindow) {\n    return () => {\n      //\n    };\n  }\n\n  mergeHooks(o, hooks);\n  let stopMutationObserver: listenerHandler | undefined;\n  if (o.recordDOM) {\n    stopMutationObserver = initMutationObserver(o, o.doc);\n  }\n  const mousemoveHandler = initMoveObserver(o);\n  const mouseInteractionHandler = initMouseInteractionObserver(o);\n  const scrollHandler = initScrollObserver(o);\n  const viewportResizeHandler = initViewportResizeObserver(o, {\n    win: currentWindow,\n  });\n  const inputHandler = initInputObserver(o);\n  const mediaInteractionHandler = initMediaInteractionObserver(o);\n\n  // eslint-disable-next-line @typescript-eslint/no-empty-function\n  let styleSheetObserver = () => {};\n  // eslint-disable-next-line @typescript-eslint/no-empty-function\n  let adoptedStyleSheetObserver = () => {};\n  // eslint-disable-next-line @typescript-eslint/no-empty-function\n  let styleDeclarationObserver = () => {};\n  // eslint-disable-next-line @typescript-eslint/no-empty-function\n  let fontObserver = () => {};\n  if (o.recordDOM) {\n    styleSheetObserver = initStyleSheetObserver(o, { win: currentWindow });\n    adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o, o.doc);\n    styleDeclarationObserver = initStyleDeclarationObserver(o, {\n      win: currentWindow,\n    });\n    if (o.collectFonts) {\n      fontObserver = initFontObserver(o);\n    }\n  }\n  const selectionObserver = initSelectionObserver(o);\n  const customElementObserver = initCustomElementObserver(o);\n\n  // plugins\n  const pluginHandlers: listenerHandler[] = [];\n  for (const plugin of o.plugins) {\n    pluginHandlers.push(\n      plugin.observer(plugin.callback, currentWindow, plugin.options),\n    );\n  }\n\n  return callbackWrapper(() => {\n    stopMutationObserver?.();\n    mousemoveHandler();\n    mouseInteractionHandler();\n    scrollHandler();\n    viewportResizeHandler();\n    inputHandler();\n    mediaInteractionHandler();\n    styleSheetObserver();\n    adoptedStyleSheetObserver();\n    styleDeclarationObserver();\n    fontObserver();\n    selectionObserver();\n    customElementObserver();\n    pluginHandlers.forEach((h) => h());\n  });\n}\n\ntype CSSGroupingProp =\n  | 'CSSGroupingRule'\n  | 'CSSMediaRule'\n  | 'CSSSupportsRule'\n  | 'CSSConditionRule';\n\nfunction hasNestedCSSRule(prop: CSSGroupingProp): boolean {\n  return typeof window[prop] !== 'undefined';\n}\n\nfunction canMonkeyPatchNestedCSSRule(prop: CSSGroupingProp): boolean {\n  return Boolean(\n    typeof window[prop] !== 'undefined' &&\n      // Note: Generally, this check _shouldn't_ be necessary\n      // However, in some scenarios (e.g. jsdom) this can sometimes fail, so we check for it here\n      window[prop].prototype &&\n      'insertRule' in window[prop].prototype &&\n      'deleteRule' in window[prop].prototype,\n  );\n}\n", "import type { ICrossOriginIframeMirror } from '@rrweb/types';\nexport default class CrossOriginIframeMirror\n  implements ICrossOriginIframeMirror\n{\n  private iframeIdToRemoteIdMap: WeakMap<\n    HTMLIFrameElement,\n    Map<number, number>\n  > = new WeakMap();\n  private iframeRemoteIdToIdMap: WeakMap<\n    HTMLIFrameElement,\n    Map<number, number>\n  > = new WeakMap();\n\n  constructor(private generateIdFn: () => number) {}\n\n  getId(\n    iframe: HTMLIFrameElement,\n    remoteId: number,\n    idToRemoteMap?: Map<number, number>,\n    remoteToIdMap?: Map<number, number>,\n  ): number {\n    const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);\n    const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);\n\n    let id = idToRemoteIdMap.get(remoteId);\n    if (!id) {\n      id = this.generateIdFn();\n      idToRemoteIdMap.set(remoteId, id);\n      remoteIdToIdMap.set(id, remoteId);\n    }\n    return id;\n  }\n\n  getIds(iframe: HTMLIFrameElement, remoteId: number[]): number[] {\n    const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);\n    const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\n    return remoteId.map((id) =>\n      this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap),\n    );\n  }\n\n  getRemoteId(\n    iframe: HTMLIFrameElement,\n    id: number,\n    map?: Map<number, number>,\n  ): number {\n    const remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);\n\n    if (typeof id !== 'number') return id;\n\n    const remoteId = remoteIdToIdMap.get(id);\n    if (!remoteId) return -1;\n    return remoteId;\n  }\n\n  getRemoteIds(iframe: HTMLIFrameElement, ids: number[]): number[] {\n    const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\n\n    return ids.map((id) => this.getRemoteId(iframe, id, remoteIdToIdMap));\n  }\n\n  reset(iframe?: HTMLIFrameElement) {\n    if (!iframe) {\n      this.iframeIdToRemoteIdMap = new WeakMap();\n      this.iframeRemoteIdToIdMap = new WeakMap();\n      return;\n    }\n    this.iframeIdToRemoteIdMap.delete(iframe);\n    this.iframeRemoteIdToIdMap.delete(iframe);\n  }\n\n  private getIdToRemoteIdMap(iframe: HTMLIFrameElement) {\n    let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);\n    if (!idToRemoteIdMap) {\n      idToRemoteIdMap = new Map();\n      this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);\n    }\n    return idToRemoteIdMap;\n  }\n\n  private getRemoteIdToIdMap(iframe: HTMLIFrameElement) {\n    let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);\n    if (!remoteIdToIdMap) {\n      remoteIdToIdMap = new Map();\n      this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);\n    }\n    return remoteIdToIdMap;\n  }\n}\n", "import type { Mirror } from 'rrweb-snapshot';\nimport { genId } from 'rrweb-snapshot';\nimport type { CrossOriginIframeMessageEvent } from '../types';\nimport CrossOriginIframeMirror from './cross-origin-iframe-mirror';\nimport { EventType, NodeType, IncrementalSource } from '@rrweb/types';\nimport type {\n  eventWithTime,\n  eventWithoutTime,\n  serializedNodeWithId,\n  mutationCallBack,\n  listenerHandler,\n  IWindow,\n} from '@rrweb/types';\nimport type { StylesheetManager } from './stylesheet-manager';\nimport { on } from '../utils';\n\nexport class IframeManager {\n  private iframes: WeakMap<HTMLIFrameElement, true> = new WeakMap();\n  private crossOriginIframeMap: WeakMap<MessageEventSource, HTMLIFrameElement> =\n    new WeakMap();\n  public crossOriginIframeMirror = new CrossOriginIframeMirror(genId);\n  public crossOriginIframeStyleMirror: CrossOriginIframeMirror;\n  public crossOriginIframeRootIdMap: WeakMap<HTMLIFrameElement, number> =\n    new WeakMap();\n  private mirror: Mirror;\n  private mutationCb: mutationCallBack;\n  private wrappedEmit: (e: eventWithoutTime, isCheckout?: boolean) => void;\n  private loadListener?: (iframeEl: HTMLIFrameElement) => unknown;\n  private unloadListener?: (doc: Document) => unknown;\n  // Windows of attached same-origin iframes, with the handler that stops listening to them.\n  private attachedWindows: Map<Window, listenerHandler> = new Map();\n  // One handler for all windows, so that attaching an iframe again (e.g. on every full snapshot) doesn't add another.\n  private messageHandler = (message: Event) =>\n    this.handleMessage(message as MessageEvent);\n  private stylesheetManager: StylesheetManager;\n  private recordCrossOriginIframes: boolean;\n\n  constructor(options: {\n    mirror: Mirror;\n    mutationCb: mutationCallBack;\n    stylesheetManager: StylesheetManager;\n    recordCrossOriginIframes: boolean;\n    wrappedEmit: (e: eventWithoutTime, isCheckout?: boolean) => void;\n  }) {\n    this.mutationCb = options.mutationCb;\n    this.wrappedEmit = options.wrappedEmit;\n    this.stylesheetManager = options.stylesheetManager;\n    this.recordCrossOriginIframes = options.recordCrossOriginIframes;\n    this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(\n      this.stylesheetManager.styleMirror.generateId.bind(\n        this.stylesheetManager.styleMirror,\n      ),\n    );\n    this.mirror = options.mirror;\n    if (this.recordCrossOriginIframes) {\n      window.addEventListener('message', this.messageHandler);\n    }\n  }\n\n  public addIframe(iframeEl: HTMLIFrameElement) {\n    this.iframes.set(iframeEl, true);\n    if (iframeEl.contentWindow)\n      this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);\n  }\n\n  public addLoadListener(cb: (iframeEl: HTMLIFrameElement) => unknown) {\n    this.loadListener = cb;\n  }\n\n  public addUnloadListener(cb: (doc: Document) => unknown) {\n    this.unloadListener = cb;\n  }\n\n  public attachIframe(\n    iframeEl: HTMLIFrameElement,\n    childSn: serializedNodeWithId,\n  ) {\n    this.mutationCb({\n      adds: [\n        {\n          parentId: this.mirror.getId(iframeEl),\n          nextId: null,\n          node: childSn,\n        },\n      ],\n      removes: [],\n      texts: [],\n      attributes: [],\n      isAttachIframe: true,\n    });\n\n    this.watchIframeWindow(iframeEl);\n\n    this.loadListener?.(iframeEl);\n\n    if (\n      iframeEl.contentDocument &&\n      iframeEl.contentDocument.adoptedStyleSheets &&\n      iframeEl.contentDocument.adoptedStyleSheets.length > 0\n    )\n      this.stylesheetManager.adoptStyleSheets(\n        iframeEl.contentDocument.adoptedStyleSheets,\n        this.mirror.getId(iframeEl.contentDocument),\n      );\n  }\n\n  public destroy() {\n    window.removeEventListener('message', this.messageHandler);\n    this.attachedWindows.forEach((stop) => stop());\n  }\n\n  private watchIframeWindow(iframeEl: HTMLIFrameElement) {\n    const win = iframeEl.contentWindow as IWindow | null;\n    if (!win || this.attachedWindows.has(win)) return;\n    const handlers: listenerHandler[] = [];\n    const stop = () => {\n      this.attachedWindows.delete(win);\n      handlers.forEach((handler) => {\n        try {\n          handler();\n        } catch {\n          // the iframe may have navigated to a cross-origin page by now\n        }\n      });\n    };\n    this.attachedWindows.set(win, stop);\n\n    // Receive messages (events) coming from cross-origin iframes that are nested in this same-origin iframe.\n    if (this.recordCrossOriginIframes) {\n      handlers.push(on('message', this.messageHandler, win));\n    }\n    handlers.push(\n      on(\n        'pagehide',\n        (event) => {\n          // A persisted page is kept in the back/forward cache and may be shown again.\n          if ((event as PageTransitionEvent).persisted) return;\n          const doc = win.document;\n          stop();\n          this.unloadListener?.(doc);\n        },\n        win,\n      ),\n    );\n  }\n\n  private handleMessage(message: MessageEvent | CrossOriginIframeMessageEvent) {\n    const crossOriginMessageEvent = message as CrossOriginIframeMessageEvent;\n    if (\n      crossOriginMessageEvent.data.type !== 'rrweb' ||\n      // To filter out the rrweb messages which are forwarded by some sites.\n      crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin\n    )\n      return;\n\n    const iframeSourceWindow = message.source;\n    if (!iframeSourceWindow) return;\n\n    const iframeEl = this.crossOriginIframeMap.get(message.source);\n    if (!iframeEl) return;\n\n    const transformedEvent = this.transformCrossOriginEvent(\n      iframeEl,\n      crossOriginMessageEvent.data.event,\n    );\n\n    if (transformedEvent)\n      this.wrappedEmit(\n        transformedEvent,\n        crossOriginMessageEvent.data.isCheckout,\n      );\n  }\n\n  private transformCrossOriginEvent(\n    iframeEl: HTMLIFrameElement,\n    e: eventWithTime,\n  ): eventWithTime | false {\n    switch (e.type) {\n      case EventType.FullSnapshot: {\n        this.crossOriginIframeMirror.reset(iframeEl);\n        this.crossOriginIframeStyleMirror.reset(iframeEl);\n        /**\n         * Replaces the original id of the iframe with a new set of unique ids\n         */\n        this.replaceIdOnNode(e.data.node, iframeEl);\n        const rootId = e.data.node.id;\n        this.crossOriginIframeRootIdMap.set(iframeEl, rootId);\n        this.patchRootIdOnNode(e.data.node, rootId);\n        return {\n          timestamp: e.timestamp,\n          type: EventType.IncrementalSnapshot,\n          data: {\n            source: IncrementalSource.Mutation,\n            adds: [\n              {\n                parentId: this.mirror.getId(iframeEl),\n                nextId: null,\n                node: e.data.node,\n              },\n            ],\n            removes: [],\n            texts: [],\n            attributes: [],\n            isAttachIframe: true,\n          },\n        };\n      }\n      case EventType.Meta:\n      case EventType.Load:\n      case EventType.DomContentLoaded: {\n        return false;\n      }\n      case EventType.Annotation:\n      case EventType.Plugin: {\n        return e;\n      }\n      case EventType.Custom: {\n        this.replaceIds(\n          e.data.payload as {\n            id?: unknown;\n            parentId?: unknown;\n            previousId?: unknown;\n            nextId?: unknown;\n          },\n          iframeEl,\n          ['id', 'parentId', 'previousId', 'nextId'],\n        );\n        return e;\n      }\n      case EventType.IncrementalSnapshot: {\n        switch (e.data.source) {\n          case IncrementalSource.Mutation: {\n            e.data.adds.forEach((n) => {\n              this.replaceIds(n, iframeEl, [\n                'parentId',\n                'nextId',\n                'previousId',\n              ]);\n              this.replaceIdOnNode(n.node, iframeEl);\n              const rootId = this.crossOriginIframeRootIdMap.get(iframeEl);\n              rootId && this.patchRootIdOnNode(n.node, rootId);\n            });\n            e.data.removes.forEach((n) => {\n              this.replaceIds(n, iframeEl, ['parentId', 'id']);\n            });\n            e.data.attributes.forEach((n) => {\n              this.replaceIds(n, iframeEl, ['id']);\n            });\n            e.data.texts.forEach((n) => {\n              this.replaceIds(n, iframeEl, ['id']);\n            });\n            return e;\n          }\n          case IncrementalSource.Drag:\n          case IncrementalSource.TouchMove:\n          case IncrementalSource.MouseMove: {\n            e.data.positions.forEach((p) => {\n              this.replaceIds(p, iframeEl, ['id']);\n            });\n            return e;\n          }\n          case IncrementalSource.ViewportResize: {\n            // can safely ignore these events\n            return false;\n          }\n          case IncrementalSource.MediaInteraction:\n          case IncrementalSource.MouseInteraction:\n          case IncrementalSource.Scroll:\n          case IncrementalSource.CanvasMutation:\n          case IncrementalSource.Input: {\n            this.replaceIds(e.data, iframeEl, ['id']);\n            return e;\n          }\n          case IncrementalSource.StyleSheetRule:\n          case IncrementalSource.StyleDeclaration: {\n            this.replaceIds(e.data, iframeEl, ['id']);\n            this.replaceStyleIds(e.data, iframeEl, ['styleId']);\n            return e;\n          }\n          case IncrementalSource.Font: {\n            // fine as-is no modification needed\n            return e;\n          }\n          case IncrementalSource.Selection: {\n            e.data.ranges.forEach((range) => {\n              this.replaceIds(range, iframeEl, ['start', 'end']);\n            });\n            return e;\n          }\n          case IncrementalSource.AdoptedStyleSheet: {\n            this.replaceIds(e.data, iframeEl, ['id']);\n            this.replaceStyleIds(e.data, iframeEl, ['styleIds']);\n            e.data.styles?.forEach((style) => {\n              this.replaceStyleIds(style, iframeEl, ['styleId']);\n            });\n            return e;\n          }\n        }\n      }\n    }\n    return false;\n  }\n\n  private replace<T extends Record<string, unknown>>(\n    iframeMirror: CrossOriginIframeMirror,\n    obj: T,\n    iframeEl: HTMLIFrameElement,\n    keys: Array<keyof T>,\n  ): T {\n    for (const key of keys) {\n      if (!Array.isArray(obj[key]) && typeof obj[key] !== 'number') continue;\n      if (Array.isArray(obj[key])) {\n        obj[key] = iframeMirror.getIds(\n          iframeEl,\n          obj[key] as number[],\n        ) as T[keyof T];\n      } else {\n        (obj[key] as number) = iframeMirror.getId(iframeEl, obj[key] as number);\n      }\n    }\n\n    return obj;\n  }\n\n  private replaceIds<T extends Record<string, unknown>>(\n    obj: T,\n    iframeEl: HTMLIFrameElement,\n    keys: Array<keyof T>,\n  ): T {\n    return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);\n  }\n\n  private replaceStyleIds<T extends Record<string, unknown>>(\n    obj: T,\n    iframeEl: HTMLIFrameElement,\n    keys: Array<keyof T>,\n  ): T {\n    return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);\n  }\n\n  private replaceIdOnNode(\n    node: serializedNodeWithId,\n    iframeEl: HTMLIFrameElement,\n  ) {\n    this.replaceIds(node, iframeEl, ['id', 'rootId']);\n    if ('childNodes' in node) {\n      node.childNodes.forEach((child) => {\n        this.replaceIdOnNode(child, iframeEl);\n      });\n    }\n  }\n\n  private patchRootIdOnNode(node: serializedNodeWithId, rootId: number) {\n    if (node.type !== NodeType.Document && !node.rootId) node.rootId = rootId;\n    if ('childNodes' in node) {\n      node.childNodes.forEach((child) => {\n        this.patchRootIdOnNode(child, rootId);\n      });\n    }\n  }\n}\n", "import type { MutationBufferParam } from '../types';\nimport type {\n  listenerHandler,\n  mutationCallBack,\n  scrollCallback,\n  SamplingStrategy,\n} from '@rrweb/types';\nimport {\n  initMutationObserver,\n  initScrollObserver,\n  initAdoptedStyleSheetObserver,\n} from './observer';\nimport { inDom } from '../utils';\nimport type { Mirror } from 'rrweb-snapshot';\nimport { isNativeShadowDom } from 'rrweb-snapshot';\nimport dom, { patch } from '@rrweb/utils';\n\ntype BypassOptions = Omit<\n  MutationBufferParam,\n  'doc' | 'mutationCb' | 'mirror' | 'shadowDomManager'\n> & {\n  sampling: SamplingStrategy;\n};\n\nexport class ShadowDomManager {\n  /** Observed shadow roots and the handlers that stop observing them. */\n  private shadowDoms = new Map<ShadowRoot, listenerHandler[]>();\n  private mutationCb: mutationCallBack;\n  private scrollCb: scrollCallback;\n  private bypassOptions: BypassOptions;\n  private mirror: Mirror;\n  private restoreHandlers: (() => void)[] = [];\n\n  constructor(options: {\n    mutationCb: mutationCallBack;\n    scrollCb: scrollCallback;\n    bypassOptions: BypassOptions;\n    mirror: Mirror;\n  }) {\n    this.mutationCb = options.mutationCb;\n    this.scrollCb = options.scrollCb;\n    this.bypassOptions = options.bypassOptions;\n    this.mirror = options.mirror;\n\n    this.init();\n  }\n\n  public init() {\n    this.reset();\n    // Patch 'attachShadow' to observe newly added shadow doms.\n    this.patchAttachShadow(Element, document);\n  }\n\n  public addShadowRoot(shadowRoot: ShadowRoot, doc: Document) {\n    if (!isNativeShadowDom(shadowRoot)) return;\n    if (this.shadowDoms.has(shadowRoot)) return;\n    const handlers: listenerHandler[] = [];\n    this.shadowDoms.set(shadowRoot, handlers);\n    const stopMutationObserver = initMutationObserver(\n      {\n        ...this.bypassOptions,\n        doc,\n        mutationCb: this.mutationCb,\n        mirror: this.mirror,\n        shadowDomManager: this,\n      },\n      shadowRoot,\n    );\n    handlers.push(stopMutationObserver);\n    handlers.push(\n      initScrollObserver({\n        ...this.bypassOptions,\n        scrollCb: this.scrollCb,\n        // https://gist.github.com/praveenpuglia/0832da687ed5a5d7a0907046c9ef1813\n        // scroll is not allowed to pass the boundary, so we need to listen the shadow document\n        doc: shadowRoot as unknown as Document,\n        mirror: this.mirror,\n      }),\n    );\n    // Defer this to avoid adoptedStyleSheet events being created before the full snapshot is created or attachShadow action is recorded.\n    setTimeout(() => {\n      // The shadow root was released, or the manager reset, in the meantime.\n      if (this.shadowDoms.get(shadowRoot) !== handlers) return;\n      if (\n        shadowRoot.adoptedStyleSheets &&\n        shadowRoot.adoptedStyleSheets.length > 0\n      )\n        this.bypassOptions.stylesheetManager.adoptStyleSheets(\n          shadowRoot.adoptedStyleSheets,\n          this.mirror.getId(dom.host(shadowRoot)),\n        );\n      handlers.push(\n        initAdoptedStyleSheetObserver(\n          {\n            mirror: this.mirror,\n            stylesheetManager: this.bypassOptions.stylesheetManager,\n          },\n          shadowRoot,\n        ),\n      );\n    }, 0);\n  }\n\n  public removeShadowRootsIn(n: Node) {\n    if (this.shadowDoms.size === 0) return;\n    const shadowRoot = dom.shadowRoot(n);\n    if (shadowRoot) {\n      if (this.shadowDoms.has(shadowRoot)) {\n        this.removeShadowRoot(shadowRoot);\n      }\n      this.removeShadowRootsIn(shadowRoot);\n    }\n    dom.childNodes(n).forEach((child) => this.removeShadowRootsIn(child));\n  }\n\n  private removeShadowRoot(shadowRoot: ShadowRoot) {\n    const handlers = this.shadowDoms.get(shadowRoot);\n    this.shadowDoms.delete(shadowRoot);\n    handlers?.forEach(runHandler);\n  }\n\n  /**\n   * Monkey patch 'attachShadow' of an IFrameElement to observe newly added shadow doms.\n   */\n  public observeAttachShadow(iframeElement: HTMLIFrameElement) {\n    if (!iframeElement.contentWindow || !iframeElement.contentDocument) return;\n\n    this.patchAttachShadow(\n      (\n        iframeElement.contentWindow as Window & {\n          Element: { prototype: Element };\n        }\n      ).Element,\n      iframeElement.contentDocument,\n    );\n  }\n\n  /**\n   * Patch 'attachShadow' to observe newly added shadow doms.\n   */\n  private patchAttachShadow(\n    element: {\n      prototype: Element;\n    },\n    doc: Document,\n  ) {\n    // eslint-disable-next-line @typescript-eslint/no-this-alias\n    const manager = this;\n    this.restoreHandlers.push(\n      patch(\n        element.prototype,\n        'attachShadow',\n        function (original: (init: ShadowRootInit) => ShadowRoot) {\n          return function (this: Element, option: ShadowRootInit) {\n            const sRoot = original.call(this, option);\n            // For the shadow dom elements in the document, monitor their dom mutations.\n            // For shadow dom elements that aren't in the document yet,\n            // we start monitoring them once their shadow dom host is appended to the document.\n            const shadowRootEl = dom.shadowRoot(this);\n            if (shadowRootEl && inDom(this))\n              manager.addShadowRoot(shadowRootEl, doc);\n            return sRoot;\n          };\n        },\n      ),\n    );\n  }\n\n  public reset() {\n    this.restoreHandlers.forEach(runHandler);\n    this.restoreHandlers = [];\n    const shadowDoms = this.shadowDoms;\n    this.shadowDoms = new Map();\n    shadowDoms.forEach((handlers) => handlers.forEach(runHandler));\n  }\n}\n\nfunction runHandler(handler: listenerHandler) {\n  try {\n    handler();\n  } catch (e) {\n    //\n  }\n}\n", "/*\n * base64-arraybuffer 1.0.2 <https://github.com/niklasvh/base64-arraybuffer>\n * Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>\n * Released under MIT License\n */\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\nvar lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (var i = 0; i < chars.length; i++) {\n    lookup[chars.charCodeAt(i)] = i;\n}\nvar encode = function (arraybuffer) {\n    var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n    for (i = 0; i < len; i += 3) {\n        base64 += chars[bytes[i] >> 2];\n        base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n        base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n        base64 += chars[bytes[i + 2] & 63];\n    }\n    if (len % 3 === 2) {\n        base64 = base64.substring(0, base64.length - 1) + '=';\n    }\n    else if (len % 3 === 1) {\n        base64 = base64.substring(0, base64.length - 2) + '==';\n    }\n    return base64;\n};\nvar decode = function (base64) {\n    var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;\n    if (base64[base64.length - 1] === '=') {\n        bufferLength--;\n        if (base64[base64.length - 2] === '=') {\n            bufferLength--;\n        }\n    }\n    var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);\n    for (i = 0; i < len; i += 4) {\n        encoded1 = lookup[base64.charCodeAt(i)];\n        encoded2 = lookup[base64.charCodeAt(i + 1)];\n        encoded3 = lookup[base64.charCodeAt(i + 2)];\n        encoded4 = lookup[base64.charCodeAt(i + 3)];\n        bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n        bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n        bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n    }\n    return arraybuffer;\n};\n\nexport { decode, encode };\n//# sourceMappingURL=base64-arraybuffer.es5.js.map\n", "import { encode } from 'base64-arraybuffer';\nimport type { IWindow, CanvasArg } from '@rrweb/types';\n\n// TODO: unify with `replay/webgl.ts`\ntype CanvasVarMap = Map<string, unknown[]>;\nconst canvasVarMap: Map<RenderingContext, CanvasVarMap> = new Map();\nexport function variableListFor(ctx: RenderingContext, ctor: string) {\n  let contextMap = canvasVarMap.get(ctx);\n  if (!contextMap) {\n    contextMap = new Map();\n    canvasVarMap.set(ctx, contextMap);\n  }\n  if (!contextMap.has(ctor)) {\n    contextMap.set(ctor, []);\n  }\n  return contextMap.get(ctor) as unknown[];\n}\n\nexport const saveWebGLVar = (\n  value: unknown,\n  win: IWindow,\n  ctx: RenderingContext,\n): number | void => {\n  if (\n    !value ||\n    !(isInstanceOfWebGLObject(value, win) || typeof value === 'object')\n  )\n    return;\n\n  const name = value.constructor.name;\n  const list = variableListFor(ctx, name);\n  let index = list.indexOf(value);\n\n  if (index === -1) {\n    index = list.length;\n    list.push(value);\n  }\n  return index;\n};\n\n// from webgl-recorder: https://github.com/evanw/webgl-recorder/blob/bef0e65596e981ee382126587e2dcbe0fc7748e2/webgl-recorder.js#L50-L77\nexport function serializeArg(\n  value: unknown,\n  win: IWindow,\n  ctx: RenderingContext,\n): CanvasArg {\n  if (value instanceof Array) {\n    return value.map((arg) => serializeArg(arg, win, ctx));\n  } else if (value === null) {\n    return value;\n  } else if (\n    value instanceof Float32Array ||\n    value instanceof Float64Array ||\n    value instanceof Int32Array ||\n    value instanceof Uint32Array ||\n    value instanceof Uint8Array ||\n    value instanceof Uint16Array ||\n    value instanceof Int16Array ||\n    value instanceof Int8Array ||\n    value instanceof Uint8ClampedArray\n  ) {\n    const name = value.constructor.name;\n    return {\n      rr_type: name,\n      args: [Object.values(value)],\n    };\n  } else if (\n    // SharedArrayBuffer disabled on most browsers due to spectre.\n    // More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/SharedArrayBuffer\n    // value instanceof SharedArrayBuffer ||\n    value instanceof ArrayBuffer\n  ) {\n    const name = value.constructor.name as 'ArrayBuffer';\n    const base64 = encode(value);\n\n    return {\n      rr_type: name,\n      base64,\n    };\n  } else if (value instanceof DataView) {\n    const name = value.constructor.name;\n    return {\n      rr_type: name,\n      args: [\n        serializeArg(value.buffer, win, ctx),\n        value.byteOffset,\n        value.byteLength,\n      ],\n    };\n  } else if (value instanceof HTMLImageElement) {\n    const name = value.constructor.name;\n    const { src } = value;\n    return {\n      rr_type: name,\n      src,\n    };\n  } else if (value instanceof HTMLCanvasElement) {\n    const name = 'HTMLImageElement';\n    // TODO: move `toDataURL` to web worker if possible\n    const src = value.toDataURL(); // heavy on large canvas\n    return {\n      rr_type: name,\n      src,\n    };\n  } else if (value instanceof ImageData) {\n    const name = value.constructor.name;\n    return {\n      rr_type: name,\n      args: [serializeArg(value.data, win, ctx), value.width, value.height],\n    };\n    // } else if (value instanceof Blob) {\n    //   const name = value.constructor.name;\n    //   return {\n    //     rr_type: name,\n    //     data: [serializeArg(await value.arrayBuffer(), win, ctx)],\n    //     type: value.type,\n    //   };\n  } else if (isInstanceOfWebGLObject(value, win) || typeof value === 'object') {\n    const name = value.constructor.name;\n    const index = saveWebGLVar(value, win, ctx) as number;\n\n    return {\n      rr_type: name,\n      index: index,\n    };\n  }\n\n  return value as unknown as CanvasArg;\n}\n\nexport const serializeArgs = (\n  args: Array<unknown>,\n  win: IWindow,\n  ctx: RenderingContext,\n) => {\n  return args.map((arg) => serializeArg(arg, win, ctx));\n};\n\nexport const isInstanceOfWebGLObject = (\n  value: unknown,\n  win: IWindow,\n): value is\n  | WebGLActiveInfo\n  | WebGLBuffer\n  | WebGLFramebuffer\n  | WebGLProgram\n  | WebGLRenderbuffer\n  | WebGLShader\n  | WebGLShaderPrecisionFormat\n  | WebGLTexture\n  | WebGLUniformLocation\n  | WebGLVertexArrayObject => {\n  const webGLConstructorNames: string[] = [\n    'WebGLActiveInfo',\n    'WebGLBuffer',\n    'WebGLFramebuffer',\n    'WebGLProgram',\n    'WebGLRenderbuffer',\n    'WebGLShader',\n    'WebGLShaderPrecisionFormat',\n    'WebGLTexture',\n    'WebGLUniformLocation',\n    'WebGLVertexArrayObject',\n    // In old Chrome versions, value won't be an instanceof WebGLVertexArrayObject.\n    'WebGLVertexArrayObjectOES',\n  ];\n  const supportedWebGLConstructorNames = webGLConstructorNames.filter(\n    (name: string) => typeof win[name as keyof Window] === 'function',\n  );\n  return Boolean(\n    supportedWebGLConstructorNames.find(\n      (name: string) => value instanceof win[name as keyof Window],\n    ),\n  );\n};\n", "import {\n  type blockClass,\n  CanvasContext,\n  type canvasManagerMutationCallback,\n  type IWindow,\n  type listenerHandler,\n} from '@rrweb/types';\nimport { hookSetter, isBlocked } from '../../../utils';\nimport { patch } from '@rrweb/utils';\nimport { serializeArgs } from './serialize-args';\n\nexport default function initCanvas2DMutationObserver(\n  cb: canvasManagerMutationCallback,\n  win: IWindow,\n  blockClass: blockClass,\n  blockSelector: string | null,\n): listenerHandler {\n  const handlers: listenerHandler[] = [];\n  const props2D = Object.getOwnPropertyNames(\n    win.CanvasRenderingContext2D.prototype,\n  );\n  for (const prop of props2D) {\n    try {\n      if (\n        typeof win.CanvasRenderingContext2D.prototype[\n          prop as keyof CanvasRenderingContext2D\n        ] !== 'function'\n      ) {\n        continue;\n      }\n      const restoreHandler = patch(\n        win.CanvasRenderingContext2D.prototype,\n        prop,\n        function (\n          original: (\n            this: CanvasRenderingContext2D,\n            ...args: unknown[]\n          ) => void,\n        ) {\n          return function (\n            this: CanvasRenderingContext2D,\n            ...args: Array<unknown>\n          ) {\n            if (!isBlocked(this.canvas, blockClass, blockSelector, true)) {\n              // Using setTimeout as toDataURL can be heavy\n              // and we'd rather not block the main thread\n              setTimeout(() => {\n                const recordArgs = serializeArgs(args, win, this);\n                cb(this.canvas, {\n                  type: CanvasContext['2D'],\n                  property: prop,\n                  args: recordArgs,\n                });\n              }, 0);\n            }\n            return original.apply(this, args);\n          };\n        },\n      );\n      handlers.push(restoreHandler);\n    } catch {\n      const hookHandler = hookSetter<CanvasRenderingContext2D>(\n        win.CanvasRenderingContext2D.prototype,\n        prop,\n        {\n          set(v) {\n            // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access\n            cb(this.canvas, {\n              type: CanvasContext['2D'],\n              property: prop,\n              args: [v],\n              setter: true,\n            });\n          },\n        },\n      );\n      handlers.push(hookHandler);\n    }\n  }\n  return () => {\n    handlers.forEach((h) => h());\n  };\n}\n", "import type { ICanvas } from 'rrweb-snapshot';\nimport type { blockClass, IWindow, listenerHandler } from '@rrweb/types';\nimport { isBlocked } from '../../../utils';\nimport { patch } from '@rrweb/utils';\n\nfunction getNormalizedContextName(contextType: string) {\n  return contextType === 'experimental-webgl' ? 'webgl' : contextType;\n}\n\nexport default function initCanvasContextObserver(\n  win: IWindow,\n  blockClass: blockClass,\n  blockSelector: string | null,\n  setPreserveDrawingBufferToTrue: boolean,\n): listenerHandler {\n  const handlers: listenerHandler[] = [];\n  try {\n    const restoreHandler = patch(\n      win.HTMLCanvasElement.prototype,\n      'getContext',\n      function (\n        original: (\n          this: ICanvas | HTMLCanvasElement,\n          contextType: string,\n          ...args: Array<unknown>\n        ) => void,\n      ) {\n        return function (\n          this: ICanvas | HTMLCanvasElement,\n          contextType: string,\n          ...args: Array<unknown>\n        ) {\n          if (!isBlocked(this, blockClass, blockSelector, true)) {\n            const ctxName = getNormalizedContextName(contextType);\n            if (!('__context' in this)) (this as ICanvas).__context = ctxName;\n\n            if (\n              setPreserveDrawingBufferToTrue &&\n              ['webgl', 'webgl2'].includes(ctxName)\n            ) {\n              if (args[0] && typeof args[0] === 'object') {\n                const contextAttributes = args[0] as WebGLContextAttributes;\n                if (!contextAttributes.preserveDrawingBuffer) {\n                  contextAttributes.preserveDrawingBuffer = true;\n                }\n              } else {\n                args.splice(0, 1, {\n                  preserveDrawingBuffer: true,\n                });\n              }\n            }\n          }\n          return original.apply(this, [contextType, ...args]);\n        };\n      },\n    );\n    handlers.push(restoreHandler);\n  } catch {\n    console.error('failed to patch HTMLCanvasElement.prototype.getContext');\n  }\n  return () => {\n    handlers.forEach((h) => h());\n  };\n}\n", "import {\n  type blockClass,\n  CanvasContext,\n  type canvasManagerMutationCallback,\n  type canvasMutationWithType,\n  type IWindow,\n  type listenerHandler,\n} from '@rrweb/types';\nimport { hookSetter, isBlocked } from '../../../utils';\nimport { patch } from '@rrweb/utils';\nimport { saveWebGLVar, serializeArgs } from './serialize-args';\n\nfunction patchGLPrototype(\n  prototype: WebGLRenderingContext | WebGL2RenderingContext,\n  type: CanvasContext,\n  cb: canvasManagerMutationCallback,\n  blockClass: blockClass,\n  blockSelector: string | null,\n  win: IWindow,\n): listenerHandler[] {\n  const handlers: listenerHandler[] = [];\n\n  const props = Object.getOwnPropertyNames(prototype);\n\n  for (const prop of props) {\n    if (\n      //prop.startsWith('get') ||  // e.g. getProgramParameter, but too risky\n      [\n        'isContextLost',\n        'canvas',\n        'drawingBufferWidth',\n        'drawingBufferHeight',\n      ].includes(prop)\n    ) {\n      // skip read only propery/functions\n      continue;\n    }\n    try {\n      if (typeof prototype[prop as keyof typeof prototype] !== 'function') {\n        continue;\n      }\n      const restoreHandler = patch(\n        prototype,\n        prop,\n        function (\n          original: (this: typeof prototype, ...args: Array<unknown>) => void,\n        ) {\n          return function (this: typeof prototype, ...args: Array<unknown>) {\n            const result = original.apply(this, args);\n            saveWebGLVar(result, win, this);\n            if (\n              'tagName' in this.canvas &&\n              !isBlocked(this.canvas, blockClass, blockSelector, true)\n            ) {\n              const recordArgs = serializeArgs(args, win, this);\n              const mutation: canvasMutationWithType = {\n                type,\n                property: prop,\n                args: recordArgs,\n              };\n              // TODO: this could potentially also be an OffscreenCanvas as well as HTMLCanvasElement\n              cb(this.canvas, mutation);\n            }\n\n            return result;\n          };\n        },\n      );\n      handlers.push(restoreHandler);\n    } catch {\n      const hookHandler = hookSetter<typeof prototype>(prototype, prop, {\n        set(v) {\n          // TODO: this could potentially also be an OffscreenCanvas as well as HTMLCanvasElement\n          // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n          cb(this.canvas as HTMLCanvasElement, {\n            type,\n            property: prop,\n            args: [v],\n            setter: true,\n          });\n        },\n      });\n      handlers.push(hookHandler);\n    }\n  }\n\n  return handlers;\n}\n\nexport default function initCanvasWebGLMutationObserver(\n  cb: canvasManagerMutationCallback,\n  win: IWindow,\n  blockClass: blockClass,\n  blockSelector: string | null,\n): listenerHandler {\n  const handlers: listenerHandler[] = [];\n\n  if (typeof win.WebGLRenderingContext !== 'undefined') {\n    handlers.push(\n      ...patchGLPrototype(\n        win.WebGLRenderingContext.prototype,\n        CanvasContext.WebGL,\n        cb,\n        blockClass,\n        blockSelector,\n        win,\n      ),\n    );\n  }\n\n  if (typeof win.WebGL2RenderingContext !== 'undefined') {\n    handlers.push(\n      ...patchGLPrototype(\n        win.WebGL2RenderingContext.prototype,\n        CanvasContext.WebGL2,\n        cb,\n        blockClass,\n        blockSelector,\n        win,\n      ),\n    );\n  }\n\n  return () => {\n    handlers.forEach((h) => h());\n  };\n}\n", "import type { ICanvas, Mirror } from 'rrweb-snapshot';\nimport type {\n  blockClass,\n  canvasManagerMutationCallback,\n  canvasMutationCallback,\n  canvasMutationCommand,\n  canvasMutationWithType,\n  IWindow,\n  listenerHandler,\n  CanvasArg,\n  DataURLOptions,\n} from '@rrweb/types';\nimport { isBlocked } from '../../../utils';\nimport { CanvasContext } from '@rrweb/types';\nimport initCanvas2DMutationObserver from './2d';\nimport initCanvasContextObserver from './canvas';\nimport initCanvasWebGLMutationObserver from './webgl';\nimport ImageBitmapDataURLWorker from '../../workers/image-bitmap-data-url-worker?worker&inline';\nimport type { ImageBitmapDataURLRequestWorker } from '../../workers/image-bitmap-data-url-worker';\n\nexport type RafStamps = { latestId: number; invokeId: number | null };\n\ntype pendingCanvasMutationsMap = Map<\n  HTMLCanvasElement,\n  canvasMutationWithType[]\n>;\n\nexport class CanvasManager {\n  private pendingCanvasMutations: pendingCanvasMutationsMap = new Map();\n  private rafStamps: RafStamps = { latestId: 0, invokeId: null };\n  private mirror: Mirror;\n\n  private mutationCb: canvasMutationCallback;\n  private resetObservers?: listenerHandler;\n  private frozen = false;\n  private locked = false;\n\n  public reset() {\n    this.pendingCanvasMutations.clear();\n    this.resetObservers && this.resetObservers();\n  }\n\n  public freeze() {\n    this.frozen = true;\n  }\n\n  public unfreeze() {\n    this.frozen = false;\n  }\n\n  public lock() {\n    this.locked = true;\n  }\n\n  public unlock() {\n    this.locked = false;\n  }\n\n  constructor(options: {\n    recordCanvas: boolean;\n    mutationCb: canvasMutationCallback;\n    win: IWindow;\n    blockClass: blockClass;\n    blockSelector: string | null;\n    mirror: Mirror;\n    sampling?: 'all' | number;\n    dataURLOptions: DataURLOptions;\n  }) {\n    const {\n      sampling = 'all',\n      win,\n      blockClass,\n      blockSelector,\n      recordCanvas,\n      dataURLOptions,\n    } = options;\n    this.mutationCb = options.mutationCb;\n    this.mirror = options.mirror;\n\n    if (recordCanvas && sampling === 'all')\n      this.initCanvasMutationObserver(win, blockClass, blockSelector);\n    if (recordCanvas && typeof sampling === 'number')\n      this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, {\n        dataURLOptions,\n      });\n  }\n\n  private processMutation: canvasManagerMutationCallback = (\n    target,\n    mutation,\n  ) => {\n    const newFrame =\n      this.rafStamps.invokeId &&\n      this.rafStamps.latestId !== this.rafStamps.invokeId;\n    if (newFrame || !this.rafStamps.invokeId)\n      this.rafStamps.invokeId = this.rafStamps.latestId;\n\n    if (!this.pendingCanvasMutations.has(target)) {\n      this.pendingCanvasMutations.set(target, []);\n    }\n\n    this.pendingCanvasMutations.get(target)!.push(mutation);\n  };\n\n  private initCanvasFPSObserver(\n    fps: number,\n    win: IWindow,\n    blockClass: blockClass,\n    blockSelector: string | null,\n    options: {\n      dataURLOptions: DataURLOptions;\n    },\n  ) {\n    const canvasContextReset = initCanvasContextObserver(\n      win,\n      blockClass,\n      blockSelector,\n      true,\n    );\n    const snapshotInProgressMap: Map<number, boolean> = new Map();\n    const worker =\n      new ImageBitmapDataURLWorker() as ImageBitmapDataURLRequestWorker;\n    worker.onmessage = (e) => {\n      const { id } = e.data;\n      snapshotInProgressMap.set(id, false);\n\n      if (!('base64' in e.data)) return;\n\n      const { base64, type, width, height } = e.data;\n      this.mutationCb({\n        id,\n        type: CanvasContext['2D'],\n        commands: [\n          {\n            property: 'clearRect', // wipe canvas\n            args: [0, 0, width, height],\n          },\n          {\n            property: 'drawImage', // draws (semi-transparent) image\n            args: [\n              {\n                rr_type: 'ImageBitmap',\n                args: [\n                  {\n                    rr_type: 'Blob',\n                    data: [{ rr_type: 'ArrayBuffer', base64 }],\n                    type,\n                  },\n                ],\n              } as CanvasArg,\n              0,\n              0,\n            ],\n          },\n        ],\n      });\n    };\n\n    const timeBetweenSnapshots = 1000 / fps;\n    let lastSnapshotTime = 0;\n    let rafId: number;\n\n    const getCanvas = (): HTMLCanvasElement[] => {\n      const matchedCanvas: HTMLCanvasElement[] = [];\n      win.document.querySelectorAll('canvas').forEach((canvas) => {\n        if (!isBlocked(canvas, blockClass, blockSelector, true)) {\n          matchedCanvas.push(canvas);\n        }\n      });\n      return matchedCanvas;\n    };\n\n    const takeCanvasSnapshots = (timestamp: DOMHighResTimeStamp) => {\n      if (\n        lastSnapshotTime &&\n        timestamp - lastSnapshotTime < timeBetweenSnapshots\n      ) {\n        rafId = requestAnimationFrame(takeCanvasSnapshots);\n        return;\n      }\n      lastSnapshotTime = timestamp;\n\n      getCanvas()\n        // eslint-disable-next-line @typescript-eslint/no-misused-promises\n        .forEach(async (canvas: HTMLCanvasElement) => {\n          const id = this.mirror.getId(canvas);\n          if (snapshotInProgressMap.get(id)) return;\n\n          // The browser throws if the canvas is 0 in size\n          // Uncaught (in promise) DOMException: Failed to execute 'createImageBitmap' on 'Window': The source image width is 0.\n          // Assuming the same happens with height\n          if (canvas.width === 0 || canvas.height === 0) return;\n\n          snapshotInProgressMap.set(id, true);\n          if (['webgl', 'webgl2'].includes((canvas as ICanvas).__context)) {\n            // if the canvas hasn't been modified recently,\n            // its contents won't be in memory and `createImageBitmap`\n            // will return a transparent imageBitmap\n\n            const context = canvas.getContext((canvas as ICanvas).__context) as\n              | WebGLRenderingContext\n              | WebGL2RenderingContext\n              | null;\n            if (\n              context?.getContextAttributes()?.preserveDrawingBuffer === false\n            ) {\n              // Hack to load canvas back into memory so `createImageBitmap` can grab it's contents.\n              // Context: https://twitter.com/Juice10/status/1499775271758704643\n              // Preferably we set `preserveDrawingBuffer` to true, but that's not always possible,\n              // especially when canvas is loaded before rrweb.\n              // This hack can wipe the background color of the canvas in the (unlikely) event that\n              // the canvas background was changed but clear was not called directly afterwards.\n              // Example of this hack having negative side effect: https://visgl.github.io/react-map-gl/examples/layers\n              context.clear(context.COLOR_BUFFER_BIT);\n            }\n          }\n          const bitmap = await createImageBitmap(canvas);\n          worker.postMessage(\n            {\n              id,\n              bitmap,\n              width: canvas.width,\n              height: canvas.height,\n              dataURLOptions: options.dataURLOptions,\n            },\n            [bitmap],\n          );\n        });\n      rafId = requestAnimationFrame(takeCanvasSnapshots);\n    };\n\n    rafId = requestAnimationFrame(takeCanvasSnapshots);\n\n    this.resetObservers = () => {\n      canvasContextReset();\n      cancelAnimationFrame(rafId);\n    };\n  }\n\n  private initCanvasMutationObserver(\n    win: IWindow,\n    blockClass: blockClass,\n    blockSelector: string | null,\n  ): void {\n    this.startRAFTimestamping();\n    this.startPendingCanvasMutationFlusher();\n\n    const canvasContextReset = initCanvasContextObserver(\n      win,\n      blockClass,\n      blockSelector,\n      false,\n    );\n    const canvas2DReset = initCanvas2DMutationObserver(\n      this.processMutation.bind(this),\n      win,\n      blockClass,\n      blockSelector,\n    );\n\n    const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(\n      this.processMutation.bind(this),\n      win,\n      blockClass,\n      blockSelector,\n    );\n\n    this.resetObservers = () => {\n      canvasContextReset();\n      canvas2DReset();\n      canvasWebGL1and2Reset();\n    };\n  }\n\n  private startPendingCanvasMutationFlusher() {\n    requestAnimationFrame(() => this.flushPendingCanvasMutations());\n  }\n\n  private startRAFTimestamping() {\n    const setLatestRAFTimestamp = (timestamp: DOMHighResTimeStamp) => {\n      this.rafStamps.latestId = timestamp;\n      requestAnimationFrame(setLatestRAFTimestamp);\n    };\n    requestAnimationFrame(setLatestRAFTimestamp);\n  }\n\n  flushPendingCanvasMutations() {\n    this.pendingCanvasMutations.forEach(\n      (_values: canvasMutationCommand[], canvas: HTMLCanvasElement) => {\n        const id = this.mirror.getId(canvas);\n        this.flushPendingCanvasMutationFor(canvas, id);\n      },\n    );\n    requestAnimationFrame(() => this.flushPendingCanvasMutations());\n  }\n\n  flushPendingCanvasMutationFor(canvas: HTMLCanvasElement, id: number) {\n    if (this.frozen || this.locked) {\n      return;\n    }\n\n    const valuesWithType = this.pendingCanvasMutations.get(canvas);\n    if (!valuesWithType || id === -1) return;\n\n    const values = valuesWithType.map((value) => {\n      const { type, ...rest } = value;\n      return rest;\n    });\n    const { type } = valuesWithType[0];\n\n    this.mutationCb({ id, type, commands: values });\n\n    this.pendingCanvasMutations.delete(canvas);\n  }\n}\n", "import { stringifyRule } from 'rrweb-snapshot';\nimport type {\n  elementNode,\n  serializedNodeWithId,\n  adoptedStyleSheetCallback,\n  adoptedStyleSheetParam,\n  attributeMutation,\n  mutationCallBack,\n} from '@rrweb/types';\nimport { StyleSheetMirror } from '../utils';\n\nexport class StylesheetManager {\n  private trackedLinkElements: WeakSet<HTMLLinkElement> = new WeakSet();\n  private mutationCb: mutationCallBack;\n  private adoptedStyleSheetCb: adoptedStyleSheetCallback;\n  public styleMirror = new StyleSheetMirror();\n\n  constructor(options: {\n    mutationCb: mutationCallBack;\n    adoptedStyleSheetCb: adoptedStyleSheetCallback;\n  }) {\n    this.mutationCb = options.mutationCb;\n    this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;\n  }\n\n  public attachLinkElement(\n    linkEl: HTMLLinkElement,\n    childSn: serializedNodeWithId,\n  ) {\n    if ('_cssText' in (childSn as elementNode).attributes)\n      this.mutationCb({\n        adds: [],\n        removes: [],\n        texts: [],\n        attributes: [\n          {\n            id: childSn.id,\n            attributes: (childSn as elementNode)\n              .attributes as attributeMutation['attributes'],\n          },\n        ],\n      });\n\n    this.trackLinkElement(linkEl);\n  }\n\n  public trackLinkElement(linkEl: HTMLLinkElement) {\n    if (this.trackedLinkElements.has(linkEl)) return;\n\n    this.trackedLinkElements.add(linkEl);\n    this.trackStylesheetInLinkElement(linkEl);\n  }\n\n  public adoptStyleSheets(\n    sheets: CSSStyleSheet[] | readonly CSSStyleSheet[],\n    hostId: number,\n  ) {\n    if (sheets.length === 0) return;\n    const adoptedStyleSheetData: adoptedStyleSheetParam = {\n      id: hostId,\n      styleIds: [] as number[],\n    };\n    const styles: NonNullable<adoptedStyleSheetParam['styles']> = [];\n    for (const sheet of sheets) {\n      let styleId;\n      if (!this.styleMirror.has(sheet)) {\n        styleId = this.styleMirror.add(sheet);\n        styles.push({\n          styleId,\n          rules: Array.from(sheet.rules || CSSRule, (r, index) => ({\n            rule: stringifyRule(r, sheet.href),\n            index,\n          })),\n        });\n      } else styleId = this.styleMirror.getId(sheet);\n      adoptedStyleSheetData.styleIds.push(styleId);\n    }\n    if (styles.length > 0) adoptedStyleSheetData.styles = styles;\n    this.adoptedStyleSheetCb(adoptedStyleSheetData);\n  }\n\n  public reset() {\n    this.styleMirror.reset();\n    this.trackedLinkElements = new WeakSet();\n  }\n\n  // TODO: take snapshot on stylesheet reload by applying event listener\n  private trackStylesheetInLinkElement(_linkEl: HTMLLinkElement) {\n    // linkEl.addEventListener('load', () => {\n    //   // re-loaded, maybe take another snapshot?\n    // });\n  }\n}\n", "import type MutationBuffer from './mutation';\n\n/**\n * Keeps a log of nodes that could show up in multiple mutation buffer but shouldn't be handled twice.\n */\nexport default class ProcessedNodeManager {\n  private nodeMap: WeakMap<Node, Set<MutationBuffer>> = new WeakMap();\n\n  private active = false;\n\n  public inOtherBuffer(node: Node, thisBuffer: MutationBuffer) {\n    const buffers = this.nodeMap.get(node);\n    return (\n      buffers && Array.from(buffers).some((buffer) => buffer !== thisBuffer)\n    );\n  }\n\n  public add(node: Node, buffer: MutationBuffer) {\n    if (!this.active) {\n      this.active = true;\n      requestAnimationFrame(() => {\n        this.nodeMap = new WeakMap();\n        this.active = false;\n      });\n    }\n    this.nodeMap.set(node, (this.nodeMap.get(node) || new Set()).add(buffer));\n  }\n\n  public destroy() {\n    // cleanup no longer needed\n  }\n}\n", "import {\n  snapshot,\n  slimDOMDefaults,\n  type MaskInputOptions,\n  createMirror,\n} from 'rrweb-snapshot';\nimport { initObservers, mutationBuffers } from './observer';\nimport {\n  on,\n  getWindowWidth,\n  getWindowHeight,\n  getWindowScroll,\n  polyfill,\n  hasShadowRoot,\n  isSerializedIframe,\n  isSerializedStylesheet,\n  nowTimestamp,\n} from '../utils';\nimport type { recordOptions } from '../types';\nimport {\n  EventType,\n  type annotationData,\n  type eventWithoutTime,\n  type eventWithTime,\n  IncrementalSource,\n  type listenerHandler,\n  type mutationCallbackParam,\n  type scrollCallback,\n  type canvasMutationParam,\n  type adoptedStyleSheetParam,\n} from '@rrweb/types';\nimport type { CrossOriginIframeMessageEventContent } from '../types';\nimport { IframeManager } from './iframe-manager';\nimport { ShadowDomManager } from './shadow-dom-manager';\nimport { CanvasManager } from './observers/canvas/canvas-manager';\nimport { StylesheetManager } from './stylesheet-manager';\nimport ProcessedNodeManager from './processed-node-manager';\nimport {\n  callbackWrapper,\n  registerErrorHandler,\n  unregisterErrorHandler,\n} from './error-handler';\nimport dom from '@rrweb/utils';\n\nlet wrappedEmit!: (e: eventWithoutTime, isCheckout?: boolean) => void;\n\nlet takeFullSnapshot!: (isCheckout?: boolean) => void;\nlet canvasManager!: CanvasManager;\nlet recording = false;\n\n// Multiple tools (i.e. MooTools, Prototype.js) override Array.from and drop support for the 2nd parameter\n// Try to pull a clean implementation from a newly created iframe\ntry {\n  if (Array.from([1], (x) => x * 2)[0] !== 2) {\n    const cleanFrame = document.createElement('iframe');\n    document.body.appendChild(cleanFrame);\n    // eslint-disable-next-line @typescript-eslint/unbound-method -- Array.from is static and doesn't rely on binding\n    Array.from = cleanFrame.contentWindow?.Array.from || Array.from;\n    document.body.removeChild(cleanFrame);\n  }\n} catch (err) {\n  console.debug('Unable to override Array.from', err);\n}\n\nconst mirror = createMirror();\nfunction record<T = eventWithTime>(\n  options: recordOptions<T> = {},\n): listenerHandler | undefined {\n  const {\n    emit,\n    checkoutEveryNms,\n    checkoutEveryNth,\n    blockClass = 'rr-block',\n    blockSelector = null,\n    ignoreClass = 'rr-ignore',\n    ignoreSelector = null,\n    maskTextClass = 'rr-mask',\n    maskTextSelector = null,\n    inlineStylesheet = true,\n    maskAllInputs,\n    maskInputOptions: _maskInputOptions,\n    slimDOMOptions: _slimDOMOptions,\n    maskInputFn,\n    maskTextFn,\n    hooks,\n    packFn,\n    sampling = {},\n    dataURLOptions = {},\n    mousemoveWait,\n    recordDOM = true,\n    recordCanvas = false,\n    recordCrossOriginIframes = false,\n    recordAfter = options.recordAfter === 'DOMContentLoaded'\n      ? options.recordAfter\n      : 'load',\n    userTriggeredOnInput = false,\n    collectFonts = false,\n    inlineImages = false,\n    plugins,\n    keepIframeSrcFn = () => false,\n    ignoreCSSAttributes = new Set([]),\n    errorHandler,\n  } = options;\n\n  registerErrorHandler(errorHandler);\n\n  const inEmittingFrame = recordCrossOriginIframes\n    ? window.parent === window\n    : true;\n\n  let passEmitsToParent = false;\n  if (!inEmittingFrame) {\n    try {\n      // throws if parent is cross-origin\n      if (window.parent.document) {\n        passEmitsToParent = false; // if parent is same origin we collect iframe events from the parent\n      }\n    } catch (e) {\n      passEmitsToParent = true;\n    }\n  }\n\n  // runtime checks for user options\n  if (inEmittingFrame && !emit) {\n    throw new Error('emit function is required');\n  }\n  if (!inEmittingFrame && !passEmitsToParent) {\n    return () => {\n      /* no-op since in this case we don't need to record anything from this frame in particular */\n    };\n  }\n  // move departed options to new options\n  if (mousemoveWait !== undefined && sampling.mousemove === undefined) {\n    sampling.mousemove = mousemoveWait;\n  }\n\n  // reset mirror in case `record` this was called earlier\n  mirror.reset();\n\n  const maskInputOptions: MaskInputOptions =\n    maskAllInputs === true\n      ? {\n          color: true,\n          date: true,\n          'datetime-local': true,\n          email: true,\n          month: true,\n          number: true,\n          range: true,\n          search: true,\n          tel: true,\n          text: true,\n          time: true,\n          url: true,\n          week: true,\n          textarea: true,\n          select: true,\n          password: true,\n        }\n      : _maskInputOptions !== undefined\n      ? _maskInputOptions\n      : { password: true };\n\n  const slimDOMOptions = slimDOMDefaults(_slimDOMOptions);\n\n  polyfill();\n\n  let lastFullSnapshotEvent: eventWithTime;\n  let incrementalSnapshotCount = 0;\n\n  const eventProcessor = (e: eventWithTime): T => {\n    for (const plugin of plugins || []) {\n      if (plugin.eventProcessor) {\n        e = plugin.eventProcessor(e);\n      }\n    }\n    if (\n      packFn &&\n      // Disable packing events which will be emitted to parent frames.\n      !passEmitsToParent\n    ) {\n      e = packFn(e) as unknown as eventWithTime;\n    }\n    return e as unknown as T;\n  };\n  wrappedEmit = (r: eventWithoutTime, isCheckout?: boolean) => {\n    const e = r as eventWithTime;\n    e.timestamp = nowTimestamp();\n    if (\n      e.type !== EventType.FullSnapshot &&\n      !(\n        e.type === EventType.IncrementalSnapshot &&\n        e.data.source === IncrementalSource.Mutation\n      )\n    ) {\n      // we've got a user initiated event so if we've been frozen we first need\n      // to apply all DOM changes that have been buffering during paused state\n      canvasManager.unfreeze();\n      for (const buf of mutationBuffers) {\n        if (buf.isFrozen()) {\n          buf.unfreeze();\n        } else {\n          break; // just need to check one as they all get frozen together\n        }\n      }\n    }\n\n    if (inEmittingFrame) {\n      emit?.(eventProcessor(e), isCheckout);\n    } else if (passEmitsToParent) {\n      const message: CrossOriginIframeMessageEventContent<T> = {\n        type: 'rrweb',\n        event: eventProcessor(e),\n        origin: window.location.origin,\n        isCheckout,\n      };\n      window.parent.postMessage(message, '*');\n    }\n\n    if (e.type === EventType.FullSnapshot) {\n      lastFullSnapshotEvent = e;\n      incrementalSnapshotCount = 0;\n    } else if (e.type === EventType.IncrementalSnapshot) {\n      // attach iframe should be considered as full snapshot\n      if (\n        e.data.source === IncrementalSource.Mutation &&\n        e.data.isAttachIframe\n      ) {\n        return;\n      }\n\n      incrementalSnapshotCount++;\n      const exceedCount =\n        checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;\n      const exceedTime =\n        checkoutEveryNms &&\n        e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;\n      if (exceedCount || exceedTime) {\n        takeFullSnapshot(true);\n      }\n    }\n  };\n\n  const wrappedMutationEmit = (m: mutationCallbackParam) => {\n    wrappedEmit({\n      type: EventType.IncrementalSnapshot,\n      data: {\n        source: IncrementalSource.Mutation,\n        ...m,\n      },\n    });\n  };\n  const wrappedScrollEmit: scrollCallback = (p) =>\n    wrappedEmit({\n      type: EventType.IncrementalSnapshot,\n      data: {\n        source: IncrementalSource.Scroll,\n        ...p,\n      },\n    });\n  const wrappedCanvasMutationEmit = (p: canvasMutationParam) =>\n    wrappedEmit({\n      type: EventType.IncrementalSnapshot,\n      data: {\n        source: IncrementalSource.CanvasMutation,\n        ...p,\n      },\n    });\n\n  const wrappedAdoptedStyleSheetEmit = (a: adoptedStyleSheetParam) =>\n    wrappedEmit({\n      type: EventType.IncrementalSnapshot,\n      data: {\n        source: IncrementalSource.AdoptedStyleSheet,\n        ...a,\n      },\n    });\n\n  const stylesheetManager = new StylesheetManager({\n    mutationCb: wrappedMutationEmit,\n    adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit,\n  });\n\n  const iframeManager = new IframeManager({\n    mirror,\n    mutationCb: wrappedMutationEmit,\n    stylesheetManager: stylesheetManager,\n    recordCrossOriginIframes,\n    wrappedEmit,\n  });\n\n  /**\n   * Exposes mirror to the plugins\n   */\n  for (const plugin of plugins || []) {\n    if (plugin.getMirror)\n      plugin.getMirror({\n        nodeMirror: mirror,\n        crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,\n        crossOriginIframeStyleMirror:\n          iframeManager.crossOriginIframeStyleMirror,\n      });\n  }\n\n  const processedNodeManager = new ProcessedNodeManager();\n\n  canvasManager = new CanvasManager({\n    recordCanvas,\n    mutationCb: wrappedCanvasMutationEmit,\n    win: window,\n    blockClass,\n    blockSelector,\n    mirror,\n    sampling: sampling.canvas,\n    dataURLOptions,\n  });\n\n  const shadowDomManager = new ShadowDomManager({\n    mutationCb: wrappedMutationEmit,\n    scrollCb: wrappedScrollEmit,\n    bypassOptions: {\n      blockClass,\n      blockSelector,\n      maskTextClass,\n      maskTextSelector,\n      inlineStylesheet,\n      maskInputOptions,\n      dataURLOptions,\n      maskTextFn,\n      maskInputFn,\n      recordCanvas,\n      inlineImages,\n      sampling,\n      slimDOMOptions,\n      iframeManager,\n      stylesheetManager,\n      canvasManager,\n      keepIframeSrcFn,\n      processedNodeManager,\n    },\n    mirror,\n  });\n\n  takeFullSnapshot = (isCheckout = false) => {\n    if (!recordDOM) {\n      return;\n    }\n    wrappedEmit(\n      {\n        type: EventType.Meta,\n        data: {\n          href: window.location.href,\n          width: getWindowWidth(),\n          height: getWindowHeight(),\n        },\n      },\n      isCheckout,\n    );\n\n    // When we take a full snapshot, old tracked StyleSheets need to be removed.\n    stylesheetManager.reset();\n\n    shadowDomManager.init();\n\n    canvasManager.lock();\n    mutationBuffers.forEach((buf) => buf.lock()); // don't allow any mirror modifications during snapshotting\n    const node = snapshot(document, {\n      mirror,\n      blockClass,\n      blockSelector,\n      maskTextClass,\n      maskTextSelector,\n      inlineStylesheet,\n      maskAllInputs: maskInputOptions,\n      maskTextFn,\n      maskInputFn,\n      slimDOM: slimDOMOptions,\n      dataURLOptions,\n      recordCanvas,\n      inlineImages,\n      onSerialize: (n) => {\n        if (isSerializedIframe(n, mirror)) {\n          iframeManager.addIframe(n as HTMLIFrameElement);\n        }\n        if (isSerializedStylesheet(n, mirror)) {\n          stylesheetManager.trackLinkElement(n as HTMLLinkElement);\n        }\n        if (hasShadowRoot(n)) {\n          // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n          shadowDomManager.addShadowRoot(dom.shadowRoot(n as Node)!, document);\n        }\n      },\n      onIframeLoad: (iframe, childSn) => {\n        iframeManager.attachIframe(iframe, childSn);\n        shadowDomManager.observeAttachShadow(iframe);\n      },\n      onStylesheetLoad: (linkEl, childSn) => {\n        stylesheetManager.attachLinkElement(linkEl, childSn);\n      },\n      keepIframeSrcFn,\n    });\n\n    if (!node) {\n      return console.warn('Failed to snapshot the document');\n    }\n\n    wrappedEmit(\n      {\n        type: EventType.FullSnapshot,\n        data: {\n          node,\n          initialOffset: getWindowScroll(window),\n        },\n      },\n      isCheckout,\n    );\n    canvasManager.unlock();\n    mutationBuffers.forEach((buf) => buf.unlock()); // generate & emit any mutations that happened during snapshotting, as can now apply against the newly built mirror\n\n    // Some old browsers don't support adoptedStyleSheets.\n    if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0)\n      stylesheetManager.adoptStyleSheets(\n        document.adoptedStyleSheets,\n        mirror.getId(document),\n      );\n  };\n\n  try {\n    const handlers: listenerHandler[] = [];\n\n    const observe = (doc: Document) => {\n      return callbackWrapper(initObservers)(\n        {\n          mutationCb: wrappedMutationEmit,\n          mousemoveCb: (positions, source) =>\n            wrappedEmit({\n              type: EventType.IncrementalSnapshot,\n              data: {\n                source,\n                positions,\n              },\n            }),\n          mouseInteractionCb: (d) =>\n            wrappedEmit({\n              type: EventType.IncrementalSnapshot,\n              data: {\n                source: IncrementalSource.MouseInteraction,\n                ...d,\n              },\n            }),\n          scrollCb: wrappedScrollEmit,\n          viewportResizeCb: (d) =>\n            wrappedEmit({\n              type: EventType.IncrementalSnapshot,\n              data: {\n                source: IncrementalSource.ViewportResize,\n                ...d,\n              },\n            }),\n          inputCb: (v) =>\n            wrappedEmit({\n              type: EventType.IncrementalSnapshot,\n              data: {\n                source: IncrementalSource.Input,\n                ...v,\n              },\n            }),\n          mediaInteractionCb: (p) =>\n            wrappedEmit({\n              type: EventType.IncrementalSnapshot,\n              data: {\n                source: IncrementalSource.MediaInteraction,\n                ...p,\n              },\n            }),\n          styleSheetRuleCb: (r) =>\n            wrappedEmit({\n              type: EventType.IncrementalSnapshot,\n              data: {\n                source: IncrementalSource.StyleSheetRule,\n                ...r,\n              },\n            }),\n          styleDeclarationCb: (r) =>\n            wrappedEmit({\n              type: EventType.IncrementalSnapshot,\n              data: {\n                source: IncrementalSource.StyleDeclaration,\n                ...r,\n              },\n            }),\n          canvasMutationCb: wrappedCanvasMutationEmit,\n          fontCb: (p) =>\n            wrappedEmit({\n              type: EventType.IncrementalSnapshot,\n              data: {\n                source: IncrementalSource.Font,\n                ...p,\n              },\n            }),\n          selectionCb: (p) => {\n            wrappedEmit({\n              type: EventType.IncrementalSnapshot,\n              data: {\n                source: IncrementalSource.Selection,\n                ...p,\n              },\n            });\n          },\n          customElementCb: (c) => {\n            wrappedEmit({\n              type: EventType.IncrementalSnapshot,\n              data: {\n                source: IncrementalSource.CustomElement,\n                ...c,\n              },\n            });\n          },\n          blockClass,\n          ignoreClass,\n          ignoreSelector,\n          maskTextClass,\n          maskTextSelector,\n          maskInputOptions,\n          inlineStylesheet,\n          sampling,\n          recordDOM,\n          recordCanvas,\n          inlineImages,\n          userTriggeredOnInput,\n          collectFonts,\n          doc,\n          maskInputFn,\n          maskTextFn,\n          keepIframeSrcFn,\n          blockSelector,\n          slimDOMOptions,\n          dataURLOptions,\n          mirror,\n          iframeManager,\n          stylesheetManager,\n          shadowDomManager,\n          processedNodeManager,\n          canvasManager,\n          ignoreCSSAttributes,\n          plugins:\n            plugins\n              ?.filter((p) => p.observer)\n              ?.map((p) => ({\n                observer: p.observer!,\n                options: p.options,\n                callback: (payload: object) =>\n                  wrappedEmit({\n                    type: EventType.Plugin,\n                    data: {\n                      plugin: p.name,\n                      payload,\n                    },\n                  }),\n              })) || [],\n        },\n        hooks,\n      );\n    };\n\n    // Observers of same-origin iframe documents, stopped when the document unloads.\n    const iframeObservers = new Map<Document, listenerHandler>();\n    iframeManager.addLoadListener((iframeEl) => {\n      try {\n        const doc = iframeEl.contentDocument!;\n        // Iframes are attached again on every full snapshot, but each document needs to be observed only once.\n        if (iframeObservers.has(doc)) return;\n        iframeObservers.set(doc, observe(doc));\n      } catch (error) {\n        // TODO: handle internal error\n        console.warn(error);\n      }\n    });\n    iframeManager.addUnloadListener((doc) => {\n      const stopObserving = iframeObservers.get(doc);\n      if (!stopObserving) return;\n      iframeObservers.delete(doc);\n      stopObserving();\n      shadowDomManager.removeShadowRootsIn(doc);\n      mirror.removeNodeFromMap(doc);\n    });\n\n    const init = () => {\n      takeFullSnapshot();\n      handlers.push(observe(document));\n      recording = true;\n    };\n    if (['interactive', 'complete'].includes(document.readyState)) {\n      init();\n    } else {\n      handlers.push(\n        on('DOMContentLoaded', () => {\n          wrappedEmit({\n            type: EventType.DomContentLoaded,\n            data: {},\n          });\n          if (recordAfter === 'DOMContentLoaded') init();\n        }),\n      );\n      handlers.push(\n        on(\n          'load',\n          () => {\n            wrappedEmit({\n              type: EventType.Load,\n              data: {},\n            });\n            if (recordAfter === 'load') init();\n          },\n          window,\n        ),\n      );\n    }\n    return () => {\n      [...handlers, ...iframeObservers.values()].forEach((handler) => {\n        try {\n          handler();\n        } catch (error) {\n          const msg = String(error).toLowerCase();\n          /**\n           * https://github.com/rrweb-io/rrweb/pull/1695\n           * This error can occur in a known scenario:\n           * If an iframe is initially same-origin and observed, but later its \n           location is changed in an opaque way to a cross-origin URL (perhaps within the iframe via its `document.location` or a redirect) \n           * attempting to execute the handler in the stop record function will \n           throw a \"cannot access cross-origin frame\" error.\n           * This error is expected and can be safely ignored.\n           */\n          if (!msg.includes('cross-origin')) {\n            console.warn(error);\n          }\n        }\n      });\n      iframeObservers.clear();\n      iframeManager.destroy();\n      processedNodeManager.destroy();\n      shadowDomManager.reset();\n      canvasManager.reset();\n      recording = false;\n      unregisterErrorHandler();\n    };\n  } catch (error) {\n    // TODO: handle internal error\n    console.warn(error);\n  }\n}\n\nrecord.addCustomEvent = <T>(tag: string, payload: T) => {\n  if (!recording) {\n    throw new Error('please add custom event after start recording');\n  }\n  wrappedEmit({\n    type: EventType.Custom,\n    data: {\n      tag,\n      payload,\n    },\n  });\n};\n\nrecord.addAnnotation = (annotation: annotationData) => {\n  if (!recording) {\n    throw new Error('please add annotation after recording started');\n  }\n  wrappedEmit({ type: EventType.Annotation, data: annotation });\n};\n\nrecord.freezePage = () => {\n  canvasManager.freeze();\n  mutationBuffers.forEach((buf) => buf.freeze());\n};\n\nrecord.takeFullSnapshot = (isCheckout?: boolean) => {\n  if (!recording) {\n    throw new Error('please take full snapshot after start recording');\n  }\n  takeFullSnapshot(isCheckout);\n};\n\nrecord.mirror = mirror;\n\nexport default record;\n"],
  "mappings": ";;;;;;;;;;;;;suBACA,IAAIA,EAA4B,SAASA,EAAW,CACnD,OAAAA,EAAUA,EAAU,iBAAsB,CAAA,EAAK,mBAC/CA,EAAUA,EAAU,KAAU,CAAA,EAAK,OACnCA,EAAUA,EAAU,aAAkB,CAAA,EAAK,eAC3CA,EAAUA,EAAU,oBAAyB,CAAA,EAAK,sBAClDA,EAAUA,EAAU,KAAU,CAAA,EAAK,OACnCA,EAAUA,EAAU,OAAY,CAAA,EAAK,SACrCA,EAAUA,EAAU,OAAY,CAAA,EAAK,SACrCA,EAAUA,EAAU,MAAW,CAAA,EAAK,QACpCA,EAAUA,EAAU,WAAgB,CAAA,EAAK,aAClCA,CACR,EAAE,CAAC,CAAC,EACAC,EAAoC,SAASA,EAAmB,CACnE,OAAAA,EAAkB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qB,QAAQ,EAC7BC,GAAiB,MAAM,EACvB9B,GAAc,MAAM,EACpBC,GAAY,GACZjP,GAAuB,CACzB,CACF,OAAStS,EAAO,CAEd,QAAQ,KAAKA,CAAK,CACpB,CACF,CAEAyhB,GAAO,eAAA,CAAqBgC,EAAa9S,IAAe,CACtD,GAAI,CAAC4Q,GACH,MAAM,IAAI,MAAM,+CAA+C,EAEjEH,EAAY,CACV,KAAM3mB,EAAU,OAChB,KAAM,CACJ,IAAAgpB,EACA,QAAA9S,CACF,CACF,CAAC,CACH,EAEA8Q,GAAO,cAAiBiC,GAA+B,CACrD,GAAI,CAACnC,GACH,MAAM,IAAI,MAAM,+CAA+C,EAEjEH,EAAY,CAAE,KAAM3mB,EAAU,WAAY,KAAMipB,CAAW,CAAC,CAC9D,EAEAjC,GAAO,WAAA,IAAmB,CACxBH,GAAc,OAAO,EACrB5O,GAAgB,QAASiQ,GAAQA,EAAI,OAAO,CAAC,CAC/C,EAEAlB,GAAO,iBAAoBiB,GAAyB,CAClD,GAAI,CAACnB,GACH,MAAM,IAAI,MAAM,iDAAiD,EAEnEF,GAAiBqB,CAAU,CAC7B,EAEAjB,GAAO,OAAS5Y",
  "names": ["EventType", "IncrementalSource", "MouseInteractions", "PointerTypes", "CanvasContext", "MediaInteractions", "NodeType", "testableAccessors", "testableMethods", "untaintedBasePrototype", "untaintedBaseIframeCleanup", "mutationObserverUsers", "angularZoneUnpatchedAlternative", "key", "angularUnpatchedVersionSymbol", "_b", "_a", "getUntaintedPrototype", "defaultObj", "defaultPrototype", "accessorNames", "isUntaintedAccessors", "accessor", "methodNames", "isUntaintedMethods", "method", "iframeEl", "win", "untaintedObject", "ua", "e", "untaintedAccessorCache", "getUntaintedAccessor", "instance", "cached", "untaintedPrototype", "untaintedAccessor", "untaintedMethodCache", "getUntaintedMethod", "cacheKey", "untaintedMethod", "ownerDocument", "n", "childNodes", "parentNode", "parentElement", "textContent", "firstChild", "lastChild", "nextSibling", "previousSibling", "contains", "other", "getRootNode", "host", "styleSheets", "shadowRoot", "querySelector", "selectors", "querySelectorAll", "mutationObserverCtor", "prototype", "stopCalled", "cleanup", "nowTimestamp", "patch", "source", "name", "replacement", "original", "wrapped", "src_default", "isElement", "isShadowRoot", "hostEl", "dom", "isNativeShadowDom", "fixBrowserCompatibilityIssuesInCSS", "cssText", "escapeImportStatement", "rule", "statement", "stringifyStylesheet", "s", "rules", "sheetHref", "stringifyRule", "error", "isCSSImportRule", "importStringified", "absolutifyURLs", "ruleStringified", "isCSSStyleRule", "fixSafariColons", "cssStringified", "Mirror", "__publicField", "id", "childNode", "node", "meta", "oldNode", "createMirror", "maskInputValue", "element", "maskInputOptions", "tagName", "type", "value", "maskInputFn", "text", "actualType", "toLowerCase", "str", "ORIGINAL_ATTRIBUTE_NAME", "is2DCanvasBlank", "canvas", "ctx", "chunkSize", "x", "y", "getImageData", "originalGetImageData", "pixel", "getInputType", "extractFileExtension", "path", "baseURL", "url", "err", "extractOrigin", "origin", "URL_IN_CSS_REF", "URL_PROTOCOL_MATCH", "URL_WWW_MATCH", "DATA_URI", "BLOB_URI", "href", "quote1", "path1", "quote2", "path2", "path3", "filePath", "maybeQuote", "filePathNoHash", "maybeHash", "stack", "parts", "part", "cssNormalizeBase", "cssNormalizeRe", "cssNormalizeReNoPx", "normalizeCssString", "_testNoPxNorm", "splitCssText", "style", "splits", "iterCount", "cssTextNorm", "normFactor", "i", "textContentNorm", "jLimit", "j", "startSubstring", "cssNormSplits", "splitNorm", "prevTextContent", "prevMinLength", "k", "normPart", "markCssSplits", "_id", "tagNameRegex", "genId", "getValidTagName", "processedTagName", "canvasService", "canvasCtx", "SRCSET_NOT_SPACES", "SRCSET_COMMAS_OR_SPACES", "getAbsoluteSrcsetString", "doc", "attributeValue", "pos", "collectCharacters", "regEx", "chars", "match", "output", "absoluteToDoc", "descriptorsStr", "inParens", "c", "cachedDocument", "getHref", "isSVGElement", "el", "customHref", "a", "transformAttribute", "ignoreAttribute", "_value", "_isBlockedElement", "blockClass", "blockSelector", "eIndex", "className", "classMatchesRegex", "regex", "checkAncestors", "needMaskingText", "maskTextClass", "maskTextSelector", "onceIframeLoaded", "listener", "iframeLoadTimeout", "fired", "readyState", "timer", "blankUrl", "onceStylesheetLoaded", "link", "styleSheetLoadTimeout", "styleSheetLoaded", "serializeNode", "options", "mirror", "needsMask", "inlineStylesheet", "maskTextFn", "dataURLOptions", "inlineImages", "recordCanvas", "keepIframeSrcFn", "newlyAddedElement", "cssCaptured", "rootId", "getRootId", "serializeElementNode", "serializeTextNode", "docId", "parent", "parentTagName", "isStyle", "isScript", "needBlock", "attributes", "len", "attr", "stylesheet", "checked", "canvasDataURL", "blankCanvas", "image", "imageSrc", "priorCrossOrigin", "recordInlineImage", "mediaAttributes", "width", "height", "isCustomElement", "lowerIfExists", "maybeAttr", "slimDOMDefaults", "_slimDOMOptions", "slimDOMExcluded", "sn", "slimDOMOptions", "serializeNodeWithId", "skipChild", "onSerialize", "onIframeLoad", "onStylesheetLoad", "stylesheetLoadTimeout", "preserveWhiteSpace", "_serializedNode", "serializedNode", "recordChild", "shadowRootEl", "bypassOptions", "childN", "serializedChildNode", "iframeDoc", "serializedIframeNode", "serializedLinkNode", "snapshot", "maskAllInputs", "slimDOM", "BaseRRNode", "_args", "childIterator", "_newChild", "_refChild", "_node", "on", "fn", "target", "DEPARTED_MIRROR_ACCESS_WARNING", "_mirror", "prop", "receiver", "throttle", "func", "wait", "timeout", "previous", "args", "now", "remaining", "context", "hookSetter", "d", "isRevoked", "getWindowScroll", "_d", "getWindowHeight", "getWindowWidth", "closestElementOfNode", "isBlocked", "isSerialized", "isIgnored", "isAncestorRemoved", "legacy_isTouchEvent", "event", "polyfill", "isSerializedIframe", "isSerializedStylesheet", "hasShadowRoot", "StyleSheetMirror", "newId", "getShadowHost", "shadowHost", "getRootShadowHost", "rootShadowHost", "shadowHostInDom", "inDom", "moveKey", "parentId", "MutationBuffer", "mutations", "adds", "addedIds", "ancestorBad", "missingParents", "iter", "curr", "isSelfOrAncestorInSet", "parentTag", "nextId", "currentN", "iframe", "childSn", "payload", "attribute", "diffAsStr", "unchangedAsStr", "textarea", "item", "cn", "m", "tagNameLower", "attributeName", "old", "pname", "newValue", "newPriority", "nodeId", "deepDelete", "processRemoves", "targetId", "addsSet", "cache", "queue", "next", "set", "_isSelfOrAncestorInSet", "errorHandler", "registerErrorHandler", "handler", "unregisterErrorHandler", "callbackWrapper", "cb", "rest", "mutationBuffers", "getEventTarget", "initMutationObserver", "rootEl", "mutationBuffer", "ObserverCtor", "releaseObserverConstructor", "observer", "initMoveObserver", "mousemoveCb", "sampling", "threshold", "callbackThreshold", "positions", "timeBaseline", "wrappedCb", "totalOffset", "updatePosition", "evt", "clientX", "clientY", "handlers", "h", "initMouseInteractionObserver", "mouseInteractionCb", "disableMap", "currentPointerType", "getHandler", "eventKey", "pointerType", "thisEventKey", "__spreadValues", "eventName", "initScrollObserver", "scrollCb", "scrollLeftTop", "initViewportResizeObserver", "viewportResizeCb", "lastH", "lastW", "INPUT_TAGS", "lastInputValueMap", "initInputObserver", "inputCb", "ignoreClass", "ignoreSelector", "userTriggeredOnInput", "eventHandler", "userTriggered", "isChecked", "cbWithDedup", "v", "lastInputValue", "__spreadProps", "currentWindow", "propertyDescriptor", "hookProperties", "p", "getNestedCSSRulePositions", "recurse", "childRule", "hasNestedCSSRule", "index", "getIdAndStyleId", "sheet", "styleMirror", "styleId", "initStyleSheetObserver", "styleSheetRuleCb", "stylesheetManager", "insertRule", "thisArg", "argumentsList", "selector", "styleBlock", "deleteRule", "replace", "replaceSync", "supportedNestedCSSRuleTypes", "canMonkeyPatchNestedCSSRule", "unmodifiedFunctions", "typeKey", "initAdoptedStyleSheetObserver", "hostId", "patchTarget", "_c", "originalPropertyDescriptor", "sheets", "result", "initStyleDeclarationObserver", "styleDeclarationCb", "ignoreCSSAttributes", "setProperty", "property", "priority", "removeProperty", "initMediaInteractionObserver", "mediaInteractionCb", "currentTime", "volume", "muted", "playbackRate", "loop", "initFontObserver", "fontCb", "fontMap", "originalFontFace", "family", "descriptors", "fontFace", "restoreHandler", "initSelectionObserver", "param", "selectionCb", "collapsed", "updateSelection", "selection", "ranges", "count", "startContainer", "startOffset", "endContainer", "endOffset", "initCustomElementObserver", "customElementCb", "constructor", "mergeHooks", "o", "hooks", "mutationCb", "canvasMutationCb", "initObservers", "stopMutationObserver", "mousemoveHandler", "mouseInteractionHandler", "scrollHandler", "viewportResizeHandler", "inputHandler", "mediaInteractionHandler", "styleSheetObserver", "adoptedStyleSheetObserver", "styleDeclarationObserver", "fontObserver", "selectionObserver", "customElementObserver", "pluginHandlers", "plugin", "CrossOriginIframeMirror", "generateIdFn", "remoteId", "idToRemoteMap", "remoteToIdMap", "idToRemoteIdMap", "remoteIdToIdMap", "map", "ids", "IframeManager", "message", "stop", "crossOriginMessageEvent", "transformedEvent", "range", "iframeMirror", "obj", "keys", "child", "ShadowDomManager", "runHandler", "iframeElement", "manager", "option", "sRoot", "shadowDoms", "lookup", "encode", "arraybuffer", "bytes", "base64", "canvasVarMap", "variableListFor", "ctor", "contextMap", "saveWebGLVar", "isInstanceOfWebGLObject", "list", "serializeArg", "arg", "src", "serializeArgs", "initCanvas2DMutationObserver", "props2D", "recordArgs", "hookHandler", "getNormalizedContextName", "contextType", "initCanvasContextObserver", "setPreserveDrawingBufferToTrue", "ctxName", "contextAttributes", "patchGLPrototype", "props", "mutation", "initCanvasWebGLMutationObserver", "CanvasManager", "fps", "canvasContextReset", "snapshotInProgressMap", "worker", "ImageBitmapDataURLWorker", "timeBetweenSnapshots", "lastSnapshotTime", "rafId", "getCanvas", "matchedCanvas", "takeCanvasSnapshots", "timestamp", "bitmap", "canvas2DReset", "canvasWebGL1and2Reset", "setLatestRAFTimestamp", "_values", "valuesWithType", "values", "__objRest", "StylesheetManager", "linkEl", "adoptedStyleSheetData", "styles", "r", "_linkEl", "ProcessedNodeManager", "thisBuffer", "buffers", "buffer", "wrappedEmit", "takeFullSnapshot", "canvasManager", "recording", "cleanFrame", "record", "emit", "checkoutEveryNms", "checkoutEveryNth", "_maskInputOptions", "packFn", "mousemoveWait", "recordDOM", "recordCrossOriginIframes", "recordAfter", "collectFonts", "plugins", "inEmittingFrame", "passEmitsToParent", "lastFullSnapshotEvent", "incrementalSnapshotCount", "eventProcessor", "isCheckout", "buf", "exceedCount", "exceedTime", "wrappedMutationEmit", "wrappedScrollEmit", "wrappedCanvasMutationEmit", "wrappedAdoptedStyleSheetEmit", "iframeManager", "processedNodeManager", "shadowDomManager", "observe", "iframeObservers", "stopObserving", "init", "tag", "annotation"]
}
