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