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

CdpRelay.ts

418 lines16.0 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 /** Marks the frame-tree snapshot boundary before the host finishes the command. */
11 received?: () => void,
12 ) => Promise<unknown>;
13 readonly sessionDetached?: (owner: string) => void;
14 /** Whether a page session, by owner as `send` names it, gets the page's screencast frames. */
15 readonly receivesScreencast: (owner: string | undefined) => boolean;
16 /** Acknowledges a native screencast frame, letting Chromium send the next one. */
17 readonly ackScreencastFrame: (frameId: number) => void;
18 /** The page's own CDP target id; Playwright keys the main frame by it. */
19 readonly targetId: () => Promise<string>;
20 readonly url: () => string;
21 readonly title: () => string;
22 readonly userAgent: () => string;
23 /** The desktop and its server share a disk; download paths need no translation. */
24 readonly setDownloadDirectory: (directory: string | null) => void;
26​
27export interface CdpRelayConnection {
28 readonly receive: (raw: string) => void;
29 readonly event: (method: string, params: unknown, sessionId: string | undefined) => void;
31​
32interface CdpCommand {
33 readonly id: number;
34 readonly method: string;
35 readonly params?: Record<string, unknown>;
36 readonly sessionId?: string;
38​
39const isCommand = (value: unknown): value is CdpCommand =>
40 typeof value === "object" &&
41 value !== null &&
42 typeof (value as { id?: unknown }).id === "number" &&
43 typeof (value as { method?: unknown }).method === "string";
44​
45// CDP values are plain JSON data, so their serialized size can be bounded before
46// JSON.stringify allocates it. A string counts at its length unless it holds a
47// character JSON may escape, which can take six code units.
48const MAX_CDP_PAYLOAD_SIZE = 64 * 1024 * 1024;
49const MAY_ESCAPE = /[^\x20\x21\x23-\x5b\x5d-\ud7ff\ue000-\uffff]/;
50const serializedSize = (text: string) =>
51 (MAY_ESCAPE.test(text) ? text.length * 6 : text.length) + 3;
52​
53const fitsPayloadBudget = (message: unknown) => {
54 let remaining = MAX_CDP_PAYLOAD_SIZE;
55 const visit = (value: unknown): boolean => {
56 remaining -= typeof value === "string" ? serializedSize(value) : 26;
57 if (remaining < 0) return false;
58 if (typeof value !== "object" || value === null) return true;
59 if (Array.isArray(value)) return value.every(visit);
60 return Object.entries(value).every(([key, item]) => {
61 remaining -= serializedSize(key);
62 return visit(item);
63 });
64 };
65 return visit(message);
66};
67​
68const BROWSER_CONTEXT_ID = "t3-preview";
69const ANNOUNCE = Symbol("announce");
70const PAGE_SESSION_ID = "t3-preview-page";
71​
72const ACKNOWLEDGED = new Set([
73 "Target.setDiscoverTargets",
74 "Browser.grantPermissions",
75 "Browser.resetPermissions",
76 "Browser.cancelDownload",
77]);
78​
79export function createCdpRelayConnection(
80 target: CdpRelayTarget,
81 write: (message: string) => void,
82 close: () => void,
83): CdpRelayConnection {
84 let closed = false;
85 let initialized = false;
86 let initialization: Promise<void> | undefined;
87 let releaseInitialization: (() => void) | undefined;
88 let initialEvents: Array<string> | undefined;
89 let initialEventSize = 0;
90 const closeRelay = () => {
91 closed = true;
92 initialEvents = undefined;
93 initialEventSize = 0;
94 releaseInitialization?.();
95 releaseInitialization = undefined;
96 close();
97 };
98 const finishInitialization = () => {
99 const pending = initialEvents;
100 initialized = true;
101 initialEvents = undefined;
102 initialEventSize = 0;
103 if (!closed) for (const message of pending ?? []) write(message);
104 releaseInitialization?.();
105 releaseInitialization = undefined;
106 initialization = undefined;
107 };
108 const send = (message: Record<string, unknown>) => {
109 if (closed) return false;
110 if (fitsPayloadBudget(message)) {
111 const encoded = JSON.stringify(message);
112 // Playwright installs renderer listeners after its first frame-tree reply. Other
113 // sessions can consume events immediately, including viewers and raw CDP callers.
114 if (
115 initialEvents !== undefined &&
116 message["sessionId"] === PAGE_SESSION_ID &&
117 typeof message["method"] === "string" &&
118 /^(?:(?:Page|Runtime)\.|Target\.(?:attachedToTarget|detachedFromTarget)$)/.test(
119 message["method"],
120 )
121 ) {
122 initialEventSize += encoded.length;
123 if (initialEventSize > MAX_CDP_PAYLOAD_SIZE) closeRelay();
124 else initialEvents.push(encoded);
125 } else write(encoded);
126 return !closed;
127 }
128 // An error reply fails only that command. A dropped event would leave
129 // Playwright out of step with the page, so the relay closes instead.
130 if (typeof message["id"] === "number") {
131 write(
132 JSON.stringify({
133 id: message["id"],
134 error: { code: -32000, message: "CDP payload too large" },
135 ...(message["sessionId"] === undefined ? {} : { sessionId: message["sessionId"] }),
136 }),
137 );
138 return false;
139 }
140 closeRelay();
141 return false;
142 };
143 let attached = false;
144 let downloadEventsEnabled = false;
145 /** Relay-created page sessions share one real debugger; child frame sessions retain their own ids. */
146 const sessions = new Map<string, "browser" | "page">([[PAGE_SESSION_ID, "page"]]);
147 // Each page session holds one unacknowledged frame and keeps the newest one skipped meanwhile.
148 const unackedFrames = new Map<string, number>();
149 const skippedFrames = new Map<string, Record<string, unknown>>();
150 // Chromium keeps a few frames in flight and reuses one frame id per run, so pacing it means
151 // leaving frames every session is busy for unacknowledged and releasing one per consumer ack.
152 const heldNativeFrames: Array<number> = [];
153 const releaseHeldFramesWithoutHolders = () => {
154 if (skippedFrames.size === 0)
155 for (const frameId of heldNativeFrames.splice(0)) target.ackScreencastFrame(frameId);
156 };
157 const sendFrame = (sessionId: string, params: Record<string, unknown>) => {
158 unackedFrames.set(sessionId, params["sessionId"] as number);
159 send({ method: "Page.screencastFrame", params, sessionId });
160 };
161 let sessionSequence = 0;
162 const newSession = (kind: "browser" | "page") => {
163 const sessionId = `t3-preview-${kind}-${++sessionSequence}`;
164 sessions.set(sessionId, kind);
165 return sessionId;
166 };
167 const targetInfo = async () => ({
168 targetId: await target.targetId(),
169 type: "page",
170 title: target.title(),
171 url: target.url(),
172 attached: true,
173 canAccessOpener: false,
174 browserContextId: BROWSER_CONTEXT_ID,
175 });
176​
177 const browserCommand = async (command: CdpCommand): Promise<unknown> => {
178 if (ACKNOWLEDGED.has(command.method)) return {};
179 switch (command.method) {
180 case "Browser.setDownloadBehavior": {
181 const directory = command.params?.["downloadPath"];
182 const allowed = command.params?.["behavior"] !== "deny" && typeof directory === "string";
183 // Browser-scoped behavior targets Electron's app session; preview paths belong to will-download.
184 const result = await target.send(
185 "Page.setDownloadBehavior",
186 { behavior: command.params?.["behavior"] === "deny" ? "deny" : "default" },
187 undefined,
188 );
189 target.setDownloadDirectory(allowed ? directory : null);
190 downloadEventsEnabled = command.params?.["eventsEnabled"] === true;
191 return result;
192 }
193 case "Browser.getVersion":
194 return {
195 protocolVersion: "1.3",
196 product: "Electron",
197 revision: "",
198 userAgent: target.userAgent(),
199 jsVersion: "",
200 };
201 case "Target.getTargetInfo":
202 return {
203 targetInfo: {
204 targetId: "browser",
205 type: "browser",
206 title: "",
207 url: "",
208 attached: true,
209 canAccessOpener: false,
210 },
211 };
212 case "Target.getBrowserContexts":
213 return { browserContextIds: [] };
214 case "Target.getTargets":
215 return { targetInfos: [await targetInfo()] };
216 case "Target.attachToBrowserTarget":
217 return { sessionId: newSession("browser") };
218 case "Target.attachToTarget": {
219 const targetId = command.params?.["targetId"];
220 if (targetId !== (await target.targetId()))
221 throw new Error("Only this preview tab's page can be attached.");
222 return { sessionId: newSession("page") };
223 }
224 case "Target.detachFromTarget": {
225 const sessionId = command.params?.["sessionId"];
226 if (typeof sessionId === "string" && sessionId !== PAGE_SESSION_ID) {
227 sessions.delete(sessionId);
228 unackedFrames.delete(sessionId);
229 skippedFrames.delete(sessionId);
230 releaseHeldFramesWithoutHolders();
231 target.sessionDetached?.(sessionId);
232 }
233 return {};
234 }
235 case "Target.setAutoAttach": {
236 if (attached) return {};
237 attached = true;
238 const info = await targetInfo();
239 return {
240 [ANNOUNCE]: {
241 method: "Target.attachedToTarget",
242 params: { sessionId: PAGE_SESSION_ID, targetInfo: info, waitingForDebugger: false },
243 },
244 };
245 }
246 default:
247 throw new Error(`Not supported for a desktop preview tab: ${command.method}`);
248 }
249 };
250​
251 let runtimeReset: Promise<unknown> | undefined;
252​
253 const pageCommand = (command: CdpCommand, received?: () => void): Promise<unknown> => {
254 const child = sessions.get(command.sessionId!) === "page" ? undefined : command.sessionId;
255 const owner =
256 child === undefined && command.sessionId !== PAGE_SESSION_ID ? command.sessionId : undefined;
257 // Child frames/workers pause on auto-attach until resumed; only the main page can skip this command.
258 if (command.method === "Runtime.runIfWaitingForDebugger" && child === undefined) {
259 return Promise.resolve({});
260 }
261 // Playwright asks for this on every page; the host emulates focus only while it is in use.
262 if (command.method === "Emulation.setFocusEmulationEnabled") return Promise.resolve({});
263 if (command.method === "Page.screencastFrameAck" && child === undefined) {
264 // A restart keeps the slot too, or restarting would let frames past an unacknowledged one.
265 const sessionId = command.sessionId!;
266 if (unackedFrames.get(sessionId) === command.params?.["sessionId"]) {
267 unackedFrames.delete(sessionId);
268 const skipped = skippedFrames.get(sessionId);
269 skippedFrames.delete(sessionId);
270 if (
271 skipped !== undefined &&
272 target.receivesScreencast(sessionId === PAGE_SESSION_ID ? undefined : sessionId)
273 )
274 sendFrame(sessionId, skipped);
275 const released = heldNativeFrames.shift();
276 if (released !== undefined) target.ackScreencastFrame(released);
277 }
278 return Promise.resolve({});
279 }
280 if (command.method === "Page.stopScreencast" && child === undefined) {
281 skippedFrames.delete(command.sessionId!);
282 releaseHeldFramesWithoutHolders();
283 }
284 // A frame can load after the snapshot while Playwright's empty world script waits for the reply.
285 if (
286 command.sessionId === PAGE_SESSION_ID &&
287 command.method === "Page.addScriptToEvaluateOnNewDocument" &&
288 command.params?.["source"] === "" &&
289 typeof command.params["worldName"] === "string"
290 ) {
291 return target.send(
292 command.method,
293 { ...command.params, runImmediately: true },
294 undefined,
295 owner,
296 );
297 }
298 // The shared debugger keeps Runtime enabled after an earlier connection, and a repeated
299 // enable reports no existing contexts; Playwright waits for them, so reset once per connection.
300 if (command.method === "Runtime.enable" && child === undefined) {
301 runtimeReset ??= target.send("Runtime.disable", {}, undefined, owner).catch(() => undefined);
302 return runtimeReset.then(() =>
303 target.send(command.method, command.params ?? {}, undefined, owner),
304 );
305 }
306 return received === undefined
307 ? target.send(command.method, command.params ?? {}, child, owner)
308 : target.send(command.method, command.params ?? {}, child, owner, received);
309 };
310​
311 return {
312 receive: (raw) => {
313 if (closed) return;
314 let command: unknown;
315 try {
316 command = JSON.parse(raw);
317 } catch {
318 return;
319 }
320 if (!isCommand(command)) return;
321 const initializesPage =
322 !initialized &&
323 initialization === undefined &&
324 command.sessionId === PAGE_SESSION_ID &&
325 command.method === "Page.getFrameTree";
326 if (initializesPage)
327 initialization = new Promise<void>((resolve) => {
328 releaseInitialization = resolve;
329 });
330 const run = () =>
331 command.sessionId === undefined || sessions.get(command.sessionId) === "browser"
332 ? browserCommand(command)
333 : pageCommand(
334 command,
335 initializesPage
336 ? () => {
337 if (!closed) initialEvents = [];
338 }
339 : undefined,
340 );
341 const result =
342 initialization !== undefined &&
343 !initializesPage &&
344 command.sessionId === PAGE_SESSION_ID &&
345 // Crash detection must work even when the renderer never returns its frame tree.
346 command.method !== "Inspector.enable"
347 ? initialization.then(() => {
348 if (closed) throw new Error("The preview relay closed during initialization.");
349 return run();
350 })
351 : run();
352 const route = command.sessionId === undefined ? {} : { sessionId: command.sessionId };
353 // Reply as commands finish so slow commands cannot block later replies.
354 void result.then(
355 (value) => {
356 const announce =
357 typeof value === "object" && value !== null && ANNOUNCE in value
358 ? (value as { [ANNOUNCE]: Record<string, unknown> })[ANNOUNCE]
359 : undefined;
360 const sent = send({ id: command.id, result: announce ? {} : (value ?? {}), ...route });
361 if (initializesPage) {
362 if (sent) finishInitialization();
363 else if (!closed) closeRelay();
364 }
365 if (announce) send(announce);
366 },
367 (cause: unknown) => {
368 send({
369 id: command.id,
370 error: {
371 code: -32000,
372 message: cause instanceof Error ? cause.message : String(cause),
373 },
374 ...route,
375 });
376 if (initializesPage && !closed) closeRelay();
377 },
378 );
379 },
380 event: (method, params, sessionId) => {
381 if (!attached) return;
382 if (method.startsWith("Page.download")) method = method.replace("Page.", "Browser.");
383 // Download events are the browser's; Playwright listens on its root session.
384 if (method.startsWith("Browser.download")) {
385 if (downloadEventsEnabled) send({ method, params });
386 return;
387 }
388 // Electron reports the page's own events with an empty session id.
389 if (sessionId) {
390 send({ method, params, sessionId });
391 return;
392 }
393 if (method === "Page.screencastFrame") {
394 const frame = (params ?? {}) as Record<string, unknown>;
395 const frameId = frame["sessionId"];
396 if (typeof frameId !== "number") return;
397 let held = false;
398 let delivered = false;
399 for (const [id, kind] of sessions) {
400 if (kind !== "page") continue;
401 if (!target.receivesScreencast(id === PAGE_SESSION_ID ? undefined : id)) continue;
402 if (unackedFrames.has(id)) {
403 skippedFrames.set(id, frame);
404 held = true;
405 } else {
406 sendFrame(id, frame);
407 delivered = true;
408 }
409 }
410 if (held && !delivered) heldNativeFrames.push(frameId);
411 else target.ackScreencastFrame(frameId);
412 return;
413 }
414 for (const [id, kind] of sessions)
415 if (kind === "page") send({ method, params, sessionId: id });
416 },
417 };