Open History to see the last commit
1import { describe, expect, it, vi } from "vite-plus/test";
2
3import { createCdpRelayConnection, type CdpRelayTarget } from "./CdpRelay.ts";
4
5const makeTarget = (
6 send: CdpRelayTarget["send"],
7 setDownloadDirectory: CdpRelayTarget["setDownloadDirectory"] = () => {},
8): CdpRelayTarget => ({
9 send,
10 targetId: async () => "GUEST-TARGET",
11 url: () => "http://localhost:4719/",
12 title: () => "Fixture",
13 userAgent: () => "Electron",
14 setDownloadDirectory,
15});
16
17const makeRelay = (target: CdpRelayTarget, write: (raw: string) => void) =>
18 createCdpRelayConnection(target, write, () => {});
19
20// Each relay reply resolves after a few microtasks; one macrotask lets them all land.
21// oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- a zero-delay macrotask boundary, not a wait for time
22const settle = () => new Promise<void>((resolve) => setImmediate(resolve));
23
24describe("CDP relay", () => {
25 it("announces only the tab's page, under its real target id", async () => {
26 const written: Array<Record<string, unknown>> = [];
27 const relay = makeRelay(makeTarget(vi.fn()), (raw) => written.push(JSON.parse(raw)));
28 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
29 relay.receive(JSON.stringify({ id: 2, method: "Target.createTarget", params: {} }));
30 await settle();
31 const attach = written.findIndex((message) => message["id"] === 1);
32 expect(written.slice(attach, attach + 2)).toEqual([
33 { id: 1, result: {} },
34 {
35 method: "Target.attachedToTarget",
36 params: expect.objectContaining({
37 sessionId: "t3-preview-page",
38 targetInfo: expect.objectContaining({ targetId: "GUEST-TARGET", type: "page" }),
39 }),
40 },
41 ]);
42 expect(written).toContainEqual({
43 id: 2,
44 error: expect.objectContaining({ message: expect.stringContaining("createTarget") }),
45 });
46 });
47
48 it("forwards page commands to the tab and lets a slow one finish last", async () => {
49 const pending: Array<() => void> = [];
50 const send = vi.fn(
51 (method: string) =>
52 new Promise<unknown>((resolve) => pending.push(() => resolve({ method }))),
53 );
54 const written: Array<Record<string, unknown>> = [];
55 const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw)));
56 relay.receive(
57 JSON.stringify({ id: 5, method: "Page.captureScreenshot", sessionId: "t3-preview-page" }),
58 );
59 relay.receive(JSON.stringify({ id: 6, method: "DOM.enable", sessionId: "iframe-session" }));
60 pending[1]!();
61 await settle();
62 expect(written).toEqual([
63 { id: 6, result: { method: "DOM.enable" }, sessionId: "iframe-session" },
64 ]);
65 pending[0]!();
66 await settle();
67 expect(send).toHaveBeenNthCalledWith(1, "Page.captureScreenshot", {}, undefined, undefined);
68 expect(send).toHaveBeenNthCalledWith(2, "DOM.enable", {}, "iframe-session", undefined);
69 expect(written.at(-1)).toEqual({
70 id: 5,
71 result: { method: "Page.captureScreenshot" },
72 sessionId: "t3-preview-page",
73 });
74 });
75
76 it("resumes paused child frames, so cross-site iframes run", async () => {
77 const send = vi.fn(async () => ({}));
78 const relay = makeRelay(makeTarget(send), () => {});
79 relay.receive(
80 JSON.stringify({
81 id: 1,
82 method: "Runtime.runIfWaitingForDebugger",
83 sessionId: "t3-preview-page",
84 }),
85 );
86 relay.receive(
87 JSON.stringify({
88 id: 2,
89 method: "Runtime.runIfWaitingForDebugger",
90 sessionId: "iframe-session",
91 }),
92 );
93 await settle();
94 expect(send.mock.calls).toEqual([
95 ["Runtime.runIfWaitingForDebugger", {}, "iframe-session", undefined],
96 ]);
97 });
98
99 // Playwright enables focus emulation on every page it connects to, and Chromium then
100 // counts the guest as captured: a preview the panel hides keeps its timers unthrottled.
101 it("acknowledges Playwright's focus emulation without forcing it onto the guest", async () => {
102 const send = vi.fn(async () => ({}));
103 const written: Array<Record<string, unknown>> = [];
104 const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw)));
105 relay.receive(
106 JSON.stringify({
107 id: 1,
108 method: "Emulation.setFocusEmulationEnabled",
109 params: { enabled: true },
110 sessionId: "t3-preview-page",
111 }),
112 );
113 await settle();
114 expect(written).toEqual([{ id: 1, result: {}, sessionId: "t3-preview-page" }]);
115 expect(send).not.toHaveBeenCalled();
116 });
117
118 it("routes tab events to the page session once the page is announced", async () => {
119 const written: Array<Record<string, unknown>> = [];
120 const relay = makeRelay(makeTarget(vi.fn()), (raw) => written.push(JSON.parse(raw)));
121 relay.event("Page.loadEventFired", {}, undefined);
122 expect(written).toEqual([]);
123 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
124 await settle();
125 relay.event("Page.loadEventFired", { timestamp: 1 }, "");
126 relay.event("Runtime.consoleAPICalled", {}, "iframe-session");
127 expect(written.slice(-2)).toEqual([
128 { method: "Page.loadEventFired", params: { timestamp: 1 }, sessionId: "t3-preview-page" },
129 { method: "Runtime.consoleAPICalled", params: {}, sessionId: "iframe-session" },
130 ]);
131 });
132});
133
134describe("CDP relay extra sessions", () => {
135 it("gives a second page session the page's commands and events", async () => {
136 const send = vi.fn(async () => ({}));
137 const written: Array<Record<string, unknown>> = [];
138 const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw)));
139 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
140 relay.receive(JSON.stringify({ id: 2, method: "Target.attachToBrowserTarget" }));
141 await settle();
142 const browserSession = (written.find((m) => m["id"] === 2)!["result"] as { sessionId: string })
143 .sessionId;
144 relay.receive(
145 JSON.stringify({
146 id: 3,
147 method: "Target.attachToTarget",
148 params: { targetId: "GUEST-TARGET", flatten: true },
149 sessionId: browserSession,
150 }),
151 );
152 relay.receive(
153 JSON.stringify({
154 id: 4,
155 method: "Target.attachToTarget",
156 params: { targetId: "SOMETHING-ELSE" },
157 sessionId: browserSession,
158 }),
159 );
160 await settle();
161 const extra = (written.find((m) => m["id"] === 3)!["result"] as { sessionId: string })
162 .sessionId;
163 expect(written.find((m) => m["id"] === 4)).toHaveProperty("error");
164 relay.receive(JSON.stringify({ id: 5, method: "Page.startScreencast", sessionId: extra }));
165 await settle();
166 expect(send).toHaveBeenLastCalledWith("Page.startScreencast", {}, undefined, extra);
167 written.length = 0;
168 relay.event("Page.screencastFrame", { data: "x" }, undefined);
169 expect(written.map((m) => m["sessionId"])).toEqual(["t3-preview-page", extra]);
170 });
171});
172
173describe("CDP relay downloads", () => {
174 it("applies the server's download directory and reports downloads on the root session", async () => {
175 const send = vi.fn(async () => ({}));
176 const directories: Array<string | null> = [];
177 const written: Array<Record<string, unknown>> = [];
178 const relay = makeRelay(
179 makeTarget(send, (directory) => directories.push(directory)),
180 (raw) => written.push(JSON.parse(raw)),
181 );
182 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
183 relay.receive(
184 JSON.stringify({
185 id: 2,
186 method: "Browser.setDownloadBehavior",
187 params: {
188 behavior: "allowAndName",
189 browserContextId: "t3-preview",
190 downloadPath: "/srv/artifacts",
191 eventsEnabled: true,
192 },
193 }),
194 );
195 await settle();
196 expect(directories).toEqual(["/srv/artifacts"]);
197 expect(send).toHaveBeenCalledWith(
198 "Browser.setDownloadBehavior",
199 { behavior: "allowAndName", downloadPath: "/srv/artifacts", eventsEnabled: true },
200 undefined,
201 );
202 written.length = 0;
203 relay.event("Browser.downloadWillBegin", { guid: "g1", suggestedFilename: "r.csv" }, "");
204 expect(written).toEqual([
205 { method: "Browser.downloadWillBegin", params: { guid: "g1", suggestedFilename: "r.csv" } },
206 ]);
207 });
208});
209
210describe("CDP relay payload budget", () => {
211 // 2,048 references to one 40 KiB string: about 80 MiB once serialized, little memory here.
212 const oversized = Array(2048).fill("x".repeat(40 * 1024));
213
214 it("fails only an oversized reply and still returns a large screenshot", async () => {
215 const screenshot = "A".repeat(16 * 1024 * 1024);
216 const send = vi.fn(async (method: string) =>
217 method === "DOM.getDocument" ? { nodes: oversized } : { data: screenshot },
218 );
219 const written: Array<Record<string, unknown>> = [];
220 const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw)));
221 relay.receive(
222 JSON.stringify({ id: 1, method: "DOM.getDocument", sessionId: "t3-preview-page" }),
223 );
224 relay.receive(
225 JSON.stringify({ id: 2, method: "Page.captureScreenshot", sessionId: "t3-preview-page" }),
226 );
227 await settle();
228
229 const replies = written.map(({ id, error, result }) => ({
230 id,
231 error,
232 size: (result as { data?: string } | undefined)?.data?.length,
233 }));
234 expect(replies).toEqual([
235 { id: 1, error: { code: -32000, message: "CDP payload too large" }, size: undefined },
236 { id: 2, error: undefined, size: screenshot.length },
237 ]);
238 });
239
240 it.each([
241 { args: oversized },
242 { args: "\u0001".repeat(12 * 1024 * 1024) },
243 { args: Array(2_700_000).fill(-0.0000010000000000000002) },
244 ])("closes instead of dropping an oversized event (%#)", async ({ args }) => {
245 const written: Array<Record<string, unknown>> = [];
246 const close = vi.fn();
247 const relay = createCdpRelayConnection(
248 makeTarget(vi.fn()),
249 (raw) => written.push(JSON.parse(raw)),
250 close,
251 );
252 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
253 await settle();
254 written.length = 0;
255
256 relay.event("Runtime.consoleAPICalled", { args }, "");
257 relay.event("Page.loadEventFired", { timestamp: 1 }, "");
258
259 relay.receive(JSON.stringify({ id: 2, method: "Target.setAutoAttach" }));
260 expect(close).toHaveBeenCalledOnce();
261 expect(written.map((message) => message["method"])).toEqual([]);
262 });
263});