-
Notifications
You must be signed in to change notification settings - Fork 19
/
browser.ts
293 lines (250 loc) · 7.76 KB
/
browser.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import { retry } from "@std/async/retry";
import { deadline } from "@std/async/deadline";
import { Celestial, PROTOCOL_VERSION } from "../bindings/celestial.ts";
import { getBinary } from "./cache.ts";
import { Page, type SandboxOptions, type WaitForOptions } from "./page.ts";
import { WEBSOCKET_ENDPOINT_REGEX, websocketReady } from "./util.ts";
import { DEBUG } from "./debug.ts";
async function runCommand(
command: Deno.Command,
{ retries = 60 } = {},
): Promise<{ process: Deno.ChildProcess; endpoint: string }> {
const process = command.spawn();
let endpoint = null;
// Wait until write to stdout containing the localhost address
// This probably means that the process is read to accept communication
const textDecoder = new TextDecoder();
const stack: string[] = [];
let error = true;
for await (const chunk of process.stderr) {
const message = textDecoder.decode(chunk);
stack.push(message);
endpoint = message.trim().match(WEBSOCKET_ENDPOINT_REGEX)?.[1];
if (endpoint) {
error = false;
break;
}
// Recover from garbage "SingletonLock" nonsense
if (message.includes("SingletonLock")) {
const path = message.split("Failed to create ")[1].split(":")[0];
process.kill();
await process.status;
try {
Deno.removeSync(path);
} catch (error) {
if (!(error instanceof Deno.errors.NotFound)) {
throw error;
}
}
return runCommand(command);
}
}
if (error) {
const { code } = await process.status;
stack.push(`Process exited with code ${code}`);
// Handle recoverable error code 21 on Windows
// https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h;l=90-91
if (Deno.build.os === "windows" && code === 21 && retries > 0) {
return runCommand(command, { retries: retries - 1 });
}
console.error(stack.join("\n"));
throw new Error("Your binary refused to boot");
}
if (!endpoint) throw new Error("Somehow did not get a websocket endpoint");
return { process, endpoint };
}
export interface BrowserOptions {
headless: boolean;
product: "chrome" | "firefox";
}
/**
* The browser class is instantiated when you run the `launch` method.
*
* @example
* ```ts
* const browser = await launch();
* ```
*/
export class Browser {
#options: BrowserOptions;
#celestial: Celestial;
#process: Deno.ChildProcess | null;
readonly pages: Page[] = [];
constructor(
ws: WebSocket,
process: Deno.ChildProcess | null,
opts: BrowserOptions,
) {
this.#celestial = new Celestial(ws);
this.#process = process;
this.#options = opts;
}
[Symbol.asyncDispose](): Promise<void> {
return this.close();
}
/** Returns true if browser is connected remotely instead of using a subprocess */
get isRemoteConnection(): boolean {
return !this.#process;
}
/**
* Returns raw celestial bindings for the browser. Super unsafe unless you know what you're doing.
*/
unsafelyGetCelestialBindings(): Celestial {
return this.#celestial;
}
/**
* Closes the browser and all of its pages (if any were opened). The Browser object itself is considered to be disposed and cannot be used anymore.
*/
async close() {
await this.#celestial.Browser.close();
await this.#celestial.close();
// First we get the process, if this is null then this is a remote connection
const process = this.#process;
// If we use a remote connection, then close all pages websockets
if (!process) {
await Promise.allSettled(this.pages.map((page) => page.close()));
} else {
try {
// ask nicely first
process.kill();
await deadline(process.status, 10 * 1000);
} catch {
// then force
process.kill("SIGKILL");
await process.status;
}
}
}
/**
* Promise which resolves to a new `Page` object.
*/
async newPage(
url?: string,
options?: WaitForOptions & SandboxOptions,
): Promise<Page> {
const { targetId } = await this.#celestial.Target.createTarget({
url: "",
});
const browserWsUrl = new URL(this.#celestial.ws.url);
const wsUrl =
`${browserWsUrl.origin}/devtools/page/${targetId}${browserWsUrl.search}`;
const websocket = new WebSocket(wsUrl);
await websocketReady(websocket);
const { waitUntil, sandbox } = options ?? {};
const page = new Page(targetId, url, websocket, this, { sandbox });
this.pages.push(page);
const celestial = page.unsafelyGetCelestialBindings();
const { userAgent } = await celestial.Browser.getVersion();
await Promise.all([
celestial.Emulation.setUserAgentOverride({
userAgent: userAgent.replaceAll("Headless", ""),
}),
celestial.Page.enable(),
celestial.Runtime.enable(),
celestial.Network.enable({}),
celestial.Page.setInterceptFileChooserDialog({ enabled: true }),
sandbox ? celestial.Fetch.enable({}) : null,
]);
if (url) {
await page.goto(url, { waitUntil });
}
return page;
}
/**
* The browser's original user agent.
*/
async userAgent(): Promise<string> {
const { userAgent } = await this.#celestial.Browser.getVersion();
return userAgent;
}
/**
* A string representing the browser name and version.
*/
async version(): Promise<string> {
const { product, revision } = await this.#celestial.Browser.getVersion();
return `${product}/${revision}`;
}
/**
* The browser's websocket endpoint
*/
wsEndpoint(): string {
return this.#celestial.ws.url;
}
/**
* Returns true if the browser and its websocket have benn closed
*/
get closed(): boolean {
return this.#celestial.ws.readyState === WebSocket.CLOSED;
}
}
export interface LaunchOptions {
headless?: boolean;
path?: string;
product?: "chrome" | "firefox";
args?: string[];
wsEndpoint?: string;
cache?: string;
}
/**
* Launches a browser instance with given arguments and options when specified.
*/
export async function launch(opts?: LaunchOptions): Promise<Browser> {
const headless = opts?.headless ?? true;
const product = opts?.product ?? "chrome";
const args = opts?.args ?? [];
const wsEndpoint = opts?.wsEndpoint;
const cache = opts?.cache;
let path = opts?.path;
const options: BrowserOptions = {
headless,
product,
};
// Connect to endpoint directly if one was specified
if (wsEndpoint) {
const ws = new WebSocket(wsEndpoint);
await websocketReady(ws);
return new Browser(ws, null, options);
}
if (!path) {
path = await getBinary(product, { cache });
}
const tempDir = Deno.makeTempDirSync();
// Launch child process
const binArgs = [
"--remote-debugging-port=0",
"--no-first-run",
"--password-store=basic",
"--use-mock-keychain",
`--user-data-dir=${tempDir}`,
// "--no-startup-window",
...(headless
? [
product === "chrome" ? "--headless=new" : "--headless",
"--hide-scrollbars",
]
: []),
...args,
];
if (DEBUG) {
console.log(`Launching: ${path} ${binArgs.join(" ")}`);
}
const launch = new Deno.Command(path, {
args: binArgs,
stderr: "piped",
});
const { process, endpoint } = await runCommand(launch);
// Fetch browser websocket
const browserRes = await retry(async () => {
const browserReq = await fetch(`http://${endpoint}/json/version`);
return await browserReq.json();
});
if (browserRes["Protocol-Version"] !== PROTOCOL_VERSION) {
throw new Error("Differing protocol versions between binary and bindings.");
}
// Set up browser websocket
const ws = new WebSocket(browserRes.webSocketDebuggerUrl);
// Make sure that websocket is open before continuing
await websocketReady(ws);
// Construct browser and return
return new Browser(ws, process, options);
}