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

CdpRelay.ts

267 lines9.8 KB

1// Electron allows one debugger per webContents; share the manager's attachment.
2​
3export interface CdpRelayTarget {
4 readonly send: (
5 method: string,
6 params: Record<string, unknown>,
7 sessionId: string | undefined,
8 /** The extra session that sent it, such as a viewer's; the main connection has none. */
9 owner?: string,
10 ) => Promise<unknown>;
11 readonly sessionDetached?: (owner: string) => void;
12 /** The page's own CDP target id; Playwright keys the main frame by it. */
13 readonly targetId: () => Promise<string>;
14 readonly url: () => string;
15 readonly title: () => string;
16 readonly userAgent: () => string;
17 /** The desktop and its server share a disk; download paths need no translation. */
18 readonly setDownloadDirectory: (directory: string | null) => void;
20​
21export interface CdpRelayConnection {
22 readonly receive: (raw: string) => void;
23 readonly event: (method: string, params: unknown, sessionId: string | undefined) => void;
25​
26interface CdpCommand {
27 readonly id: number;
28 readonly method: string;
29 readonly params?: Record<string, unknown>;
30 readonly sessionId?: string;
32​
33const isCommand = (value: unknown): value is CdpCommand =>
34 typeof value === "object" &&
35 value !== null &&
36 typeof (value as { id?: unknown }).id === "number" &&
37 typeof (value as { method?: unknown }).method === "string";
38​
39// CDP values are plain JSON data, so their serialized size can be bounded before
40// JSON.stringify allocates it. A string counts at its length unless it holds a
41// character JSON may escape, which can take six code units.
42const MAX_CDP_PAYLOAD_SIZE = 64 * 1024 * 1024;
43const MAY_ESCAPE = /[^\x20\x21\x23-\x5b\x5d-\ud7ff\ue000-\uffff]/;
44const serializedSize = (text: string) =>
45 (MAY_ESCAPE.test(text) ? text.length * 6 : text.length) + 3;
46​
47const fitsPayloadBudget = (message: unknown) => {
48 let remaining = MAX_CDP_PAYLOAD_SIZE;
49 const visit = (value: unknown): boolean => {
50 remaining -= typeof value === "string" ? serializedSize(value) : 26;
51 if (remaining < 0) return false;
52 if (typeof value !== "object" || value === null) return true;
53 if (Array.isArray(value)) return value.every(visit);
54 return Object.entries(value).every(([key, item]) => {
55 remaining -= serializedSize(key);
56 return visit(item);
57 });
58 };
59 return visit(message);
60};
61​
62const BROWSER_CONTEXT_ID = "t3-preview";
63const ANNOUNCE = Symbol("announce");
64const PAGE_SESSION_ID = "t3-preview-page";
65​
66const ACKNOWLEDGED = new Set([
67 "Target.setDiscoverTargets",
68 "Browser.grantPermissions",
69 "Browser.resetPermissions",
70 "Browser.cancelDownload",
71]);
72​
73export function createCdpRelayConnection(
74 target: CdpRelayTarget,
75 write: (message: string) => void,
76 close: () => void,
77): CdpRelayConnection {
78 let closed = false;
79 const send = (message: Record<string, unknown>) => {
80 if (closed) return;
81 if (fitsPayloadBudget(message)) {
82 write(JSON.stringify(message));
83 return;
84 }
85 // An error reply fails only that command. A dropped event would leave
86 // Playwright out of step with the page, so the relay closes instead.
87 if (typeof message["id"] === "number") {
88 write(
89 JSON.stringify({
90 id: message["id"],
91 error: { code: -32000, message: "CDP payload too large" },
92 ...(message["sessionId"] === undefined ? {} : { sessionId: message["sessionId"] }),
93 }),
94 );
95 return;
96 }
97 closed = true;
98 close();
99 };
100 let attached = false;
101 let downloadEventsEnabled = false;
102 /** Relay-created page sessions share one real debugger; child frame sessions retain their own ids. */
103 const sessions = new Map<string, "browser" | "page">([[PAGE_SESSION_ID, "page"]]);
104 let sessionSequence = 0;
105 const newSession = (kind: "browser" | "page") => {
106 const sessionId = `t3-preview-${kind}-${++sessionSequence}`;
107 sessions.set(sessionId, kind);
108 return sessionId;
109 };
110 const targetInfo = async () => ({
111 targetId: await target.targetId(),
112 type: "page",
113 title: target.title(),
114 url: target.url(),
115 attached: true,
116 canAccessOpener: false,
117 browserContextId: BROWSER_CONTEXT_ID,
118 });
119​
120 const browserCommand = async (command: CdpCommand): Promise<unknown> => {
121 if (ACKNOWLEDGED.has(command.method)) return {};
122 switch (command.method) {
123 case "Browser.setDownloadBehavior": {
124 const directory = command.params?.["downloadPath"];
125 const allowed = command.params?.["behavior"] !== "deny" && typeof directory === "string";
126 // Browser-scoped behavior targets Electron's app session; preview paths belong to will-download.
127 const result = await target.send(
128 "Page.setDownloadBehavior",
129 { behavior: command.params?.["behavior"] === "deny" ? "deny" : "default" },
130 undefined,
131 );
132 target.setDownloadDirectory(allowed ? directory : null);
133 downloadEventsEnabled = command.params?.["eventsEnabled"] === true;
134 return result;
135 }
136 case "Browser.getVersion":
137 return {
138 protocolVersion: "1.3",
139 product: "Electron",
140 revision: "",
141 userAgent: target.userAgent(),
142 jsVersion: "",
143 };
144 case "Target.getTargetInfo":
145 return {
146 targetInfo: {
147 targetId: "browser",
148 type: "browser",
149 title: "",
150 url: "",
151 attached: true,
152 canAccessOpener: false,
153 },
154 };
155 case "Target.getBrowserContexts":
156 return { browserContextIds: [] };
157 case "Target.getTargets":
158 return { targetInfos: [await targetInfo()] };
159 case "Target.attachToBrowserTarget":
160 return { sessionId: newSession("browser") };
161 case "Target.attachToTarget": {
162 const targetId = command.params?.["targetId"];
163 if (targetId !== (await target.targetId()))
164 throw new Error("Only this preview tab's page can be attached.");
165 return { sessionId: newSession("page") };
166 }
167 case "Target.detachFromTarget": {
168 const sessionId = command.params?.["sessionId"];
169 if (typeof sessionId === "string" && sessionId !== PAGE_SESSION_ID) {
170 sessions.delete(sessionId);
171 target.sessionDetached?.(sessionId);
172 }
173 return {};
174 }
175 case "Target.setAutoAttach": {
176 if (attached) return {};
177 attached = true;
178 const info = await targetInfo();
179 return {
180 [ANNOUNCE]: {
181 method: "Target.attachedToTarget",
182 params: { sessionId: PAGE_SESSION_ID, targetInfo: info, waitingForDebugger: false },
183 },
184 };
185 }
186 default:
187 throw new Error(`Not supported for a desktop preview tab: ${command.method}`);
188 }
189 };
190​
191 let runtimeReset: Promise<unknown> | undefined;
192​
193 const pageCommand = (command: CdpCommand): Promise<unknown> => {
194 const child = sessions.get(command.sessionId!) === "page" ? undefined : command.sessionId;
195 const owner =
196 child === undefined && command.sessionId !== PAGE_SESSION_ID ? command.sessionId : undefined;
197 // Child frames/workers pause on auto-attach until resumed; only the main page can skip this command.
198 if (command.method === "Runtime.runIfWaitingForDebugger" && child === undefined) {
199 return Promise.resolve({});
200 }
201 // Playwright asks for this on every page; the host emulates focus only while it is in use.
202 if (command.method === "Emulation.setFocusEmulationEnabled") return Promise.resolve({});
203 // The shared debugger keeps Runtime enabled after an earlier connection, and a repeated
204 // enable reports no existing contexts; Playwright waits for them, so reset once per connection.
205 if (command.method === "Runtime.enable" && child === undefined) {
206 runtimeReset ??= target.send("Runtime.disable", {}, undefined, owner).catch(() => undefined);
207 return runtimeReset.then(() =>
208 target.send(command.method, command.params ?? {}, undefined, owner),
209 );
210 }
211 return target.send(command.method, command.params ?? {}, child, owner);
212 };
213​
214 return {
215 receive: (raw) => {
216 if (closed) return;
217 let command: unknown;
218 try {
219 command = JSON.parse(raw);
220 } catch {
221 return;
222 }
223 if (!isCommand(command)) return;
224 const result =
225 command.sessionId === undefined || sessions.get(command.sessionId) === "browser"
226 ? browserCommand(command)
227 : pageCommand(command);
228 const route = command.sessionId === undefined ? {} : { sessionId: command.sessionId };
229 // Reply as commands finish so slow commands cannot block later replies.
230 void result.then(
231 (value) => {
232 const announce =
233 typeof value === "object" && value !== null && ANNOUNCE in value
234 ? (value as { [ANNOUNCE]: Record<string, unknown> })[ANNOUNCE]
235 : undefined;
236 send({ id: command.id, result: announce ? {} : (value ?? {}), ...route });
237 if (announce) send(announce);
238 },
239 (cause: unknown) =>
240 send({
241 id: command.id,
242 error: {
243 code: -32000,
244 message: cause instanceof Error ? cause.message : String(cause),
245 },
246 ...route,
247 }),
248 );
249 },
250 event: (method, params, sessionId) => {
251 if (!attached) return;
252 if (method.startsWith("Page.download")) method = method.replace("Page.", "Browser.");
253 // Download events are the browser's; Playwright listens on its root session.
254 if (method.startsWith("Browser.download")) {
255 if (downloadEventsEnabled) send({ method, params });
256 return;
257 }
258 // Electron reports the page's own events with an empty session id.
259 if (sessionId) {
260 send({ method, params, sessionId });
261 return;
262 }
263 for (const [id, kind] of sessions)
264 if (kind === "page") send({ method, params, sessionId: id });
265 },
266 };