// Adapted from ego lite (MIT): src/page-ref-registry.ts import type { Frame, JSHandle } from 'playwright-core'; import { StaleRefError, type StaleRefReason } from './errors.js'; import type { RoleRefInfo } from './types.js'; /** * - `aria`: a Playwright ref in an aria capture * - `role`: an interactive aria line Playwright gave no ref, resolved by role, name and occurrence * - `native`: a role-mode node bound through its `data-browserclaw-ref` marker * - `dom`: an element found by the enrichment scan, bound through its `data-bc-ref` stamp * - `ax`: a node of `ariaSnapshot()`, numbered per call */ export type RefKind = 'aria' | 'role' | 'native' | 'dom' | 'ax'; export interface RoleMatch { role: string; name?: string; occurrence: number; total: number; } export interface RefEntry { readonly id: string; readonly kind: RefKind; readonly frame: Frame; readonly epoch: number; readonly key: string; info: RoleRefInfo; readonly pwRef?: string; readonly backendNodeId?: number; readonly roleMatch?: RoleMatch; active: boolean; published: boolean; reason?: StaleRefReason; seen: number; } export interface RefSpec { kind: RefKind; frame: Frame; epoch: number; identity: string; info: RoleRefInfo; pwRef?: string; backendNodeId?: number; roleMatch?: RoleMatch; id?: string; } export interface RefCapture { register(spec: RefSpec): string; commit(): void; abandon(): void; /** Expire `id` on commit unless this capture registers it. */ retire(id: string): void; } export interface FrameDocument { epoch: number; doc: JSHandle; } type Race = (work: Promise, onLate?: (value: T) => void) => Promise; interface FrameRecord { epoch: number; doc?: JSHandle; navSeq: number; checkedSeq: number; } const MAX_INACTIVE_REFS = 10_000; const DOCUMENT_GONE = /Execution context was destroyed|Frame was detached|Cannot find context with specified id/i; // One counter for every tab and connection, so an id never names two elements. let nextRefNumber = 1; export function allocateRefId(): string { const id = `e${String(nextRefNumber)}`; nextRefNumber += 1; return id; } /** Whether `id` was ever issued in this process. */ export function refIdIssued(id: string): boolean { const match = /^e(\d+)$/.exec(id); return match !== null && Number(match[1]) < nextRefNumber; } const frameKeys = new WeakMap(); let nextFrameKey = 1; function frameKey(frame: Frame): number { let key = frameKeys.get(frame); if (key === undefined) { key = nextFrameKey; nextFrameKey += 1; frameKeys.set(frame, key); } return key; } function disposeLater(handle: JSHandle | undefined): void { if (!handle) return; void handle.dispose().catch((error: unknown) => { console.warn( `[browserclaw] could not release a document handle (${error instanceof Error ? error.name : 'error'})`, ); }); } export function namespaceOf(kind: RefKind): 'e' | 'ax' { return kind === 'ax' ? 'ax' : 'e'; } export class RefRegistry { private readonly entries = new Map(); private readonly byIdentity = new Map(); private readonly frames = new Map(); private captureSeq = 0; private lockTail: Promise = Promise.resolve(); private axIssued = 0; entry(id: string): RefEntry | undefined { return this.entries.get(id); } /** Why `id` does not resolve, when it is not an active entry. */ missingReason(id: string): StaleRefReason { const entry = this.entries.get(id); if (entry) return entry.reason ?? 'expired'; const ax = /^ax(\d+)$/.exec(id); if (ax) return Number(ax[1]) <= this.axIssued ? 'expired' : 'unknown'; return refIdIssued(id) ? 'expired' : 'unknown'; } staleError(id: string): StaleRefError { const reason = this.missingReason(id); if (reason === 'expired' && this.entries.get(id)?.kind === 'role') return new StaleRefError( id, `Stale ref ${id}: a newer snapshot replaced it (refs for controls Playwright cannot bind last only until the next snapshot). Take a new snapshot.`, reason, ); return new StaleRefError(id, undefined, reason); } info(id: string): RoleRefInfo | undefined { const entry = this.entries.get(id); return entry?.active === true ? entry.info : undefined; } /** Synchronous: only flags the frame for a document check. */ frameNavigated(frame: Frame): void { const record = this.frames.get(frame); if (record) record.navSeq += 1; } /** Synchronous: expires the frame's entries and releases its document handle. */ frameDetached(frame: Frame): void { this.expireFrame(frame, 'frame-detached'); disposeLater(this.frames.get(frame)?.doc); this.frames.delete(frame); } /** The frame navigated since its document was last checked. */ unverified(frame: Frame): boolean { const record = this.frames.get(frame); return record !== undefined && record.checkedSeq !== record.navSeq; } navigationCount(frame: Frame): number { return this.frames.get(frame)?.navSeq ?? 0; } document(frame: Frame, epoch: number): JSHandle | undefined { const record = this.frames.get(frame); return record?.epoch === epoch ? record.doc : undefined; } expireFrame(frame: Frame, reason: StaleRefReason): void { for (const entry of this.entries.values()) { if (entry.frame === frame && entry.active) { entry.active = false; entry.reason = reason; } } } markRemoved(id: string): void { const entry = this.entries.get(id); if (entry?.active !== true) return; entry.active = false; entry.reason = 'removed'; } /** The frame's current document epoch; a replaced document expires that frame's entries. */ async documentEpoch(frame: Frame, race: Race, opts: { verify?: boolean } = {}): Promise { let record = this.frames.get(frame); if (!record) { record = { epoch: 1, navSeq: 0, checkedSeq: -1 }; this.frames.set(frame, record); } const navSeq = record.navSeq; if (record.doc && record.checkedSeq === navSeq && opts.verify !== true) return { epoch: record.epoch, doc: record.doc }; if (record.doc) { const current = await race(record.doc.evaluate((doc) => doc === document)).catch((error: unknown) => { // A deadline or an abort says nothing about the document, so only a lost context counts as replaced. if (error instanceof Error && DOCUMENT_GONE.test(error.message)) return false; throw error; }); if (current) { record.checkedSeq = navSeq; return { epoch: record.epoch, doc: record.doc }; } this.replaceDocument(frame, record); } const doc = await race( frame.evaluateHandle(() => document), (late) => { disposeLater(late); }, ); if (this.frames.get(frame) !== record || record.doc) { disposeLater(doc); throw new Error('Frame changed while its browser snapshot was being captured; retry.'); } record.doc = doc; record.checkedSeq = navSeq; return { epoch: record.epoch, doc }; } /** Called when a resolve-time document check fails. */ documentReplaced(frame: Frame, epoch: number): void { const record = this.frames.get(frame); if (record?.epoch === epoch) this.replaceDocument(frame, record); } private replaceDocument(frame: Frame, record: FrameRecord): void { this.expireFrame(frame, 'document-replaced'); disposeLater(record.doc); record.doc = undefined; record.epoch += 1; } activeNative(frame: Frame, epoch: number): { ref: string; backendDOMNodeId: number }[] { const out: { ref: string; backendDOMNodeId: number }[] = []; for (const entry of this.entries.values()) { if ( entry.kind === 'native' && entry.active && entry.frame === frame && entry.epoch === epoch && entry.backendNodeId !== undefined ) out.push({ ref: entry.id, backendDOMNodeId: entry.backendNodeId }); } return out; } /** Stamps the enrichment scan may keep: this frame's dom entries of the current epoch. */ domStamps(frame: Frame, epoch: number): string[] { const out: string[] = []; for (const entry of this.entries.values()) if (entry.kind === 'dom' && entry.frame === frame && entry.epoch === epoch) out.push(entry.id); return out; } /** Captures on one page run one at a time; a waiter that gives up never runs. */ async lock(opts: { deadline: number; signal?: AbortSignal }): Promise<() => void> { const previous = this.lockTail; let release: () => void = () => undefined; const mine = new Promise((resolve) => { release = resolve; }); this.lockTail = previous.then(() => mine); let timer: ReturnType | undefined; let onAbort: (() => void) | undefined; try { opts.signal?.throwIfAborted(); await Promise.race([ previous, new Promise((_resolve, reject) => { timer = setTimeout( () => { reject(new Error('Browser snapshot capture timed out.')); }, Math.max(1, opts.deadline - Date.now()), ); if (opts.signal) { const signal = opts.signal; onAbort = () => { reject(signal.reason as Error); }; signal.addEventListener('abort', onAbort, { once: true }); } }), ]); } catch (error) { void previous.then(release); throw error; } finally { clearTimeout(timer); if (onAbort) opts.signal?.removeEventListener('abort', onAbort); } let released = false; return () => { if (released) return; released = true; release(); }; } /** `spare`: a complete capture leaves entries of this kind it did not see as they are. */ beginCapture(opts: { complete: boolean; namespace: 'e' | 'ax'; spare?: RefKind }): RefCapture { this.captureSeq += 1; const seq = this.captureSeq; const staged = new Map(); const retired = new Set(); let closed = false; const register = (spec: RefSpec): string => { if (closed) throw new Error('Snapshot capture already finished.'); const identity = `${spec.kind}|${String(frameKey(spec.frame))}|${String(spec.epoch)}|${spec.identity}`; const existing = this.byIdentity.get(identity); // A role-kind identity can match a different element next time, so only unpublished ids come back. if ( existing && (spec.id === undefined || existing.id === spec.id) && (existing.kind !== 'role' || !existing.published) ) { staged.set(existing, spec.info); return existing.id; } if (existing && spec.id !== undefined) this.forget(existing); const id = spec.id ?? allocateRefId(); const previous = this.entries.get(id); if (previous) { staged.delete(previous); this.forget(previous); } const entry: RefEntry = { id, kind: spec.kind, frame: spec.frame, epoch: spec.epoch, key: identity, info: spec.info, ...(spec.pwRef !== undefined ? { pwRef: spec.pwRef } : {}), ...(spec.backendNodeId !== undefined ? { backendNodeId: spec.backendNodeId } : {}), ...(spec.roleMatch ? { roleMatch: spec.roleMatch } : {}), active: false, published: false, reason: 'expired', seen: seq, }; this.entries.set(id, entry); this.byIdentity.set(identity, entry); staged.set(entry, spec.info); return id; }; const commit = (): void => { if (closed) return; closed = true; for (const [entry, info] of staged) { entry.info = info; entry.active = true; entry.published = true; entry.reason = undefined; entry.seen = seq; if (entry.kind === 'ax') this.axIssued = Math.max(this.axIssued, Number(entry.id.slice(2))); } for (const entry of this.entries.values()) { if (staged.has(entry) || !entry.active) continue; const unseen = opts.complete && namespaceOf(entry.kind) === opts.namespace && entry.kind !== opts.spare; if (!unseen && !retired.has(entry.id)) continue; entry.active = false; entry.reason = 'expired'; } this.prune(); }; const abandon = (): void => { closed = true; }; const retire = (id: string): void => { if (!closed) retired.add(id); }; return { register, commit, abandon, retire }; } private forget(entry: RefEntry): void { this.entries.delete(entry.id); if (this.byIdentity.get(entry.key) === entry) this.byIdentity.delete(entry.key); } private prune(): void { const inactive = [...this.entries.values()].filter((entry) => !entry.active); if (inactive.length <= MAX_INACTIVE_REFS) return; inactive.sort((a, b) => a.seen - b.seen); const dropped = new Set(inactive.slice(0, inactive.length - MAX_INACTIVE_REFS)); for (const entry of dropped) this.forget(entry); } }