Remove INode (node.__sn) and use Mirror as source of truth (#868)

* Move ids to weakmap

* Fix typo

* Move from INode to storing serialized data in mirror

* Update packages/rrweb-snapshot/src/rebuild.ts

Co-authored-by: Yun Feng <yun.feng@anu.edu.au>

* Remove unnessisary `as Node` typecastings

Fixes: https://github.com/rrweb-io/rrweb/pull/868#discussion_r842240758

* Remove unnessisary `as unknown as ...`

* Remove unnessisary `as unknown as ...`

* Reset mirror when recording starts

Solves: https://github.com/rrweb-io/rrweb/pull/868#discussion_r842249599

* API has changed for snapshot, change test to reflect that

* Allow for es5 compatibility

* Remove unnessisary as unknown as ... and change test to reflect the API change

* Refactor mirror to remove `nodeIdMap`

Fixes: https://github.com/rrweb-io/rrweb/pull/868#discussion_r842732696

Co-authored-by: Yun Feng <yun.feng@anu.edu.au>
This commit is contained in:
Justin Halsall
2022-04-06 17:56:39 +02:00
committed by GitHub
parent 539f7c8c06
commit e4f680e8c9
36 changed files with 442 additions and 382 deletions

View File

@@ -37,4 +37,4 @@ There are several things will be done during rebuild:
#### buildNodeWithSN #### buildNodeWithSN
`buildNodeWithSN` will build DOM from serialized node and store serialized information in `__sn` property. `buildNodeWithSN` will build DOM from serialized node and store serialized information in the `mirror.getMeta(node)`.

View File

@@ -892,7 +892,7 @@ function addParent(obj: Stylesheet, parent?: Stylesheet) {
addParent(v, childParent); addParent(v, childParent);
}); });
} else if (value && typeof value === 'object') { } else if (value && typeof value === 'object') {
addParent((value as unknown) as Stylesheet, childParent); addParent(value as Stylesheet, childParent);
} }
} }

View File

