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
17// Each relay reply resolves after a few microtasks; one macrotask lets them all land.
18// oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- a zero-delay macrotask boundary, not a wait for time
19const settle = () => new Promise<void>((resolve) => setImmediate(resolve));
20
21describe("CDP relay", () => {
22 it("announces only the tab's page, under its real target id", async () => {
23 const written: Array<Record<string, unknown>> = [];
24 const relay = createCdpRelayConnection(makeTarget(vi.fn()), (raw) =>
25 written.push(JSON.parse(raw)),
26 );
27 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
28 relay.receive(JSON.stringify({ id: 2, method: "Target.createTarget", params: {} }));
29 await settle();
30 const attach = written.findIndex((message) => message["id"] === 1);
31 expect(written.slice(attach, attach + 2)).toEqual([
32 { id: 1, result: {} },
33 {
34 method: "Target.attachedToTarget",
35 params: expect.objectContaining({
36 sessionId: "t3-preview-page",
37 targetInfo: expect.objectContaining({ targetId: "GUEST-TARGET", type: "page" }),
38 }),
39 },
40 ]);
41 expect(written).toContainEqual({
42 id: 2,
43 error: expect.objectContaining({ message: expect.stringContaining("createTarget") }),
44 });
45 });
46
47 it("forwards page commands to the tab and lets a slow one finish last", async () => {
48 const pending: Array<() => void> = [];
49 const send = vi.fn(
50 (method: string) =>
51 new Promise<unknown>((resolve) => pending.push(() => resolve({ method }))),
52 );
53 const written: Array<Record<string, unknown>> = [];
54 const relay = createCdpRelayConnection(makeTarget(send), (raw) =>
55 written.push(JSON.parse(raw)),
56 );
57 relay.receive(
58 JSON.stringify({ id: 5, method: "Page.captureScreenshot", sessionId: "t3-preview-page" }),
59 );
60 relay.receive(JSON.stringify({ id: 6, method: "DOM.enable", sessionId: "iframe-session" }));
61 pending[1]!();
62 await settle();
63 expect(written).toEqual([
64 { id: 6, result: { method: "DOM.enable" }, sessionId: "iframe-session" },
65 ]);
66 pending[0]!();
67 await settle();
68 expect(send).toHaveBeenNthCalledWith(1, "Page.captureScreenshot", {}, undefined);
69 expect(send).toHaveBeenNthCalledWith(2, "DOM.enable", {}, "iframe-session");
70 expect(written.at(-1)).toEqual({
71 id: 5,
72 result: { method: "Page.captureScreenshot" },
73 sessionId: "t3-preview-page",
74 });
75 });
76
77 it("resumes paused child frames, so cross-site iframes run", async () => {
78 const send = vi.fn(async () => ({}));
79 const relay = createCdpRelayConnection(makeTarget(send), () => {});
80 relay.receive(
81 JSON.stringify({
82 id: 1,
83 method: "Runtime.runIfWaitingForDebugger",
84 sessionId: "t3-preview-page",
85 }),
86 );
87 relay.receive(
88 JSON.stringify({
89 id: 2,
90 method: "Runtime.runIfWaitingForDebugger",
91 sessionId: "iframe-session",
92 }),
93 );
94 await settle();
95 expect(send.mock.calls).toEqual([["Runtime.runIfWaitingForDebugger", {}, "iframe-session"]]);
96 });
97
98 it("routes tab events to the page session once the page is announced", async () => {
99 const written: Array<Record<string, unknown>> = [];
100 const relay = createCdpRelayConnection(makeTarget(vi.fn()), (raw) =>
101 written.push(JSON.parse(raw)),
102 );
103 relay.event("Page.loadEventFired", {}, undefined);
104 expect(written).toEqual([]);
105 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
106 await settle();
107 // Electron passes an empty session id for the page's own events.
108 relay.event("Page.loadEventFired", { timestamp: 1 }, "");
109 relay.event("Runtime.consoleAPICalled", {}, "iframe-session");
110 expect(written.slice(-2)).toEqual([
111 { method: "Page.loadEventFired", params: { timestamp: 1 }, sessionId: "t3-preview-page" },
112 { method: "Runtime.consoleAPICalled", params: {}, sessionId: "iframe-session" },
113 ]);
114 });
115});
116
117describe("CDP relay extra sessions", () => {
118 it("gives a second page session the page's commands and events", async () => {
119 const send = vi.fn(async () => ({}));
120 const written: Array<Record<string, unknown>> = [];
121 const relay = createCdpRelayConnection(makeTarget(send), (raw) =>
122 written.push(JSON.parse(raw)),
123 );
124 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
125 relay.receive(JSON.stringify({ id: 2, method: "Target.attachToBrowserTarget" }));
126 await settle();
127 const browserSession = (written.find((m) => m["id"] === 2)!["result"] as { sessionId: string })
128 .sessionId;
129 relay.receive(
130 JSON.stringify({
131 id: 3,
132 method: "Target.attachToTarget",
133 params: { targetId: "GUEST-TARGET", flatten: true },
134 sessionId: browserSession,
135 }),
136 );
137 relay.receive(
138 JSON.stringify({
139 id: 4,
140 method: "Target.attachToTarget",
141 params: { targetId: "SOMETHING-ELSE" },
142 sessionId: browserSession,
143 }),
144 );
145 await settle();
146 const extra = (written.find((m) => m["id"] === 3)!["result"] as { sessionId: string })
147 .sessionId;
148 expect(written.find((m) => m["id"] === 4)).toHaveProperty("error");
149 relay.receive(JSON.stringify({ id: 5, method: "Page.startScreencast", sessionId: extra }));
150 await settle();
151 expect(send).toHaveBeenLastCalledWith("Page.startScreencast", {}, undefined);
152 written.length = 0;
153 relay.event("Page.screencastFrame", { data: "x" }, undefined);
154 expect(written.map((m) => m["sessionId"])).toEqual(["t3-preview-page", extra]);
155 });
156});
157
158describe("CDP relay downloads", () => {
159 it("applies the server's download directory and reports downloads on the root session", async () => {
160 const send = vi.fn(async () => ({}));
161 const directories: Array<string | null> = [];
162 const written: Array<Record<string, unknown>> = [];
163 const relay = createCdpRelayConnection(
164 makeTarget(send, (directory) => directories.push(directory)),
165 (raw) => written.push(JSON.parse(raw)),
166 );
167 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
168 relay.receive(
169 JSON.stringify({
170 id: 2,
171 method: "Browser.setDownloadBehavior",
172 params: {
173 behavior: "allowAndName",
174 browserContextId: "t3-preview",
175 downloadPath: "/srv/artifacts",
176 eventsEnabled: true,
177 },
178 }),
179 );
180 await settle();
181 expect(directories).toEqual(["/srv/artifacts"]);
182 expect(send).toHaveBeenCalledWith(
183 "Browser.setDownloadBehavior",
184 { behavior: "allowAndName", downloadPath: "/srv/artifacts", eventsEnabled: true },
185 undefined,
186 );
187 written.length = 0;
188 relay.event("Browser.downloadWillBegin", { guid: "g1", suggestedFilename: "r.csv" }, "");
189 expect(written).toEqual([
190 { method: "Browser.downloadWillBegin", params: { guid: "g1", suggestedFilename: "r.csv" } },
191 ]);
192 });
193});