Open History to see the last commit
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 ) => Promise<unknown>;
9 /** The page's own CDP target id; Playwright keys the main frame by it. */
10 readonly targetId: () => Promise<string>;
11 readonly url: () => string;
12 readonly title: () => string;
13 readonly userAgent: () => string;
14 /** The desktop and its server share a disk; download paths need no translation. */
15 readonly setDownloadDirectory: (directory: string | null) => void;
16}
17
18export interface CdpRelayConnection {
19 readonly receive: (raw: string) => void;
20 readonly event: (method: string, params: unknown, sessionId: string | undefined) => void;
21}
22
23interface CdpCommand {
24 readonly id: number;
25 readonly method: string;
26 readonly params?: Record<string, unknown>;
27 readonly sessionId?: string;
28}
29
30const isCommand = (value: unknown): value is CdpCommand =>
31 typeof value === "object" &&
32 value !== null &&
33 typeof (value as { id?: unknown }).id === "number" &&
34 typeof (value as { method?: unknown }).method === "string";
35
36const BROWSER_CONTEXT_ID = "t3-preview";
37const ANNOUNCE = Symbol("announce");
38const PAGE_SESSION_ID = "t3-preview-page";
39
40const ACKNOWLEDGED = new Set([
41 "Target.setDiscoverTargets",
42 "Browser.grantPermissions",
43 "Browser.resetPermissions",
44 "Browser.cancelDownload",
45]);
46
47export function createCdpRelayConnection(
48 target: CdpRelayTarget,
49 write: (message: string) => void,
50): CdpRelayConnection {
51 const send = (message: Record<string, unknown>) => write(JSON.stringify(message));
52 let attached = false;
53 /** Relay-created page sessions share one real debugger; child frame sessions retain their own ids. */
54 const sessions = new Map<string, "browser" | "page">([[PAGE_SESSION_ID, "page"]]);
55 let sessionSequence = 0;
56 const newSession = (kind: "browser" | "page") => {
57 const sessionId = `t3-preview-${kind}-${++sessionSequence}`;
58 sessions.set(sessionId, kind);
59 return sessionId;
60 };
61 const targetInfo = async () => ({
62 targetId: await target.targetId(),
63 type: "page",
64 title: target.title(),
65 url: target.url(),
66 attached: true,
67 canAccessOpener: false,
68 browserContextId: BROWSER_CONTEXT_ID,
69 });
70
71 const browserCommand = async (command: CdpCommand): Promise<unknown> => {
72 if (ACKNOWLEDGED.has(command.method)) return {};
73 switch (command.method) {
74 case "Browser.setDownloadBehavior": {
75 const directory = command.params?.["downloadPath"];
76 const allowed = command.params?.["behavior"] !== "deny" && typeof directory === "string";
77 target.setDownloadDirectory(allowed ? directory : null);
78 const { browserContextId: _ignored, ...params } = command.params ?? {};
79 return target.send("Browser.setDownloadBehavior", params, undefined);
80 }
81 case "Browser.getVersion":
82 return {
83 protocolVersion: "1.3",
84 product: "Electron",
85 revision: "",
86 userAgent: target.userAgent(),
87 jsVersion: "",
88 };
89 case "Target.getTargetInfo":
90 return {
91 targetInfo: {
92 targetId: "browser",
93 type: "browser",
94 title: "",
95 url: "",
96 attached: true,
97 canAccessOpener: false,
98 },
99 };
100 case "Target.getBrowserContexts":
101 return { browserContextIds: [] };
102 case "Target.getTargets":
103 return { targetInfos: [await targetInfo()] };
104 case "Target.attachToBrowserTarget":
105 return { sessionId: newSession("browser") };
106 case "Target.attachToTarget": {
107 const targetId = command.params?.["targetId"];
108 if (targetId !== (await target.targetId()))
109 throw new Error("Only this preview tab's page can be attached.");
110 return { sessionId: newSession("page") };
111 }
112 case "Target.detachFromTarget": {
113 const sessionId = command.params?.["sessionId"];
114 if (typeof sessionId === "string" && sessionId !== PAGE_SESSION_ID)
115 sessions.delete(sessionId);
116 return {};
117 }
118 case "Target.setAutoAttach": {
119 if (attached) return {};
120 attached = true;
121 const info = await targetInfo();
122 return {
123 [ANNOUNCE]: {
124 method: "Target.attachedToTarget",
125 params: { sessionId: PAGE_SESSION_ID, targetInfo: info, waitingForDebugger: false },
126 },
127 };
128 }
129 default:
130 throw new Error(`Not supported for a desktop preview tab: ${command.method}`);
131 }
132 };
133
134 const pageCommand = (command: CdpCommand): Promise<unknown> => {
135 const child = sessions.get(command.sessionId!) === "page" ? undefined : command.sessionId;
136 // Child frames/workers pause on auto-attach until resumed; only the main page can skip this command.
137 if (command.method === "Runtime.runIfWaitingForDebugger" && child === undefined) {
138 return Promise.resolve({});
139 }
140 return target.send(command.method, command.params ?? {}, child);
141 };
142
143 return {
144 receive: (raw) => {
145 let command: unknown;
146 try {
147 command = JSON.parse(raw);
148 } catch {
149 return;
150 }
151 if (!isCommand(command)) return;
152 const result =
153 command.sessionId === undefined || sessions.get(command.sessionId) === "browser"
154 ? browserCommand(command)
155 : pageCommand(command);
156 const route = command.sessionId === undefined ? {} : { sessionId: command.sessionId };
157 // Reply as commands finish so slow commands cannot block later replies.
158 void result.then(
159 (value) => {
160 const announce =
161 typeof value === "object" && value !== null && ANNOUNCE in value
162 ? (value as { [ANNOUNCE]: Record<string, unknown> })[ANNOUNCE]
163 : undefined;
164 send({ id: command.id, result: announce ? {} : (value ?? {}), ...route });
165 if (announce) send(announce);
166 },
167 (cause: unknown) =>
168 send({
169 id: command.id,
170 error: {
171 code: -32000,
172 message: cause instanceof Error ? cause.message : String(cause),
173 },
174 ...route,
175 }),
176 );
177 },
178 event: (method, params, sessionId) => {
179 if (!attached) return;
180 // Download events are the browser's; Playwright listens on its root session.
181 if (method.startsWith("Browser.download")) {
182 send({ method, params });
183 return;
184 }
185 // Electron reports the page's own events with an empty session id.
186 if (sessionId) {
187 send({ method, params, sessionId });
188 return;
189 }
190 for (const [id, kind] of sessions)
191 if (kind === "page") send({ method, params, sessionId: id });
192 },
193 };
194}