@@ -4,11 +4,9 @@ import {
NodeType, NodeType,
tagMap, tagMap,
elementNode, elementNode,
idNodeMap,
INode,
BuildCache, BuildCache,
} from './types'; } from './types';
import { isElement } from './utils'; import { isElement, Mirror } from './utils';
const tagMap: tagMap = { const tagMap: tagMap = {
script: 'noscript', script: 'noscript',
@@ -215,7 +213,10 @@ function buildNode(
n.attributes.rr_dataURL n.attributes.rr_dataURL
) { ) {
// backup original img srcset // backup original img srcset
node.setAttribute('rrweb-original-srcset', n.attributes.srcset as string); node.setAttribute(
'rrweb-original-srcset',
n.attributes.srcset as string,
);
} else { } else {
node.setAttribute(name, value); node.setAttribute(name, value);
} }
@@ -307,16 +308,16 @@ export function buildNodeWithSN(
n: serializedNodeWithId, n: serializedNodeWithId,
options: { options: {
doc: Document; doc: Document;
map: idNodeMap; mirror: Mirror;
skipChild?: boolean; skipChild?: boolean;
hackCss: boolean; hackCss: boolean;
afterAppend?: (n: INode) => unknown; afterAppend?: (n: Node) => unknown;
cache: BuildCache; cache: BuildCache;
}, },
): INode | null { ): Node | null {
const { const {
doc, doc,
map, mirror,
skipChild = false, skipChild = false,
hackCss = true, hackCss = true,
afterAppend, afterAppend,
@@ -328,7 +329,7 @@ export function buildNodeWithSN(
} }
if (n.rootId) { if (n.rootId) {
console.assert( console.assert(
((map[n.rootId] as unknown) as Document) === doc, (mirror.getNode(n.rootId) as Document) === doc,
'Target document should has the same root id.', 'Target document should has the same root id.',
); );
} }
@@ -362,8 +363,7 @@ export function buildNodeWithSN(
node = doc; node = doc;
} }
(node as INode).__sn = n; mirror.add(node, n);
map[n.id] = node as INode;
if ( if (
(n.type === NodeType.Document || n.type === NodeType.Element) && (n.type === NodeType.Document || n.type === NodeType.Element) &&
@@ -372,7 +372,7 @@ export function buildNodeWithSN(
for (const childN of n.childNodes) { for (const childN of n.childNodes) {
const childNode = buildNodeWithSN(childN, { const childNode = buildNodeWithSN(childN, {
doc, doc,
map, mirror,
skipChild: false, skipChild: false,
hackCss, hackCss,
afterAppend, afterAppend,
@@ -394,27 +394,27 @@ export function buildNodeWithSN(
} }
} }
return node as INode; return node;
} }
function visit(idNodeMap: idNodeMap, onVisit: (node: INode) => void) { function visit(mirror: Mirror, onVisit: (node: Node) => void) {
function walk(node: INode) { function walk(node: Node) {
onVisit(node); onVisit(node);
} }
for (const key in idNodeMap) { for (const id of mirror.getIds()) {
if (idNodeMap[key]) { if (mirror.has(id)) {
walk(idNodeMap[key]); walk(mirror.getNode(id)!);
} }
} }
} }
function handleScroll(node: INode) { function handleScroll(node: Node, mirror: Mirror) {
const n = node.__sn; const n = mirror.getMeta(node);
if (n.type !== NodeType.Element) { if (n?.type !== NodeType.Element) {
return; return;
} }
const el = (node as Node) as HTMLElement; const el = node as HTMLElement;
for (const name in n.attributes) { for (const name in n.attributes) {
if (!(n.attributes.hasOwnProperty(name) && name.startsWith('rr_'))) { if (!(n.attributes.hasOwnProperty(name) && name.startsWith('rr_'))) {
continue; continue;
@@ -433,29 +433,36 @@ function rebuild(
n: serializedNodeWithId, n: serializedNodeWithId,
options: { options: {
doc: Document; doc: Document;
onVisit?: (node: INode) => unknown; onVisit?: (node: Node) => unknown;
hackCss?: boolean; hackCss?: boolean;
afterAppend?: (n: INode) => unknown; afterAppend?: (n: Node) => unknown;
cache: BuildCache; cache: BuildCache;
mirror: Mirror;
}, },
): [Node | null, idNodeMap] { ): Node | null {
const { doc, onVisit, hackCss = true, afterAppend, cache } = options; const {
const idNodeMap: idNodeMap = {}; doc,
onVisit,
hackCss = true,
afterAppend,
cache,
mirror = new Mirror(),
} = options;
const node = buildNodeWithSN(n, { const node = buildNodeWithSN(n, {
doc, doc,
map: idNodeMap, mirror,
skipChild: false, skipChild: false,
hackCss, hackCss,
afterAppend, afterAppend,
cache, cache,
}); });
visit(idNodeMap, (visitedNode) => { visit(mirror, (visitedNode) => {
if (onVisit) { if (onVisit) {
onVisit(visitedNode); onVisit(visitedNode);
} }
handleScroll(visitedNode); handleScroll(visitedNode, mirror);
}); });
return [node, idNodeMap]; return node;
} }
export default rebuild; export default rebuild;

View File

@@ -3,8 +3,6 @@ import {
serializedNodeWithId, serializedNodeWithId,
NodeType, NodeType,
attributes, attributes,
INode,
idNodeMap,
MaskInputOptions, MaskInputOptions,
SlimDOMOptions, SlimDOMOptions,
DataURLOptions, DataURLOptions,
@@ -14,6 +12,7 @@ import {
ICanvas, ICanvas,
} from './types'; } from './types';
import { import {
Mirror,
is2DCanvasBlank, is2DCanvasBlank,
isElement, isElement,
isShadowRoot, isShadowRoot,
@@ -377,6 +376,7 @@ function serializeNode(
n: Node, n: Node,
options: { options: {
doc: Document; doc: Document;
mirror: Mirror;
blockClass: string | RegExp; blockClass: string | RegExp;
blockSelector: string | null; blockSelector: string | null;
maskTextClass: string | RegExp; maskTextClass: string | RegExp;
@@ -393,6 +393,7 @@ function serializeNode(
): serializedNode | false { ): serializedNode | false {
const { const {
doc, doc,
mirror,
blockClass, blockClass,
blockSelector, blockSelector,
maskTextClass, maskTextClass,
@@ -408,8 +409,8 @@ function serializeNode(
} = options; } = options;
// Only record root id when document object is not the base document // Only record root id when document object is not the base document
let rootId: number | undefined; let rootId: number | undefined;
if (((doc as unknown) as INode).__sn) { if (mirror.getMeta(doc)) {
const docId = ((doc as unknown) as INode).__sn.id; const docId = mirror.getId(doc);
rootId = docId === 1 ? undefined : docId; rootId = docId === 1 ? undefined : docId;
} }
switch (n.nodeType) { switch (n.nodeType) {
@@ -786,10 +787,10 @@ function slimDOMExcluded(
} }
export function serializeNodeWithId( export function serializeNodeWithId(
n: Node | INode, n: Node,
options: { options: {
doc: Document; doc: Document;
map: idNodeMap; mirror: Mirror;
blockClass: string | RegExp; blockClass: string | RegExp;
blockSelector: string | null; blockSelector: string | null;
maskTextClass: string | RegExp; maskTextClass: string | RegExp;
@@ -805,14 +806,17 @@ export function serializeNodeWithId(
inlineImages?: boolean; inlineImages?: boolean;
recordCanvas?: boolean; recordCanvas?: boolean;
preserveWhiteSpace?: boolean; preserveWhiteSpace?: boolean;
onSerialize?: (n: INode) => unknown; onSerialize?: (n: Node) => unknown;
onIframeLoad?: (iframeINode: INode, node: serializedNodeWithId) => unknown; onIframeLoad?: (
iframeNode: HTMLIFrameElement,
node: serializedNodeWithId,
) => unknown;
iframeLoadTimeout?: number; iframeLoadTimeout?: number;
}, },
): serializedNodeWithId | null { ): serializedNodeWithId | null {
const { const {
doc, doc,
map, mirror,
blockClass, blockClass,
blockSelector, blockSelector,
maskTextClass, maskTextClass,
@@ -834,6 +838,7 @@ export function serializeNodeWithId(
let { preserveWhiteSpace = true } = options; let { preserveWhiteSpace = true } = options;
const _serializedNode = serializeNode(n, { const _serializedNode = serializeNode(n, {
doc, doc,
mirror,
blockClass, blockClass,
blockSelector, blockSelector,
maskTextClass, maskTextClass,
@@ -853,10 +858,10 @@ export function serializeNodeWithId(
return null; return null;
} }
let id; let id: number | undefined;
// Try to reuse the previous id if (mirror.hasNode(n)) {
if ('__sn' in n) { // Reuse the previous id
id = n.__sn.id; id = mirror.getId(n);
} else if ( } else if (
slimDOMExcluded(_serializedNode, slimDOMOptions) || slimDOMExcluded(_serializedNode, slimDOMOptions) ||
(!preserveWhiteSpace && (!preserveWhiteSpace &&
@@ -868,14 +873,16 @@ export function serializeNodeWithId(
} else { } else {
id = genId(); id = genId();
} }
const serializedNode = Object.assign(_serializedNode, { id });
(n as INode).__sn = serializedNode;
if (id === IGNORED_NODE) { if (id === IGNORED_NODE) {
return null; // slimDOM return null; // slimDOM
} }
map[id] = n as INode;
const serializedNode = Object.assign(_serializedNode, { id });
mirror.add(n, serializedNode);
if (onSerialize) { if (onSerialize) {
onSerialize(n as INode); onSerialize(n);
} }
let recordChild = !skipChild; let recordChild = !skipChild;
if (serializedNode.type === NodeType.Element) { if (serializedNode.type === NodeType.Element) {
@@ -891,15 +898,15 @@ export function serializeNodeWithId(
) { ) {
if ( if (
slimDOMOptions.headWhitespace && slimDOMOptions.headWhitespace &&
_serializedNode.type === NodeType.Element && serializedNode.type === NodeType.Element &&
_serializedNode.tagName === 'head' serializedNode.tagName === 'head'
// would impede performance: || getComputedStyle(n)['white-space'] === 'normal' // would impede performance: || getComputedStyle(n)['white-space'] === 'normal'
) { ) {
preserveWhiteSpace = false; preserveWhiteSpace = false;
} }
const bypassOptions = { const bypassOptions = {
doc, doc,
map, mirror,
blockClass, blockClass,
blockSelector, blockSelector,
maskTextClass, maskTextClass,
@@ -952,7 +959,7 @@ export function serializeNodeWithId(
if (iframeDoc && onIframeLoad) { if (iframeDoc && onIframeLoad) {
const serializedIframeNode = serializeNodeWithId(iframeDoc, { const serializedIframeNode = serializeNodeWithId(iframeDoc, {
doc: iframeDoc, doc: iframeDoc,
map, mirror,
blockClass, blockClass,
blockSelector, blockSelector,
maskTextClass, maskTextClass,
@@ -974,7 +981,7 @@ export function serializeNodeWithId(
}); });
if (serializedIframeNode) { if (serializedIframeNode) {
onIframeLoad(n as INode, serializedIframeNode); onIframeLoad(n as HTMLIFrameElement, serializedIframeNode);
} }
} }
}, },
@@ -988,6 +995,7 @@ export function serializeNodeWithId(
function snapshot( function snapshot(
n: Document, n: Document,
options?: { options?: {
mirror?: Mirror;
blockClass?: string | RegExp; blockClass?: string | RegExp;
blockSelector?: string | null; blockSelector?: string | null;
maskTextClass?: string | RegExp; maskTextClass?: string | RegExp;
@@ -1001,13 +1009,17 @@ function snapshot(
inlineImages?: boolean; inlineImages?: boolean;
recordCanvas?: boolean; recordCanvas?: boolean;
preserveWhiteSpace?: boolean; preserveWhiteSpace?: boolean;
onSerialize?: (n: INode) => unknown; onSerialize?: (n: Node) => unknown;
onIframeLoad?: (iframeINode: INode, node: serializedNodeWithId) => unknown; onIframeLoad?: (
iframeNode: HTMLIFrameElement,
node: serializedNodeWithId,
) => unknown;
iframeLoadTimeout?: number; iframeLoadTimeout?: number;
keepIframeSrcFn?: KeepIframeSrcFn; keepIframeSrcFn?: KeepIframeSrcFn;
}, },
): [serializedNodeWithId | null, idNodeMap] { ): serializedNodeWithId | null {
const { const {
mirror = new Mirror(),
blockClass = 'rr-block', blockClass = 'rr-block',
blockSelector = null, blockSelector = null,
maskTextClass = 'rr-mask', maskTextClass = 'rr-mask',
@@ -1026,7 +1038,6 @@ function snapshot(
iframeLoadTimeout, iframeLoadTimeout,
keepIframeSrcFn = () => false, keepIframeSrcFn = () => false,
} = options || {}; } = options || {};
const idNodeMap: idNodeMap = {};
const maskInputOptions: MaskInputOptions = const maskInputOptions: MaskInputOptions =
maskAllInputs === true maskAllInputs === true
? { ? {
@@ -1070,31 +1081,28 @@ function snapshot(
: slimDOM === false : slimDOM === false
? {} ? {}
: slimDOM; : slimDOM;
return [ return serializeNodeWithId(n, {
serializeNodeWithId(n, { doc: n,
doc: n, mirror,
map: idNodeMap, blockClass,
blockClass, blockSelector,
blockSelector, maskTextClass,
maskTextClass, maskTextSelector,
maskTextSelector, skipChild: false,
skipChild: false, inlineStylesheet,
inlineStylesheet, maskInputOptions,
maskInputOptions, maskTextFn,
maskTextFn, maskInputFn,
maskInputFn, slimDOMOptions,
slimDOMOptions, dataURLOptions,
dataURLOptions, inlineImages,
inlineImages, recordCanvas,
recordCanvas, preserveWhiteSpace,
preserveWhiteSpace, onSerialize,
onSerialize, onIframeLoad,
onIframeLoad, iframeLoadTimeout,
iframeLoadTimeout, keepIframeSrcFn,
keepIframeSrcFn, });
}),
idNodeMap,
];
} }
export function visitSnapshot( export function visitSnapshot(

View File

@@ -67,6 +67,7 @@ export type tagMap = {
[key: string]: string; [key: string]: string;
}; };
// @deprecated
export interface INode extends Node { export interface INode extends Node {
__sn: serializedNodeWithId; __sn: serializedNodeWithId;
} }
@@ -75,9 +76,9 @@ export interface ICanvas extends HTMLCanvasElement {
__context: string; __context: string;
} }
export type idNodeMap = { export type idNodeMap = Map<number, Node>;
[key: number]: INode;
}; export type nodeMetaMap = WeakMap<Node, serializedNodeWithId>;
export type MaskInputOptions = Partial<{ export type MaskInputOptions = Partial<{
color: boolean; color: boolean;

View File

@@ -1,6 +1,12 @@
import { INode, MaskInputFn, MaskInputOptions } from './types'; import {
idNodeMap,
MaskInputFn,
MaskInputOptions,
nodeMetaMap,
serializedNodeWithId,
} from './types';
export function isElement(n: Node | INode): n is Element { export function isElement(n: Node): n is Element {
return n.nodeType === n.ELEMENT_NODE; return n.nodeType === n.ELEMENT_NODE;
} }
@@ -9,6 +15,69 @@ export function isShadowRoot(n: Node): n is ShadowRoot {
return Boolean(host && host.shadowRoot && host.shadowRoot === n); return Boolean(host && host.shadowRoot && host.shadowRoot === n);
} }
export class Mirror {
private idNodeMap: idNodeMap = new Map();
private nodeMetaMap: nodeMetaMap = new WeakMap();
getId(n: Node | undefined | null): number {
if (!n) return -1;
const id = this.getMeta(n)?.id;
// if n is not a serialized Node, use -1 as its id.
return id ?? -1;
}
getNode(id: number): Node | null {
return this.idNodeMap.get(id) || null;
}
getIds(): number[] {
return Array.from(this.idNodeMap.keys());
}
getMeta(n: Node): serializedNodeWithId | null {
return this.nodeMetaMap.get(n) || null;
}
// removes the node from idNodeMap
// doesn't remove the node from nodeMetaMap
removeNodeFromMap(n: Node) {
const id = this.getId(n);
this.idNodeMap.delete(id);
if (n.childNodes) {
n.childNodes.forEach((childNode) => this.removeNodeFromMap(childNode));
}
}
has(id: number): boolean {
return this.idNodeMap.has(id);
}
hasNode(node: Node): boolean {
return this.nodeMetaMap.has(node);
}
add(n: Node, meta: serializedNodeWithId) {
const id = meta.id;
this.idNodeMap.set(id, n);
this.nodeMetaMap.set(n, meta);
}
replace(id: number, n: Node) {
this.idNodeMap.set(id, n);
}
reset() {
this.idNodeMap = new Map();
this.nodeMetaMap = new WeakMap();
}
}
export function createMirror(): Mirror {
return new Mirror();
}
export function maskInputValue({ export function maskInputValue({
maskInputOptions, maskInputOptions,
tagName, tagName,

View File

@@ -131,8 +131,8 @@ describe('integration tests', function (this: ISuite) {
const rebuildHtml = ( const rebuildHtml = (
await page.evaluate(`${code} await page.evaluate(`${code}
const x = new XMLSerializer(); const x = new XMLSerializer();
const [snap] = rrweb.snapshot(document); const snap = rrweb.snapshot(document);
let out = x.serializeToString(rrweb.rebuild(snap, { doc: document })[0]); let out = x.serializeToString(rrweb.rebuild(snap, { doc: document }));
if (document.querySelector('html').getAttribute('xmlns') !== 'http://www.w3.org/1999/xhtml') { if (document.querySelector('html').getAttribute('xmlns') !== 'http://www.w3.org/1999/xhtml') {
// this is just an artefact of serializeToString // this is just an artefact of serializeToString
out = out.replace(' xmlns=\"http://www.w3.org/1999/xhtml\"', ''); out = out.replace(' xmlns=\"http://www.w3.org/1999/xhtml\"', '');
@@ -168,7 +168,7 @@ describe('integration tests', function (this: ISuite) {
`pre-check: images will be rendered ~326px high in BackCompat mode, and ~588px in CSS1Compat mode; getting: ${renderedHeight}px`, `pre-check: images will be rendered ~326px high in BackCompat mode, and ~588px in CSS1Compat mode; getting: ${renderedHeight}px`,
); );
const rebuildRenderedHeight = await page.evaluate(`${code} const rebuildRenderedHeight = await page.evaluate(`${code}
const [snap] = rrweb.snapshot(document); const snap = rrweb.snapshot(document);
const iframe = document.createElement('iframe'); const iframe = document.createElement('iframe');
iframe.setAttribute('width', document.body.clientWidth) iframe.setAttribute('width', document.body.clientWidth)
iframe.setAttribute('height', document.body.clientHeight) iframe.setAttribute('height', document.body.clientHeight)
@@ -205,9 +205,7 @@ iframe.contentDocument.querySelector('center').clientHeight
inlineStylesheet: false inlineStylesheet: false
})`); })`);
await page.waitFor(100); await page.waitFor(100);
const snapshot = await page.evaluate( const snapshot = await page.evaluate('JSON.stringify(snapshot, null, 2);');
'JSON.stringify(snapshot[0], null, 2);',
);
assert(snapshot.includes('"rr_dataURL"')); assert(snapshot.includes('"rr_dataURL"'));
assert(snapshot.includes('data:image/webp;base64,')); assert(snapshot.includes('data:image/webp;base64,'));
}); });
@@ -253,7 +251,7 @@ describe('iframe integration tests', function (this: ISuite) {
}); });
const snapshotResult = JSON.stringify( const snapshotResult = JSON.stringify(
await page.evaluate(`${code}; await page.evaluate(`${code};
rrweb.snapshot(document)[0]; rrweb.snapshot(document);
`), `),
null, null,
2, 2,
@@ -302,7 +300,7 @@ describe('shadow DOM integration tests', function (this: ISuite) {
}); });
const snapshotResult = JSON.stringify( const snapshotResult = JSON.stringify(
await page.evaluate(`${code}; await page.evaluate(`${code};
rrweb.snapshot(document)[0]; rrweb.snapshot(document);
`), `),
null, null,
2, 2,

View File

@@ -8,6 +8,7 @@ import {
_isBlockedElement, _isBlockedElement,
} from '../src/snapshot'; } from '../src/snapshot';
import { serializedNodeWithId } from '../src/types'; import { serializedNodeWithId } from '../src/types';
import { Mirror } from '../src/utils';
describe('absolute url to stylesheet', () => { describe('absolute url to stylesheet', () => {
const href = 'http://localhost/css/style.css'; const href = 'http://localhost/css/style.css';
@@ -139,7 +140,7 @@ describe('style elements', () => {
const serializeNode = (node: Node): serializedNodeWithId | null => { const serializeNode = (node: Node): serializedNodeWithId | null => {
return serializeNodeWithId(node, { return serializeNodeWithId(node, {
doc: document, doc: document,
map: {}, mirror: new Mirror(),
blockClass: 'blockblock', blockClass: 'blockblock',
blockSelector: null, blockSelector: null,
maskTextClass: 'maskmask', maskTextClass: 'maskmask',

View File

@@ -1,19 +1,21 @@
import { serializedNodeWithId, idNodeMap, INode, BuildCache } from './types'; import { serializedNodeWithId, BuildCache } from './types';
import { Mirror } from './utils';
export declare function addHoverClass(cssText: string, cache: BuildCache): string; export declare function addHoverClass(cssText: string, cache: BuildCache): string;
export declare function createCache(): BuildCache; export declare function createCache(): BuildCache;
export declare function buildNodeWithSN(n: serializedNodeWithId, options: { export declare function buildNodeWithSN(n: serializedNodeWithId, options: {
doc: Document; doc: Document;
map: idNodeMap; mirror: Mirror;
skipChild?: boolean; skipChild?: boolean;
hackCss: boolean; hackCss: boolean;
afterAppend?: (n: INode) => unknown; afterAppend?: (n: Node) => unknown;
cache: BuildCache; cache: BuildCache;
}): INode | null; }): Node | null;
declare function rebuild(n: serializedNodeWithId, options: { declare function rebuild(n: serializedNodeWithId, options: {
doc: Document; doc: Document;
onVisit?: (node: INode) => unknown; onVisit?: (node: Node) => unknown;
hackCss?: boolean; hackCss?: boolean;
afterAppend?: (n: INode) => unknown; afterAppend?: (n: Node) => unknown;
cache: BuildCache; cache: BuildCache;
}): [Node | null, idNodeMap]; mirror: Mirror;
}): Node | null;
export default rebuild; export default rebuild;

View File

@@ -1,13 +1,14 @@
import { serializedNodeWithId, INode, idNodeMap, MaskInputOptions, SlimDOMOptions, DataURLOptions, MaskTextFn, MaskInputFn, KeepIframeSrcFn } from './types'; import { serializedNodeWithId, MaskInputOptions, SlimDOMOptions, DataURLOptions, MaskTextFn, MaskInputFn, KeepIframeSrcFn } from './types';
import { Mirror } from './utils';
export declare const IGNORED_NODE = -2; export declare const IGNORED_NODE = -2;
export declare function absoluteToStylesheet(cssText: string | null, href: string): string; export declare function absoluteToStylesheet(cssText: string | null, href: string): string;
export declare function absoluteToDoc(doc: Document, attributeValue: string): string; export declare function absoluteToDoc(doc: Document, attributeValue: string): string;
export declare function transformAttribute(doc: Document, tagName: string, name: string, value: string): string; export declare function transformAttribute(doc: Document, tagName: string, name: string, value: string): string;
export declare function _isBlockedElement(element: HTMLElement, blockClass: string | RegExp, blockSelector: string | null): boolean; export declare function _isBlockedElement(element: HTMLElement, blockClass: string | RegExp, blockSelector: string | null): boolean;
export declare function needMaskingText(node: Node | null, maskTextClass: string | RegExp, maskTextSelector: string | null): boolean; export declare function needMaskingText(node: Node | null, maskTextClass: string | RegExp, maskTextSelector: string | null): boolean;
export declare function serializeNodeWithId(n: Node | INode, options: { export declare function serializeNodeWithId(n: Node, options: {
doc: Document; doc: Document;
map: idNodeMap; mirror: Mirror;
blockClass: string | RegExp; blockClass: string | RegExp;
blockSelector: string | null; blockSelector: string | null;
maskTextClass: string | RegExp; maskTextClass: string | RegExp;
@@ -23,11 +24,12 @@ export declare function serializeNodeWithId(n: Node | INode, options: {
inlineImages?: boolean; inlineImages?: boolean;
recordCanvas?: boolean; recordCanvas?: boolean;
preserveWhiteSpace?: boolean; preserveWhiteSpace?: boolean;
onSerialize?: (n: INode) => unknown; onSerialize?: (n: Node) => unknown;
onIframeLoad?: (iframeINode: INode, node: serializedNodeWithId) => unknown; onIframeLoad?: (iframeNode: HTMLIFrameElement, node: serializedNodeWithId) => unknown;
iframeLoadTimeout?: number; iframeLoadTimeout?: number;
}): serializedNodeWithId | null; }): serializedNodeWithId | null;
declare function snapshot(n: Document, options?: { declare function snapshot(n: Document, options?: {
mirror?: Mirror;
blockClass?: string | RegExp; blockClass?: string | RegExp;
blockSelector?: string | null; blockSelector?: string | null;
maskTextClass?: string | RegExp; maskTextClass?: string | RegExp;
@@ -41,11 +43,11 @@ declare function snapshot(n: Document, options?: {
inlineImages?: boolean; inlineImages?: boolean;
recordCanvas?: boolean; recordCanvas?: boolean;
preserveWhiteSpace?: boolean; preserveWhiteSpace?: boolean;
onSerialize?: (n: INode) => unknown; onSerialize?: (n: Node) => unknown;
onIframeLoad?: (iframeINode: INode, node: serializedNodeWithId) => unknown; onIframeLoad?: (iframeNode: HTMLIFrameElement, node: serializedNodeWithId) => unknown;
iframeLoadTimeout?: number; iframeLoadTimeout?: number;
keepIframeSrcFn?: KeepIframeSrcFn; keepIframeSrcFn?: KeepIframeSrcFn;
}): [serializedNodeWithId | null, idNodeMap]; }): serializedNodeWithId | null;
export declare function visitSnapshot(node: serializedNodeWithId, onVisit: (node: serializedNodeWithId) => unknown): void; export declare function visitSnapshot(node: serializedNodeWithId, onVisit: (node: serializedNodeWithId) => unknown): void;
export declare function cleanupSnapshot(): void; export declare function cleanupSnapshot(): void;
export default snapshot; export default snapshot;

View File

@@ -58,9 +58,8 @@ export interface INode extends Node {
export interface ICanvas extends HTMLCanvasElement { export interface ICanvas extends HTMLCanvasElement {
__context: string; __context: string;
} }
export declare type idNodeMap = { export declare type idNodeMap = Map<number, Node>;
[key: number]: INode; export declare type nodeMetaMap = WeakMap<Node, serializedNodeWithId>;
};
export declare type MaskInputOptions = Partial<{ export declare type MaskInputOptions = Partial<{
color: boolean; color: boolean;
date: boolean; date: boolean;

View File

@@ -1,6 +1,21 @@
import { INode, MaskInputFn, MaskInputOptions } from './types'; import { MaskInputFn, MaskInputOptions, serializedNodeWithId } from './types';
export declare function isElement(n: Node | INode): n is Element; export declare function isElement(n: Node): n is Element;
export declare function isShadowRoot(n: Node): n is ShadowRoot; export declare function isShadowRoot(n: Node): n is ShadowRoot;
export declare class Mirror {
private idNodeMap;
private nodeMetaMap;
getId(n: Node | undefined | null): number;
getNode(id: number): Node | null;
getIds(): number[];
getMeta(n: Node): serializedNodeWithId | null;
removeNodeFromMap(n: Node): void;
has(id: number): boolean;
hasNode(node: Node): boolean;
add(n: Node, meta: serializedNodeWithId): void;
replace(id: number, n: Node): void;
reset(): void;
}
export declare function createMirror(): Mirror;
export declare function maskInputValue({ maskInputOptions, tagName, type, value, maskInputFn, }: { export declare function maskInputValue({ maskInputOptions, tagName, type, value, maskInputFn, }: {
maskInputOptions: MaskInputOptions; maskInputOptions: MaskInputOptions;
tagName: string; tagName: string;

View File

@@ -1,4 +1,4 @@
import { serializedNodeWithId, INode } from 'rrweb-snapshot'; import { Mirror, serializedNodeWithId } from 'rrweb-snapshot';
import { mutationCallBack } from '../types'; import { mutationCallBack } from '../types';
export class IframeManager { export class IframeManager {
@@ -18,11 +18,15 @@ export class IframeManager {
this.loadListener = cb; this.loadListener = cb;
} }
public attachIframe(iframeEl: INode, childSn: serializedNodeWithId) { public attachIframe(
iframeEl: HTMLIFrameElement,
childSn: serializedNodeWithId,
mirror: Mirror,
) {
this.mutationCb({ this.mutationCb({
adds: [ adds: [
{ {
parentId: iframeEl.__sn.id, parentId: mirror.getId(iframeEl),
nextId: null, nextId: null,
node: childSn, node: childSn,
}, },
@@ -32,6 +36,6 @@ export class IframeManager {
attributes: [], attributes: [],
isAttachIframe: true, isAttachIframe: true,
}); });
this.loadListener?.((iframeEl as unknown) as HTMLIFrameElement); this.loadListener?.(iframeEl);
} }
} }

View File

@@ -1,13 +1,17 @@
import { snapshot, MaskInputOptions, SlimDOMOptions } from 'rrweb-snapshot'; import {
snapshot,
MaskInputOptions,
SlimDOMOptions,
createMirror,
} from 'rrweb-snapshot';
import { initObservers, mutationBuffers } from './observer'; import { initObservers, mutationBuffers } from './observer';
import { import {
on, on,
getWindowWidth, getWindowWidth,
getWindowHeight, getWindowHeight,
polyfill, polyfill,
isIframeINode,
hasShadowRoot, hasShadowRoot,
createMirror, isSerializedIframe,
} from '../utils'; } from '../utils';
import { import {
EventType, EventType,
@@ -74,6 +78,9 @@ function record<T = eventWithTime>(
sampling.mousemove = mousemoveWait; sampling.mousemove = mousemoveWait;
} }
// reset mirror in case `record` this was called earlier
mirror.reset();
const maskInputOptions: MaskInputOptions = const maskInputOptions: MaskInputOptions =
maskAllInputs === true maskAllInputs === true
? { ? {
@@ -252,7 +259,8 @@ function record<T = eventWithTime>(
); );
mutationBuffers.forEach((buf) => buf.lock()); // don't allow any mirror modifications during snapshotting mutationBuffers.forEach((buf) => buf.lock()); // don't allow any mirror modifications during snapshotting
const [node, idNodeMap] = snapshot(document, { const node = snapshot(document, {
mirror,
blockClass, blockClass,
blockSelector, blockSelector,
maskTextClass, maskTextClass,
@@ -264,18 +272,16 @@ function record<T = eventWithTime>(
recordCanvas, recordCanvas,
inlineImages, inlineImages,
onSerialize: (n) => { onSerialize: (n) => {
if (isIframeINode(n)) { if (isSerializedIframe(n, mirror)) {
iframeManager.addIframe(n); iframeManager.addIframe(n as HTMLIFrameElement);
} }
if (hasShadowRoot(n)) { if (hasShadowRoot(n)) {
shadowDomManager.addShadowRoot(n.shadowRoot, document); shadowDomManager.addShadowRoot(n.shadowRoot, document);
} }
}, },
onIframeLoad: (iframe, childSn) => { onIframeLoad: (iframe, childSn) => {
iframeManager.attachIframe(iframe, childSn); iframeManager.attachIframe(iframe, childSn, mirror);
shadowDomManager.observeAttachShadow( shadowDomManager.observeAttachShadow(iframe);
(iframe as Node) as HTMLIFrameElement,
);
}, },
keepIframeSrcFn, keepIframeSrcFn,
}); });
@@ -284,7 +290,6 @@ function record<T = eventWithTime>(
return console.warn('Failed to snapshot the document'); return console.warn('Failed to snapshot the document');
} }
mirror.map = idNodeMap;
wrappedEmit( wrappedEmit(
wrapEvent({ wrapEvent({
type: EventType.FullSnapshot, type: EventType.FullSnapshot,

View File

@@ -1,11 +1,11 @@
import { import {
INode,
serializeNodeWithId, serializeNodeWithId,
transformAttribute, transformAttribute,
IGNORED_NODE, IGNORED_NODE,
isShadowRoot, isShadowRoot,
needMaskingText, needMaskingText,
maskInputValue, maskInputValue,
Mirror,
} from 'rrweb-snapshot'; } from 'rrweb-snapshot';
import { import {
mutationRecord, mutationRecord,
@@ -13,7 +13,6 @@ import {
attributeCursor, attributeCursor,
removedNodeMutation, removedNodeMutation,
addedNodeMutation, addedNodeMutation,
Mirror,
styleAttributeValue, styleAttributeValue,
observerParam, observerParam,
MutationBufferParam, MutationBufferParam,
@@ -23,8 +22,8 @@ import {
isBlocked, isBlocked,
isAncestorRemoved, isAncestorRemoved,
isIgnored, isIgnored,
isIframeINode,
hasShadowRoot, hasShadowRoot,
isSerializedIframe,
} from '../utils'; } from '../utils';
type DoubleLinkedListNode = { type DoubleLinkedListNode = {
@@ -39,6 +38,7 @@ type NodeInLinkedList = Node & {
function isNodeInLinkedList(n: Node | NodeInLinkedList): n is NodeInLinkedList { function isNodeInLinkedList(n: Node | NodeInLinkedList): n is NodeInLinkedList {
return '__ln' in n; return '__ln' in n;
} }
class DoubleLinkedList { class DoubleLinkedList {
public length = 0; public length = 0;
public head: DoubleLinkedListNode | null = null; public head: DoubleLinkedListNode | null = null;
@@ -117,9 +117,6 @@ class DoubleLinkedList {
} }
const moveKey = (id: number, parentId: number) => `${id}@${parentId}`; const moveKey = (id: number, parentId: number) => `${id}@${parentId}`;
function isINode(n: Node | INode): n is INode {
return '__sn' in n;
}
/** /**
* controls behaviour of a MutationObserver * controls behaviour of a MutationObserver
@@ -255,7 +252,7 @@ export default class MutationBuffer {
let nextId: number | null = IGNORED_NODE; // slimDOM: ignored let nextId: number | null = IGNORED_NODE; // slimDOM: ignored
while (nextId === IGNORED_NODE) { while (nextId === IGNORED_NODE) {
ns = ns && ns.nextSibling; ns = ns && ns.nextSibling;
nextId = ns && this.mirror.getId((ns as unknown) as INode); nextId = ns && this.mirror.getId(ns);
} }
return nextId; return nextId;
}; };
@@ -277,15 +274,15 @@ export default class MutationBuffer {
return; return;
} }
const parentId = isShadowRoot(n.parentNode) const parentId = isShadowRoot(n.parentNode)
? this.mirror.getId((shadowHost as unknown) as INode) ? this.mirror.getId(shadowHost)
: this.mirror.getId((n.parentNode as Node) as INode); : this.mirror.getId(n.parentNode);
const nextId = getNextId(n); const nextId = getNextId(n);
if (parentId === -1 || nextId === -1) { if (parentId === -1 || nextId === -1) {
return addList.addNode(n); return addList.addNode(n);
} }
let sn = serializeNodeWithId(n, { let sn = serializeNodeWithId(n, {
doc: this.doc, doc: this.doc,
map: this.mirror.map, mirror: this.mirror,
blockClass: this.blockClass, blockClass: this.blockClass,
blockSelector: this.blockSelector, blockSelector: this.blockSelector,
maskTextClass: this.maskTextClass, maskTextClass: this.maskTextClass,
@@ -299,7 +296,7 @@ export default class MutationBuffer {
recordCanvas: this.recordCanvas, recordCanvas: this.recordCanvas,
inlineImages: this.inlineImages, inlineImages: this.inlineImages,
onSerialize: (currentN) => { onSerialize: (currentN) => {
if (isIframeINode(currentN)) { if (isSerializedIframe(currentN, this.mirror)) {
this.iframeManager.addIframe(currentN); this.iframeManager.addIframe(currentN);
} }
if (hasShadowRoot(n)) { if (hasShadowRoot(n)) {
@@ -307,10 +304,8 @@ export default class MutationBuffer {
} }
}, },
onIframeLoad: (iframe, childSn) => { onIframeLoad: (iframe, childSn) => {
this.iframeManager.attachIframe(iframe, childSn); this.iframeManager.attachIframe(iframe, childSn, this.mirror);
this.shadowDomManager.observeAttachShadow( this.shadowDomManager.observeAttachShadow(iframe);
(iframe as Node) as HTMLIFrameElement,
);
}, },
}); });
if (sn) { if (sn) {
@@ -323,7 +318,7 @@ export default class MutationBuffer {
}; };
while (this.mapRemoves.length) { while (this.mapRemoves.length) {
this.mirror.removeNodeFromMap(this.mapRemoves.shift() as INode); this.mirror.removeNodeFromMap(this.mapRemoves.shift()!);
} }
for (const n of this.movedSet) { for (const n of this.movedSet) {
@@ -353,9 +348,7 @@ export default class MutationBuffer {
while (addList.length) { while (addList.length) {
let node: DoubleLinkedListNode | null = null; let node: DoubleLinkedListNode | null = null;
if (candidate) { if (candidate) {
const parentId = this.mirror.getId( const parentId = this.mirror.getId(candidate.value.parentNode);
(candidate.value.parentNode as Node) as INode,
);
const nextId = getNextId(candidate.value); const nextId = getNextId(candidate.value);
if (parentId !== -1 && nextId !== -1) { if (parentId !== -1 && nextId !== -1) {
node = candidate; node = candidate;
@@ -366,9 +359,7 @@ export default class MutationBuffer {
const _node = addList.get(index)!; const _node = addList.get(index)!;
// ensure _node is defined before attempting to find value // ensure _node is defined before attempting to find value
if (_node) { if (_node) {
const parentId = this.mirror.getId( const parentId = this.mirror.getId(_node.value.parentNode);
(_node.value.parentNode as Node) as INode,
);
const nextId = getNextId(_node.value); const nextId = getNextId(_node.value);
if (parentId !== -1 && nextId !== -1) { if (parentId !== -1 && nextId !== -1) {
node = _node; node = _node;
@@ -396,14 +387,14 @@ export default class MutationBuffer {
const payload = { const payload = {
texts: this.texts texts: this.texts
.map((text) => ({ .map((text) => ({
id: this.mirror.getId(text.node as INode), id: this.mirror.getId(text.node),
value: text.value, value: text.value,
})) }))
// text mutation's id was not in the mirror map means the target node has been removed // text mutation's id was not in the mirror map means the target node has been removed
.filter((text) => this.mirror.has(text.id)), .filter((text) => this.mirror.has(text.id)),
attributes: this.attributes attributes: this.attributes
.map((attribute) => ({ .map((attribute) => ({
id: this.mirror.getId(attribute.node as INode), id: this.mirror.getId(attribute.node),
attributes: attribute.attributes, attributes: attribute.attributes,
})) }))
// attribute mutation's id was not in the mirror map means the target node has been removed // attribute mutation's id was not in the mirror map means the target node has been removed
@@ -434,7 +425,7 @@ export default class MutationBuffer {
}; };
private processMutation = (m: mutationRecord) => { private processMutation = (m: mutationRecord) => {
if (isIgnored(m.target)) { if (isIgnored(m.target, this.mirror)) {
return; return;
} }
switch (m.type) { switch (m.type) {
@@ -528,11 +519,14 @@ export default class MutationBuffer {
case 'childList': { case 'childList': {
m.addedNodes.forEach((n) => this.genAdds(n, m.target)); m.addedNodes.forEach((n) => this.genAdds(n, m.target));
m.removedNodes.forEach((n) => { m.removedNodes.forEach((n) => {
const nodeId = this.mirror.getId(n as INode); const nodeId = this.mirror.getId(n);
const parentId = isShadowRoot(m.target) const parentId = isShadowRoot(m.target)
? this.mirror.getId((m.target.host as unknown) as INode) ? this.mirror.getId(m.target.host)
: this.mirror.getId(m.target as INode); : this.mirror.getId(m.target);
if (isBlocked(m.target, this.blockClass) || isIgnored(n)) { if (
isBlocked(m.target, this.blockClass) ||
isIgnored(n, this.mirror)
) {
return; return;
} }
// removed node has not been serialized yet, just remove it from the Set // removed node has not been serialized yet, just remove it from the Set
@@ -547,7 +541,7 @@ export default class MutationBuffer {
* newly added node will be serialized without child nodes. * newly added node will be serialized without child nodes.
* TODO: verify this * TODO: verify this
*/ */
} else if (isAncestorRemoved(m.target as INode, this.mirror)) { } else if (isAncestorRemoved(m.target, this.mirror)) {
/** /**
* If parent id was not in the mirror map any more, it * If parent id was not in the mirror map any more, it
* means the parent node has already been removed. So * means the parent node has already been removed. So
@@ -575,22 +569,23 @@ export default class MutationBuffer {
} }
}; };
private genAdds = (n: Node | INode, target?: Node | INode) => { private genAdds = (n: Node, target?: Node) => {
// parent was blocked, so we can ignore this node // parent was blocked, so we can ignore this node
if (target && isBlocked(target, this.blockClass)) { if (target && isBlocked(target, this.blockClass)) {
return; return;
} }
if (isINode(n)) {
if (isIgnored(n)) { if (this.mirror.getMeta(n)) {
if (isIgnored(n, this.mirror)) {
return; return;
} }
this.movedSet.add(n); this.movedSet.add(n);
let targetId: number | null = null; let targetId: number | null = null;
if (target && isINode(target)) { if (target && this.mirror.getMeta(target)) {
targetId = target.__sn.id; targetId = this.mirror.getId(target);
} }
if (targetId) { if (targetId && targetId !== -1) {
this.movedMap[moveKey(n.__sn.id, targetId)] = true; this.movedMap[moveKey(this.mirror.getId(n), targetId)] = true;
} }
} else { } else {
this.addedSet.add(n); this.addedSet.add(n);
@@ -600,7 +595,7 @@ export default class MutationBuffer {
// if this node is blocked `serializeNode` will turn it into a placeholder element // if this node is blocked `serializeNode` will turn it into a placeholder element
// but we have to remove it's children otherwise they will be added as placeholders too // but we have to remove it's children otherwise they will be added as placeholders too
if (!isBlocked(n, this.blockClass)) if (!isBlocked(n, this.blockClass))
n.childNodes.forEach((childN) => this.genAdds(childN)); (n as Node).childNodes.forEach((childN) => this.genAdds(childN));
}; };
} }
@@ -624,7 +619,7 @@ function isParentRemoved(
if (!parentNode) { if (!parentNode) {
return false; return false;
} }
const parentId = mirror.getId((parentNode as Node) as INode); const parentId = mirror.getId(parentNode);
if (removes.some((r) => r.id === parentId)) { if (removes.some((r) => r.id === parentId)) {
return true; return true;
} }

View File

@@ -1,4 +1,4 @@
import { INode, MaskInputOptions, maskInputValue } from 'rrweb-snapshot'; import { MaskInputOptions, maskInputValue } from 'rrweb-snapshot';
import { FontFaceSet } from 'css-font-loading-module'; import { FontFaceSet } from 'css-font-loading-module';
import { import {
throttle, throttle,
@@ -173,7 +173,7 @@ function initMoveObserver({
positions.push({ positions.push({
x: clientX, x: clientX,
y: clientY, y: clientY,
id: mirror.getId(target as INode), id: mirror.getId(target as Node),
timeOffset: Date.now() - timeBaseline, timeOffset: Date.now() - timeBaseline,
}); });
// it is possible DragEvent is undefined even on devices // it is possible DragEvent is undefined even on devices
@@ -221,14 +221,14 @@ function initMouseInteractionObserver({
const getHandler = (eventKey: keyof typeof MouseInteractions) => { const getHandler = (eventKey: keyof typeof MouseInteractions) => {
return (event: MouseEvent | TouchEvent) => { return (event: MouseEvent | TouchEvent) => {
const target = getEventTarget(event) as Node; const target = getEventTarget(event) as Node;
if (isBlocked(target as Node, blockClass)) { if (isBlocked(target, blockClass)) {
return; return;
} }
const e = isTouchEvent(event) ? event.changedTouches[0] : event; const e = isTouchEvent(event) ? event.changedTouches[0] : event;
if (!e) { if (!e) {
return; return;
} }
const id = mirror.getId(target as INode); const id = mirror.getId(target);
const { clientX, clientY } = e; const { clientX, clientY } = e;
mouseInteractionCb({ mouseInteractionCb({
type: MouseInteractions[eventKey], type: MouseInteractions[eventKey],
@@ -270,7 +270,7 @@ export function initScrollObserver({
if (!target || isBlocked(target as Node, blockClass)) { if (!target || isBlocked(target as Node, blockClass)) {
return; return;
} }
const id = mirror.getId(target as INode); const id = mirror.getId(target as Node);
if (target === doc) { if (target === doc) {
const scrollEl = (doc.scrollingElement || doc.documentElement)!; const scrollEl = (doc.scrollingElement || doc.documentElement)!;
scrollCb({ scrollCb({
@@ -408,7 +408,7 @@ function initInputObserver({
lastInputValue.isChecked !== v.isChecked lastInputValue.isChecked !== v.isChecked
) { ) {
lastInputValueMap.set(target, v); lastInputValueMap.set(target, v);
const id = mirror.getId(target as INode); const id = mirror.getId(target as Node);
inputCb({ inputCb({
...v, ...v,
id, id,
@@ -497,7 +497,7 @@ function initStyleSheetObserver(
rule: string, rule: string,
index?: number, index?: number,
) { ) {
const id = mirror.getId(this.ownerNode as INode); const id = mirror.getId(this.ownerNode);
if (id !== -1) { if (id !== -1) {
styleSheetRuleCb({ styleSheetRuleCb({
id, id,
@@ -509,7 +509,7 @@ function initStyleSheetObserver(
const deleteRule = win.CSSStyleSheet.prototype.deleteRule; const deleteRule = win.CSSStyleSheet.prototype.deleteRule;
win.CSSStyleSheet.prototype.deleteRule = function (index: number) { win.CSSStyleSheet.prototype.deleteRule = function (index: number) {
const id = mirror.getId(this.ownerNode as INode); const id = mirror.getId(this.ownerNode);
if (id !== -1) { if (id !== -1) {
styleSheetRuleCb({ styleSheetRuleCb({
id, id,
@@ -554,7 +554,7 @@ function initStyleSheetObserver(
}; };
type.prototype.insertRule = function (rule: string, index?: number) { type.prototype.insertRule = function (rule: string, index?: number) {
const id = mirror.getId(this.parentStyleSheet.ownerNode as INode); const id = mirror.getId(this.parentStyleSheet.ownerNode);
if (id !== -1) { if (id !== -1) {
styleSheetRuleCb({ styleSheetRuleCb({
id, id,
@@ -573,7 +573,7 @@ function initStyleSheetObserver(
}; };
type.prototype.deleteRule = function (index: number) { type.prototype.deleteRule = function (index: number) {
const id = mirror.getId(this.parentStyleSheet.ownerNode as INode); const id = mirror.getId(this.parentStyleSheet.ownerNode);
if (id !== -1) { if (id !== -1) {
styleSheetRuleCb({ styleSheetRuleCb({
id, id,
@@ -605,9 +605,7 @@ function initStyleDeclarationObserver(
value: string, value: string,
priority: string, priority: string,
) { ) {
const id = mirror.getId( const id = mirror.getId(this.parentRule?.parentStyleSheet?.ownerNode);
(this.parentRule?.parentStyleSheet?.ownerNode as unknown) as INode,
);
if (id !== -1) { if (id !== -1) {
styleDeclarationCb({ styleDeclarationCb({
id, id,
@@ -627,9 +625,7 @@ function initStyleDeclarationObserver(
this: CSSStyleDeclaration, this: CSSStyleDeclaration,
property: string, property: string,
) { ) {
const id = mirror.getId( const id = mirror.getId(this.parentRule?.parentStyleSheet?.ownerNode);
(this.parentRule?.parentStyleSheet?.ownerNode as unknown) as INode,
);
if (id !== -1) { if (id !== -1) {
styleDeclarationCb({ styleDeclarationCb({
id, id,
@@ -663,7 +659,7 @@ function initMediaInteractionObserver({
const { currentTime, volume, muted } = target as HTMLMediaElement; const { currentTime, volume, muted } = target as HTMLMediaElement;
mediaInteractionCb({ mediaInteractionCb({
type, type,
id: mirror.getId(target as INode), id: mirror.getId(target as Node),
currentTime, currentTime,
volume, volume,
muted, muted,

View File

@@ -1,11 +1,10 @@
import { INode } from 'rrweb-snapshot'; import { Mirror } from 'rrweb-snapshot';
import { import {
blockClass, blockClass,
CanvasContext, CanvasContext,
canvasManagerMutationCallback, canvasManagerMutationCallback,
IWindow, IWindow,
listenerHandler, listenerHandler,
Mirror,
} from '../../../types'; } from '../../../types';
import { hookSetter, isBlocked, patch } from '../../../utils'; import { hookSetter, isBlocked, patch } from '../../../utils';
@@ -36,7 +35,7 @@ export default function initCanvas2DMutationObserver(
this: CanvasRenderingContext2D, this: CanvasRenderingContext2D,
...args: Array<unknown> ...args: Array<unknown>
) { ) {
if (!isBlocked((this.canvas as unknown) as INode, blockClass)) { if (!isBlocked(this.canvas, blockClass)) {
// Using setTimeout as getImageData + JSON.stringify can be heavy // Using setTimeout as getImageData + JSON.stringify can be heavy
// and we'd rather not block the main thread // and we'd rather not block the main thread
setTimeout(() => { setTimeout(() => {

View File

@@ -1,4 +1,4 @@
import { INode } from 'rrweb-snapshot'; import { Mirror } from 'rrweb-snapshot';
import { import {
blockClass, blockClass,
canvasManagerMutationCallback, canvasManagerMutationCallback,
@@ -7,7 +7,6 @@ import {
canvasMutationWithType, canvasMutationWithType,
IWindow, IWindow,
listenerHandler, listenerHandler,
Mirror,
} from '../../../types'; } from '../../../types';
import initCanvas2DMutationObserver from './2d'; import initCanvas2DMutationObserver from './2d';
import initCanvasContextObserver from './canvas'; import initCanvasContextObserver from './canvas';
@@ -126,7 +125,7 @@ export class CanvasManager {
flushPendingCanvasMutations() { flushPendingCanvasMutations() {
this.pendingCanvasMutations.forEach( this.pendingCanvasMutations.forEach(
(values: canvasMutationCommand[], canvas: HTMLCanvasElement) => { (values: canvasMutationCommand[], canvas: HTMLCanvasElement) => {
const id = this.mirror.getId((canvas as unknown) as INode); const id = this.mirror.getId(canvas);
this.flushPendingCanvasMutationFor(canvas, id); this.flushPendingCanvasMutationFor(canvas, id);
}, },
); );

View File

@@ -1,4 +1,4 @@
import { INode, ICanvas } from 'rrweb-snapshot'; import { ICanvas } from 'rrweb-snapshot';
import { blockClass, IWindow, listenerHandler } from '../../../types'; import { blockClass, IWindow, listenerHandler } from '../../../types';
import { isBlocked, patch } from '../../../utils'; import { isBlocked, patch } from '../../../utils';
@@ -17,7 +17,7 @@ export default function initCanvasContextObserver(
contextType: string, contextType: string,
...args: Array<unknown> ...args: Array<unknown>
) { ) {
if (!isBlocked((this as unknown) as INode, blockClass)) { if (!isBlocked(this, blockClass)) {
if (!('__context' in this)) if (!('__context' in this))
(this as ICanvas).__context = contextType; (this as ICanvas).__context = contextType;
} }

View File

@@ -1,4 +1,4 @@
import { INode } from 'rrweb-snapshot'; import { Mirror } from 'rrweb-snapshot';
import { import {
blockClass, blockClass,
CanvasContext, CanvasContext,
@@ -6,7 +6,6 @@ import {
canvasMutationWithType, canvasMutationWithType,
IWindow, IWindow,
listenerHandler, listenerHandler,
Mirror,
} from '../../../types'; } from '../../../types';
import { hookSetter, isBlocked, patch } from '../../../utils'; import { hookSetter, isBlocked, patch } from '../../../utils';
import { saveWebGLVar, serializeArgs } from './serialize-args'; import { saveWebGLVar, serializeArgs } from './serialize-args';
@@ -32,8 +31,8 @@ function patchGLPrototype(
return function (this: typeof prototype, ...args: Array<unknown>) { return function (this: typeof prototype, ...args: Array<unknown>) {
const result = original.apply(this, args); const result = original.apply(this, args);
saveWebGLVar(result, win, prototype); saveWebGLVar(result, win, prototype);
if (!isBlocked((this.canvas as unknown) as INode, blockClass)) { if (!isBlocked(this.canvas, blockClass)) {
const id = mirror.getId((this.canvas as unknown) as INode); const id = mirror.getId(this.canvas);
const recordArgs = serializeArgs([...args], win, prototype); const recordArgs = serializeArgs([...args], win, prototype);
const mutation: canvasMutationWithType = { const mutation: canvasMutationWithType = {

View File

@@ -1,12 +1,12 @@
import { import {
mutationCallBack, mutationCallBack,
Mirror,
scrollCallback, scrollCallback,
MutationBufferParam, MutationBufferParam,
SamplingStrategy, SamplingStrategy,
} from '../types'; } from '../types';
import { initMutationObserver, initScrollObserver } from './observer'; import { initMutationObserver, initScrollObserver } from './observer';
import { patch } from '../utils'; import { patch } from '../utils';
import { Mirror } from 'rrweb-snapshot';
type BypassOptions = Omit< type BypassOptions = Omit<
MutationBufferParam, MutationBufferParam,

View File

@@ -15,7 +15,7 @@ export default function canvasMutation({
errorHandler: Replayer['warnCanvasMutationFailed']; errorHandler: Replayer['warnCanvasMutationFailed'];
}): void { }): void {
try { try {
const ctx = ((target as unknown) as HTMLCanvasElement).getContext('2d')!; const ctx = target.getContext('2d')!;
if (mutation.setter) { if (mutation.setter) {
// skip some read-only type checks // skip some read-only type checks

View File

@@ -1,10 +1,11 @@
import { import {
rebuild, rebuild,
buildNodeWithSN, buildNodeWithSN,
INode,
NodeType, NodeType,
BuildCache, BuildCache,
createCache, createCache,
Mirror,
createMirror,
} from 'rrweb-snapshot'; } from 'rrweb-snapshot';
import * as mittProxy from 'mitt'; import * as mittProxy from 'mitt';
import { polyfill as smoothscrollPolyfill } from './smoothscroll'; import { polyfill as smoothscrollPolyfill } from './smoothscroll';
@@ -33,7 +34,6 @@ import {
scrollData, scrollData,
inputData, inputData,
canvasMutationData, canvasMutationData,
Mirror,
ElementState, ElementState,
styleAttributeValue, styleAttributeValue,
styleValueWithPriority, styleValueWithPriority,
@@ -43,15 +43,14 @@ import {
textMutation, textMutation,
} from '../types'; } from '../types';
import { import {
createMirror,
polyfill, polyfill,
TreeIndex, TreeIndex,
queueToResolveTrees, queueToResolveTrees,
iterateResolveTree, iterateResolveTree,
AppendedIframe, AppendedIframe,
isIframeINode,
getBaseDimension, getBaseDimension,
hasShadowRoot, hasShadowRoot,
isSerializedIframe,
} from '../utils'; } from '../utils';
import getInjectStyleRules from './styles/inject-style'; import getInjectStyleRules from './styles/inject-style';
import './styles/style.css'; import './styles/style.css';
@@ -115,8 +114,8 @@ export class Replayer {
private legacy_missingNodeRetryMap: missingNodeMap = {}; private legacy_missingNodeRetryMap: missingNodeMap = {};
private treeIndex!: TreeIndex; private treeIndex!: TreeIndex;
private fragmentParentMap!: Map<INode, INode>; private fragmentParentMap!: Map<Node, Node>;
private elementStateMap!: Map<INode, ElementState>; private elementStateMap!: Map<Node, ElementState>;
// Hold the list of CSSRules for in-memory state restoration // Hold the list of CSSRules for in-memory state restoration
private virtualStyleRulesMap!: VirtualStyleRulesMap; private virtualStyleRulesMap!: VirtualStyleRulesMap;
@@ -167,8 +166,8 @@ export class Replayer {
this.setupDom(); this.setupDom();
this.treeIndex = new TreeIndex(); this.treeIndex = new TreeIndex();
this.fragmentParentMap = new Map<INode, INode>(); this.fragmentParentMap = new Map<Node, Node>();
this.elementStateMap = new Map<INode, ElementState>(); this.elementStateMap = new Map<Node, ElementState>();
this.virtualStyleRulesMap = new Map(); this.virtualStyleRulesMap = new Map();
this.emitter.on(ReplayerEvents.Flush, () => { this.emitter.on(ReplayerEvents.Flush, () => {
@@ -657,13 +656,14 @@ export class Replayer {
} }
this.legacy_missingNodeRetryMap = {}; this.legacy_missingNodeRetryMap = {};
const collected: AppendedIframe[] = []; const collected: AppendedIframe[] = [];
this.mirror.map = rebuild(event.data.node, { rebuild(event.data.node, {
doc: this.iframe.contentDocument, doc: this.iframe.contentDocument,
afterAppend: (builtNode) => { afterAppend: (builtNode) => {
this.collectIframeAndAttachDocument(collected, builtNode); this.collectIframeAndAttachDocument(collected, builtNode);
}, },
cache: this.cache, cache: this.cache,
})[1]; mirror: this.mirror,
});
for (const { mutationInQueue, builtNode } of collected) { for (const { mutationInQueue, builtNode } of collected) {
this.attachDocumentToIframe(mutationInQueue, builtNode); this.attachDocumentToIframe(mutationInQueue, builtNode);
this.newDocumentQueue = this.newDocumentQueue.filter( this.newDocumentQueue = this.newDocumentQueue.filter(
@@ -715,8 +715,8 @@ export class Replayer {
let parent = iframeEl.parentNode; let parent = iframeEl.parentNode;
while (parent) { while (parent) {
// The parent of iframeEl is virtual parent and we need to mount it on the dom. // The parent of iframeEl is virtual parent and we need to mount it on the dom.
if (this.fragmentParentMap.has((parent as unknown) as INode)) { if (this.fragmentParentMap.has(parent)) {
const frag = (parent as unknown) as INode; const frag = parent;
const realParent = this.fragmentParentMap.get(frag)!; const realParent = this.fragmentParentMap.get(frag)!;
this.restoreRealParent(frag, realParent); this.restoreRealParent(frag, realParent);
break; break;
@@ -726,14 +726,15 @@ export class Replayer {
} }
buildNodeWithSN(mutation.node, { buildNodeWithSN(mutation.node, {
doc: iframeEl.contentDocument!, doc: iframeEl.contentDocument!,
map: this.mirror.map, mirror: this.mirror,
hackCss: true, hackCss: true,
skipChild: false, skipChild: false,
afterAppend: (builtNode) => { afterAppend: (builtNode) => {
this.collectIframeAndAttachDocument(collected, builtNode); this.collectIframeAndAttachDocument(collected, builtNode);
const sn = this.mirror.getMeta(builtNode);
if ( if (
builtNode.__sn.type === NodeType.Element && sn?.type === NodeType.Element &&
builtNode.__sn.tagName.toUpperCase() === 'HTML' sn?.tagName.toUpperCase() === 'HTML'
) { ) {
const { documentElement, head } = iframeEl.contentDocument!; const { documentElement, head } = iframeEl.contentDocument!;
this.insertStyleRules(documentElement, head); this.insertStyleRules(documentElement, head);
@@ -751,11 +752,11 @@ export class Replayer {
private collectIframeAndAttachDocument( private collectIframeAndAttachDocument(
collected: AppendedIframe[], collected: AppendedIframe[],
builtNode: INode, builtNode: Node,
) { ) {
if (isIframeINode(builtNode)) { if (isSerializedIframe(builtNode, this.mirror)) {
const mutationInQueue = this.newDocumentQueue.find( const mutationInQueue = this.newDocumentQueue.find(
(m) => m.parentId === builtNode.__sn.id, (m) => m.parentId === this.mirror.getId(builtNode),
); );
if (mutationInQueue) { if (mutationInQueue) {
collected.push({ mutationInQueue, builtNode }); collected.push({ mutationInQueue, builtNode });
@@ -905,7 +906,7 @@ export class Replayer {
d.adds.forEach((m) => this.treeIndex.add(m)); d.adds.forEach((m) => this.treeIndex.add(m));
d.texts.forEach((m) => { d.texts.forEach((m) => {
const target = this.mirror.getNode(m.id); const target = this.mirror.getNode(m.id);
const parent = (target?.parentNode as unknown) as INode | null; const parent = target?.parentNode;
// remove any style rules that pending // remove any style rules that pending
// for stylesheets where the contents get replaced // for stylesheets where the contents get replaced
if (parent && this.virtualStyleRulesMap.has(parent)) if (parent && this.virtualStyleRulesMap.has(parent))
@@ -973,13 +974,13 @@ export class Replayer {
const { triggerFocus } = this.config; const { triggerFocus } = this.config;
switch (d.type) { switch (d.type) {
case MouseInteractions.Blur: case MouseInteractions.Blur:
if ('blur' in ((target as Node) as HTMLElement)) { if ('blur' in (target as HTMLElement)) {
((target as Node) as HTMLElement).blur(); (target as HTMLElement).blur();
} }
break; break;
case MouseInteractions.Focus: case MouseInteractions.Focus:
if (triggerFocus && ((target as Node) as HTMLElement).focus) { if (triggerFocus && (target as HTMLElement).focus) {
((target as Node) as HTMLElement).focus({ (target as HTMLElement).focus({
preventScroll: true, preventScroll: true,
}); });
} }
@@ -1080,7 +1081,7 @@ export class Replayer {
if (!target) { if (!target) {
return this.debugNodeNotFound(d, d.id); return this.debugNodeNotFound(d, d.id);
} }
const mediaEl = (target as Node) as HTMLMediaElement; const mediaEl = target as HTMLMediaElement;
try { try {
if (d.currentTime) { if (d.currentTime) {
mediaEl.currentTime = d.currentTime; mediaEl.currentTime = d.currentTime;
@@ -1116,8 +1117,8 @@ export class Replayer {
return this.debugNodeNotFound(d, d.id); return this.debugNodeNotFound(d, d.id);
} }
const styleEl = (target as Node) as HTMLStyleElement; const styleEl = target as HTMLStyleElement;
const parent = (target.parentNode as unknown) as INode; const parent = target.parentNode!;
const usingVirtualParent = this.fragmentParentMap.has(parent); const usingVirtualParent = this.fragmentParentMap.has(parent);
/** /**
@@ -1218,8 +1219,8 @@ export class Replayer {
return this.debugNodeNotFound(d, d.id); return this.debugNodeNotFound(d, d.id);
} }
const styleEl = (target as Node) as HTMLStyleElement; const styleEl = target as HTMLStyleElement;
const parent = (target.parentNode as unknown) as INode; const parent = target.parentNode!;
const usingVirtualParent = this.fragmentParentMap.has(parent); const usingVirtualParent = this.fragmentParentMap.has(parent);
const styleSheet = usingVirtualParent ? null : styleEl.sheet; const styleSheet = usingVirtualParent ? null : styleEl.sheet;
@@ -1279,7 +1280,7 @@ export class Replayer {
canvasMutation({ canvasMutation({
event: e, event: e,
mutation: d, mutation: d,
target: (target as unknown) as HTMLCanvasElement, target: target as HTMLCanvasElement,
imageMap: this.imageMap, imageMap: this.imageMap,
errorHandler: this.warnCanvasMutationFailed.bind(this), errorHandler: this.warnCanvasMutationFailed.bind(this),
}); });
@@ -1318,7 +1319,7 @@ export class Replayer {
if (this.virtualStyleRulesMap.has(target)) { if (this.virtualStyleRulesMap.has(target)) {
this.virtualStyleRulesMap.delete(target); this.virtualStyleRulesMap.delete(target);
} }
let parent: INode | null | ShadowRoot = this.mirror.getNode( let parent: Node | null | ShadowRoot = this.mirror.getNode(
mutation.parentId, mutation.parentId,
); );
if (!parent) { if (!parent) {
@@ -1331,8 +1332,9 @@ export class Replayer {
this.mirror.removeNodeFromMap(target); this.mirror.removeNodeFromMap(target);
if (parent) { if (parent) {
let realTarget = null; let realTarget = null;
const realParent = const realParent = this.mirror.getMeta(parent)
'__sn' in parent ? this.fragmentParentMap.get(parent) : undefined; ? this.fragmentParentMap.get(parent)
: undefined;
if (realParent && realParent.contains(target)) { if (realParent && realParent.contains(target)) {
parent = realParent; parent = realParent;
} else if (this.fragmentParentMap.has(target)) { } else if (this.fragmentParentMap.has(target)) {
@@ -1373,7 +1375,7 @@ export class Replayer {
const nextNotInDOM = (mutation: addedNodeMutation) => { const nextNotInDOM = (mutation: addedNodeMutation) => {
let next: Node | null = null; let next: Node | null = null;
if (mutation.nextId) { if (mutation.nextId) {
next = this.mirror.getNode(mutation.nextId) as Node; next = this.mirror.getNode(mutation.nextId);
} }
// next not present at this moment // next not present at this moment
if ( if (
@@ -1391,7 +1393,7 @@ export class Replayer {
if (!this.iframe.contentDocument) { if (!this.iframe.contentDocument) {
return console.warn('Looks like your replayer has been destroyed.'); return console.warn('Looks like your replayer has been destroyed.');
} }
let parent: INode | null | ShadowRoot = this.mirror.getNode( let parent: Node | null | ShadowRoot = this.mirror.getNode(
mutation.parentId, mutation.parentId,
); );
if (!parent) { if (!parent) {
@@ -1412,20 +1414,19 @@ export class Replayer {
} }
const hasIframeChild = const hasIframeChild =
((parent as unknown) as HTMLElement).getElementsByTagName?.('iframe') (parent as HTMLElement).getElementsByTagName?.('iframe').length > 0;
.length > 0;
/** /**
* Why !isIframeINode(parent)? If parent element is an iframe, iframe document can't be appended to virtual parent. * Why !isSerializedIframe(parent)? If parent element is an iframe, iframe document can't be appended to virtual parent.
* Why !hasIframeChild? If we move iframe elements from dom to fragment document, we will lose the contentDocument of iframe. So we need to disable the virtual dom optimization if a parent node contains iframe elements. * Why !hasIframeChild? If we move iframe elements from dom to fragment document, we will lose the contentDocument of iframe. So we need to disable the virtual dom optimization if a parent node contains iframe elements.
*/ */
if ( if (
useVirtualParent && useVirtualParent &&
parentInDocument && parentInDocument &&
!isIframeINode(parent) && !isSerializedIframe(parent, this.mirror) &&
!hasIframeChild !hasIframeChild
) { ) {
const virtualParent = (document.createDocumentFragment() as unknown) as INode; const virtualParent = document.createDocumentFragment();
this.mirror.map[mutation.parentId] = virtualParent; this.mirror.replace(mutation.parentId, virtualParent);
this.fragmentParentMap.set(virtualParent, parent); this.fragmentParentMap.set(virtualParent, parent);
// store the state, like scroll position, of child nodes before they are unmounted from dom // store the state, like scroll position, of child nodes before they are unmounted from dom
@@ -1440,18 +1441,18 @@ export class Replayer {
if (mutation.node.isShadow) { if (mutation.node.isShadow) {
// If the parent is attached a shadow dom after it's created, it won't have a shadow root. // If the parent is attached a shadow dom after it's created, it won't have a shadow root.
if (!hasShadowRoot(parent)) { if (!hasShadowRoot(parent)) {
((parent as Node) as HTMLElement).attachShadow({ mode: 'open' }); (parent as HTMLElement).attachShadow({ mode: 'open' });
parent = ((parent as Node) as HTMLElement).shadowRoot!; parent = (parent as HTMLElement).shadowRoot!;
} else parent = parent.shadowRoot; } else parent = parent.shadowRoot;
} }
let previous: Node | null = null; let previous: Node | null = null;
let next: Node | null = null; let next: Node | null = null;
if (mutation.previousId) { if (mutation.previousId) {
previous = this.mirror.getNode(mutation.previousId) as Node; previous = this.mirror.getNode(mutation.previousId);
} }
if (mutation.nextId) { if (mutation.nextId) {
next = this.mirror.getNode(mutation.nextId) as Node; next = this.mirror.getNode(mutation.nextId);
} }
if (nextNotInDOM(mutation)) { if (nextNotInDOM(mutation)) {
return queue.push(mutation); return queue.push(mutation);
@@ -1464,17 +1465,17 @@ export class Replayer {
const targetDoc = mutation.node.rootId const targetDoc = mutation.node.rootId
? this.mirror.getNode(mutation.node.rootId) ? this.mirror.getNode(mutation.node.rootId)
: this.iframe.contentDocument; : this.iframe.contentDocument;
if (isIframeINode(parent)) { if (isSerializedIframe(parent, this.mirror)) {
this.attachDocumentToIframe(mutation, parent); this.attachDocumentToIframe(mutation, parent);
return; return;
} }
const target = buildNodeWithSN(mutation.node, { const target = buildNodeWithSN(mutation.node, {
doc: targetDoc as Document, doc: targetDoc as Document,
map: this.mirror.map, mirror: this.mirror,
skipChild: true, skipChild: true,
hackCss: true, hackCss: true,
cache: this.cache, cache: this.cache,
}) as INode; })!;
// legacy data, we should not have -1 siblings any more // legacy data, we should not have -1 siblings any more
if (mutation.previousId === -1 || mutation.nextId === -1) { if (mutation.previousId === -1 || mutation.nextId === -1) {
@@ -1485,10 +1486,11 @@ export class Replayer {
return; return;
} }
const parentSn = this.mirror.getMeta(parent);
if ( if (
'__sn' in parent && parentSn &&
parent.__sn.type === NodeType.Element && parentSn.type === NodeType.Element &&
parent.__sn.tagName === 'textarea' && parentSn.tagName === 'textarea' &&
mutation.node.type === NodeType.Text mutation.node.type === NodeType.Text
) { ) {
// https://github.com/rrweb-io/rrweb/issues/745 // https://github.com/rrweb-io/rrweb/issues/745
@@ -1521,9 +1523,10 @@ export class Replayer {
parent.appendChild(target); parent.appendChild(target);
} }
if (isIframeINode(target)) { if (isSerializedIframe(target, this.mirror)) {
const targetId = this.mirror.getId(target);
const mutationInQueue = this.newDocumentQueue.find( const mutationInQueue = this.newDocumentQueue.find(
(m) => m.parentId === target.__sn.id, (m) => m.parentId === targetId,
); );
if (mutationInQueue) { if (mutationInQueue) {
this.attachDocumentToIframe(mutationInQueue, target); this.attachDocumentToIframe(mutationInQueue, target);
@@ -1611,10 +1614,10 @@ export class Replayer {
if (typeof attributeName === 'string') { if (typeof attributeName === 'string') {
const value = mutation.attributes[attributeName]; const value = mutation.attributes[attributeName];
if (value === null) { if (value === null) {
((target as Node) as Element).removeAttribute(attributeName); (target as Element).removeAttribute(attributeName);
} else if (typeof value === 'string') { } else if (typeof value === 'string') {
try { try {
((target as Node) as Element).setAttribute(attributeName, value); (target as Element).setAttribute(attributeName, value);
} catch (error) { } catch (error) {
if (this.config.showWarning) { if (this.config.showWarning) {
console.warn( console.warn(
@@ -1625,7 +1628,7 @@ export class Replayer {
} }
} else if (attributeName === 'style') { } else if (attributeName === 'style') {
let styleValues = value as styleAttributeValue; let styleValues = value as styleAttributeValue;
const targetEl = (target as Node) as HTMLElement; const targetEl = target as HTMLElement;
for (var s in styleValues) { for (var s in styleValues) {
if (styleValues[s] === false) { if (styleValues[s] === false) {
targetEl.style.removeProperty(s); targetEl.style.removeProperty(s);
@@ -1654,23 +1657,24 @@ export class Replayer {
if (!target) { if (!target) {
return this.debugNodeNotFound(d, d.id); return this.debugNodeNotFound(d, d.id);
} }
if ((target as Node) === this.iframe.contentDocument) { const sn = this.mirror.getMeta(target);
if (target === this.iframe.contentDocument) {
this.iframe.contentWindow!.scrollTo({ this.iframe.contentWindow!.scrollTo({
top: d.y, top: d.y,
left: d.x, left: d.x,
behavior: isSync ? 'auto' : 'smooth', behavior: isSync ? 'auto' : 'smooth',
}); });
} else if (target.__sn.type === NodeType.Document) { } else if (sn?.type === NodeType.Document) {
// nest iframe content document // nest iframe content document
((target as unknown) as Document).defaultView!.scrollTo({ (target as Document).defaultView!.scrollTo({
top: d.y, top: d.y,
left: d.x, left: d.x,
behavior: isSync ? 'auto' : 'smooth', behavior: isSync ? 'auto' : 'smooth',
}); });
} else { } else {
try { try {
((target as Node) as Element).scrollTop = d.y; (target as Element).scrollTop = d.y;
((target as Node) as Element).scrollLeft = d.x; (target as Element).scrollLeft = d.x;
} catch (error) { } catch (error) {
/** /**
* Seldomly we may found scroll target was removed before * Seldomly we may found scroll target was removed before
@@ -1686,8 +1690,8 @@ export class Replayer {
return this.debugNodeNotFound(d, d.id); return this.debugNodeNotFound(d, d.id);
} }
try { try {
((target as Node) as HTMLInputElement).checked = d.isChecked; (target as HTMLInputElement).checked = d.isChecked;
((target as Node) as HTMLInputElement).value = d.text; (target as HTMLInputElement).value = d.text;
} catch (error) { } catch (error) {
// for safe // for safe
} }
@@ -1699,7 +1703,7 @@ export class Replayer {
return this.debugNodeNotFound(mutation, d.id); return this.debugNodeNotFound(mutation, d.id);
} }
try { try {
((target as Node) as HTMLElement).textContent = d.value; (target as HTMLElement).textContent = d.value;
} catch (error) { } catch (error) {
// for safe // for safe
} }
@@ -1720,7 +1724,7 @@ export class Replayer {
delete map[mutation.node.id]; delete map[mutation.node.id];
delete this.legacy_missingNodeRetryMap[mutation.node.id]; delete this.legacy_missingNodeRetryMap[mutation.node.id];
if (mutation.previousId || mutation.nextId) { if (mutation.previousId || mutation.nextId) {
this.legacy_resolveMissingNode(map, parent, node as Node, mutation); this.legacy_resolveMissingNode(map, parent, node, mutation);
} }
} }
if (nextInMap) { if (nextInMap) {
@@ -1729,7 +1733,7 @@ export class Replayer {
delete map[mutation.node.id]; delete map[mutation.node.id];
delete this.legacy_missingNodeRetryMap[mutation.node.id]; delete this.legacy_missingNodeRetryMap[mutation.node.id];
if (mutation.previousId || mutation.nextId) { if (mutation.previousId || mutation.nextId) {
this.legacy_resolveMissingNode(map, parent, node as Node, mutation); this.legacy_resolveMissingNode(map, parent, node, mutation);
} }
} }
} }
@@ -1755,7 +1759,7 @@ export class Replayer {
if (!isSync) { if (!isSync) {
this.drawMouseTail({ x: _x, y: _y }); this.drawMouseTail({ x: _x, y: _y });
} }
this.hoverElements((target as Node) as Element); this.hoverElements(target as Element);
} }
private drawMouseTail(position: { x: number; y: number }) { private drawMouseTail(position: { x: number; y: number }) {
@@ -1835,18 +1839,21 @@ export class Replayer {
* @param frag fragment document, the virtual parent * @param frag fragment document, the virtual parent
* @param parent real parent element * @param parent real parent element
*/ */
private restoreRealParent(frag: INode, parent: INode) { private restoreRealParent(frag: Node, parent: Node) {
this.mirror.map[parent.__sn.id] = parent; const id = this.mirror.getId(frag);
const parentSn = this.mirror.getMeta(parent);
this.mirror.replace(id, parent);
/** /**
* If we have already set value attribute on textarea, * If we have already set value attribute on textarea,
* then we could not apply text content as default value any more. * then we could not apply text content as default value any more.
*/ */
if ( if (
parent.__sn.type === NodeType.Element && parentSn?.type === NodeType.Element &&
parent.__sn.tagName === 'textarea' && parentSn?.tagName === 'textarea' &&
frag.textContent frag.textContent
) { ) {
((parent as unknown) as HTMLTextAreaElement).value = frag.textContent; (parent as HTMLTextAreaElement).value = frag.textContent;
} }
parent.appendChild(frag); parent.appendChild(frag);
// restore state of elements after they are mounted // restore state of elements after they are mounted
@@ -1858,10 +1865,10 @@ export class Replayer {
* the state should be restored in the handler of event ReplayerEvents.Flush * the state should be restored in the handler of event ReplayerEvents.Flush
* e.g. browser would lose scroll position after the process that we add children of parent node to Fragment Document as virtual dom * e.g. browser would lose scroll position after the process that we add children of parent node to Fragment Document as virtual dom
*/ */
private storeState(parent: INode) { private storeState(parent: Node) {
if (parent) { if (parent) {
if (parent.nodeType === parent.ELEMENT_NODE) { if (parent.nodeType === parent.ELEMENT_NODE) {
const parentElement = (parent as unknown) as HTMLElement; const parentElement = parent as HTMLElement;
if (parentElement.scrollLeft || parentElement.scrollTop) { if (parentElement.scrollLeft || parentElement.scrollTop) {
// store scroll position state // store scroll position state
this.elementStateMap.set(parent, { this.elementStateMap.set(parent, {
@@ -1875,7 +1882,7 @@ export class Replayer {
); );
const children = parentElement.children; const children = parentElement.children;
for (const child of Array.from(children)) { for (const child of Array.from(children)) {
this.storeState((child as unknown) as INode); this.storeState(child);
} }
} }
} }
@@ -1885,9 +1892,9 @@ export class Replayer {
* restore the state of elements recursively, which was stored before elements were unmounted from dom in virtual parent mode * restore the state of elements recursively, which was stored before elements were unmounted from dom in virtual parent mode
* this function corresponds to function storeState * this function corresponds to function storeState
*/ */
private restoreState(parent: INode) { private restoreState(parent: Node) {
if (parent.nodeType === parent.ELEMENT_NODE) { if (parent.nodeType === parent.ELEMENT_NODE) {
const parentElement = (parent as unknown) as HTMLElement; const parentElement = parent as HTMLElement;
if (this.elementStateMap.has(parent)) { if (this.elementStateMap.has(parent)) {
const storedState = this.elementStateMap.get(parent)!; const storedState = this.elementStateMap.get(parent)!;
// restore scroll position // restore scroll position
@@ -1899,12 +1906,12 @@ export class Replayer {
} }
const children = parentElement.children; const children = parentElement.children;
for (const child of Array.from(children)) { for (const child of Array.from(children)) {
this.restoreState((child as unknown) as INode); this.restoreState(child);
} }
} }
} }
private restoreNodeSheet(node: INode) { private restoreNodeSheet(node: Node) {
const storedRules = this.virtualStyleRulesMap.get(node); const storedRules = this.virtualStyleRulesMap.get(node);
if (node.nodeName !== 'STYLE') { if (node.nodeName !== 'STYLE') {
return; return;
@@ -1914,7 +1921,7 @@ export class Replayer {
return; return;
} }
const styleNode = (node as unknown) as HTMLStyleElement; const styleNode = node as HTMLStyleElement;
applyVirtualStyleRulesToNode(storedRules, styleNode); applyVirtualStyleRulesToNode(storedRules, styleNode);
} }

View File

@@ -1,5 +1,3 @@
import { INode } from 'rrweb-snapshot';
export enum StyleRuleType { export enum StyleRuleType {
Insert, Insert,
Remove, Remove,
@@ -37,7 +35,7 @@ type RemovePropertyRule = {
export type VirtualStyleRules = Array< export type VirtualStyleRules = Array<
InsertRule | RemoveRule | SnapshotRule | SetPropertyRule | RemovePropertyRule InsertRule | RemoveRule | SnapshotRule | SetPropertyRule | RemovePropertyRule
>; >;
export type VirtualStyleRulesMap = Map<INode, VirtualStyleRules>; export type VirtualStyleRulesMap = Map<Node, VirtualStyleRules>;
export function getNestedRule( export function getNestedRule(
rules: CSSRuleList, rules: CSSRuleList,
@@ -173,7 +171,7 @@ export function storeCSSRules(
const cssTexts = Array.from( const cssTexts = Array.from(
(parentElement as HTMLStyleElement).sheet?.cssRules || [], (parentElement as HTMLStyleElement).sheet?.cssRules || [],
).map((rule) => rule.cssText); ).map((rule) => rule.cssText);
virtualStyleRulesMap.set((parentElement as unknown) as INode, [ virtualStyleRulesMap.set(parentElement, [
{ {
type: StyleRuleType.Snapshot, type: StyleRuleType.Snapshot,
cssTexts, cssTexts,

View File

@@ -1,6 +1,6 @@
import { import {
serializedNodeWithId, serializedNodeWithId,
idNodeMap, Mirror,
INode, INode,
MaskInputOptions, MaskInputOptions,
SlimDOMOptions, SlimDOMOptions,
@@ -571,11 +571,13 @@ export type DocumentDimension = {
absoluteScale: number; absoluteScale: number;
}; };
export type Mirror = { export type DeprecatedMirror = {
map: idNodeMap; map: {
getId: (n: INode) => number; [key: number]: INode;
};
getId: (n: Node) => number;
getNode: (id: number) => INode | null; getNode: (id: number) => INode | null;
removeNodeFromMap: (n: INode) => void; removeNodeFromMap: (n: Node) => void;
has: (id: number) => boolean; has: (id: number) => boolean;
reset: () => void; reset: () => void;
}; };

View File

@@ -1,5 +1,4 @@
import { import {
Mirror,
throttleOptions, throttleOptions,
listenerHandler, listenerHandler,
hookResetter, hookResetter,
@@ -14,14 +13,9 @@ import {
inputData, inputData,
DocumentDimension, DocumentDimension,
IWindow, IWindow,
DeprecatedMirror,
} from './types'; } from './types';
import { import { Mirror, IGNORED_NODE, isShadowRoot } from 'rrweb-snapshot';
INode,
IGNORED_NODE,
serializedNodeWithId,
NodeType,
isShadowRoot,
} from 'rrweb-snapshot';
export function on( export function on(
type: string, type: string,
@@ -33,38 +27,6 @@ export function on(
return () => target.removeEventListener(type, fn, options); return () => target.removeEventListener(type, fn, options);
} }
export function createMirror(): Mirror {
return {
map: {},
getId(n) {
// if n is not a serialized INode, use -1 as its id.
if (!n || !n.__sn) {
return -1;
}
return n.__sn.id;
},
getNode(id) {
return this.map[id] || null;
},
// TODO: use a weakmap to get rid of manually memory management
removeNodeFromMap(n) {
const id = n.__sn && n.__sn.id;
delete this.map[id];
if (n.childNodes) {
n.childNodes.forEach((child) =>
this.removeNodeFromMap((child as Node) as INode),
);
}
},
has(id) {
return this.map.hasOwnProperty(id);
},
reset() {
this.map = {};
},
};
}
// https://github.com/rrweb-io/rrweb/pull/407 // https://github.com/rrweb-io/rrweb/pull/407
const DEPARTED_MIRROR_ACCESS_WARNING = const DEPARTED_MIRROR_ACCESS_WARNING =
'Please stop import mirror directly. Instead of that,' + 'Please stop import mirror directly. Instead of that,' +
@@ -72,7 +34,7 @@ const DEPARTED_MIRROR_ACCESS_WARNING =
'now you can use replayer.getMirror() to access the mirror instance of a replayer,' + 'now you can use replayer.getMirror() to access the mirror instance of a replayer,' +
'\r\n' + '\r\n' +
'or you can use record.mirror to access the mirror instance during recording.'; 'or you can use record.mirror to access the mirror instance during recording.';
export let _mirror: Mirror = { export let _mirror: DeprecatedMirror = {
map: {}, map: {},
getId() { getId() {
console.error(DEPARTED_MIRROR_ACCESS_WARNING); console.error(DEPARTED_MIRROR_ACCESS_WARNING);
@@ -251,16 +213,13 @@ export function isBlocked(node: Node | null, blockClass: blockClass): boolean {
return isBlocked(node.parentNode, blockClass); return isBlocked(node.parentNode, blockClass);
} }
export function isIgnored(n: Node | INode): boolean { export function isIgnored(n: Node, mirror: Mirror): boolean {
if ('__sn' in n) {
return (n as INode).__sn.id === IGNORED_NODE;
}
// The main part of the slimDOM check happens in // The main part of the slimDOM check happens in
// rrweb-snapshot::serializeNodeWithId // rrweb-snapshot::serializeNodeWithId
return false; return mirror.getId(n) === IGNORED_NODE;
} }
export function isAncestorRemoved(target: INode, mirror: Mirror): boolean { export function isAncestorRemoved(target: Node, mirror: Mirror): boolean {
if (isShadowRoot(target)) { if (isShadowRoot(target)) {
return false; return false;
} }
@@ -278,7 +237,7 @@ export function isAncestorRemoved(target: INode, mirror: Mirror): boolean {
if (!target.parentNode) { if (!target.parentNode) {
return true; return true;
} }
return isAncestorRemoved((target.parentNode as unknown) as INode, mirror); return isAncestorRemoved(target.parentNode, mirror);
} }
export function isTouchEvent( export function isTouchEvent(
@@ -325,6 +284,7 @@ export type TreeNode = {
texts: textMutation[]; texts: textMutation[];
attributes: attributeMutation[]; attributes: attributeMutation[];
}; };
export class TreeIndex { export class TreeIndex {
public tree!: Record<number, TreeNode>; public tree!: Record<number, TreeNode>;
@@ -363,12 +323,12 @@ export class TreeIndex {
const treeNode = this.indexes.get(mutation.id); const treeNode = this.indexes.get(mutation.id);
const deepRemoveFromMirror = (id: number) => { const deepRemoveFromMirror = (id: number) => {
if (id === -1) return;
this.removeIdSet.add(id); this.removeIdSet.add(id);
const node = mirror.getNode(id); const node = mirror.getNode(id);
node?.childNodes.forEach((childNode) => { node?.childNodes.forEach((childNode) => {
if ('__sn' in childNode) { deepRemoveFromMirror(mirror.getId(childNode));
deepRemoveFromMirror(((childNode as unknown) as INode).__sn.id);
}
}); });
}; };
const deepRemoveFromTreeIndex = (node: TreeNode) => { const deepRemoveFromTreeIndex = (node: TreeNode) => {
@@ -576,24 +536,16 @@ export function iterateResolveTree(
} }
} }
type HTMLIFrameINode = HTMLIFrameElement & {
__sn: serializedNodeWithId;
};
export type AppendedIframe = { export type AppendedIframe = {
mutationInQueue: addedNodeMutation; mutationInQueue: addedNodeMutation;
builtNode: HTMLIFrameINode; builtNode: HTMLIFrameElement;
}; };
export function isIframeINode( export function isSerializedIframe(
node: INode | ShadowRoot, n: Node,
): node is HTMLIFrameINode { mirror: Mirror,
if ('__sn' in node) { ): n is HTMLIFrameElement {
return ( return Boolean(n.nodeName === 'IFRAME' && mirror.getMeta(n));
node.__sn.type === NodeType.Element && node.__sn.tagName === 'iframe'
);
}
// node can be document fragment when using the virtual parent feature
return false;
} }
export function getBaseDimension( export function getBaseDimension(

View File

@@ -1,4 +1,4 @@
import { serializedNodeWithId, INode } from 'rrweb-snapshot'; import { Mirror, serializedNodeWithId } from 'rrweb-snapshot';
import { mutationCallBack } from '../types'; import { mutationCallBack } from '../types';
export declare class IframeManager { export declare class IframeManager {
private iframes; private iframes;
@@ -9,5 +9,5 @@ export declare class IframeManager {
}); });
addIframe(iframeEl: HTMLIFrameElement): void; addIframe(iframeEl: HTMLIFrameElement): void;
addLoadListener(cb: (iframeEl: HTMLIFrameElement) => unknown): void; addLoadListener(cb: (iframeEl: HTMLIFrameElement) => unknown): void;
attachIframe(iframeEl: INode, childSn: serializedNodeWithId): void; attachIframe(iframeEl: HTMLIFrameElement, childSn: serializedNodeWithId, mirror: Mirror): void;
} }

View File

@@ -4,6 +4,6 @@ declare namespace record {
var addCustomEvent: <T>(tag: string, payload: T) => void; var addCustomEvent: <T>(tag: string, payload: T) => void;
var freezePage: () => void; var freezePage: () => void;
var takeFullSnapshot: (isCheckout?: boolean | undefined) => void; var takeFullSnapshot: (isCheckout?: boolean | undefined) => void;
var mirror: import("../types").Mirror; var mirror: import("rrweb-snapshot").Mirror;
} }
export default record; export default record;

View File

@@ -1,2 +1,3 @@
import { blockClass, canvasManagerMutationCallback, IWindow, listenerHandler, Mirror } from '../../../types'; import { Mirror } from 'rrweb-snapshot';
import { blockClass, canvasManagerMutationCallback, IWindow, listenerHandler } from '../../../types';
export default function initCanvas2DMutationObserver(cb: canvasManagerMutationCallback, win: IWindow, blockClass: blockClass, mirror: Mirror): listenerHandler; export default function initCanvas2DMutationObserver(cb: canvasManagerMutationCallback, win: IWindow, blockClass: blockClass, mirror: Mirror): listenerHandler;

View File

@@ -1,4 +1,5 @@
import { blockClass, canvasMutationCallback, IWindow, Mirror } from '../../../types'; import { Mirror } from 'rrweb-snapshot';
import { blockClass, canvasMutationCallback, IWindow } from '../../../types';
export declare type RafStamps = { export declare type RafStamps = {
latestId: number; latestId: number;
invokeId: number | null; invokeId: number | null;

View File

@@ -1,2 +1,3 @@
import { blockClass, canvasManagerMutationCallback, IWindow, listenerHandler, Mirror } from '../../../types'; import { Mirror } from 'rrweb-snapshot';
import { blockClass, canvasManagerMutationCallback, IWindow, listenerHandler } from '../../../types';
export default function initCanvasWebGLMutationObserver(cb: canvasManagerMutationCallback, win: IWindow, blockClass: blockClass, mirror: Mirror): listenerHandler; export default function initCanvasWebGLMutationObserver(cb: canvasManagerMutationCallback, win: IWindow, blockClass: blockClass, mirror: Mirror): listenerHandler;

View File

@@ -1,4 +1,5 @@
import { mutationCallBack, Mirror, scrollCallback, MutationBufferParam, SamplingStrategy } from '../types'; import { mutationCallBack, scrollCallback, MutationBufferParam, SamplingStrategy } from '../types';
import { Mirror } from 'rrweb-snapshot';
declare type BypassOptions = Omit<MutationBufferParam, 'doc' | 'mutationCb' | 'mirror' | 'shadowDomManager'> & { declare type BypassOptions = Omit<MutationBufferParam, 'doc' | 'mutationCb' | 'mirror' | 'shadowDomManager'> & {
sampling: SamplingStrategy; sampling: SamplingStrategy;
}; };

View File

@@ -1,6 +1,7 @@
import { Mirror } from 'rrweb-snapshot';
import { Timer } from './timer'; import { Timer } from './timer';
import { createPlayerService, createSpeedService } from './machine'; import { createPlayerService, createSpeedService } from './machine';
import { eventWithTime, playerConfig, playerMetaData, Handler, Mirror } from '../types'; import { eventWithTime, playerConfig, playerMetaData, Handler } from '../types';
import './styles/style.css'; import './styles/style.css';
export declare class Replayer { export declare class Replayer {
wrapper: HTMLDivElement; wrapper: HTMLDivElement;

View File

@@ -1,4 +1,3 @@
import { INode } from 'rrweb-snapshot';
export declare enum StyleRuleType { export declare enum StyleRuleType {
Insert = 0, Insert = 0,
Remove = 1, Remove = 1,
@@ -32,7 +31,7 @@ declare type RemovePropertyRule = {
property: string; property: string;
}; };
export declare type VirtualStyleRules = Array<InsertRule | RemoveRule | SnapshotRule | SetPropertyRule | RemovePropertyRule>; export declare type VirtualStyleRules = Array<InsertRule | RemoveRule | SnapshotRule | SetPropertyRule | RemovePropertyRule>;
export declare type VirtualStyleRulesMap = Map<INode, VirtualStyleRules>; export declare type VirtualStyleRulesMap = Map<Node, VirtualStyleRules>;
export declare function getNestedRule(rules: CSSRuleList, position: number[]): CSSGroupingRule; export declare function getNestedRule(rules: CSSRuleList, position: number[]): CSSGroupingRule;
export declare function getPositionsAndIndex(nestedIndex: number[]): { export declare function getPositionsAndIndex(nestedIndex: number[]): {
positions: number[]; positions: number[];

View File

@@ -1,4 +1,4 @@
import { serializedNodeWithId, idNodeMap, INode, MaskInputOptions, SlimDOMOptions, MaskInputFn, MaskTextFn } from 'rrweb-snapshot'; import { serializedNodeWithId, Mirror, INode, MaskInputOptions, SlimDOMOptions, MaskInputFn, MaskTextFn } from 'rrweb-snapshot';
import { PackFn, UnpackFn } from './packer/base'; import { PackFn, UnpackFn } from './packer/base';
import { IframeManager } from './record/iframe-manager'; import { IframeManager } from './record/iframe-manager';
import { ShadowDomManager } from './record/shadow-dom-manager'; import { ShadowDomManager } from './record/shadow-dom-manager';
@@ -401,11 +401,13 @@ export declare type DocumentDimension = {
relativeScale: number; relativeScale: number;
absoluteScale: number; absoluteScale: number;
}; };
export declare type Mirror = { export declare type DeprecatedMirror = {
map: idNodeMap; map: {
getId: (n: INode) => number; [key: number]: INode;
};
getId: (n: Node) => number;
getNode: (id: number) => INode | null; getNode: (id: number) => INode | null;
removeNodeFromMap: (n: INode) => void; removeNodeFromMap: (n: Node) => void;
has: (id: number) => boolean; has: (id: number) => boolean;
reset: () => void; reset: () => void;
}; };

View File

@@ -1,8 +1,7 @@
import { Mirror, throttleOptions, listenerHandler, hookResetter, blockClass, addedNodeMutation, removedNodeMutation, textMutation, attributeMutation, mutationData, scrollData, inputData, DocumentDimension, IWindow } from './types'; import { throttleOptions, listenerHandler, hookResetter, blockClass, addedNodeMutation, removedNodeMutation, textMutation, attributeMutation, mutationData, scrollData, inputData, DocumentDimension, IWindow, DeprecatedMirror } from './types';
import { INode, serializedNodeWithId } from 'rrweb-snapshot'; import { Mirror } from 'rrweb-snapshot';
export declare function on(type: string, fn: EventListenerOrEventListenerObject, target?: Document | IWindow): listenerHandler; export declare function on(type: string, fn: EventListenerOrEventListenerObject, target?: Document | IWindow): listenerHandler;
export declare function createMirror(): Mirror; export declare let _mirror: DeprecatedMirror;
export declare let _mirror: Mirror;
export declare function throttle<T>(func: (arg: T) => void, wait: number, options?: throttleOptions): (arg: T) => void; export declare function throttle<T>(func: (arg: T) => void, wait: number, options?: throttleOptions): (arg: T) => void;
export declare function hookSetter<T>(target: T, key: string | number | symbol, d: PropertyDescriptor, isRevoked?: boolean, win?: Window & typeof globalThis): hookResetter; export declare function hookSetter<T>(target: T, key: string | number | symbol, d: PropertyDescriptor, isRevoked?: boolean, win?: Window & typeof globalThis): hookResetter;
export declare function patch(source: { export declare function patch(source: {
@@ -11,8 +10,8 @@ export declare function patch(source: {
export declare function getWindowHeight(): number; export declare function getWindowHeight(): number;
export declare function getWindowWidth(): number; export declare function getWindowWidth(): number;
export declare function isBlocked(node: Node | null, blockClass: blockClass): boolean; export declare function isBlocked(node: Node | null, blockClass: blockClass): boolean;
export declare function isIgnored(n: Node | INode): boolean; export declare function isIgnored(n: Node, mirror: Mirror): boolean;
export declare function isAncestorRemoved(target: INode, mirror: Mirror): boolean; export declare function isAncestorRemoved(target: Node, mirror: Mirror): boolean;
export declare function isTouchEvent(event: MouseEvent | TouchEvent): event is TouchEvent; export declare function isTouchEvent(event: MouseEvent | TouchEvent): event is TouchEvent;
export declare function polyfill(win?: Window & typeof globalThis): void; export declare function polyfill(win?: Window & typeof globalThis): void;
export declare type TreeNode = { export declare type TreeNode = {
@@ -54,14 +53,11 @@ declare type ResolveTree = {
}; };
export declare function queueToResolveTrees(queue: addedNodeMutation[]): ResolveTree[]; export declare function queueToResolveTrees(queue: addedNodeMutation[]): ResolveTree[];
export declare function iterateResolveTree(tree: ResolveTree, cb: (mutation: addedNodeMutation) => unknown): void; export declare function iterateResolveTree(tree: ResolveTree, cb: (mutation: addedNodeMutation) => unknown): void;
declare type HTMLIFrameINode = HTMLIFrameElement & {
__sn: serializedNodeWithId;
};
export declare type AppendedIframe = { export declare type AppendedIframe = {
mutationInQueue: addedNodeMutation; mutationInQueue: addedNodeMutation;
builtNode: HTMLIFrameINode; builtNode: HTMLIFrameElement;
}; };
export declare function isIframeINode(node: INode | ShadowRoot): node is HTMLIFrameINode; export declare function isSerializedIframe(n: Node, mirror: Mirror): n is HTMLIFrameElement;
export declare function getBaseDimension(node: Node, rootIframe: Node): DocumentDimension; export declare function getBaseDimension(node: Node, rootIframe: Node): DocumentDimension;
export declare function hasShadowRoot<T extends Node>(n: T): n is T & { export declare function hasShadowRoot<T extends Node>(n: T): n is T & {
shadowRoot: ShadowRoot; shadowRoot: ShadowRoot;