Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ServerBrowserPage.test.ts

1,113 lines43.7 KB

1import { PreviewAutomationEvaluateInput } from "@t3tools/contracts";
2import * as Schema from "effect/Schema";
3import {
4 chromium,
5 type Browser,
6 type BrowserContext,
7 type CDPSession,
8 type Page,
9} from "playwright-core";
10import {
11 afterAll,
12 afterEach,
13 beforeAll,
14 beforeEach,
15 describe,
16 expect,
17 it,
18 vi,
19} from "vite-plus/test";
20​
21import * as ServerBrowserPage from "./ServerBrowserPage.ts";
22import { SessionControl } from "./SessionControl.ts";
23​
24const decodeEvaluateInput = Schema.decodeUnknownSync(PreviewAutomationEvaluateInput);
25​
26describe("JPEG screenshot dimensions", () => {
27 const encode = (bytes: number[]) => Buffer.from(bytes).toString("base64");
28 const frame = [0xff, 0xd8, 0xff, 0xc0, 0, 7, 8, 0, 24, 0, 32];
29​
30 it("reads valid dimensions and rejects invalid or incomplete frames", () => {
31 expect(ServerBrowserPage.jpegSize(encode(frame))).toEqual({ width: 32, height: 24 });
32 for (const bytes of [
33 [],
34 [0xff, 0xd8, 0xff, 0xe1, 0, 20, 1],
35 frame.slice(0, -1),
36 [...frame.slice(0, 7), 0, 0, 0, 32],
37 [...frame.slice(0, 9), 0, 0],
38 ]) {
39 expect(() => ServerBrowserPage.jpegSize(encode(bytes))).toThrow("Invalid JPEG screenshot.");
40 }
41 });
42});
43​
44describe("snapshot deadline diagnostics", () => {
45 const never = () => new Promise<never>(() => {});
46 const stalledSnapshot = async (options: {
47 readonly stalled?: "metrics";
48 readonly page?: Partial<Record<keyof Page, unknown>>;
49 readonly advanceMs: number;
50 }) => {
51 vi.useFakeTimers();
52 try {
53 const frame = {};
54 const page = {
55 viewportSize: () => ({ width: 1280, height: 800 }),
56 mainFrame: () => frame,
57 frames: () => [frame],
58 on: () => {},
59 evaluate: async () => ({
60 url: "about:blank",
61 title: "",
62 loading: false,
63 visibleText: "",
64 }),
65 ariaSnapshot: async () => "",
66 ...options.page,
67 } as unknown as Page;
68 const cdp = {
69 send: async (method: string) => {
70 if (options.stalled === "metrics") return never();
71 if (method === "Page.captureScreenshot") return { data: "" };
72 if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } };
73 if (method === "Page.createIsolatedWorld") return { executionContextId: 1 };
74 if (method === "Runtime.evaluate") return { result: { value: [] } };
75 throw new Error(`Unexpected command: ${method}`);
76 },
77 } as unknown as CDPSession;
78 const captured = ServerBrowserPage.snapshot({
79 page,
80 cdp,
81 renderScale: options.stalled === "metrics" ? "display" : 1,
82 consoleEntries: [],
83 networkEntries: [],
84 actionTimeline: [],
85 }).catch((error: unknown) => error);
86 await vi.advanceTimersByTimeAsync(options.advanceMs);
87 return await captured;
88 } finally {
89 vi.useRealTimers();
90 }
91 };
92​
93 it("identifies a stalled metrics read", async () => {
94 expect(await stalledSnapshot({ stalled: "metrics", advanceMs: 10_000 })).toMatchObject({
95 tag: "PreviewAutomationTimeoutError",
96 detail: { timeoutMs: 10_000, pendingStages: ["metrics"] },
97 });
98 });
99​
100 it("keeps an accessibility tree that hit its own timeout", async () => {
101 const timedOut = Object.assign(new Error("Timeout exceeded"), { name: "TimeoutError" });
102 const captured = await stalledSnapshot({
103 page: { ariaSnapshot: () => Promise.reject(timedOut) },
104 advanceMs: 0,
105 });
106 expect(captured).toMatchObject({
107 tag: "PreviewAutomationTimeoutError",
108 detail: { timeoutMs: 10_000 },
109 });
110 expect((captured as ServerBrowserPage.ServerBrowserOperationError).detail).toMatchObject({
111 pendingStages: expect.arrayContaining(["accessibility tree"]),
112 });
113 });
114​
115 it("omits a timed-out stage after it succeeds on retry", async () => {
116 let attempts = 0;
117 const timedOut = Object.assign(new Error("Timeout exceeded"), { name: "TimeoutError" });
118 expect(
119 await stalledSnapshot({
120 page: {
121 evaluate: never,
122 ariaSnapshot: async () => {
123 if (attempts++ === 0) throw timedOut;
124 return "";
125 },
126 },
127 advanceMs: 10_000,
128 }),
129 ).toMatchObject({ detail: { timeoutMs: 10_000, pendingStages: ["page state"] } });
130 });
131​
132 it.each(["elementHandle", "contentFrame"] as const)(
133 "identifies stalled iframe %s lookup",
134 async (stage) => {
135 const main = {};
136 const child = { evaluate: never, parentFrame: () => main };
137 const captured = await stalledSnapshot({
138 page: {
139 mainFrame: () => main,
140 frames: () => [main, child],
141 context: () => ({
142 newCDPSession: () =>
143 Promise.reject(new Error("Only this preview tab's page can be attached")),
144 }),
145 ariaSnapshot: async () => "- iframe [ref=f1]:\n - text: inside",
146 locator: () => ({
147 elementHandle:
148 stage === "elementHandle" ? never : async () => ({ contentFrame: never }),
149 }),
150 },
151 advanceMs: 10_000,
152 });
153 expect(captured).toMatchObject({
154 detail: { timeoutMs: 10_000, pendingStages: expect.arrayContaining(["frames"]) },
155 });
156 },
157 );
158​
159 it("reports a frame that didn't answer as the frame's own timeout", async () => {
160 const main = {};
161 // A desktop tab refuses frame sessions, so the frame is read in its own world.
162 const child = { evaluate: never, parentFrame: () => main };
163 const captured = await stalledSnapshot({
164 page: {
165 mainFrame: () => main,
166 frames: () => [main, child],
167 context: () => ({
168 newCDPSession: () =>
169 Promise.reject(new Error("Only this preview tab's page can be attached")),
170 }),
171 ariaSnapshot: async () => "- iframe [ref=f1]:\n - text: inside",
172 locator: () => ({
173 elementHandle: async () => ({ contentFrame: async () => child, dispose: async () => {} }),
174 }),
175 },
176 // Both attempts wait out the frame; neither reaches the capture deadline.
177 advanceMs: 2_000,
178 });
179 expect(captured).toMatchObject({
180 tag: "PreviewAutomationTimeoutError",
181 detail: { timeoutMs: 1_000, pendingStages: ["frames"] },
182 });
183 });
184});
185​
186describe("server browser capture deadlines", () => {
187 it("releases control after an unanswered capture and ignores its late reply", async () => {
188 vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
189 try {
190 const captured = Promise.withResolvers<{ data: string }>();
191 const send = vi.fn(async (method: string) =>
192 method === "Page.captureScreenshot"
193 ? captured.promise
194 : { result: { value: "still responsive" } },
195 );
196 const cdp = { send } as unknown as CDPSession;
197 const control = new SessionControl("agent");
198 let outcome: unknown;
199 const capture = control
200 .agent("agent", () => ServerBrowserPage.captureViewport(cdp, { format: "png" }))
201 .catch((cause: unknown) => {
202 outcome = cause;
203 });
204 const evaluation = control.agent("agent", () =>
205 ServerBrowserPage.evaluate(cdp, { expression: "document.title" }, 1_000),
206 );
207​
208 await vi.advanceTimersByTimeAsync(3_000);
209 expect(outcome).toMatchObject({
210 tag: "PreviewAutomationExecutionError",
211 message: expect.stringContaining("not producing screenshot frames"),
212 });
213 await capture;
214 expect(await evaluation).toBe("still responsive");
215 expect(vi.getTimerCount()).toBe(0);
216​
217 captured.resolve({ data: "late-frame" });
218 await captured.promise;
219 expect(outcome).toBeInstanceOf(ServerBrowserPage.ServerBrowserOperationError);
220 expect(send.mock.calls.map(([method]) => method)).toEqual([
221 "Page.captureScreenshot",
222 "Runtime.evaluate",
223 ]);
224 } finally {
225 vi.useRealTimers();
226 }
227 });
228});
229​
230describe("server browser element refs", () => {
231 let browser: Browser;
232 let context: BrowserContext;
233 let page: Page;
234 let cdp: CDPSession;
235​
236 beforeAll(async () => {
237 browser = await chromium.launch({ headless: true });
238 });
239 afterAll(async () => {
240 await browser?.close();
241 });
242 beforeEach(async () => {
243 context = await browser.newContext();
244 page = await context.newPage();
245 cdp = await context.newCDPSession(page);
246 });
247 afterEach(async () => {
248 await context.close();
249 });
250​
251 const takeSnapshot = () =>
252 ServerBrowserPage.snapshot({
253 page,
254 cdp,
255 renderScale: 1,
256 consoleEntries: [],
257 networkEntries: [],
258 actionTimeline: [],
259 });
260 const locators = (tree: unknown) => {
261 expect(typeof tree).toBe("string");
262 return Array.from(
263 String(tree).matchAll(/\[ref=([^\]]+)\]/g),
264 (match) => `aria-ref=${match[1]}`,
265 );
266 };
267 const buttonLocator = (tree: unknown, name: string) => {
268 const line = String(tree)
269 .split("\n")
270 .find((line) => line.includes(`button "${name}"`));
271 const locator = locators(line)[0];
272 expect(locator).toBeDefined();
273 return locator!;
274 };
275 const repeatedRows = `<ul>${Array.from({ length: 5 }, (_, i) => `<li>row ${i + 1}<button data-testid="delete-row" onclick="this.parentElement.remove()">delete</button></li>`).join("")}</ul>`;
276​
277 it("does not report an empty interactiveElements list beside a tree full of controls", async () => {
278 await page.setContent(
279 `<a href="#signin">Sign in</a><button>Open menu</button><button>Dismiss local database notice</button>`,
280 );
281 const result = await takeSnapshot();
282 expect(buttonLocator(result.accessibilityTree, "Open menu")).toBeDefined();
283 expect(String(result.accessibilityTree)).toContain('link "Sign in"');
284 const elements = (
285 result as { readonly interactiveElements?: ReadonlyArray<{ readonly name: string }> }
286 ).interactiveElements;
287 if (elements !== undefined) {
288 expect(elements.map((element) => element.name)).toEqual(
289 expect.arrayContaining(["Sign in", "Open menu", "Dismiss local database notice"]),
290 );
291 }
292 });
293​
294 it("clicks the fifth repeated delete control without touching row one", async () => {
295 await page.setContent(repeatedRows);
296 const result = await takeSnapshot();
297 const buttons = String(result.accessibilityTree)
298 .split("\n")
299 .filter((line) => line.includes('button "delete"'));
300 expect(buttons).toHaveLength(5);
301 await ServerBrowserPage.click(page, { locator: locators(buttons[4])[0]!, timeoutMs: 1_000 });
302 expect(await page.locator("li").allTextContents()).toEqual([
303 "row 1delete",
304 "row 2delete",
305 "row 3delete",
306 "row 4delete",
307 ]);
308 });
309​
310 it("returns from a click once it opens a dialog", async () => {
311 await page.setContent(
312 `<button onclick="document.body.dataset.answer = String(confirm('sure?'))">Confirm</button>`,
313 );
314 const dialog = new Promise<import("playwright-core").Dialog>((resolve) =>
315 page.once("dialog", resolve),
316 );
317 await ServerBrowserPage.click(page, {
318 locator: buttonLocator((await takeSnapshot()).accessibilityTree, "Confirm"),
319 timeoutMs: 1_000,
320 });
321 await (await dialog).accept();
322 await expect.poll(() => page.locator("body").getAttribute("data-answer")).toBe("true");
323 });
324​
325 it("rejects ambiguous CSS controls without clicking any row", async () => {
326 await page.setContent(repeatedRows);
327 await expect(
328 ServerBrowserPage.click(page, {
329 selector: 'button[data-testid="delete-row"]',
330 timeoutMs: 1_000,
331 }),
332 ).rejects.toThrow(/strict mode violation/);
333 expect(await page.locator("li").count()).toBe(5);
334 });
335​
336 it("tells a click target that matches nothing from one that never becomes clickable", async () => {
337 await page.setContent(`<button hidden>hidden</button>`);
338 const failure = (selector: string) =>
339 ServerBrowserPage.click(page, { selector, timeoutMs: 500 }).then(
340 () => expect.unreachable(),
341 ServerBrowserPage.toOperationError,
342 );
343​
344 const absent = await failure(".definitely-no-such-t3-target");
345 expect(absent.tag).toBe("PreviewAutomationTimeoutError");
346 expect(absent.message).toBe(
347 'The click may have happened and removed its target or navigated; check the page before retrying. No element matches ".definitely-no-such-t3-target" after the timeout; take a fresh snapshot and use its locator.',
348 );
349 expect(absent.cause).toMatchObject({ name: "TimeoutError" });
350 const hidden = await failure("button");
351 expect(hidden.tag).toBe("PreviewAutomationTimeoutError");
352 expect(hidden.message).toBe(
353 'The click may have happened; check the page before retrying. "button" still matches an element after the timeout. Playwright last saw: element is not visible.',
354 );
355 });
356​
357 it("gives a late target only the click's remaining time, not a fresh timeout", async () => {
358 await page.setContent(`<script>
359 setTimeout(() => document.body.insertAdjacentHTML("beforeend",
360 '<button id="save" disabled onclick="document.body.dataset.clicked = 1">Save</button>'), 1000);
361 setTimeout(() => document.querySelector("#save").disabled = false, 2500);
362 </script>`);
363 await expect(
364 ServerBrowserPage.click(page, { selector: "#save", timeoutMs: 2_000 }),
365 ).rejects.toThrow();
366 expect(await page.locator("body").getAttribute("data-clicked")).toBeNull();
367 });
368​
369 it("does not retarget a removed ref to a replacement node", async () => {
370 await page.setContent("<button onclick=\"this.textContent='clicked'\">original</button>");
371 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "original");
372 await page.setContent("<button onclick=\"this.textContent='clicked'\">replacement</button>");
373 await expect(ServerBrowserPage.click(page, { locator, timeoutMs: 100 })).rejects.toThrow();
374 expect(await page.locator("button").textContent()).toBe("replacement");
375 });
376​
377 it("targets iframe input refs and preserves the parent form", async () => {
378 await page.setContent(
379 '<input aria-label="parent"><iframe srcdoc="<input aria-label=child>"></iframe>',
380 );
381 await page.frameLocator("iframe").getByRole("textbox").waitFor();
382 const result = await takeSnapshot();
383 const line = String(result.accessibilityTree)
384 .split("\n")
385 .find((line) => line.includes('textbox "child"'));
386 const locator = locators(line)[0]!;
387 await ServerBrowserPage.type(page, { locator, text: "inside iframe", clear: true });
388 expect(await page.frameLocator("iframe").getByRole("textbox").inputValue()).toBe(
389 "inside iframe",
390 );
391 expect(await page.getByRole("textbox", { name: "parent" }).inputValue()).toBe("");
392 });
393​
394 it("types after a click by coordinates into a shadow-root field, and refuses a field inside an editable frame", async () => {
395 await page.setContent(
396 `<div id="host"></div><div contenteditable="true"><iframe srcdoc="<input id=inner>"></iframe></div><script>document.getElementById("host").attachShadow({mode:"open"}).innerHTML = "<input id=field>";</script>`,
397 );
398 const field = page.locator("#host #field");
399 const box = (await field.boundingBox())!;
400 await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
401 await ServerBrowserPage.type(page, { text: "shadow" });
402 expect(await field.inputValue()).toBe("shadow");
403​
404 // Refused for now: focus inside a frame cannot be checked from the top document.
405 const inner = page.frameLocator("iframe").locator("#inner");
406 await inner.click();
407 await expect(ServerBrowserPage.type(page, { text: "frame" })).rejects.toMatchObject({
408 tag: "PreviewAutomationTargetNotEditableError",
409 });
410 expect(await inner.inputValue()).toBe("");
411 });
412​
413 it("types into a field that builds its value from keydown, with and without clear", async () => {
414 await page.setContent(
415 `<input id=a><input id=b><script>for(const f of[a,b]){f.keys="";f.onkeydown=e=>{if(e.key.length===1){e.preventDefault();f.keys+=e.key}}}</script>`,
416 );
417 const keys = (selector: string) =>
418 page.locator(selector).evaluate((field) => (field as unknown as { keys: string }).keys);
419 await ServerBrowserPage.type(page, { locator: "#a", text: "girona42" });
420 expect(await keys("#a")).toBe("girona42");
421 await ServerBrowserPage.type(page, { locator: "#b", text: "girona42", clear: true });
422 expect(await keys("#b")).toBe("girona42");
423 await ServerBrowserPage.type(page, { locator: "#b", text: "a".repeat(501), clear: true });
424 expect(await keys("#b")).toBe(`girona42${"a".repeat(501)}`);
425​
426 await page.setContent(
427 `<form onsubmit="event.preventDefault();sent.value='sent'"><label for=e>Email</label><input id=e value=old><input id=d type=date value=2020-02-02><label>Tint <input id=c type=color></label><input id=r type=range><textarea id=t></textarea><input id=sent></form>`,
428 );
429 await ServerBrowserPage.type(page, { locator: "text=Email", text: "a@b.c", clear: true });
430 expect(await page.locator("#e").inputValue()).toBe("a@b.c");
431 await ServerBrowserPage.type(page, { locator: "#d", text: "2026-01-31", clear: true });
432 expect(await page.locator("#d").inputValue()).toBe("2026-01-31");
433 await ServerBrowserPage.type(page, { locator: "text=Tint", text: "#ff0000", clear: true });
434 expect(await page.locator("#c").inputValue()).toBe("#ff0000");
435 await ServerBrowserPage.type(page, { locator: "#r", text: "70", clear: true });
436 expect(await page.locator("#r").inputValue()).toBe("70");
437 await ServerBrowserPage.type(page, { locator: "#e", text: "x\ny" });
438 await ServerBrowserPage.type(page, { locator: "#t", text: "one\r\ntwo" });
439 expect(await page.locator("#t").inputValue()).toBe("one\ntwo");
440 expect(await page.locator("#sent").inputValue()).toBe("");
441 });
442​
443 it("shows dotted fields as dots wherever their value appears, keeping text values and refs", async () => {
444 await page.setContent(`
445 <table><tr><td>password:</td><td><input id="pw" type="password" aria-label="Password"></td></tr></table>
446 <input aria-label="Username" value="maria">
447 <input type="password" aria-label='saved" [ref=e2]: x' placeholder="hint" value="saved-pass">
448 <input type="password" role="combobox" aria-label="Code" value="role-pass">
449 <input aria-label="PIN" style="-webkit-text-security: disc" value="styled-pass">
450 <div contenteditable style="-webkit-text-security: disc">editable-pass</div>
451 <iframe srcdoc="<input type=password aria-label=child value=frame-pass>"></iframe>
452 <iframe id="blank" src="javascript:false"></iframe>
453 <p>Order styled-pass-2</p>
454 <script>
455 // A frame that never commits a document, filled by its parent.
456 blank.contentDocument.body.innerHTML = "<input type=password aria-label=blank value=blank-pass>";
457 // Page script can't change the value the snapshot sees.
458 Object.defineProperty(HTMLInputElement.prototype, "value", { get: () => "" });
459 </script>`);
460 await page.frameLocator("iframe[srcdoc]").getByRole("textbox").waitFor();
461 await ServerBrowserPage.type(page, { locator: "#pw", text: "typed-pass" });
462 const result = await takeSnapshot();
463 const tree = String(result.accessibilityTree);
464 expect(tree).toContain('textbox "blank"');
465 expect(tree).not.toMatch(
466 /typed-pass|saved-pass|role-pass|styled-pass|editable-pass|frame-pass|blank-pass/,
467 );
468 expect(result.visibleText).not.toContain("editable-pass");
469 expect(result.visibleText).toContain("Order ••••••••-2");
470 expect(tree).toMatch(/textbox "Username" [^\n]*: maria$/m);
471 const line = tree.split("\n").find((line) => line.includes('textbox "Password"'));
472 expect(line).toMatch(/: •+$/);
473 await ServerBrowserPage.type(page, { locator: locators(line)[0]!, text: "next", clear: true });
474 expect(await page.locator("#pw").inputValue()).toBe("next");
475 });
476​
477 it("masks dotted values in page text next to punctuation, with odd spaces, and at the cut", async () => {
478 await page.setContent(`
479 <input type="password" aria-label="PIN" value="123">
480 <input type="password" aria-label="Phrase" value="open&nbsp;sesame">
481 <p>PIN: 123. Code (123) id 1234</p>
482 <p>open&nbsp;sesame</p>`);
483 const text = (await takeSnapshot()).visibleText;
484 expect(text).toContain("PIN: ••••••••. Code (••••••••) id 1234");
485 expect(text).not.toMatch(/open|sesame/);
486 await page.setContent(`
487 <p>${"x".repeat(19_995)}long-secret</p>
488 <input type="password" aria-label="Long" value="long-secret">`);
489 const cut = (await takeSnapshot()).visibleText;
490 expect(cut.length).toBe(20_000);
491 expect(cut.slice(-8)).toBe("xxx•••••");
492 });
493​
494 it("shows a data: link or blocked data: navigation by media type only", async () => {
495 // Chromium keeps raw spaces and quotes in both, so a payload can't be cut at either.
496 await page.setContent(`
497 <a download href="data:text/plain;charset=&quot;a,b&quot;,head PAYLOAD'tail">Key</a>
498 <a href="https://example.com/data:report,2026">Report</a>
499 <a href="#">data:text/plain,label</a>
500 <a href='"data:text/plain,relative'>Relative</a>
501 <a href=" data:text/plain,PAYLOAD">Spaced</a>
502 <a href="da&#9;ta:text/plain,PAYLOAD">Tabbed</a>
503 <a href="data:text/plain,head&#x2028;PAYLOAD">Separated</a>
504 <a href="data:PAYLOAD,x">Typeless</a>
505 <a href="&#11;data:text/plain,PAYLOAD">Vertical tab</a>
506 <a href="&#8;data:text/plain,PAYLOAD">Backspace</a>
507 <a id="controlled">Controlled</a>
508 <a id="escaped">Escaped</a>
509 <script>
510 controlled.href = "\\x01data:text/plain,PAYLOAD";
511 escaped.href = "\\x02da\\tta:text/plain,PAYLOAD";
512 </script>`);
513 const tree = String((await takeSnapshot()).accessibilityTree);
514 expect(tree.match(/\/url: data:text\/plain,…$/gm)).toHaveLength(8);
515 expect(tree).toContain("/url: data:,…");
516 expect(tree).toContain("/url: https://example.com/data:report,2026");
517 expect(tree).toMatch(/link "data:text\/plain,label" \[ref=t3-/);
518 expect(tree).not.toMatch(/PAYLOAD|tail|charset|\u2028/);
519 expect(tree).toContain('/url: "\\"data:text/plain,relative"');
520 });
521​
522 it("redacts a data: link whose scheme a password value would mask", async () => {
523 await page.setContent(`
524 <input type="password" aria-label="Scheme" value="data">
525 <a download href="data:text/plain,PAYLOAD">Key</a>`);
526 const tree = String((await takeSnapshot()).accessibilityTree);
527 expect(tree).toContain("/url: ••••••••:text/plain,…");
528 expect(tree).not.toContain("PAYLOAD");
529 });
530​
531 it("shows a data: page's own URL by media type only", async () => {
532 await page.goto("data:text/html,<title>Key</title>PAYLOAD");
533 expect((await takeSnapshot()).url).toBe("data:text/html,…");
534 });
535​
536 it("rejects refs from another tab", async () => {
537 await page.setContent("<button>same label</button>");
538 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "same label");
539 const other = await context.newPage();
540 await other.setContent("<button>same label</button>");
541 await expect(ServerBrowserPage.click(other, { locator })).rejects.toThrow(/another tab/);
542 });
543​
544 it("revokes refs after navigation even when labels are identical", async () => {
545 await page.goto("data:text/html,<button>continue</button>");
546 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "continue");
547 await page.goto("data:text/html,<button>continue</button><p>new document</p>");
548 await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/);
549 });
550​
551 it.each(["aria-ref=e1", " aria-ref=e1", "css=body >> aria-ref=e1"])(
552 "does not allow native refs to bypass generation validation (%s)",
553 async (locator) => {
554 await page.setContent("<button>continue</button>");
555 await takeSnapshot();
556 await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/);
557 },
558 );
559​
560 it("preserves quoted attribute values containing ref engine text", async () => {
561 await page.setContent(
562 '<button data-example=" >> aria-ref=e1" onclick="this.textContent=\'saved\'">save</button>',
563 );
564 await ServerBrowserPage.click(page, { selector: 'button[data-example=" >> aria-ref=e1"]' });
565 expect(await page.locator("button").textContent()).toBe("saved");
566 });
567​
568 it("evaluates top-level await and returns the last expression's value", async () => {
569 await page.setContent("<title>Ready</title>");
570 const result = await ServerBrowserPage.evaluate(
571 cdp,
572 { expression: "await Promise.resolve(); document.title" },
573 5_000,
574 );
575 expect(result).toBe("Ready");
576 });
577​
578 it("returns object contents even when a legacy caller asks for a remote reference", async () => {
579 const input = decodeEvaluateInput({
580 expression: "({ answer: 42, nested: { ready: true } })",
581 returnByValue: false,
582 });
583 const result = await ServerBrowserPage.evaluate(cdp, input, 5_000);
584 expect(result).toEqual({ answer: 42, nested: { ready: true } });
585 });
586​
587 it("still awaits the promise an async function returns", async () => {
588 const result = await ServerBrowserPage.evaluate(
589 cdp,
590 { expression: "(async () => { await 0; return 1 })()" },
591 5_000,
592 );
593 expect(result).toBe(1);
594 });
595​
596 it("does not rerun an expression whose SyntaxError is thrown at runtime", async () => {
597 const evaluation = ServerBrowserPage.evaluate(
598 cdp,
599 { expression: "window.runs = (window.runs ?? 0) + 1; new Function('await 0')" },
600 5_000,
601 );
602 await expect(evaluation).rejects.toThrow("await is only valid");
603 expect(await page.evaluate("window.runs")).toBe(1);
604 });
605​
606 it("does not rerun an expression whose awaited browser call rejects with a SyntaxError", async () => {
607 let posts = 0;
608 await page.route("http://preview.test/**", (route) => {
609 if (route.request().method() === "POST") posts++;
610 return route.fulfill({ contentType: "text/html", body: "<title>Ready</title>" });
611 });
612 await page.goto("http://preview.test/");
613 const evaluation = ServerBrowserPage.evaluate(
614 cdp,
615 {
616 expression:
617 "(async () => { const r = await fetch('/api', { method: 'POST' }); return r.json() })()",
618 },
619 5_000,
620 );
621 await expect(evaluation).rejects.toThrow("is not valid JSON");
622 expect(posts).toBe(1);
623 });
624​
625 it("returns the result of a top-level await expression that reloads the page", async () => {
626 await page.route("http://preview.test/", (route) =>
627 route.fulfill({ contentType: "text/html", body: "<title>Ready</title>" }),
628 );
629 await page.goto("http://preview.test/");
630 const result = await ServerBrowserPage.evaluate(
631 cdp,
632 { expression: "await 0; location.reload(); ({ clicked: true })" },
633 5_000,
634 );
635 expect(result).toEqual({ clicked: true });
636 });
637});
638​
639describe("server browser snapshot screenshot", () => {
640 let browser: Browser;
641 let context: BrowserContext;
642​
643 beforeAll(async () => {
644 // ServerBrowserContexts launches with these, and the capture scale depends on them.
645 browser = await chromium.launch({
646 headless: true,
647 args: ["--disable-gpu", "--force-device-scale-factor=2"],
648 });
649 });
650 afterAll(async () => {
651 await browser?.close();
652 });
653 beforeEach(async () => {
654 context = await browser.newContext({
655 viewport: { width: 1280, height: 800 },
656 deviceScaleFactor: 2,
657 });
658 });
659 afterEach(async () => {
660 await context.close();
661 });
662​
663 // Blue on the left half and red on the right, so a mirrored left half shows up on the right.
664 const halves = (overlay: string) => `
665 <style>
666 body { margin: 0; background: white; }
667 .half { position: absolute; top: 0; width: 640px; height: 800px; }
668 .overlay { position: fixed; inset: 0; ${overlay} }
669 </style>
670 <div class="half" style="left: 0; background: #2563eb"></div>
671 <div class="half" style="left: 640px; background: #ef4444"></div>
672 <div class="overlay"></div>`;
673​
674 const screenshotOf = async (html: string) => {
675 const page = await context.newPage();
676 await page.setContent(html);
677 const input = {
678 page,
679 cdp: await context.newCDPSession(page),
680 renderScale: 2,
681 fullScreenshot: true,
682 consoleEntries: [],
683 networkEntries: [],
684 actionTimeline: [],
685 };
686 const { screenshot, fullScreenshot } = await ServerBrowserPage.snapshot(input);
687 // The server has no DOM types, so the decoder runs as page source.
688 const points = [
689 [0.15, 0.75],
690 [0.85, 0.25],
691 [0.85, 0.75],
692 ];
693 const pixels = (await page.evaluate(`(async () => {
694 const bytes = Uint8Array.from(atob(${JSON.stringify(screenshot.data)}), (char) => char.charCodeAt(0));
695 const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/png" }));
696 const canvas = document.createElement("canvas");
697 canvas.width = bitmap.width;
698 canvas.height = bitmap.height;
699 const context = canvas.getContext("2d");
700 context.drawImage(bitmap, 0, 0);
701 return ${JSON.stringify(points)}.map(([x, y]) =>
702 Array.from(context.getImageData(x * bitmap.width, y * bitmap.height, 1, 1).data),
703 );
704 })()`)) as Array<[number, number, number, number]>;
705 return { screenshot, fullScreenshot, pixels, input };
706 };
707 const colorOf = ([red, green, blue]: readonly [number, number, number, number]) =>
708 blue - red > 100 ? "blue" : red - blue > 100 ? "red" : `rgb(${red}, ${green}, ${blue})`;
709​
710 it("captures a blurred backdrop-filter page as rendered, not mirrored", async () => {
711 const { screenshot, pixels } = await screenshotOf(halves("backdrop-filter: blur(4px);"));
712​
713 expect({
714 size: [screenshot.width, screenshot.height],
715 colors: pixels.map(colorOf),
716 }).toEqual({ size: [1280, 800], colors: ["blue", "red", "red"] });
717 });
718​
719 it("captures a plain page at the shrunk size with its content in place", async () => {
720 const { screenshot, fullScreenshot, pixels, input } = await screenshotOf(halves(""));
721 const metadata = await ServerBrowserPage.snapshotMetadata(input);
722​
723 expect({
724 size: [screenshot.width, screenshot.height],
725 fullSize: [fullScreenshot?.width, fullScreenshot?.height],
726 metadataSize: metadata.screenshot,
727 colors: pixels.map(colorOf),
728 }).toEqual({
729 size: [1280, 800],
730 fullSize: [2560, 1600],
731 metadataSize: { width: 1280, height: 800 },
732 colors: ["blue", "red", "red"],
733 });
734 });
735​
736 it("records the destination of a finite entrance animation without waiting on infinite ones", async () => {
737 const page = await context.newPage();
738 await page.setContent(`
739 <style>
740 body { margin: 0; background: #2563eb; }
741 @keyframes enter { from { opacity: 0; } to { opacity: 1; } }
742 @keyframes pulse { from { opacity: 0.5; } to { opacity: 1; } }
743 button { animation: pulse 2s infinite; }
744 #paused { animation: enter 2s paused; }
745 #overlay { display: none; position: fixed; inset: 0; background: #ef4444; }
746 #overlay.open { display: block; animation: enter 200ms both; }
747 </style>
748 <button onclick="document.querySelector('#overlay').classList.add('open')">Open</button>
749 <div id="paused"></div>
750 <div id="overlay"></div>
751 `);
752 await page.getByRole("button", { name: "Open" }).click();
753 const frame = await ServerBrowserPage.captureFinalRecordingFrame(
754 await context.newCDPSession(page),
755 80,
756 );
757 expect(frame).toBeDefined();
758 const pixel = (await page.evaluate(`(async () => {
759 const bytes = Uint8Array.from(atob(${JSON.stringify(frame)}), char => char.charCodeAt(0));
760 const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/jpeg" }));
761 const canvas = document.createElement("canvas");
762 canvas.width = bitmap.width;
763 canvas.height = bitmap.height;
764 const context = canvas.getContext("2d");
765 context.drawImage(bitmap, 0, 0);
766 return Array.from(context.getImageData(bitmap.width / 2, bitmap.height / 2, 1, 1).data);
767 })()`)) as [number, number, number, number];
768 expect(colorOf(pixel)).toBe("red");
769 });
770​
771 it("shrinks the screenshot of an XML document, whose createElement makes no canvas", async () => {
772 const page = await context.newPage();
773 await page.goto("data:text/xml,<a/>");
774 const { screenshot } = await ServerBrowserPage.snapshot({
775 page,
776 cdp: await context.newCDPSession(page),
777 renderScale: 2,
778 consoleEntries: [],
779 networkEntries: [],
780 actionTimeline: [],
781 });
782​
783 expect([screenshot.width, screenshot.height]).toEqual([1280, 800]);
784 });
785});
786​
787describe("server browser drag", () => {
788 it("fails the drag, not the server, when it times out while the cursor is still moving", async () => {
789 const timedOut = new Error("locator.dragTo: Timeout 30000ms exceeded.");
790 const box = { x: 0, y: 0, width: 20, height: 20 };
791 const targetBox = Promise.withResolvers<typeof box>();
792 const page = {
793 locator: (selector: string) =>
794 selector === "#card"
795 ? {
796 scrollIntoViewIfNeeded: async () => {},
797 boundingBox: async () => box,
798 dragTo: () => Promise.reject(timedOut),
799 }
800 : { boundingBox: () => targetBox.promise },
801 } as unknown as Page;
802 const unobserved: Array<unknown> = [];
803 const onUnhandled = (reason: unknown) => unobserved.push(reason);
804 process.on("unhandledRejection", onUnhandled);
805 try {
806 let finished = false;
807 const settled = ServerBrowserPage.drag(page, { source: "#card", target: "#lane" }).then(
808 () => null,
809 (error: unknown) => error,
810 );
811 void settled.then(() => (finished = true));
812 // Two macrotask turns: Node reports a rejection nobody observed after the first.
813 for (let turn = 0; turn < 2; turn++) {
814 // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- Node emits unhandledRejection only between macrotasks; no promise can mark that point.
815 await new Promise((resolve) => setImmediate(resolve));
816 }
817 expect(finished).toBe(false);
818 targetBox.resolve(box);
819​
820 expect(await settled).toBe(timedOut);
821 expect(unobserved).toEqual([]);
822 } finally {
823 process.off("unhandledRejection", onUnhandled);
824 }
825 });
826​
827 it("moves the mouse after dragstart, so pages that track a drag with mousemove see it", async () => {
828 const browser = await chromium.launch({ headless: true });
829 try {
830 const page = await browser.newPage();
831 await page.setContent(`
832 <div style="display:flex;gap:40px">
833 <div id="source" draggable="true" style="width:200px;height:120px">source</div>
834 <div id="target" style="width:200px;height:120px">target</div>
835 </div>
836 <script>
837 window.events = [];
838 let dragging = false;
839 source.addEventListener("dragstart", (event) => {
840 event.preventDefault();
841 dragging = true;
842 events.push("dragstart");
843 });
844 addEventListener("mousemove", () => dragging && events.push("mousemove"));
845 addEventListener("mouseup", () => events.push("mouseup"));
846 </script>`);
847​
848 await ServerBrowserPage.drag(page, { source: "#source", target: "#target" });
849​
850 const events = (await page.evaluate("window.events")) as Array<string>;
851 expect(events.slice(0, 2)).toEqual(["dragstart", "mousemove"]);
852 expect(events.at(-1)).toBe("mouseup");
853 } finally {
854 await browser.close();
855 }
856 });
857});
858​
859describe("server browser action timeout", () => {
860 type StepOptions = { readonly timeout?: number };
861 it.each([
862 {
863 action: "hover",
864 act: (page: Page) => ServerBrowserPage.hover(page, { selector: "#a", timeoutMs: 9_000 }),
865 last: ["#a.hover 1"],
866 },
867 {
868 action: "drag",
869 act: (page: Page) =>
870 ServerBrowserPage.drag(page, { source: "#a", target: "#b", timeoutMs: 9_000 }),
871 last: ["#a.dragTo 1", "#b.boundingBox 1"],
872 },
873 ])("gives the $action's steps one shared timeout", async ({ act, last }) => {
874 let now = 0;
875 using _now = vi.spyOn(Date, "now").mockImplementation(() => now);
876 const steps: Array<string> = [];
877 const box = { x: 0, y: 0, width: 20, height: 20 };
878 const page = {
879 locator: (selector: string) => {
880 const record = (step: string, options: StepOptions) =>
881 steps.push(`${selector}.${step} ${options.timeout}`);
882 return {
883 // Each step that finds the target takes 5 of the 9 seconds.
884 scrollIntoViewIfNeeded: async (options: StepOptions) => {
885 record("scrollIntoViewIfNeeded", options);
886 now += 5_000;
887 },
888 boundingBox: async (options: StepOptions) => {
889 record("boundingBox", options);
890 now += 5_000;
891 return box;
892 },
893 hover: async (options: StepOptions) => record("hover", options),
894 dragTo: async (_target: unknown, options: StepOptions) => record("dragTo", options),
895 };
896 },
897 } as unknown as Page;
898​
899 await act(page);
900​
901 expect(steps).toEqual(["#a.scrollIntoViewIfNeeded 9000", "#a.boundingBox 4000", ...last]);
902 });
903});
904​
905describe("server browser click", () => {
906 it("clicks a target the page replaced while it was being scrolled into view", async () => {
907 let scrolls = 0;
908 const clicks: Array<unknown> = [];
909 const page = {
910 locator: () => ({
911 // Playwright resolves the node once; a page re-rendering it detaches that node.
912 scrollIntoViewIfNeeded: async () => {
913 if (scrolls++ === 0) {
914 throw new Error("locator.scrollIntoViewIfNeeded: Element is not attached to the DOM");
915 }
916 },
917 boundingBox: async () => ({ x: 0, y: 0, width: 20, height: 20 }),
918 click: async (options: unknown) => {
919 clicks.push(options);
920 },
921 count: async () => 1,
922 }),
923 once: () => {},
924 off: () => {},
925 } as unknown as Page;
926​
927 await expect(ServerBrowserPage.click(page, { selector: "#save" })).resolves.toEqual({
928 x: 10,
929 y: 10,
930 });
931 expect(clicks).toHaveLength(1);
932 });
933​
934 it("retries a replaced target only within the action's timeout", async () => {
935 vi.useFakeTimers();
936 try {
937 const timeouts: Array<number | undefined> = [];
938 const clicks: Array<unknown> = [];
939 const detached = new Error(
940 "locator.scrollIntoViewIfNeeded: Element is not attached to the DOM",
941 );
942 const page = {
943 locator: () => ({
944 scrollIntoViewIfNeeded: async (options?: { timeout?: number }) => {
945 timeouts.push(options?.timeout);
946 vi.advanceTimersByTime(60);
947 throw detached;
948 },
949 click: async (options: unknown) => {
950 clicks.push(options);
951 },
952 }),
953 } as unknown as Page;
954​
955 await expect(
956 ServerBrowserPage.click(page, { selector: "#save", timeoutMs: 100 }),
957 ).rejects.toBe(detached);
958 expect(timeouts).toEqual([100, 40]);
959 expect(clicks).toHaveLength(0);
960 } finally {
961 vi.useRealTimers();
962 }
963 });
964});
965​
966describe("server browser evaluate", () => {
967 it("does not retry a parse error that arrives after the timeout", async () => {
968 vi.useFakeTimers();
969 try {
970 const classic = Promise.withResolvers<unknown>();
971 const send = vi.fn((method: string) =>
972 method === "Runtime.evaluate" ? classic.promise : Promise.resolve({}),
973 );
974 const cdp = { send } as unknown as CDPSession;
975 const evaluation = ServerBrowserPage.evaluate(cdp, { expression: "await 0; 1" }, 10);
976 const rejected = expect(evaluation).rejects.toMatchObject({
977 tag: "PreviewAutomationTimeoutError",
978 });
979 await vi.advanceTimersByTimeAsync(10);
980 await rejected;
981 classic.resolve({
982 result: { type: "object" },
983 exceptionDetails: {
984 text: "Uncaught",
985 scriptId: "4",
986 exception: { type: "object", className: "SyntaxError" },
987 },
988 });
989 await classic.promise;
990 expect(send.mock.calls.map(([method]) => method)).toEqual([
991 "Runtime.evaluate",
992 "Runtime.terminateExecution",
993 ]);
994 } finally {
995 vi.useRealTimers();
996 }
997 });
998});
999​
1000describe("server browser type", () => {
1001 // As on a desktop tab whose Playwright utility world never answers.
1002 const stalledPage = (focusAnswer: () => Promise<unknown>, typed: string[]) =>
1003 ({
1004 locator: () => ({ last: () => ({ count: () => new Promise<number>(() => {}) }) }),
1005 evaluate: focusAnswer,
1006 keyboard: { type: async (text: string) => void typed.push(text) },
1007 }) as unknown as Page;
1008​
1009 it("types into the focused field when Playwright's utility world never answers", async () => {
1010 vi.useFakeTimers();
1011 try {
1012 const typed: string[] = [];
1013 let outcome: unknown = "pending";
1014 const page = stalledPage(async () => true, typed);
1015 void ServerBrowserPage.type(page, { text: "hello", timeoutMs: 300 }).then(
1016 () => (outcome = "typed"),
1017 (error: unknown) => (outcome = error),
1018 );
1019 await vi.advanceTimersByTimeAsync(300);
1020 expect(outcome).toBe("typed");
1021 expect(typed).toEqual(["hello"]);
1022 } finally {
1023 vi.useRealTimers();
1025 });
1026​
1027 it("stops at its timeout without typing when the page never answers", async () => {
1028 vi.useFakeTimers();
1029 try {
1030 const typed: string[] = [];
1031 let outcome: unknown = "pending";
1032 const page = stalledPage(() => new Promise(() => {}), typed);
1033 void ServerBrowserPage.type(page, { text: "hello", timeoutMs: 300 }).then(
1034 () => (outcome = "typed"),
1035 (error: unknown) => (outcome = error),
1036 );
1037 await vi.advanceTimersByTimeAsync(300);
1038 expect(outcome).toMatchObject({
1039 tag: "PreviewAutomationTimeoutError",
1040 detail: { timeoutMs: 300 },
1041 });
1042 expect(typed).toEqual([]);
1043​
1044 // A target whose element is found but whose page then stops answering.
1045 const fill = vi.fn(async () => {});
1046 const hung = {
1047 locator: () => ({ evaluate: () => new Promise(() => {}), fill }),
1048 keyboard: { type: async (text: string) => void typed.push(text) },
1049 } as unknown as Page;
1050 void ServerBrowserPage.type(hung, {
1051 locator: "#field",
1052 text: "hello",
1053 clear: true,
1054 timeoutMs: 300,
1055 }).then(
1056 () => (outcome = "typed"),
1057 (error: unknown) => (outcome = error),
1058 );
1059 outcome = "pending";
1060 await vi.advanceTimersByTimeAsync(300);
1061 expect(outcome).toMatchObject({
1062 tag: "PreviewAutomationTimeoutError",
1063 detail: { timeoutMs: 300 },
1064 });
1065 expect(fill).not.toHaveBeenCalled();
1066 expect(typed).toEqual([]);
1067 } finally {
1068 vi.useRealTimers();
1070 });
1071});
1072​
1073describe("server browser unresponsive script", () => {
1074 it("leaves a page that answers alone", async () => {
1075 const send = vi.fn(async (_method: string) => ({}));
1076 await ServerBrowserPage.stopUnresponsiveScript({ send } as unknown as CDPSession);
1077 expect(send.mock.calls.map(([method]) => method)).toEqual(["Runtime.evaluate"]);
1078 });
1079});
1080​
1081describe("server browser wait", () => {
1082 it("ends at its timeout when a check never answers", async () => {
1083 // As on a desktop tab whose Playwright utility world never answers.
1084 const page = {
1085 locator: () => ({ count: () => new Promise<number>(() => {}) }),
1086 } as unknown as Page;
1087 vi.useFakeTimers();
1088 try {
1089 let failure: unknown;
1090 void ServerBrowserPage.waitFor(page, { selector: "button", timeoutMs: 300 }).catch(
1091 (error: unknown) => (failure = error),
1092 );
1093 await vi.advanceTimersByTimeAsync(300);
1094 expect(failure).toMatchObject({ tag: "PreviewAutomationTimeoutError" });
1095 } finally {
1096 vi.useRealTimers();
1098 });
1099});
1100​
1101describe("server browser net errors", () => {
1102 it.each([
1103 ["net::ERR_CONNECTION_REFUSED", "ERR_CONNECTION_REFUSED", -102],
1105 "page.goto: net::ERR_HTTP2_PROTOCOL_ERROR at https://localhost:5173/",
1106 "ERR_HTTP2_PROTOCOL_ERROR",
1107 -2,
1108 ],
1109 ["net::ERR_TLS13_DOWNGRADE_DETECTED", "ERR_TLS13_DOWNGRADE_DETECTED", -2],
1110 ])("reads the whole error name from %j", (errorText, description, code) => {
1111 expect(ServerBrowserPage.parseNetError(errorText)).toEqual({ description, code });
1112 });
1113});