import { EventEmitter } from 'node:events'; import type { Page } from 'playwright-core'; import { afterEach, describe, expect, it, vi } from 'vitest'; import * as connection from '../connection.js'; import { EvaluateTimeoutError } from '../errors.js'; import { evaluateViaPlaywright } from './evaluate.js'; import { createFakeNavigationFence } from './navigation-fence.test-support.js'; afterEach(() => vi.restoreAllMocks()); function fixture(evaluate: () => Promise) { const fence = createFakeNavigationFence({ url: () => 'http://93.184.216.34/' }); const running = new Set<(error: Error) => void>(); const answer = fence.session.send.getMockImplementation(); fence.session.send.mockImplementation(async (method, params) => { if (method === 'Runtime.terminateExecution') for (const stop of running) stop(new Error('Execution was terminated')); return await answer?.(method, params); }); const run = vi.fn(() => Promise.race([evaluate(), new Promise((_, reject) => running.add(reject))])); const page = Object.assign(new EventEmitter(), { url: () => 'http://93.184.216.34/', mainFrame: () => ({}), isClosed: () => false, evaluate: run, context: () => ({ newCDPSession: fence.newCDPSession }), }) as unknown as Page; vi.spyOn(connection, 'getPageForTargetId').mockResolvedValue(page); const sent = (method: string): number => fence.session.send.mock.calls.filter(([name]) => name === method).length; return { page, fence, sent, run }; } const permissive = { dangerouslyAllowPrivateNetwork: true }; type Fence = ReturnType; function childEvent(fence: Fence, method: string, params: unknown): void { fence.emit('Target.receivedMessageFromTarget', { sessionId: 'CHILD', message: JSON.stringify({ method, params }) }); } function childCommands(fence: Fence): string[] { return fence.session.send.mock.calls.flatMap(([method, params]) => method === 'Target.sendMessageToTarget' ? [(JSON.parse(String(params?.message)) as { method: string }).method] : [], ); } /** Answers every command sent to the child frame's session, as a responsive child renderer would. */ function childFrameAnswers(fence: Fence) { const answer = fence.session.send.getMockImplementation(); return async (method: string, params?: Record): Promise => { if (method !== 'Target.sendMessageToTarget') return await answer?.(method, params); const { id, method: command } = JSON.parse(String(params?.message)) as { id: number; method: string }; const result = command === 'Page.getFrameTree' ? { frameTree: { frame: { id: 'CHILD-FRAME', url: 'about:blank' } } } : {}; queueMicrotask(() => { fence.emit('Target.receivedMessageFromTarget', { sessionId: 'CHILD', message: JSON.stringify({ id, result }) }); }); return {}; }; } describe('evaluate hard timeout', () => { it('stops a synchronous loop on the fence session and reports the page responsive again', async () => { const { fence, sent } = fixture(() => new Promise(() => undefined)); const started = Date.now(); const result = evaluateViaPlaywright({ cdpUrl: 'http://localhost:9222', fn: '() => { while (true) {} }', timeoutMs: 500, ssrfPolicy: permissive, }); await vi.waitFor(() => { expect(sent('Network.enable')).toBe(1); }); const busy = fence.hold(['Runtime.evaluate'], { until: 'Runtime.terminateExecution' }); const error: unknown = await result.catch((caught: unknown) => caught); busy(); expect(error).toBeInstanceOf(EvaluateTimeoutError); expect(error).toMatchObject({ timeoutMs: 500, executionStopped: true, navigationStopped: false, pageResponsive: true, mayHaveLateEffects: true, }); expect((error as Error).message).toContain('evaluate timed out after 500ms and was stopped'); expect(sent('Runtime.terminateExecution')).toBe(1); expect(Date.now() - started).toBeLessThan(2000); }); it('leaves another evaluate on the tab running when one times out behind it', async () => { let finishOther: (value: unknown) => void = () => undefined; const scripts: Promise[] = [ new Promise((resolve) => { finishOther = resolve; }), ]; const { fence, sent } = fixture(() => scripts.shift() ?? new Promise(() => undefined)); const other = evaluateViaPlaywright({ cdpUrl: 'http://localhost:9222', fn: '() => { const t = Date.now(); while (Date.now() - t < 3000) {} }', timeoutMs: 10_000, ssrfPolicy: permissive, }); await vi.waitFor(() => { expect(sent('Network.enable')).toBe(1); }); const open = fence.hold(['Runtime.evaluate']); setTimeout(() => { open(); }, 1500); const error: unknown = await evaluateViaPlaywright({ cdpUrl: 'http://localhost:9222', fn: '() => 1', timeoutMs: 500, ssrfPolicy: permissive, }).catch((caught: unknown) => caught); expect(error).toMatchObject({ name: 'EvaluateTimeoutError', executionStopped: false, pageResponsive: false }); expect((error as Error).message).toContain('another evaluate still held the page'); finishOther('other done'); await expect(other).resolves.toBe('other done'); await new Promise((resolve) => setTimeout(resolve, 50)); expect(sent('Runtime.terminateExecution')).toBe(0); }, 10_000); it('reports the timeout without waiting for the evaluate that holds the page', async () => { let finishOther: (value: unknown) => void = () => undefined; const scripts: Promise[] = [ new Promise((resolve) => { finishOther = resolve; }), ]; const { fence, sent } = fixture(() => scripts.shift() ?? new Promise(() => undefined)); const call = (timeoutMs: number): Promise => evaluateViaPlaywright({ cdpUrl: 'http://localhost:9222', fn: '() => 1', timeoutMs, ssrfPolicy: permissive, }); const other = call(15_000); await vi.waitFor(() => { expect(sent('Network.enable')).toBe(1); }); const open = fence.hold(['Runtime.evaluate']); const started = Date.now(); await expect(call(500)).rejects.toMatchObject({ name: 'EvaluateTimeoutError', pageResponsive: false }); expect(Date.now() - started).toBeLessThan(3000); open(); finishOther('other done'); await expect(other).resolves.toBe('other done'); }, 10_000); it('stops an aborted script that runs once the evaluate holding the page ends', async () => { let finishOther: (value: unknown) => void = () => undefined; const scripts: Promise[] = [ new Promise((resolve) => { finishOther = resolve; }), ]; const { fence, sent, run } = fixture(() => scripts.shift() ?? new Promise(() => undefined)); const other = evaluateViaPlaywright({ cdpUrl: 'http://localhost:9222', fn: '() => 1', timeoutMs: 15_000, ssrfPolicy: permissive, }); await vi.waitFor(() => { expect(run).toHaveBeenCalledTimes(1); }); const controller = new AbortController(); const aborted = evaluateViaPlaywright({ cdpUrl: 'http://localhost:9222', fn: '() => { while (true) {} }', timeoutMs: 15_000, signal: controller.signal, ssrfPolicy: permissive, }); await vi.waitFor(() => { expect(run).toHaveBeenCalledTimes(2); }); const open = fence.hold(['Runtime.evaluate'], { until: 'Runtime.terminateExecution' }); controller.abort(new Error('stop')); await expect(aborted).rejects.toThrow('stop'); await new Promise((resolve) => setTimeout(resolve, 700)); expect(sent('Runtime.terminateExecution')).toBe(0); finishOther('other done'); await vi.waitFor( () => { expect(sent('Runtime.terminateExecution')).toBe(1); }, { timeout: 3000 }, ); open(); await expect(other).resolves.toBe('other done'); }, 10_000); it('leaves a navigation alone while another evaluate on the tab is within its budget', async () => { let finishOther: (value: unknown) => void = () => undefined; const scripts: Promise[] = [ new Promise((resolve) => { finishOther = resolve; }), ]; const { fence, sent, run } = fixture(() => scripts.shift() ?? new Promise(() => undefined)); const other = evaluateViaPlaywright({ cdpUrl: 'http://localhost:9222', fn: '() => { location.href = "/next"; return new Promise(() => {}); }', timeoutMs: 15_000, ssrfPolicy: permissive, }); await vi.waitFor(() => { expect(run).toHaveBeenCalledTimes(1); }); await fence.pauseDocument('http://93.184.216.34/next'); await expect( evaluateViaPlaywright({ cdpUrl: 'http://localhost:9222', fn: '() => new Promise(() => {})', timeoutMs: 500, ssrfPolicy: permissive, }), ).rejects.toMatchObject({ name: 'EvaluateTimeoutError', navigationStopped: false }); expect(sent('Page.stopLoading')).toBe(0); finishOther('other done'); await expect(other).resolves.toBe('other done'); await new Promise((resolve) => setTimeout(resolve, 50)); expect(sent('Page.stopLoading')).toBe(0); }, 10_000); it('stops a deferred script after a grace period when a kept document never commits', async () => { let finishOther: (value: unknown) => void = () => undefined; const scripts: Promise[] = [ new Promise((resolve) => { finishOther = resolve; }), ]; const { fence, sent, run } = fixture(() => scripts.shift() ?? new Promise(() => undefined)); const call = (timeoutMs: number): Promise => evaluateViaPlaywright({ cdpUrl: 'http://localhost:9222', fn: '() => 1', timeoutMs, ssrfPolicy: permissive }); const other = call(15_000); await vi.waitFor(() => { expect(run).toHaveBeenCalledTimes(1); }); await fence.pauseDocument('http://93.184.216.34/next'); const open = fence.hold(['Runtime.evaluate'], { until: 'Runtime.terminateExecution' }); await expect(call(500)).rejects.toMatchObject({ name: 'EvaluateTimeoutError', executionStopped: false }); finishOther('other done'); await new Promise((resolve) => setTimeout(resolve, 1500)); expect(sent('Page.stopLoading')).toBe(0); await vi.waitFor( () => { expect(sent('Page.stopLoading')).toBe(1); expect(sent('Runtime.terminateExecution')).toBe(1); }, { timeout: 8000 }, ); open(); await expect(other).resolves.toBe('other done'); }, 20_000); it('stops a deferred script in the main frame while an out-of-process iframe is loading', async () => { let finishOther: (value: unknown) => void = () => undefined; const scripts: Promise[] = [ new Promise((resolve) => { finishOther = resolve; }), ]; const { fence, sent, run } = fixture(() => scripts.shift() ?? new Promise(() => undefined)); const call = (timeoutMs: number): Promise => evaluateViaPlaywright({ cdpUrl: 'http://localhost:9222', fn: '() => 1', timeoutMs, ssrfPolicy: permissive }); const other = call(15_000); await vi.waitFor(() => { expect(run).toHaveBeenCalledTimes(1); }); fence.session.send.mockImplementation(childFrameAnswers(fence)); fence.emit('Target.attachedToTarget', { sessionId: 'CHILD', targetInfo: { targetId: 'CHILD-FRAME', type: 'iframe', url: 'http://93.184.216.34/ad' }, waitingForDebugger: true, }); await vi.waitFor(() => { expect(childCommands(fence)).toContain('Runtime.runIfWaitingForDebugger'); }); childEvent(fence, 'Fetch.requestPaused', { requestId: 'child-document', request: { url: 'http://93.184.216.34/slow-ad', headers: {} }, frameId: 'CHILD-FRAME', resourceType: 'Document', }); await vi.waitFor(() => { expect(childCommands(fence)).toContain('Fetch.continueRequest'); }); const open = fence.hold(['Runtime.evaluate'], { until: 'Runtime.terminateExecution' }); await expect(call(500)).rejects.toMatchObject({ name: 'EvaluateTimeoutError', executionStopped: false }); finishOther('other done'); await vi.waitFor( () => { expect(sent('Runtime.terminateExecution')).toBe(1); }, { timeout: 3000 }, ); expect(childCommands(fence)).not.toContain('Page.stopLoading'); open(); await expect(other).resolves.toBe('other done'); }, 20_000); it('does not terminate a pending asynchronous script on a responsive page', async () => { const { sent } = fixture(() => new Promise(() => undefined)); await expect( evaluateViaPlaywright({ cdpUrl: 'http://localhost:9222', fn: '() => new Promise(() => {})', timeoutMs: 500, ssrfPolicy: permissive, }), ).rejects.toMatchObject({ name: 'EvaluateTimeoutError', executionStopped: false, pageResponsive: true }); expect(sent('Runtime.terminateExecution')).toBe(0); }); it('reports a page that stays unresponsive after the script was told to stop', async () => { const { fence, sent } = fixture(() => new Promise(() => undefined)); const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); const result = evaluateViaPlaywright({ cdpUrl: 'http://localhost:9222', fn: '() => { while (true) {} }', timeoutMs: 500, ssrfPolicy: permissive, }); await vi.waitFor(() => { expect(sent('Network.enable')).toBe(1); }); const open = fence.hold(['Runtime.evaluate']); setTimeout(() => { open(); }, 2500); const error: unknown = await result.catch((caught: unknown) => caught); open(); expect(error).toMatchObject({ name: 'EvaluateTimeoutError', executionStopped: true, pageResponsive: false }); expect((error as Error).message).toContain('still not responding'); expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('could not stop the running script')); }, 10_000); it('stops an uncommitted main-frame document before probing the renderer', async () => { const { fence, sent } = fixture(() => new Promise(() => undefined)); const result = evaluateViaPlaywright({ cdpUrl: 'http://localhost:9222', fn: '() => { location.href = "/next"; return new Promise(() => {}); }', timeoutMs: 500, ssrfPolicy: permissive, }); await vi.waitFor(() => { expect(sent('Network.enable')).toBe(1); }); await fence.pauseDocument('http://93.184.216.34/next'); fence.hold(['Runtime.evaluate'], { until: 'Page.stopLoading' }); await expect(result).rejects.toMatchObject({ name: 'EvaluateTimeoutError', navigationStopped: true, executionStopped: false, pageResponsive: true, }); const methods = fence.session.send.mock.calls.map(([method]) => method); expect(methods.indexOf('Page.stopLoading')).toBeGreaterThan(-1); expect(sent('Runtime.terminateExecution')).toBe(0); }); it('maps the in-page promise timeout to EvaluateTimeoutError with the caller budget', async () => { fixture(() => Promise.reject(new Error('Invalid evaluate function: evaluate timed out after 1000ms'))); await expect( evaluateViaPlaywright({ cdpUrl: 'http://localhost:9222', fn: '() => new Promise(() => {})', timeoutMs: 2000, ssrfPolicy: permissive, }), ).rejects.toMatchObject({ name: 'EvaluateTimeoutError', timeoutMs: 2000, executionStopped: false }); }); });