Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off globalTimers:off -- Owns Playwright resources and their idle timer outside the Effect runtime.
2import { INCOGNITO_BROWSER_PROFILE_ID } from "@t3tools/contracts";
3import { constVoid } from "effect/Function";
4import * as NodeFSP from "node:fs/promises";
5import * as NodeModule from "node:module";
6import * as NodeOS from "node:os";
7import * as NodePath from "node:path";
8import type { Browser, BrowserContext, CDPSession } from "playwright-core";
9
10import { sandboxDisabled } from "./PreviewBrowserHost.ts";
11
12// Playwright needs its files on disk. createRequire also resolves it from a Node SEA executable.
13const requirePlaywright = NodeModule.createRequire(import.meta.url);
14const loadPlaywright = () =>
15 requirePlaywright("playwright-core") as typeof import("playwright-core");
16
17const BADGE_STUB = `if (typeof WorkerNavigator === "function") for (const name of ["setAppBadge", "clearAppBadge"]) WorkerNavigator.prototype[name] = () => Promise.resolve();`;
18
19interface CdpSession {
20 send(method: string, params?: object): Promise<unknown>;
21 createChildSession(...args: ReadonlyArray<unknown>): CdpSession;
22}
23
24// The headless shell binds no BadgeService for service workers and kills the renderer of a
25// worker that calls navigator.setAppBadge. Playwright resumes each worker itself, so the stub
26// can only go in ahead of that resume through its in-process session; without it nothing is stubbed.
27const stubWorkerBadges = (client: Browser | BrowserContext) => {
28 const { _connection: connection } = client as unknown as {
29 readonly _connection?: {
30 readonly toImpl?: (
31 client: unknown,
32 ) =>
33 | { readonly _session?: CdpSession; readonly _browser?: { readonly _session?: CdpSession } }
34 | undefined;
35 };
36 };
37 const impl = connection?.toImpl?.(client);
38 const root = impl?._browser?._session ?? impl?._session;
39 if (!root) return;
40 const createChildSession = root.createChildSession.bind(root);
41 root.createChildSession = (...args) => {
42 const session = createChildSession(...args);
43 const send = session.send.bind(session);
44 session.send = (method, params) => {
45 if (method === "Runtime.runIfWaitingForDebugger") {
46 void send("Runtime.evaluate", { expression: BADGE_STUB }).catch(constVoid);
47 }
48 return send(method, params);
49 };
50 return session;
51 };
52};
53
54interface Options {
55 readonly profilesDir: string;
56 readonly executable: () => Promise<string>;
57 /**
58 * A path that starts `executable`, such as one that moves Chrome out of the server's cgroup.
59 * Released after the whole launch call, since Playwright retries the same path after a glibc race.
60 */
61 readonly launcher?: (
62 executable: string,
63 ) => Promise<{ readonly path: string; readonly release: () => Promise<void> } | undefined>;
64 readonly diagnose?: (executable: string, cause: unknown) => Promise<unknown>;
65 readonly env?: NodeJS.ProcessEnv;
66 /** Closes the shared browser once it has held no context for this long. */
67 readonly idleBrowserMs?: number;
68 readonly onContextClose?: (context: BrowserContext) => void;
69}
70
71const UA_PLATFORMS: Partial<Record<NodeJS.Platform, string>> = {
72 darwin: "macOS",
73 linux: "Linux",
74 win32: "Windows",
75};
76
77/** Change user agent and Sec-CH-UA together; sites block mismatches. */
78const chromeIdentity = (
79 headlessUserAgent: string,
80 host: { readonly platform: NodeJS.Platform; readonly arch: string; readonly release: string },
81) => {
82 const version = /HeadlessChrome\/((\d+)[\d.]*)/.exec(headlessUserAgent);
83 const fullVersion = version?.[1];
84 const major = version?.[2];
85 if (!version || !fullVersion || !major) return null;
86 const brands = (names: (version: string) => string) => [
87 { brand: "Chromium", version: names(major) },
88 { brand: "Google Chrome", version: names(major) },
89 { brand: "Not A(Brand", version: names("99") },
90 ];
91 return {
92 userAgent: headlessUserAgent.replace(version[0], `Chrome/${major}.0.0.0`),
93 userAgentMetadata: {
94 brands: brands((value) => value),
95 fullVersionList: brands((value) => (value === major ? fullVersion : `${value}.0.0.0`)),
96 platform: UA_PLATFORMS[host.platform] ?? "Unknown",
97 platformVersion: host.platform === "linux" ? host.release : "",
98 architecture: host.arch.startsWith("arm") ? "arm" : "x86",
99 bitness: host.arch.endsWith("64") ? "64" : "32",
100 model: "",
101 mobile: false,
102 wow64: false,
103 },
104 };
105};
106
107export const presentAsChrome = async (
108 cdp: CDPSession,
109 host: { readonly platform: NodeJS.Platform; readonly arch: string },
110) => {
111 const { userAgent } = await cdp.send("Browser.getVersion");
112 const identity = chromeIdentity(userAgent, { ...host, release: NodeOS.release() });
113 if (identity) await cdp.send("Emulation.setUserAgentOverride", identity);
114};
115
116export class ServerBrowserContexts {
117 private readonly options: Options;
118 private readonly contexts = new Map<string, Promise<BrowserContext>>();
119 private readonly clearing = new Map<string, Promise<void>>();
120 private browser: Promise<Browser> | undefined;
121 private closing: Promise<void> | undefined;
122 private idleTimer: ReturnType<typeof setTimeout> | undefined;
123 private pendingSharedContexts = 0;
124
125 constructor(options: Options) {
126 this.options = options;
127 }
128
129 private async launchOptions() {
130 const executable = await this.options.executable();
131 const env = this.options.env ?? process.env;
132 return {
133 executable,
134 env,
135 args: [
136 "--disable-gpu",
137 "--force-device-scale-factor=2",
138 "--disable-blink-features=AutomationControlled",
139 ],
140 ignoreDefaultArgs: ["--enable-automation"],
141 headless: true,
142 // Only an explicit operator opt-out disables sandboxing. Launch errors never do.
143 chromiumSandbox: !sandboxDisabled(env),
144 };
145 }
146
147 private async launch<A>(executable: string, start: (executablePath: string) => Promise<A>) {
148 let release: (() => Promise<void>) | undefined;
149 try {
150 const launcher = await this.options.launcher?.(executable);
151 release = launcher?.release;
152 return await start(launcher?.path ?? executable);
153 } catch (cause) {
154 throw (await this.options.diagnose?.(executable, cause)) ?? cause;
155 } finally {
156 await release?.().catch(constVoid);
157 }
158 }
159
160 private sharedBrowser() {
161 if (!this.browser) {
162 const launched = this.launchOptions().then(async ({ executable, ...options }) => {
163 const { chromium } = loadPlaywright();
164 const browser = await this.launch(executable, (executablePath) =>
165 chromium.launch({ ...options, executablePath }),
166 );
167 stubWorkerBadges(browser);
168 browser.on("disconnected", () => {
169 if (this.browser === launched) this.browser = undefined;
170 });
171 return browser;
172 });
173 this.browser = launched;
174 void launched.catch(() => {
175 if (this.browser === launched) this.browser = undefined;
176 });
177 }
178 return this.browser;
179 }
180
181 private async sharedContext(options?: Parameters<Browser["newContext"]>[0]) {
182 clearTimeout(this.idleTimer);
183 this.pendingSharedContexts++;
184 const launched = this.sharedBrowser();
185 try {
186 const context = await (await launched).newContext(options);
187 context.on("close", () => this.retireWhenIdle(launched));
188 return context;
189 } finally {
190 this.pendingSharedContexts--;
191 this.retireWhenIdle(launched);
192 }
193 }
194
195 private retireWhenIdle(launched: Promise<Browser>) {
196 const delay = this.options.idleBrowserMs;
197 if (delay === undefined || this.closing || this.pendingSharedContexts > 0) return;
198 clearTimeout(this.idleTimer);
199 this.idleTimer = setTimeout(() => void this.retire(launched), delay);
200 this.idleTimer.unref();
201 }
202
203 private async retire(launched: Promise<Browser>) {
204 const browser = await launched.catch(() => undefined);
205 if (!browser || this.browser !== launched || this.pendingSharedContexts > 0) return;
206 if (browser.contexts().length > 0) return;
207 // Cleared first, so a request during the close launches a fresh browser.
208 this.browser = undefined;
209 await browser.close().catch(constVoid);
210 }
211
212 contextFor(profileId: string, isolationKey?: string): Promise<BrowserContext> {
213 if (this.closing) return Promise.reject(new Error("The preview browser is closed."));
214 const key = JSON.stringify([profileId, isolationKey ?? null]);
215 const cached = this.contexts.get(key);
216 if (cached) return cached;
217 const cleared = this.clearing.get(key)?.catch(constVoid) ?? Promise.resolve();
218 const pending = cleared
219 .then(() => this.createContext(profileId, isolationKey))
220 .then(async (context) => {
221 context.on("close", () => {
222 if (this.contexts.get(key) === pending) this.contexts.delete(key);
223 this.options.onContextClose?.(context);
224 });
225 for (const page of context.pages()) await page.close().catch(constVoid);
226 if (this.closing) {
227 await context.close().catch(constVoid);
228 throw new Error("The preview browser is closed.");
229 }
230 return context;
231 });
232 this.contexts.set(key, pending);
233 void pending.catch(() => {
234 if (this.contexts.get(key) === pending) this.contexts.delete(key);
235 });
236 return pending;
237 }
238
239 private async createContext(profileId: string, isolationKey?: string) {
240 const contextOptions = { viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 };
241 if (isolationKey !== undefined || profileId === INCOGNITO_BROWSER_PROFILE_ID) {
242 return this.sharedContext(contextOptions);
243 }
244 const directory = this.profileDirectory(profileId);
245 await NodeFSP.mkdir(directory, { recursive: true });
246 const { executable, ...options } = await this.launchOptions();
247 const { chromium } = loadPlaywright();
248 const context = await this.launch(executable, (executablePath) =>
249 chromium.launchPersistentContext(directory, {
250 ...options,
251 ...contextOptions,
252 executablePath,
253 }),
254 );
255 stubWorkerBadges(context);
256 return context;
257 }
258
259 private profileDirectory(profileId: string) {
260 const encoded = encodeURIComponent(profileId);
261 return NodePath.join(
262 this.options.profilesDir,
263 profileId === "." || profileId === ".." ? encoded.replaceAll(".", "%2E") : encoded,
264 );
265 }
266
267 async scratchPage() {
268 if (this.closing) throw new Error("The preview browser is closed.");
269 const context = await this.sharedContext();
270 try {
271 const page = await context.newPage();
272 page.once("close", () => void context.close().catch(constVoid));
273 return page;
274 } catch (cause) {
275 await context.close().catch(constVoid);
276 throw cause;
277 }
278 }
279
280 async connectDesktopPage(endpoint: string) {
281 const { chromium } = loadPlaywright();
282 const browser = await chromium.connectOverCDP(endpoint, { timeout: 15_000 });
283 const page = browser.contexts().flatMap((context) => context.pages())[0];
284 if (!page) {
285 await browser.close().catch(constVoid);
286 throw new Error("The desktop tab has no page.");
287 }
288 return { browser, page };
289 }
290
291 async clearProfile(profileId: string) {
292 if (profileId === INCOGNITO_BROWSER_PROFILE_ID) return;
293 const key = JSON.stringify([profileId, null]);
294 const existing = this.clearing.get(key);
295 if (existing) return existing;
296 const clearing = (async () => {
297 const pending = this.contexts.get(key);
298 if (pending) {
299 this.contexts.delete(key);
300 const context = await pending.catch(() => undefined);
301 await context?.close();
302 }
303 await NodeFSP.rm(this.profileDirectory(profileId), { recursive: true, force: true });
304 })();
305 this.clearing.set(key, clearing);
306 try {
307 await clearing;
308 } finally {
309 if (this.clearing.get(key) === clearing) this.clearing.delete(key);
310 }
311 }
312
313 close() {
314 this.closing ??= this.dispose();
315 return this.closing;
316 }
317
318 private async dispose() {
319 clearTimeout(this.idleTimer);
320 await Promise.allSettled(
321 [...this.contexts.values()].map(async (pending) => (await pending).close()),
322 );
323 const browser = await this.browser?.catch(() => undefined);
324 await browser?.close().catch(constVoid);
325 this.contexts.clear();
326 }
327}