Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - Owns Playwright resources 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
17interface Options {
18 readonly profilesDir: string;
19 readonly executable: () => Promise<string>;
20 readonly diagnose?: (executable: string, cause: unknown) => Promise<unknown>;
21 readonly env?: NodeJS.ProcessEnv;
22 readonly onContextClose?: (context: BrowserContext) => void;
23}
24
25const UA_PLATFORMS: Partial<Record<NodeJS.Platform, string>> = {
26 darwin: "macOS",
27 linux: "Linux",
28 win32: "Windows",
29};
30
31/** Change user agent and Sec-CH-UA together; sites block mismatches. */
32const chromeIdentity = (
33 headlessUserAgent: string,
34 host: { readonly platform: NodeJS.Platform; readonly arch: string; readonly release: string },
35) => {
36 const version = /HeadlessChrome\/((\d+)[\d.]*)/.exec(headlessUserAgent);
37 const fullVersion = version?.[1];
38 const major = version?.[2];
39 if (!version || !fullVersion || !major) return null;
40 const brands = (names: (version: string) => string) => [
41 { brand: "Chromium", version: names(major) },
42 { brand: "Google Chrome", version: names(major) },
43 { brand: "Not A(Brand", version: names("99") },
44 ];
45 return {
46 userAgent: headlessUserAgent.replace(version[0], `Chrome/${major}.0.0.0`),
47 userAgentMetadata: {
48 brands: brands((value) => value),
49 fullVersionList: brands((value) => (value === major ? fullVersion : `${value}.0.0.0`)),
50 platform: UA_PLATFORMS[host.platform] ?? "Unknown",
51 platformVersion: host.platform === "linux" ? host.release : "",
52 architecture: host.arch.startsWith("arm") ? "arm" : "x86",
53 bitness: host.arch.endsWith("64") ? "64" : "32",
54 model: "",
55 mobile: false,
56 wow64: false,
57 },
58 };
59};
60
61export const presentAsChrome = async (
62 cdp: CDPSession,
63 host: { readonly platform: NodeJS.Platform; readonly arch: string },
64) => {
65 const { userAgent } = await cdp.send("Browser.getVersion");
66 const identity = chromeIdentity(userAgent, { ...host, release: NodeOS.release() });
67 if (identity) await cdp.send("Emulation.setUserAgentOverride", identity);
68};
69
70export class ServerBrowserContexts {
71 private readonly options: Options;
72 private readonly contexts = new Map<string, Promise<BrowserContext>>();
73 private readonly clearing = new Map<string, Promise<void>>();
74 private browser: Promise<Browser> | undefined;
75 private closing: Promise<void> | undefined;
76
77 constructor(options: Options) {
78 this.options = options;
79 }
80
81 private async launchOptions() {
82 const executablePath = await this.options.executable();
83 const env = this.options.env ?? process.env;
84 return {
85 executablePath,
86 env,
87 args: [
88 "--disable-gpu",
89 "--force-device-scale-factor=2",
90 "--disable-blink-features=AutomationControlled",
91 ],
92 ignoreDefaultArgs: ["--enable-automation"],
93 headless: true,
94 // Only an explicit operator opt-out disables sandboxing. Launch errors never do.
95 chromiumSandbox: !sandboxDisabled(env),
96 };
97 }
98
99 private async launch<A>(options: { readonly executablePath: string }, start: () => Promise<A>) {
100 try {
101 return await start();
102 } catch (cause) {
103 throw (await this.options.diagnose?.(options.executablePath, cause)) ?? cause;
104 }
105 }
106
107 private sharedBrowser() {
108 if (!this.browser) {
109 const launched = this.launchOptions().then(async (options) => {
110 const { chromium } = loadPlaywright();
111 const browser = await this.launch(options, () => chromium.launch(options));
112 browser.on("disconnected", () => {
113 if (this.browser === launched) this.browser = undefined;
114 });
115 return browser;
116 });
117 this.browser = launched;
118 void launched.catch(() => {
119 if (this.browser === launched) this.browser = undefined;
120 });
121 }
122 return this.browser;
123 }
124
125 contextFor(profileId: string, isolationKey?: string): Promise<BrowserContext> {
126 if (this.closing) return Promise.reject(new Error("The preview browser is closed."));
127 const key = JSON.stringify([profileId, isolationKey ?? null]);
128 const cached = this.contexts.get(key);
129 if (cached) return cached;
130 const cleared = this.clearing.get(key)?.catch(constVoid) ?? Promise.resolve();
131 const pending = cleared
132 .then(() => this.createContext(profileId, isolationKey))
133 .then(async (context) => {
134 context.on("close", () => {
135 if (this.contexts.get(key) === pending) this.contexts.delete(key);
136 this.options.onContextClose?.(context);
137 });
138 for (const page of context.pages()) await page.close().catch(constVoid);
139 if (this.closing) {
140 await context.close().catch(constVoid);
141 throw new Error("The preview browser is closed.");
142 }
143 return context;
144 });
145 this.contexts.set(key, pending);
146 void pending.catch(() => {
147 if (this.contexts.get(key) === pending) this.contexts.delete(key);
148 });
149 return pending;
150 }
151
152 private async createContext(profileId: string, isolationKey?: string) {
153 const contextOptions = { viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 };
154 if (isolationKey !== undefined || profileId === INCOGNITO_BROWSER_PROFILE_ID) {
155 const browser = await this.sharedBrowser();
156 return browser.newContext(contextOptions);
157 }
158 const directory = this.profileDirectory(profileId);
159 const options = await this.launchOptions();
160 const { chromium } = loadPlaywright();
161 await NodeFSP.mkdir(directory, { recursive: true });
162 return this.launch(options, () =>
163 chromium.launchPersistentContext(directory, { ...options, ...contextOptions }),
164 );
165 }
166
167 private profileDirectory(profileId: string) {
168 const encoded = encodeURIComponent(profileId);
169 return NodePath.join(
170 this.options.profilesDir,
171 profileId === "." || profileId === ".." ? encoded.replaceAll(".", "%2E") : encoded,
172 );
173 }
174
175 async scratchPage() {
176 if (this.closing) throw new Error("The preview browser is closed.");
177 const context = await (await this.sharedBrowser()).newContext();
178 const page = await context.newPage();
179 page.once("close", () => void context.close().catch(constVoid));
180 return page;
181 }
182
183 async connectDesktopPage(endpoint: string) {
184 const { chromium } = loadPlaywright();
185 const browser = await chromium.connectOverCDP(endpoint, { timeout: 15_000 });
186 const page = browser.contexts().flatMap((context) => context.pages())[0];
187 if (!page) {
188 await browser.close().catch(constVoid);
189 throw new Error("The desktop tab has no page.");
190 }
191 return { browser, page };
192 }
193
194 async clearProfile(profileId: string) {
195 if (profileId === INCOGNITO_BROWSER_PROFILE_ID) return;
196 const key = JSON.stringify([profileId, null]);
197 const clearing = (async () => {
198 const pending = this.contexts.get(key);
199 if (pending) {
200 this.contexts.delete(key);
201 const context = await pending.catch(() => undefined);
202 await context?.close();
203 }
204 await NodeFSP.rm(this.profileDirectory(profileId), { recursive: true, force: true });
205 })();
206 this.clearing.set(key, clearing);
207 try {
208 await clearing;
209 } finally {
210 if (this.clearing.get(key) === clearing) this.clearing.delete(key);
211 }
212 }
213
214 close() {
215 this.closing ??= this.dispose();
216 return this.closing;
217 }
218
219 private async dispose() {
220 await Promise.allSettled(
221 [...this.contexts.values()].map(async (pending) => (await pending).close()),
222 );
223 const browser = await this.browser?.catch(() => undefined);
224 await browser?.close().catch(constVoid);
225 this.contexts.clear();
226 }
227}