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

CdpRelay.ts

208 lines7.2 KB

1/**
2 * Electron allows one debugger client per webContents, so the relay shares the
3 * attach the preview manager already holds.
4 */
5​
6export interface CdpRelayTarget {
7 readonly send: (
8 method: string,
9 params: Record<string, unknown>,
10 sessionId: string | undefined,
11 ) => Promise<unknown>;
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 /**
18 * The desktop app and the server it launched share a disk, so the server's
19 * Playwright reads the file where it asked for it.
20 */
21 readonly setDownloadDirectory: (directory: string | null) => void;
23​
24export interface CdpRelayConnection {
25 readonly receive: (raw: string) => void;
26 readonly event: (method: string, params: unknown, sessionId: string | undefined) => void;
28​
29interface CdpCommand {
30 readonly id: number;
31 readonly method: string;
32 readonly params?: Record<string, unknown>;
33 readonly sessionId?: string;
35​
36const isCommand = (value: unknown): value is CdpCommand =>
37 typeof value === "object" &&
38 value !== null &&
39 typeof (value as { id?: unknown }).id === "number" &&
40 typeof (value as { method?: unknown }).method === "string";
41​
42const BROWSER_CONTEXT_ID = "t3-preview";
43const ANNOUNCE = Symbol("announce");
44const PAGE_SESSION_ID = "t3-preview-page";
45​
46const ACKNOWLEDGED = new Set([
47 "Target.setDiscoverTargets",
48 "Browser.grantPermissions",
49 "Browser.resetPermissions",
50 "Browser.cancelDownload",
51]);
52​
53export function createCdpRelayConnection(
54 target: CdpRelayTarget,
55 write: (message: string) => void,
56): CdpRelayConnection {
57 const send = (message: Record<string, unknown>) => write(JSON.stringify(message));
58 let attached = false;
59 /**
60 * Sessions this relay invented. Extra page sessions (Playwright's
61 * `newCDPSession`) all reach the one real debugger session, so each gets the
62 * page's events; other ids are the page's own child sessions, such as iframes.
63 */
64 const sessions = new Map<string, "browser" | "page">([[PAGE_SESSION_ID, "page"]]);
65 let sessionSequence = 0;
66 const newSession = (kind: "browser" | "page") => {
67 const sessionId = `t3-preview-${kind}-${++sessionSequence}`;
68 sessions.set(sessionId, kind);
69 return sessionId;
70 };
71 const targetInfo = async () => ({
72 targetId: await target.targetId(),
73 type: "page",
74 title: target.title(),
75 url: target.url(),
76 attached: true,
77 canAccessOpener: false,
78 browserContextId: BROWSER_CONTEXT_ID,
79 });
80​
81 const browserCommand = async (command: CdpCommand): Promise<unknown> => {
82 if (ACKNOWLEDGED.has(command.method)) return {};
83 switch (command.method) {
84 case "Browser.setDownloadBehavior": {
85 const directory = command.params?.["downloadPath"];
86 const allowed = command.params?.["behavior"] !== "deny" && typeof directory === "string";
87 target.setDownloadDirectory(allowed ? directory : null);
88 const { browserContextId: _ignored, ...params } = command.params ?? {};
89 return target.send("Browser.setDownloadBehavior", params, undefined);
90 }
91 case "Browser.getVersion":
92 return {
93 protocolVersion: "1.3",
94 product: "Electron",
95 revision: "",
96 userAgent: target.userAgent(),
97 jsVersion: "",
98 };
99 case "Target.getTargetInfo":
100 return {
101 targetInfo: {
102 targetId: "browser",
103 type: "browser",
104 title: "",
105 url: "",
106 attached: true,
107 canAccessOpener: false,
108 },
109 };
110 case "Target.getBrowserContexts":
111 return { browserContextIds: [] };
112 case "Target.getTargets":
113 return { targetInfos: [await targetInfo()] };
114 case "Target.attachToBrowserTarget":
115 return { sessionId: newSession("browser") };
116 case "Target.attachToTarget": {
117 const targetId = command.params?.["targetId"];
118 if (targetId !== (await target.targetId()))
119 throw new Error("Only this preview tab's page can be attached.");
120 return { sessionId: newSession("page") };
121 }
122 case "Target.detachFromTarget": {
123 const sessionId = command.params?.["sessionId"];
124 if (typeof sessionId === "string" && sessionId !== PAGE_SESSION_ID)
125 sessions.delete(sessionId);
126 return {};
127 }
128 case "Target.setAutoAttach": {
129 if (attached) return {};
130 attached = true;
131 const info = await targetInfo();
132 return {
133 [ANNOUNCE]: {
134 method: "Target.attachedToTarget",
135 params: { sessionId: PAGE_SESSION_ID, targetInfo: info, waitingForDebugger: false },
136 },
137 };
138 }
139 default:
140 throw new Error(`Not supported for a desktop preview tab: ${command.method}`);
141 }
142 };
143​
144 const pageCommand = (command: CdpCommand): Promise<unknown> => {
145 const child = sessions.get(command.sessionId!) === "page" ? undefined : command.sessionId;
146 // The page itself is already running, but its child frames are not:
147 // Playwright auto-attaches with waitForDebuggerOnStart, so Chromium pauses
148 // every new cross-site iframe and worker until this reaches it. Swallowing
149 // it left sign-in checks and captchas, which run in such frames, frozen.
150 if (command.method === "Runtime.runIfWaitingForDebugger" && child === undefined) {
151 return Promise.resolve({});
152 }
153 return target.send(command.method, command.params ?? {}, child);
154 };
155​
156 return {
157 receive: (raw) => {
158 let command: unknown;
159 try {
160 command = JSON.parse(raw);
161 } catch {
162 return;
163 }
164 if (!isCommand(command)) return;
165 const result =
166 command.sessionId === undefined || sessions.get(command.sessionId) === "browser"
167 ? browserCommand(command)
168 : pageCommand(command);
169 const route = command.sessionId === undefined ? {} : { sessionId: command.sessionId };
170 // Replies leave as commands finish, as Chromium's do, so a slow command
171 // such as a screenshot never holds up the ones behind it.
172 void result.then(
173 (value) => {
174 const announce =
175 typeof value === "object" && value !== null && ANNOUNCE in value
176 ? (value as { [ANNOUNCE]: Record<string, unknown> })[ANNOUNCE]
177 : undefined;
178 send({ id: command.id, result: announce ? {} : (value ?? {}), ...route });
179 if (announce) send(announce);
180 },
181 (cause: unknown) =>
182 send({
183 id: command.id,
184 error: {
185 code: -32000,
186 message: cause instanceof Error ? cause.message : String(cause),
187 },
188 ...route,
189 }),
190 );
191 },
192 event: (method, params, sessionId) => {
193 if (!attached) return;
194 // Download events are the browser's; Playwright listens on its root session.
195 if (method.startsWith("Browser.download")) {
196 send({ method, params });
197 return;
198 }
199 // Electron reports the page's own events with an empty session id.
200 if (sessionId) {
201 send({ method, params, sessionId });
202 return;
203 }
204 for (const [id, kind] of sessions)
205 if (kind === "page") send({ method, params, sessionId: id });
206 },
207 };