import type { Frame, JSHandle } from 'playwright-core'; import { describe, expect, it } from 'vitest'; import { allocateRefId, RefRegistry, type RefSpec } from './ref-registry.js'; function fakeFrame(): { frame: Frame; replace: () => void } { let doc = { current: true }; const frame = { isDetached: () => false, evaluateHandle: () => { const owned = doc; return Promise.resolve({ evaluate: () => Promise.resolve(owned.current), dispose: () => Promise.resolve(), } as unknown as JSHandle); }, } as unknown as Frame; return { frame, replace: () => { doc.current = false; doc = { current: true }; }, }; } const passThrough = (work: Promise) => work; function spec(frame: Frame, epoch: number, identity: string, extra: Partial = {}): RefSpec { return { kind: 'aria', frame, epoch, identity, pwRef: identity, info: { role: 'button', name: identity }, ...extra }; } function capture(registry: RefRegistry, specs: RefSpec[], complete = true): string[] { const run = registry.beginCapture({ complete, namespace: 'e' }); const ids = specs.map((entry) => run.register(entry)); run.commit(); return ids; } describe('RefRegistry', () => { it('issues increasing ids and never reuses one for a different identity', () => { const { frame } = fakeFrame(); const first = new RefRegistry(); const second = new RefRegistry(); const [a, b] = capture(first, [spec(frame, 1, 'e1'), spec(frame, 1, 'e2')]); const [c] = capture(second, [spec(frame, 1, 'e1')]); const numbers = [a, b, c].map((id) => Number(id.slice(1))); expect(numbers[1]).toBeGreaterThan(numbers[0]); expect(numbers[2]).toBeGreaterThan(numbers[1]); }); it('returns the same id when a complete capture sees the same identity', () => { const { frame } = fakeFrame(); const registry = new RefRegistry(); const [first] = capture(registry, [spec(frame, 1, 'e3')]); const [again] = capture(registry, [spec(frame, 1, 'e3')]); expect(again).toBe(first); expect(registry.info(first)).toEqual({ role: 'button', name: 'e3' }); }); it('expires entries missing from a complete capture and gives the same id back when they reappear', () => { const { frame } = fakeFrame(); const registry = new RefRegistry(); const [kept, gone] = capture(registry, [spec(frame, 1, 'e1'), spec(frame, 1, 'e2')]); capture(registry, [spec(frame, 1, 'e1')]); expect(registry.entry(kept)?.active).toBe(true); expect(registry.entry(gone)?.active).toBe(false); expect(registry.missingReason(gone)).toBe('expired'); const [back] = capture(registry, [spec(frame, 1, 'e1'), spec(frame, 1, 'e2')]).slice(1); expect(back).toBe(gone); }); it('keeps entries missing from a partial capture active', () => { const { frame } = fakeFrame(); const registry = new RefRegistry(); const [first] = capture(registry, [spec(frame, 1, 'n1', { kind: 'native', backendNodeId: 1 })], false); capture(registry, [spec(frame, 1, 'n2', { kind: 'native', backendNodeId: 2 })], false); expect(registry.entry(first)?.active).toBe(true); expect(registry.activeNative(frame, 1)).toHaveLength(2); }); it('abandoned capture leaves pending entries inactive and a retry reuses their ids', () => { const { frame } = fakeFrame(); const registry = new RefRegistry(); const run = registry.beginCapture({ complete: true, namespace: 'e' }); const pending = run.register(spec(frame, 1, 'e4')); run.abandon(); expect(registry.entry(pending)?.active).toBe(false); expect(capture(registry, [spec(frame, 1, 'e4')])).toEqual([pending]); }); it('does not give a published role-kind id to the next element with that role and name', () => { const { frame } = fakeFrame(); const registry = new RefRegistry(); const role = (occurrence: number) => spec(frame, 1, `button|Save|${String(occurrence)}`, { kind: 'role', roleMatch: { role: 'button', name: 'Save', occurrence, total: 1 }, }); const [first] = capture(registry, [role(0)]); const [second] = capture(registry, [role(0)]); expect(second).not.toBe(first); expect(registry.missingReason(first)).toBe('expired'); expect(registry.staleError(first).message).toBe( `Stale ref ${first}: a newer snapshot replaced it (refs for controls Playwright cannot bind last only until the next snapshot). Take a new snapshot.`, ); }); it('a capture that spares dom entries keeps the unseen ones and expires a retired one', () => { const { frame } = fakeFrame(); const registry = new RefRegistry(); const dom = () => { const id = allocateRefId(); return spec(frame, 1, id, { kind: 'dom', id }); }; const [kept, paired, outside] = capture(registry, [dom(), dom(), dom()]); const run = registry.beginCapture({ complete: true, namespace: 'e', spare: 'dom' }); run.register(spec(frame, 1, 'aria-line')); run.retire(paired); run.commit(); expect(registry.entry(kept)?.active).toBe(true); expect(registry.entry(outside)?.active).toBe(true); expect(registry.missingReason(paired)).toBe('expired'); capture(registry, [spec(frame, 1, 'aria-line')]); expect(registry.missingReason(kept)).toBe('expired'); }); it("expires only the detached frame's entries", () => { const main = fakeFrame().frame; const child = fakeFrame().frame; const registry = new RefRegistry(); const [inMain, inChild] = capture(registry, [spec(main, 1, 'e1'), spec(child, 1, 'f1e1')]); registry.frameDetached(child); expect(registry.entry(inMain)?.active).toBe(true); expect(registry.missingReason(inChild)).toBe('frame-detached'); }); it("bumps the frame epoch and expires that frame's entries when its document is replaced", async () => { const { frame, replace } = fakeFrame(); const other = fakeFrame().frame; const registry = new RefRegistry(); const { epoch } = await registry.documentEpoch(frame, passThrough); const otherEpoch = (await registry.documentEpoch(other, passThrough)).epoch; const [old, untouched] = capture(registry, [spec(frame, epoch, 'e1'), spec(other, otherEpoch, 'e1')]); registry.frameNavigated(frame); expect(registry.entry(old)?.active).toBe(true); replace(); const next = await registry.documentEpoch(frame, passThrough); expect(next.epoch).toBe(epoch + 1); expect(registry.missingReason(old)).toBe('document-replaced'); expect(registry.entry(untouched)?.active).toBe(true); expect(capture(registry, [spec(frame, next.epoch, 'e1')])).not.toEqual([old]); }); it('a document check that times out after frameNavigated leaves the entries and the epoch alone', async () => { const registry = new RefRegistry(); const frame = { isDetached: () => false, evaluateHandle: () => Promise.resolve({ evaluate: () => new Promise(() => undefined), dispose: () => Promise.resolve(), } as unknown as JSHandle), } as unknown as Frame; const { epoch } = await registry.documentEpoch(frame, passThrough); const [id] = capture(registry, [spec(frame, epoch, 'e5')]); registry.frameNavigated(frame); const timeout = new Error('Timeout 300ms exceeded.'); const timedOut = (work: Promise) => Promise.race([work, Promise.reject(timeout)]); await expect(registry.documentEpoch(frame, timedOut)).rejects.toBe(timeout); expect(registry.entry(id)?.active).toBe(true); expect(registry.document(frame, epoch)).toBeDefined(); expect(registry.unverified(frame)).toBe(true); }); it('a lost execution context after frameNavigated counts as a replaced document', async () => { const registry = new RefRegistry(); let handles = 0; const frame = { isDetached: () => false, evaluateHandle: () => { handles += 1; const first = handles === 1; return Promise.resolve({ evaluate: () => first ? Promise.reject(new Error('elementHandle.evaluate: Execution context was destroyed')) : Promise.resolve(true), dispose: () => Promise.resolve(), } as unknown as JSHandle); }, } as unknown as Frame; const { epoch } = await registry.documentEpoch(frame, passThrough); const [id] = capture(registry, [spec(frame, epoch, 'e6')]); registry.frameNavigated(frame); expect((await registry.documentEpoch(frame, passThrough)).epoch).toBe(epoch + 1); expect(registry.missingReason(id)).toBe('document-replaced'); }); it('keeps the document epoch across a same-document navigation', async () => { const { frame } = fakeFrame(); const registry = new RefRegistry(); const { epoch } = await registry.documentEpoch(frame, passThrough); registry.frameNavigated(frame); expect((await registry.documentEpoch(frame, passThrough)).epoch).toBe(epoch); }); it('drops the oldest inactive entries past 10,000 and reports their ids as expired', () => { const { frame } = fakeFrame(); const registry = new RefRegistry(); const [oldest] = capture(registry, [spec(frame, 1, 'first')]); for (let round = 0; round < 4; round++) capture( registry, Array.from({ length: 4000 }, (_, i) => spec(frame, 1, `r${String(round)}-${String(i)}`)), ); expect(registry.entry(oldest)).toBeUndefined(); expect(registry.missingReason(oldest)).toBe('expired'); }); it('runs concurrent captures on one page one at a time and skips a waiter that gave up', async () => { const registry = new RefRegistry(); const order: string[] = []; const releaseFirst = await registry.lock({ deadline: Date.now() + 1000 }); const quitter = new AbortController(); const gaveUp = registry.lock({ deadline: Date.now() + 1000, signal: quitter.signal }); const third = registry.lock({ deadline: Date.now() + 1000 }).then((release) => { order.push('third'); release(); }); quitter.abort(new Error('gave up')); await expect(gaveUp).rejects.toThrow('gave up'); await new Promise((resolve) => setTimeout(resolve, 20)); expect(order).toEqual([]); order.push('first'); releaseFirst(); await third; expect(order).toEqual(['first', 'third']); }); it('gives forced ax ids to their node and replaces the node that held the id before', () => { const { frame } = fakeFrame(); const registry = new RefRegistry(); const ax = (id: string, identity: string) => spec(frame, 1, identity, { kind: 'ax', id }); const first = registry.beginCapture({ complete: true, namespace: 'ax' }); first.register(ax('ax1', 'node-a')); first.commit(); const second = registry.beginCapture({ complete: true, namespace: 'ax' }); second.register(ax('ax1', 'node-b')); second.register(ax('ax2', 'node-a')); second.commit(); expect(registry.info('ax1')?.name).toBe('node-b'); expect(registry.info('ax2')?.name).toBe('node-a'); expect(registry.missingReason('ax3')).toBe('unknown'); }); });