change observed mutations into serializable records

This commit is contained in:
Yanzhen Yu
2026-04-01 12:00:00 +08:00
parent e2fbecea96
commit d2175eae87
6 changed files with 280 additions and 39 deletions

70
src/record/index.ts Normal file
View File

@@ -0,0 +1,70 @@
import { snapshot } from 'rrweb-snapshot';
import initObservers from './observer';
import { mirror } from '../utils';
import {
EventType,
event,
eventWithTime,
recordOptions,
IncrementalSource,
} from '../types';
function on(
type: string,
fn: EventListenerOrEventListenerObject,
target = document,
) {
target.addEventListener(type, fn, { capture: true, passive: true });
}
function wrapEvent(e: event): eventWithTime {
return {
...e,
timestamp: Date.now(),
};
}
function record(options: recordOptions) {
try {
const { emit } = options;
// runtime checks for user options
if (!emit) {
throw new Error('emit function is required');
}
on('DOMContentLoaded', () => {
emit(
wrapEvent({
type: EventType.DomContentLoaded,
data: {
href: window.location.href,
},
}),
);
});
on('load', () => {
emit(wrapEvent({ type: EventType.Load, data: {} }));
const [node, idNodeMap] = snapshot(document);
if (!node) {
return console.warn('Failed to snapshot the document');
}
mirror.map = idNodeMap;
emit(wrapEvent({ type: EventType.FullSnapshot, data: { node } }));
initObservers({
mutationCb: m =>
emit(
wrapEvent({
type: EventType.IncrementalSnapshot,
data: {
source: IncrementalSource.Mutation,
...m,
},
}),
),
});
});
} catch (error) {
// TODO: handle internal error
}
}
export default record;