@amplitude/rrweb-snapshot
Version:
rrweb's component to take a snapshot of DOM, aka DOM serializer
1,579 lines • 163 kB
JavaScript
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
var NodeType = /* @__PURE__ */ ((NodeType2) => {
NodeType2[NodeType2["Document"] = 0] = "Document";
NodeType2[NodeType2["DocumentType"] = 1] = "DocumentType";
NodeType2[NodeType2["Element"] = 2] = "Element";
NodeType2[NodeType2["Text"] = 3] = "Text";
NodeType2[NodeType2["CDATA"] = 4] = "CDATA";
NodeType2[NodeType2["Comment"] = 5] = "Comment";
return NodeType2;
})(NodeType || {});
const testableAccessors = {
Node: ["childNodes", "parentNode", "parentElement", "textContent"],
ShadowRoot: ["host", "styleSheets"],
Element: ["shadowRoot", "querySelector", "querySelectorAll"],
MutationObserver: []
};
const testableMethods = {
Node: ["contains", "getRootNode"],
ShadowRoot: ["getSelection"],
Element: [],
MutationObserver: ["constructor"]
};
const untaintedBasePrototype = {};
function angularZoneUnpatchedAlternative(key) {
var _a, _b;
const angularUnpatchedVersionSymbol = (_b = (_a = globalThis == null ? void 0 : globalThis.Zone) == null ? void 0 : _a.__symbol__) == null ? void 0 : _b.call(_a, key);
if (angularUnpatchedVersionSymbol && globalThis[angularUnpatchedVersionSymbol]) {
return globalThis[angularUnpatchedVersionSymbol];
} else {
return void 0;
}
}
function getUntaintedPrototype(key) {
if (untaintedBasePrototype[key])
return untaintedBasePrototype[key];
const candidate = angularZoneUnpatchedAlternative(key) || globalThis[key];
const defaultPrototype = candidate.prototype;
const accessorNames = key in testableAccessors ? testableAccessors[key] : void 0;
const isUntaintedAccessors = Boolean(
accessorNames && // @ts-expect-error 2345
accessorNames.every(
(accessor) => {
var _a, _b;
return Boolean(
(_b = (_a = Object.getOwnPropertyDescriptor(defaultPrototype, accessor)) == null ? void 0 : _a.get) == null ? void 0 : _b.toString().includes("[native code]")
);
}
)
);
const methodNames = key in testableMethods ? testableMethods[key] : void 0;
const isUntaintedMethods = Boolean(
methodNames && methodNames.every(
// @ts-expect-error 2345
(method) => {
var _a;
return typeof defaultPrototype[method] === "function" && ((_a = defaultPrototype[method]) == null ? void 0 : _a.toString().includes("[native code]"));
}
)
);
if (isUntaintedAccessors && isUntaintedMethods) {
untaintedBasePrototype[key] = candidate.prototype;
return candidate.prototype;
}
try {
const iframeEl = document.createElement("iframe");
document.body.appendChild(iframeEl);
const win = iframeEl.contentWindow;
if (!win) return candidate.prototype;
const untaintedObject = win[key].prototype;
document.body.removeChild(iframeEl);
if (!untaintedObject) return defaultPrototype;
return untaintedBasePrototype[key] = untaintedObject;
} catch {
return defaultPrototype;
}
}
const untaintedAccessorCache = {};
function getUntaintedAccessor(key, instance, accessor) {
var _a;
const cacheKey = `${key}.${String(accessor)}`;
if (untaintedAccessorCache[cacheKey])
return untaintedAccessorCache[cacheKey].call(
instance
);
const untaintedPrototype = getUntaintedPrototype(key);
const untaintedAccessor = (_a = Object.getOwnPropertyDescriptor(
untaintedPrototype,
accessor
)) == null ? void 0 : _a.get;
if (!untaintedAccessor) return instance[accessor];
untaintedAccessorCache[cacheKey] = untaintedAccessor;
return untaintedAccessor.call(instance);
}
const untaintedMethodCache = {};
function getUntaintedMethod(key, instance, method) {
const cacheKey = `${key}.${String(method)}`;
if (untaintedMethodCache[cacheKey])
return untaintedMethodCache[cacheKey].bind(
instance
);
const untaintedPrototype = getUntaintedPrototype(key);
const untaintedMethod = untaintedPrototype[method];
if (typeof untaintedMethod !== "function") return instance[method];
untaintedMethodCache[cacheKey] = untaintedMethod;
return untaintedMethod.bind(instance);
}
function childNodes(n) {
return getUntaintedAccessor("Node", n, "childNodes");
}
function parentNode(n) {
return getUntaintedAccessor("Node", n, "parentNode");
}
function parentElement(n) {
return getUntaintedAccessor("Node", n, "parentElement");
}
function textContent(n) {
return getUntaintedAccessor("Node", n, "textContent");
}
function contains(n, other) {
return getUntaintedMethod("Node", n, "contains")(other);
}
function getRootNode(n) {
return getUntaintedMethod("Node", n, "getRootNode")();
}
function host(n) {
if (!n || !("host" in n)) return null;
return getUntaintedAccessor("ShadowRoot", n, "host");
}
function styleSheets(n) {
return n.styleSheets;
}
function shadowRoot(n) {
if (!n || !("shadowRoot" in n)) return null;
return getUntaintedAccessor("Element", n, "shadowRoot");
}
function querySelector(n, selectors) {
return getUntaintedAccessor("Element", n, "querySelector")(selectors);
}
function querySelectorAll(n, selectors) {
return getUntaintedAccessor("Element", n, "querySelectorAll")(selectors);
}
function mutationObserverCtor() {
return getUntaintedPrototype("MutationObserver").constructor;
}
const index = {
childNodes,
parentNode,
parentElement,
textContent,
contains,
getRootNode,
host,
styleSheets,
shadowRoot,
querySelector,
querySelectorAll,
mutationObserver: mutationObserverCtor
};
function isElement(n) {
return n.nodeType === n.ELEMENT_NODE;
}
function isShadowRoot(n) {
const hostEl = (
// anchor and textarea elements also have a `host` property
// but only shadow roots have a `mode` property
n && "host" in n && "mode" in n && index.host(n) || null
);
return Boolean(
hostEl && "shadowRoot" in hostEl && index.shadowRoot(hostEl) === n
);
}
function isNativeShadowDom(shadowRoot2) {
return Object.prototype.toString.call(shadowRoot2) === "[object ShadowRoot]";
}
function fixBrowserCompatibilityIssuesInCSS(cssText) {
if (cssText.includes(" background-clip: text;") && !cssText.includes(" -webkit-background-clip: text;")) {
cssText = cssText.replace(
/\sbackground-clip:\s*text;/g,
" -webkit-background-clip: text; background-clip: text;"
);
}
return cssText;
}
function escapeImportStatement(rule2) {
const { cssText } = rule2;
if (cssText.split('"').length < 3) return cssText;
const statement = ["@import", `url(${JSON.stringify(rule2.href)})`];
if (rule2.layerName === "") {
statement.push(`layer`);
} else if (rule2.layerName) {
statement.push(`layer(${rule2.layerName})`);
}
if (rule2.supportsText) {
statement.push(`supports(${rule2.supportsText})`);
}
if (rule2.media.length) {
statement.push(rule2.media.mediaText);
}
return statement.join(" ") + ";";
}
function stringifyStylesheet(s) {
try {
const rules = s.rules || s.cssRules;
if (!rules) {
return null;
}
let sheetHref = s.href;
if (!sheetHref && s.ownerNode && s.ownerNode.ownerDocument) {
sheetHref = s.ownerNode.ownerDocument.location.href;
}
const stringifiedRules = Array.from(
rules,
(rule2) => stringifyRule(rule2, sheetHref)
).join("");
return fixBrowserCompatibilityIssuesInCSS(stringifiedRules);
} catch (error) {
return null;
}
}
function stringifyRule(rule2, sheetHref) {
if (isCSSImportRule(rule2)) {
let importStringified;
try {
importStringified = // for same-origin stylesheets,
// we can access the imported stylesheet rules directly
stringifyStylesheet(rule2.styleSheet) || // work around browser issues with the raw string `@import url(...)` statement
escapeImportStatement(rule2);
} catch (error) {
importStringified = rule2.cssText;
}
if (rule2.styleSheet.href) {
return absolutifyURLs(importStringified, rule2.styleSheet.href);
}
return importStringified;
} else {
let ruleStringified = rule2.cssText;
if (isCSSStyleRule(rule2) && rule2.selectorText.includes(":")) {
ruleStringified = fixSafariColons(ruleStringified);
}
if (sheetHref) {
return absolutifyURLs(ruleStringified, sheetHref);
}
return ruleStringified;
}
}
function fixSafariColons(cssStringified) {
const regex = /(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm;
return cssStringified.replace(regex, "$1\\$2");
}
function isCSSImportRule(rule2) {
return "styleSheet" in rule2;
}
function isCSSStyleRule(rule2) {
return "selectorText" in rule2;
}
class Mirror {
constructor() {
__publicField(this, "idNodeMap", /* @__PURE__ */ new Map());
__publicField(this, "nodeMetaMap", /* @__PURE__ */ new WeakMap());
}
getId(n) {
var _a;
if (!n) return -1;
const id = (_a = this.getMeta(n)) == null ? void 0 : _a.id;
return id ?? -1;
}
getNode(id) {
return this.idNodeMap.get(id) || null;
}
getIds() {
return Array.from(this.idNodeMap.keys());
}
getMeta(n) {
return this.nodeMetaMap.get(n) || null;
}
// removes the node from idNodeMap
// doesn't remove the node from nodeMetaMap
removeNodeFromMap(n) {
const id = this.getId(n);
this.idNodeMap.delete(id);
if (n.childNodes) {
n.childNodes.forEach(
(childNode) => this.removeNodeFromMap(childNode)
);
}
}
has(id) {
return this.idNodeMap.has(id);
}
hasNode(node2) {
return this.nodeMetaMap.has(node2);
}
add(n, meta) {
const id = meta.id;
this.idNodeMap.set(id, n);
this.nodeMetaMap.set(n, meta);
}
replace(id, n) {
const oldNode = this.getNode(id);
if (oldNode) {
const meta = this.nodeMetaMap.get(oldNode);
if (meta) this.nodeMetaMap.set(n, meta);
}
this.idNodeMap.set(id, n);
}
reset() {
this.idNodeMap = /* @__PURE__ */ new Map();
this.nodeMetaMap = /* @__PURE__ */ new WeakMap();
}
}
function createMirror() {
return new Mirror();
}
function maskInputValue({
element,
maskInputOptions,
tagName,
type,
value,
maskInputFn
}) {
let text = value || "";
const actualType = type && toLowerCase(type);
if (maskInputOptions[tagName.toLowerCase()] || actualType && maskInputOptions[actualType]) {
if (maskInputFn) {
text = maskInputFn(text, element);
} else {
text = "*".repeat(text.length);
}
}
return text;
}
function toLowerCase(str) {
return str.toLowerCase();
}
const ORIGINAL_ATTRIBUTE_NAME = "__rrweb_original__";
function is2DCanvasBlank(canvas) {
const ctx = canvas.getContext("2d");
if (!ctx) return true;
const chunkSize = 50;
for (let x2 = 0; x2 < canvas.width; x2 += chunkSize) {
for (let y = 0; y < canvas.height; y += chunkSize) {
const getImageData = ctx.getImageData;
const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData ? getImageData[ORIGINAL_ATTRIBUTE_NAME] : getImageData;
const pixelBuffer = new Uint32Array(
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access
originalGetImageData.call(
ctx,
x2,
y,
Math.min(chunkSize, canvas.width - x2),
Math.min(chunkSize, canvas.height - y)
).data.buffer
);
if (pixelBuffer.some((pixel) => pixel !== 0)) return false;
}
}
return true;
}
function isNodeMetaEqual(a, b) {
if (!a || !b || a.type !== b.type) return false;
if (a.type === NodeType.Document)
return a.compatMode === b.compatMode;
else if (a.type === NodeType.DocumentType)
return a.name === b.name && a.publicId === b.publicId && a.systemId === b.systemId;
else if (a.type === NodeType.Comment || a.type === NodeType.Text || a.type === NodeType.CDATA)
return a.textContent === b.textContent;
else if (a.type === NodeType.Element)
return a.tagName === b.tagName && JSON.stringify(a.attributes) === JSON.stringify(b.attributes) && a.isSVG === b.isSVG && a.needBlock === b.needBlock;
return false;
}
function getInputType(element) {
const type = element.type;
return element.hasAttribute("data-rr-is-password") ? "password" : type ? (
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
toLowerCase(type)
) : null;
}
function extractFileExtension(path, baseURL) {
let url;
try {
url = new URL(path, baseURL ?? window.location.href);
} catch (err) {
return null;
}
const regex = /\.([0-9a-z]+)(?:$)/i;
const match = url.pathname.match(regex);
return (match == null ? void 0 : match[1]) ?? null;
}
function extractOrigin(url) {
let origin = "";
if (url.indexOf("//") > -1) {
origin = url.split("/").slice(0, 3).join("/");
} else {
origin = url.split("/")[0];
}
origin = origin.split("?")[0];
return origin;
}
const URL_IN_CSS_REF = /url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm;
const URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\/\//i;
const URL_WWW_MATCH = /^www\..*/i;
const DATA_URI = /^(data:)([^,]*),(.*)/i;
function absolutifyURLs(cssText, href) {
return (cssText || "").replace(
URL_IN_CSS_REF,
(origin, quote1, path1, quote2, path2, path3) => {
const filePath = path1 || path2 || path3;
const maybeQuote = quote1 || quote2 || "";
if (!filePath) {
return origin;
}
if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {
return `url(${maybeQuote}${filePath}${maybeQuote})`;
}
if (DATA_URI.test(filePath)) {
return `url(${maybeQuote}${filePath}${maybeQuote})`;
}
if (filePath[0] === "/") {
return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;
}
const stack = href.split("/");
const parts = filePath.split("/");
stack.pop();
for (const part of parts) {
if (part === ".") {
continue;
} else if (part === "..") {
stack.pop();
} else {
stack.push(part);
}
}
return `url(${maybeQuote}${stack.join("/")}${maybeQuote})`;
}
);
}
function normalizeCssString(cssText, _testNoPxNorm = false) {
if (_testNoPxNorm) {
return cssText.replace(/(\/\*[^*]*\*\/)|[\s;]/g, "");
} else {
return cssText.replace(/(\/\*[^*]*\*\/)|[\s;]/g, "").replace(/0px/g, "0");
}
}
function splitCssText(cssText, style, _testNoPxNorm = false) {
const childNodes2 = Array.from(style.childNodes);
const splits = [];
let iterCount = 0;
if (childNodes2.length > 1 && cssText && typeof cssText === "string") {
let cssTextNorm = normalizeCssString(cssText, _testNoPxNorm);
const normFactor = cssTextNorm.length / cssText.length;
for (let i = 1; i < childNodes2.length; i++) {
if (childNodes2[i].textContent && typeof childNodes2[i].textContent === "string") {
const textContentNorm = normalizeCssString(
childNodes2[i].textContent,
_testNoPxNorm
);
const jLimit = 100;
let j = 3;
for (; j < textContentNorm.length; j++) {
if (
// keep consuming css identifiers (to get a decent chunk more quickly)
textContentNorm[j].match(/[a-zA-Z0-9]/) || // substring needs to be unique to this section
textContentNorm.indexOf(textContentNorm.substring(0, j), 1) !== -1
) {
continue;
}
break;
}
for (; j < textContentNorm.length; j++) {
let startSubstring = textContentNorm.substring(0, j);
let cssNormSplits = cssTextNorm.split(startSubstring);
let splitNorm = -1;
if (cssNormSplits.length === 2) {
splitNorm = cssNormSplits[0].length;
} else if (cssNormSplits.length > 2 && cssNormSplits[0] === "" && childNodes2[i - 1].textContent !== "") {
splitNorm = cssTextNorm.indexOf(startSubstring, 1);
} else if (cssNormSplits.length === 1) {
startSubstring = startSubstring.substring(
0,
startSubstring.length - 1
);
cssNormSplits = cssTextNorm.split(startSubstring);
if (cssNormSplits.length <= 1) {
splits.push(cssText);
return splits;
}
j = jLimit + 1;
} else if (j === textContentNorm.length - 1) {
splitNorm = cssTextNorm.indexOf(startSubstring);
}
if (cssNormSplits.length >= 2 && j > jLimit) {
const prevTextContent = childNodes2[i - 1].textContent;
if (prevTextContent && typeof prevTextContent === "string") {
const prevMinLength = normalizeCssString(prevTextContent).length;
splitNorm = cssTextNorm.indexOf(startSubstring, prevMinLength);
}
if (splitNorm === -1) {
splitNorm = cssNormSplits[0].length;
}
}
if (splitNorm !== -1) {
let k = Math.floor(splitNorm / normFactor);
for (; k > 0 && k < cssText.length; ) {
iterCount += 1;
if (iterCount > 50 * childNodes2.length) {
splits.push(cssText);
return splits;
}
const normPart = normalizeCssString(
cssText.substring(0, k),
_testNoPxNorm
);
if (normPart.length === splitNorm) {
splits.push(cssText.substring(0, k));
cssText = cssText.substring(k);
cssTextNorm = cssTextNorm.substring(splitNorm);
break;
} else if (normPart.length < splitNorm) {
k += Math.max(
1,
Math.floor((splitNorm - normPart.length) / normFactor)
);
} else {
k -= Math.max(
1,
Math.floor((normPart.length - splitNorm) * normFactor)
);
}
}
break;
}
}
}
}
}
splits.push(cssText);
return splits;
}
function markCssSplits(cssText, style) {
return splitCssText(cssText, style).join("/* rr_split */");
}
const _DEFAULT_BLOCKED_ELEMENT_BACKGROUND_COLOR = "lightgrey";
let _id = 1;
const tagNameRegex = new RegExp("[^a-z0-9-_:]");
const IGNORED_NODE = -2;
function genId() {
return _id++;
}
function getValidTagName(element) {
if (element instanceof HTMLFormElement) {
return "form";
}
const processedTagName = toLowerCase(element.tagName);
if (tagNameRegex.test(processedTagName)) {
return "div";
}
return processedTagName;
}
let canvasService;
let canvasCtx;
const SRCSET_NOT_SPACES = /^[^ \t\n\r\u000c]+/;
const SRCSET_COMMAS_OR_SPACES = /^[, \t\n\r\u000c]+/;
function getAbsoluteSrcsetString(doc, attributeValue) {
if (attributeValue.trim() === "") {
return attributeValue;
}
let pos = 0;
function collectCharacters(regEx) {
let chars;
const match = regEx.exec(attributeValue.substring(pos));
if (match) {
chars = match[0];
pos += chars.length;
return chars;
}
return "";
}
const output = [];
while (true) {
collectCharacters(SRCSET_COMMAS_OR_SPACES);
if (pos >= attributeValue.length) {
break;
}
let url = collectCharacters(SRCSET_NOT_SPACES);
if (url.slice(-1) === ",") {
url = absoluteToDoc(doc, url.substring(0, url.length - 1));
output.push(url);
} else {
let descriptorsStr = "";
url = absoluteToDoc(doc, url);
let inParens = false;
while (true) {
const c = attributeValue.charAt(pos);
if (c === "") {
output.push((url + descriptorsStr).trim());
break;
} else if (!inParens) {
if (c === ",") {
pos += 1;
output.push((url + descriptorsStr).trim());
break;
} else if (c === "(") {
inParens = true;
}
} else {
if (c === ")") {
inParens = false;
}
}
descriptorsStr += c;
pos += 1;
}
}
}
return output.join(", ");
}
const cachedDocument = /* @__PURE__ */ new WeakMap();
function absoluteToDoc(doc, attributeValue) {
if (!attributeValue || attributeValue.trim() === "") {
return attributeValue;
}
return getHref(doc, attributeValue);
}
function isSVGElement(el) {
return Boolean(el.tagName === "svg" || el.ownerSVGElement);
}
function getHref(doc, customHref) {
let a = cachedDocument.get(doc);
if (!a) {
a = doc.createElement("a");
cachedDocument.set(doc, a);
}
if (!customHref) {
customHref = "";
} else if (customHref.startsWith("blob:") || customHref.startsWith("data:")) {
return customHref;
}
a.setAttribute("href", customHref);
return a.href;
}
function transformAttribute(doc, tagName, name, value) {
if (!value) {
return value;
}
if (name === "src" || name === "href" && !(tagName === "use" && value[0] === "#")) {
return absoluteToDoc(doc, value);
} else if (name === "xlink:href" && value[0] !== "#") {
return absoluteToDoc(doc, value);
} else if (name === "background" && (tagName === "table" || tagName === "td" || tagName === "th")) {
return absoluteToDoc(doc, value);
} else if (name === "srcset") {
return getAbsoluteSrcsetString(doc, value);
} else if (name === "style") {
return absolutifyURLs(value, getHref(doc));
} else if (tagName === "object" && name === "data") {
return absoluteToDoc(doc, value);
}
return value;
}
function ignoreAttribute(tagName, name, _value) {
return (tagName === "video" || tagName === "audio") && name === "autoplay";
}
function _isBlockedElement(element, blockClass, blockSelector) {
try {
if (typeof blockClass === "string") {
if (element.classList.contains(blockClass)) {
return true;
}
} else {
for (let eIndex = element.classList.length; eIndex--; ) {
const className = element.classList[eIndex];
if (blockClass.test(className)) {
return true;
}
}
}
if (blockSelector) {
return element.matches(blockSelector);
}
} catch (e) {
}
return false;
}
function classMatchesRegex(node2, regex, checkAncestors) {
if (!node2) return false;
if (node2.nodeType !== node2.ELEMENT_NODE) {
if (!checkAncestors) return false;
return classMatchesRegex(index.parentNode(node2), regex, checkAncestors);
}
for (let eIndex = node2.classList.length; eIndex--; ) {
const className = node2.classList[eIndex];
if (regex.test(className)) {
return true;
}
}
if (!checkAncestors) return false;
return classMatchesRegex(index.parentNode(node2), regex, checkAncestors);
}
function needMaskingText(node2, maskTextClass, maskTextSelector, checkAncestors) {
let el;
if (isElement(node2)) {
el = node2;
if (!index.childNodes(el).length) {
return false;
}
} else if (index.parentElement(node2) === null) {
return false;
} else {
el = index.parentElement(node2);
}
try {
if (typeof maskTextClass === "string") {
if (checkAncestors) {
if (el.closest(`.${maskTextClass}`)) return true;
} else {
if (el.classList.contains(maskTextClass)) return true;
}
} else {
if (classMatchesRegex(el, maskTextClass, checkAncestors)) return true;
}
if (maskTextSelector) {
if (checkAncestors) {
if (el.closest(maskTextSelector)) return true;
} else {
if (el.matches(maskTextSelector)) return true;
}
}
} catch (e) {
}
return false;
}
function onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {
const win = iframeEl.contentWindow;
if (!win) {
return;
}
let fired = false;
let readyState;
try {
readyState = win.document.readyState;
} catch (error) {
return;
}
if (readyState !== "complete") {
const timer = setTimeout(() => {
if (!fired) {
listener();
fired = true;
}
}, iframeLoadTimeout);
iframeEl.addEventListener("load", () => {
clearTimeout(timer);
fired = true;
listener();
});
return;
}
const blankUrl = "about:blank";
if (win.location.href !== blankUrl || iframeEl.src === blankUrl || iframeEl.src === "") {
setTimeout(listener, 0);
return iframeEl.addEventListener("load", listener);
}
iframeEl.addEventListener("load", listener);
}
function onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {
let fired = false;
let styleSheetLoaded;
try {
styleSheetLoaded = link.sheet;
} catch (error) {
return;
}
if (styleSheetLoaded) return;
const timer = setTimeout(() => {
if (!fired) {
listener();
fired = true;
}
}, styleSheetLoadTimeout);
link.addEventListener("load", () => {
clearTimeout(timer);
fired = true;
listener();
});
}
function serializeNode(n, options) {
const {
doc,
mirror,
blockClass,
blockSelector,
needsMask,
inlineStylesheet,
maskInputOptions = {},
maskTextFn,
maskInputFn,
dataURLOptions = {},
inlineImages,
recordCanvas,
keepIframeSrcFn,
newlyAddedElement = false,
cssCaptured = false,
applyBackgroundColorToBlockedElements = false
} = options;
const rootId = getRootId(doc, mirror);
switch (n.nodeType) {
case n.DOCUMENT_NODE:
if (n.compatMode !== "CSS1Compat") {
return {
type: NodeType.Document,
childNodes: [],
compatMode: n.compatMode
// probably "BackCompat"
};
} else {
return {
type: NodeType.Document,
childNodes: []
};
}
case n.DOCUMENT_TYPE_NODE:
return {
type: NodeType.DocumentType,
name: n.name,
publicId: n.publicId,
systemId: n.systemId,
rootId
};
case n.ELEMENT_NODE:
return serializeElementNode(n, {
doc,
blockClass,
blockSelector,
inlineStylesheet,
maskInputOptions,
maskInputFn,
dataURLOptions,
inlineImages,
recordCanvas,
keepIframeSrcFn,
newlyAddedElement,
rootId,
applyBackgroundColorToBlockedElements
});
case n.TEXT_NODE:
return serializeTextNode(n, {
doc,
needsMask,
maskTextFn,
rootId,
cssCaptured
});
case n.CDATA_SECTION_NODE:
return {
type: NodeType.CDATA,
textContent: "",
rootId
};
case n.COMMENT_NODE:
return {
type: NodeType.Comment,
textContent: index.textContent(n) || "",
rootId
};
default:
return false;
}
}
function getRootId(doc, mirror) {
if (!mirror.hasNode(doc)) return void 0;
const docId = mirror.getId(doc);
return docId === 1 ? void 0 : docId;
}
function serializeTextNode(n, options) {
const { needsMask, maskTextFn, rootId, cssCaptured } = options;
const parent = index.parentNode(n);
const parentTagName = parent && parent.tagName;
let textContent2 = "";
const isStyle = parentTagName === "STYLE" ? true : void 0;
const isScript = parentTagName === "SCRIPT" ? true : void 0;
if (isScript) {
textContent2 = "SCRIPT_PLACEHOLDER";
} else if (!cssCaptured) {
textContent2 = index.textContent(n);
if (isStyle && textContent2) {
textContent2 = absolutifyURLs(textContent2, getHref(options.doc));
}
}
if (!isStyle && !isScript && textContent2 && needsMask) {
textContent2 = maskTextFn ? maskTextFn(textContent2, index.parentElement(n)) : textContent2.replace(/[\S]/g, "*");
}
return {
type: NodeType.Text,
textContent: textContent2 || "",
rootId
};
}
function serializeElementNode(n, options) {
const {
doc,
blockClass,
blockSelector,
inlineStylesheet,
maskInputOptions = {},
maskInputFn,
dataURLOptions = {},
inlineImages,
recordCanvas,
keepIframeSrcFn,
newlyAddedElement = false,
rootId,
applyBackgroundColorToBlockedElements = false
} = options;
const needBlock = _isBlockedElement(n, blockClass, blockSelector);
const tagName = getValidTagName(n);
let attributes = {};
const len = n.attributes.length;
for (let i = 0; i < len; i++) {
const attr = n.attributes[i];
if (!ignoreAttribute(tagName, attr.name, attr.value)) {
attributes[attr.name] = transformAttribute(
doc,
tagName,
toLowerCase(attr.name),
attr.value
);
}
}
if (tagName === "link" && inlineStylesheet) {
const stylesheet = Array.from(doc.styleSheets).find((s) => {
return s.href === n.href;
});
let cssText = null;
if (stylesheet) {
cssText = stringifyStylesheet(stylesheet);
}
if (cssText) {
delete attributes.rel;
delete attributes.href;
attributes._cssText = cssText;
}
}
if (tagName === "style" && n.sheet) {
let cssText = stringifyStylesheet(
n.sheet
);
if (cssText) {
if (n.childNodes.length > 1) {
cssText = markCssSplits(cssText, n);
}
attributes._cssText = cssText;
}
}
if (tagName === "input" || tagName === "textarea" || tagName === "select") {
const value = n.value;
const checked = n.checked;
if (attributes.type !== "radio" && attributes.type !== "checkbox" && attributes.type !== "submit" && attributes.type !== "button" && value) {
attributes.value = maskInputValue({
element: n,
type: getInputType(n),
tagName,
value,
maskInputOptions,
maskInputFn
});
} else if (checked) {
attributes.checked = checked;
}
}
if (tagName === "option") {
if (n.selected && !maskInputOptions["select"]) {
attributes.selected = true;
} else {
delete attributes.selected;
}
}
if (tagName === "dialog" && n.open) {
attributes.rr_open_mode = n.matches("dialog:modal") ? "modal" : "non-modal";
}
if (tagName === "canvas" && recordCanvas) {
if (n.__context === "2d") {
if (!is2DCanvasBlank(n)) {
attributes.rr_dataURL = n.toDataURL(
dataURLOptions.type,
dataURLOptions.quality
);
}
} else if (!("__context" in n)) {
const canvasDataURL = n.toDataURL(
dataURLOptions.type,
dataURLOptions.quality
);
const blankCanvas = doc.createElement("canvas");
blankCanvas.width = n.width;
blankCanvas.height = n.height;
const blankCanvasDataURL = blankCanvas.toDataURL(
dataURLOptions.type,
dataURLOptions.quality
);
if (canvasDataURL !== blankCanvasDataURL) {
attributes.rr_dataURL = canvasDataURL;
}
}
}
if (tagName === "img" && inlineImages) {
if (!canvasService) {
canvasService = doc.createElement("canvas");
canvasCtx = canvasService.getContext("2d");
}
const image = n;
const imageSrc = image.currentSrc || image.getAttribute("src") || "<unknown-src>";
const priorCrossOrigin = image.crossOrigin;
const recordInlineImage = () => {
image.removeEventListener("load", recordInlineImage);
try {
canvasService.width = image.naturalWidth;
canvasService.height = image.naturalHeight;
canvasCtx.drawImage(image, 0, 0);
attributes.rr_dataURL = canvasService.toDataURL(
dataURLOptions.type,
dataURLOptions.quality
);
} catch (err) {
if (image.crossOrigin !== "anonymous") {
image.crossOrigin = "anonymous";
if (image.complete && image.naturalWidth !== 0)
recordInlineImage();
else image.addEventListener("load", recordInlineImage);
return;
} else {
console.warn(
`Cannot inline img src=${imageSrc}! Error: ${err}`
);
}
}
if (image.crossOrigin === "anonymous") {
priorCrossOrigin ? attributes.crossOrigin = priorCrossOrigin : image.removeAttribute("crossorigin");
}
};
if (image.complete && image.naturalWidth !== 0) recordInlineImage();
else image.addEventListener("load", recordInlineImage);
}
if (tagName === "audio" || tagName === "video") {
const mediaAttributes = attributes;
mediaAttributes.rr_mediaState = n.paused ? "paused" : "played";
mediaAttributes.rr_mediaCurrentTime = n.currentTime;
mediaAttributes.rr_mediaPlaybackRate = n.playbackRate;
mediaAttributes.rr_mediaMuted = n.muted;
mediaAttributes.rr_mediaLoop = n.loop;
mediaAttributes.rr_mediaVolume = n.volume;
}
if (!newlyAddedElement) {
if (n.scrollLeft) {
attributes.rr_scrollLeft = n.scrollLeft;
}
if (n.scrollTop) {
attributes.rr_scrollTop = n.scrollTop;
}
}
if (needBlock) {
const { width, height } = n.getBoundingClientRect();
attributes = {
class: attributes.class,
rr_width: `${width}px`,
rr_height: `${height}px`,
...applyBackgroundColorToBlockedElements ? { rr_background_color: _DEFAULT_BLOCKED_ELEMENT_BACKGROUND_COLOR } : {}
};
}
if (tagName === "iframe" && !keepIframeSrcFn(attributes.src)) {
if (!n.contentDocument) {
attributes.rr_src = attributes.src;
}
delete attributes.src;
}
let isCustomElement;
try {
if (customElements.get(tagName)) isCustomElement = true;
} catch (e) {
}
return {
type: NodeType.Element,
tagName,
attributes,
childNodes: [],
isSVG: isSVGElement(n) || void 0,
needBlock,
rootId,
isCustom: isCustomElement
};
}
function lowerIfExists(maybeAttr) {
if (maybeAttr === void 0 || maybeAttr === null) {
return "";
} else {
return maybeAttr.toLowerCase();
}
}
function slimDOMExcluded(sn, slimDOMOptions) {
if (slimDOMOptions.comment && sn.type === NodeType.Comment) {
return true;
} else if (sn.type === NodeType.Element) {
if (slimDOMOptions.script && // script tag
(sn.tagName === "script" || // (module)preload link
sn.tagName === "link" && (sn.attributes.rel === "preload" || sn.attributes.rel === "modulepreload") && sn.attributes.as === "script" || // prefetch link
sn.tagName === "link" && sn.attributes.rel === "prefetch" && typeof sn.attributes.href === "string" && extractFileExtension(sn.attributes.href) === "js")) {
return true;
} else if (slimDOMOptions.headFavicon && (sn.tagName === "link" && sn.attributes.rel === "shortcut icon" || sn.tagName === "meta" && (lowerIfExists(sn.attributes.name).match(
/^msapplication-tile(image|color)$/
) || lowerIfExists(sn.attributes.name) === "application-name" || lowerIfExists(sn.attributes.rel) === "icon" || lowerIfExists(sn.attributes.rel) === "apple-touch-icon" || lowerIfExists(sn.attributes.rel) === "shortcut icon"))) {
return true;
} else if (sn.tagName === "meta") {
if (slimDOMOptions.headMetaDescKeywords && lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {
return true;
} else if (slimDOMOptions.headMetaSocial && (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) || // og = opengraph (facebook)
lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) || lowerIfExists(sn.attributes.name) === "pinterest")) {
return true;
} else if (slimDOMOptions.headMetaRobots && (lowerIfExists(sn.attributes.name) === "robots" || lowerIfExists(sn.attributes.name) === "googlebot" || lowerIfExists(sn.attributes.name) === "bingbot")) {
return true;
} else if (slimDOMOptions.headMetaHttpEquiv && sn.attributes["http-equiv"] !== void 0) {
return true;
} else if (slimDOMOptions.headMetaAuthorship && (lowerIfExists(sn.attributes.name) === "author" || lowerIfExists(sn.attributes.name) === "generator" || lowerIfExists(sn.attributes.name) === "framework" || lowerIfExists(sn.attributes.name) === "publisher" || lowerIfExists(sn.attributes.name) === "progid" || lowerIfExists(sn.attributes.property).match(/^article:/) || lowerIfExists(sn.attributes.property).match(/^product:/))) {
return true;
} else if (slimDOMOptions.headMetaVerification && (lowerIfExists(sn.attributes.name) === "google-site-verification" || lowerIfExists(sn.attributes.name) === "yandex-verification" || lowerIfExists(sn.attributes.name) === "csrf-token" || lowerIfExists(sn.attributes.name) === "p:domain_verify" || lowerIfExists(sn.attributes.name) === "verify-v1" || lowerIfExists(sn.attributes.name) === "verification" || lowerIfExists(sn.attributes.name) === "shopify-checkout-api-token")) {
return true;
}
}
}
return false;
}
function serializeNodeWithId(n, options) {
const {
doc,
mirror,
blockClass,
blockSelector,
maskTextClass,
maskTextSelector,
skipChild = false,
inlineStylesheet = true,
maskInputOptions = {},
maskTextFn,
maskInputFn,
slimDOMOptions,
dataURLOptions = {},
inlineImages = false,
recordCanvas = false,
onSerialize,
onIframeLoad,
iframeLoadTimeout = 5e3,
onStylesheetLoad,
stylesheetLoadTimeout = 5e3,
keepIframeSrcFn = () => false,
newlyAddedElement = false,
cssCaptured = false,
applyBackgroundColorToBlockedElements = false
} = options;
let { needsMask } = options;
let { preserveWhiteSpace = true } = options;
if (!needsMask) {
const checkAncestors = needsMask === void 0;
needsMask = needMaskingText(
n,
maskTextClass,
maskTextSelector,
checkAncestors
);
}
const _serializedNode = serializeNode(n, {
doc,
mirror,
blockClass,
blockSelector,
needsMask,
inlineStylesheet,
maskInputOptions,
maskTextFn,
maskInputFn,
dataURLOptions,
inlineImages,
recordCanvas,
keepIframeSrcFn,
newlyAddedElement,
cssCaptured,
applyBackgroundColorToBlockedElements
});
if (!_serializedNode) {
console.warn(n, "not serialized");
return null;
}
let id;
if (mirror.hasNode(n)) {
id = mirror.getId(n);
} else if (slimDOMExcluded(_serializedNode, slimDOMOptions) || !preserveWhiteSpace && _serializedNode.type === NodeType.Text && !_serializedNode.textContent.replace(/^\s+|\s+$/gm, "").length) {
id = IGNORED_NODE;
} else {
id = genId();
}
const serializedNode = Object.assign(_serializedNode, { id });
mirror.add(n, serializedNode);
if (id === IGNORED_NODE) {
return null;
}
if (onSerialize) {
onSerialize(n);
}
let recordChild = !skipChild;
if (serializedNode.type === NodeType.Element) {
recordChild = recordChild && !serializedNode.needBlock;
delete serializedNode.needBlock;
const shadowRootEl = index.shadowRoot(n);
if (shadowRootEl && isNativeShadowDom(shadowRootEl))
serializedNode.isShadowHost = true;
}
if ((serializedNode.type === NodeType.Document || serializedNode.type === NodeType.Element) && recordChild) {
if (slimDOMOptions.headWhitespace && serializedNode.type === NodeType.Element && serializedNode.tagName === "head") {
preserveWhiteSpace = false;
}
const bypassOptions = {
doc,
mirror,
blockClass,
blockSelector,
needsMask,
maskTextClass,
maskTextSelector,
skipChild,
inlineStylesheet,
maskInputOptions,
maskTextFn,
maskInputFn,
slimDOMOptions,
dataURLOptions,
inlineImages,
recordCanvas,
preserveWhiteSpace,
onSerialize,
onIframeLoad,
iframeLoadTimeout,
onStylesheetLoad,
stylesheetLoadTimeout,
keepIframeSrcFn,
cssCaptured: false,
applyBackgroundColorToBlockedElements
};
if (serializedNode.type === NodeType.Element && serializedNode.tagName === "textarea" && serializedNode.attributes.value !== void 0) ;
else {
if (serializedNode.type === NodeType.Element && serializedNode.attributes._cssText !== void 0 && typeof serializedNode.attributes._cssText === "string") {
bypassOptions.cssCaptured = true;
}
for (const childN of Array.from(index.childNodes(n))) {
const serializedChildNode = serializeNodeWithId(childN, bypassOptions);
if (serializedChildNode) {
serializedNode.childNodes.push(serializedChildNode);
}
}
}
let shadowRootEl = null;
if (isElement(n) && (shadowRootEl = index.shadowRoot(n))) {
for (const childN of Array.from(index.childNodes(shadowRootEl))) {
const serializedChildNode = serializeNodeWithId(childN, bypassOptions);
if (serializedChildNode) {
isNativeShadowDom(shadowRootEl) && (serializedChildNode.isShadow = true);
serializedNode.childNodes.push(serializedChildNode);
}
}
}
}
const parent = index.parentNode(n);
if (parent && isShadowRoot(parent) && isNativeShadowDom(parent)) {
serializedNode.isShadow = true;
}
if (serializedNode.type === NodeType.Element && serializedNode.tagName === "iframe") {
onceIframeLoaded(
n,
() => {
const iframeDoc = n.contentDocument;
if (iframeDoc && onIframeLoad) {
const serializedIframeNode = serializeNodeWithId(iframeDoc, {
doc: iframeDoc,
mirror,
blockClass,
blockSelector,
needsMask,
maskTextClass,
maskTextSelector,
skipChild: false,
inlineStylesheet,
maskInputOptions,
maskTextFn,
maskInputFn,
slimDOMOptions,
dataURLOptions,
inlineImages,
recordCanvas,
preserveWhiteSpace,
onSerialize,
onIframeLoad,
iframeLoadTimeout,
onStylesheetLoad,
stylesheetLoadTimeout,
keepIframeSrcFn
});
if (serializedIframeNode) {
onIframeLoad(
n,
serializedIframeNode
);
}
}
},
iframeLoadTimeout
);
}
if (serializedNode.type === NodeType.Element && serializedNode.tagName === "link" && typeof serializedNode.attributes.rel === "string" && (serializedNode.attributes.rel === "stylesheet" || serializedNode.attributes.rel === "preload" && typeof serializedNode.attributes.href === "string" && extractFileExtension(serializedNode.attributes.href) === "css")) {
onceStylesheetLoaded(
n,
() => {
if (onStylesheetLoad) {
const serializedLinkNode = serializeNodeWithId(n, {
doc,
mirror,
blockClass,
blockSelector,
needsMask,
maskTextClass,
maskTextSelector,
skipChild: false,
inlineStylesheet,
maskInputOptions,
maskTextFn,
maskInputFn,
slimDOMOptions,
dataURLOptions,
inlineImages,
recordCanvas,
preserveWhiteSpace,
onSerialize,
onIframeLoad,
iframeLoadTimeout,
onStylesheetLoad,
stylesheetLoadTimeout,
keepIframeSrcFn
});
if (serializedLinkNode) {
onStylesheetLoad(
n,
serializedLinkNode
);
}
}
},
stylesheetLoadTimeout
);
}
return serializedNode;
}
function snapshot(n, options) {
const {
mirror = new Mirror(),
blockClass = "rr-block",
blockSelector = null,
maskTextClass = "rr-mask",
maskTextSelector = null,
inlineStylesheet = true,
inlineImages = false,
recordCanvas = false,
maskAllInputs = false,
maskTextFn,
maskInputFn,
slimDOM = false,
dataURLOptions,
preserveWhiteSpace,
onSerialize,
onIframeLoad,
iframeLoadTimeout,
onStylesheetLoad,
stylesheetLoadTimeout,
keepIframeSrcFn = () => false,
applyBackgroundColorToBlockedElements = false
} = options || {};
const maskInputOptions = maskAllInputs === true ? {
color: true,
date: true,
"datetime-local": true,
email: true,
month: true,
number: true,
range: true,
search: true,
tel: true,
text: true,
time: true,
url: true,
week: true,
textarea: true,
select: true,
password: true
} : maskAllInputs === false ? {
password: true
} : maskAllInputs;
const slimDOMOptions = slimDOM === true || slimDOM === "all" ? (
// if true: set of sensible options that should not throw away any information
{
script: true,
comment: true,
headFavicon: true,
headWhitespace: true,
headMetaDescKeywords: slimDOM === "all",
// destructive
headMetaSocial: true,
headMetaRobots: true,
headMetaHttpEquiv: true,
headMetaAuthorship: true,
headMetaVerification: true
}
) : slimDOM === false ? {} : slimDOM;
return serializeNodeWithId(n, {
doc: n,
mirror,
blockClass,
blockSelector,
maskTextClass,
maskTextSelector,
skipChild: false,
inlineStylesheet,
maskInputOptions,
maskTextFn,
maskInputFn,
slimDOMOptions,
dataURLOptions,
inlineImages,
recordCanvas,
preserveWhiteSpace,
onSerialize,
onIframeLoad,
iframeLoadTimeout,
onStylesheetLoad,
stylesheetLoadTimeout,
keepIframeSrcFn,
newlyAddedElement: false,
applyBackgroundColorToBlockedElements
});
}
function visitSnapshot(node2, onVisit) {
function walk(current) {
onVisit(current);
if (current.type === NodeType.Document || current.type === NodeType.Element) {
current.childNodes.forEach(walk);
}
}
walk(node2);
}
function cleanupSnapshot() {
_id = 1;
}
const MEDIA_SELECTOR = /(max|min)-device-(width|height)/;
const MEDIA_SELECTOR_GLOBAL = new RegExp(MEDIA_SELECTOR.source, "g");
const mediaSelectorPlugin = {
postcssPlugin: "postcss-custom-selectors",
prepare() {
return {
postcssPlugin: "postcss-custom-selectors",
AtRule: function(atrule) {
if (atrule.params.match(MEDIA_SELECTOR_GLOBAL)) {
atrule.params = atrule.params.replace(MEDIA_SELECTOR_GLOBAL, "$1-$2");
}
}
};
}
};
const pseudoClassPlugin = {
postcssPlugin: "postcss-hover-classes",
prepare: function() {
const fixed = [];
return {
Rule: function(rule2) {
if (fixed.indexOf(rule2) !== -1) {
return;
}
fixed.push(rule2);
rule2.selectors.forEach(function(selector) {
if (selector.includes(":hover")) {
rule2.selector += ",\n" + selector.replace(/:hover/g, ".\\:hover");
}
});
}
};
}
};
function getDefaultExportFromCjs(x2) {
return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
}
function getAugmentedNamespace(n) {
if (n.__esModule) return n;
var f = n.default;
if (typeof f == "function") {
var a = function a2() {
if (this instanceof a2) {
return Reflect.construct(f, arguments, this.constructor);
}
return f.apply(this, arguments);
};
a.prototype = f.prototype;
} else a = {};
Object.defineProperty(a, "__esModule", { value: true });
Object.keys(n).forEach(function(k) {
var d = Object.getOwnPropertyDescriptor(n, k);
Object.defineProperty(a, k, d.get ? d : {
enumerable: true,
get: function() {
return n[k];
}
});
});
return a;
}
var picocolors_browser = { exports: {} };
var x = String;
var create = function() {
return { isColorSupported: false, reset: x, bold: x, dim: x, italic: x, underline: x, inverse: x, hidden: x, strikethrough: x, black: x, red: x, green: x, yellow: x, blue: x, magenta: x, cyan: x, white: x, gray: x, bgBlack: x, bgRed: x, bgGreen: x, bgYellow: x, bgBlue: x, bgMagenta: x, bgCyan: x, bgWhite: x };
};
picocolors_browser.exports = create();
picocolors_browser.exports.createColors = create;
var picocolors_browserExports = picocolors_browser.exports;
const __viteBrowserExternal = {};
const __viteBrowserExternal$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
__proto__: null,
default: __viteBrowserExternal
}, Symbol.toStringTag, { value: "Module" }));
const require$$2 = /* @__PURE__ */ getAugmentedNamespace(__viteBrowserExternal$1);
let pico = picocolors_browserExports;
let terminalHighlight$1 = require$$2;
let CssSyntaxError$3 = class CssSyntaxError extends Error {
constructor(message, line, column, source, file, plugin2) {
super(message);
this.name = "CssSyntaxError";
this.reason = message;
if (file) {
this.file = file;
}
if (source) {
this.source = source;
}
if (plugin2) {
this.plugin = plugin2;
}
if (typeof line !== "undefined" && typeof column !== "undefined") {
if (typeof line === "number") {
this.line = line;
this.column = column;
} else {
this.line = line.line;
this.column = line.column;
this.endLine = column.line;
this.endColumn = column.column;
}
}
this.setMessage();
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CssSyntaxError);
}
}
setMessage() {
this.message = this.plugin ? this.plugin + ": " : "";
this.message += this.file ? this.file : "<css input>";
if (typeof this.line !== "undefined") {
this.message += ":" + this.line + ":" + this.column;
}
this.message += ": " + this.reason;
}
showSourceCode(color) {
if (!this.source) return "";
let css = this.source;
if (color == null) color = pico.isColorSupported;
if (terminalHighlight$1) {
if (co