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("announces only the tab's page, under its real target id", async () => {
22 const written: Array<Record<string, unknown>> = [];
23 const relay = createCdpRelayConnection(makeTarget(vi.fn()), (raw) =>
24 written.push(JSON.parse(raw)),
25 );
26 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
27 relay.receive(JSON.stringify({ id: 2, method: "Target.createTarget", params: {} }));
28 await settle();
29 const attach = written.findIndex((message) => message["id"] === 1);
30 expect(written.slice(attach, attach + 2)).toEqual([
31 { id: 1, result: {} },
32 {
33 method: "Target.attachedToTarget",
34 params: expect.objectContaining({
35 sessionId: "t3-preview-page",
36 targetInfo: expect.objectContaining({ targetId: "GUEST-TARGET", type: "page" }),
37 }),
38 },
39 ]);
40 expect(written).toContainEqual({
41 id: 2,
42 error: expect.objectContaining({ message: expect.stringContaining("createTarget") }),
43 });
44 });
45
46 it("forwards page commands to the tab and lets a slow one finish last", async () => {
47 const pending: Array<() => void> = [];
48 const send = vi.fn(
49 (method: string) =>
50 new Promise<unknown>((resolve) => pending.push(() => resolve({ method }))),
51 );
52 const written: Array<Record<string, unknown>> = [];
53 const relay = createCdpRelayConnection(makeTarget(send), (raw) =>
54 written.push(JSON.parse(raw)),
55 );
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);
68 expect(send).toHaveBeenNthCalledWith(2, "DOM.enable", {}, "iframe-session");
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 = createCdpRelayConnection(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([["Runtime.runIfWaitingForDebugger", {}, "iframe-session"]]);
95 });
96
97 it("routes tab events to the page session once the page is announced", async () => {
98 const written: Array<Record<string, unknown>> = [];
99 const relay = createCdpRelayConnection(makeTarget(vi.fn()), (raw) =>
100 written.push(JSON.parse(raw)),
101 );
102 relay.event("Page.loadEventFired", {}, undefined);
103 expect(written).toEqual([]);
104 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
105 await settle();
106 // Electron passes an empty session id for the page's own events.
107 relay.event("Page.loadEventFired", { timestamp: 1 }, "");
108 relay.event("Runtime.consoleAPICalled", {}, "iframe-session");
109 expect(written.slice(-2)).toEqual([
110 { method: "Page.loadEventFired", params: { timestamp: 1 }, sessionId: "t3-preview-page" },
111 { method: "Runtime.consoleAPICalled", params: {}, sessionId: "iframe-session" },
112 ]);
113 });
114});
115
116describe("CDP relay extra sessions", () => {
117 it("gives a second page session the page's commands and events", async () => {
118 const send = vi.fn(async () => ({}));
119 const written: Array<Record<string, unknown>> = [];
120 const relay = createCdpRelayConnection(makeTarget(send), (raw) =>
121 written.push(JSON.parse(raw)),
122 );
123 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
124 relay.receive(JSON.stringify({ id: 2, method: "Target.attachToBrowserTarget" }));
125 await settle();
126 const browserSession = (written.find((m) => m["id"] === 2)!["result"] as { sessionId: string })
127 .sessionId;
128 relay.receive(
129 JSON.stringify({
130 id: 3,
131 method: "Target.attachToTarget",
132 params: { targetId: "GUEST-TARGET", flatten: true },
133 sessionId: browserSession,
134 }),
135 );
136 relay.receive(
137 JSON.stringify({
138 id: 4,
139 method: "Target.attachToTarget",
140 params: { targetId: "SOMETHING-ELSE" },
141 sessionId: browserSession,
142 }),
143 );
144 await settle();
145 const extra = (written.find((m) => m["id"] === 3)!["result"] as { sessionId: string })
146 .sessionId;
147 expect(written.find((m) => m["id"] === 4)).toHaveProperty("error");
148 relay.receive(JSON.stringify({ id: 5, method: "Page.startScreencast", sessionId: extra }));
149 await settle();
150 expect(send).toHaveBeenLastCalledWith("Page.startScreencast", {}, undefined);
151 written.length = 0;
152 relay.event("Page.screencastFrame", { data: "x" }, undefined);
153 expect(written.map((m) => m["sessionId"])).toEqual(["t3-preview-page", extra]);
154 });
155});
156
157describe("CDP relay downloads", () => {
158 it("applies the server's download directory and reports downloads on the root session", async () => {
159 const send = vi.fn(async () => ({}));
160 const directories: Array<string | null> = [];
161 const written: Array<Record<string, unknown>> = [];
162 const relay = createCdpRelayConnection(
163 makeTarget(send, (directory) => directories.push(directory)),
164 (raw) => written.push(JSON.parse(raw)),
165 );
166 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
167 relay.receive(
168 JSON.stringify({
169 id: 2,
170 method: "Browser.setDownloadBehavior",
171 params: {
172 behavior: "allowAndName",
173 browserContextId: "t3-preview",
174 downloadPath: "/srv/artifacts",
175 eventsEnabled: true,
176 },
177 }),
178 );
179 await settle();
180 expect(directories).toEqual(["/srv/artifacts"]);
181 expect(send).toHaveBeenCalledWith(
182 "Browser.setDownloadBehavior",
183 { behavior: "allowAndName", downloadPath: "/srv/artifacts", eventsEnabled: true },
184 undefined,
185 );
186 written.length = 0;
187 relay.event("Browser.downloadWillBegin", { guid: "g1", suggestedFilename: "r.csv" }, "");
188 expect(written).toEqual([
189 { method: "Browser.downloadWillBegin", params: { guid: "g1", suggestedFilename: "r.csv" } },
190 ]);
191 });
192});