@howaboua/pi-browser 0.0.15 → 0.0.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/README.md +4 -2
- package/dist/remote-worker.js +281 -29
- package/dist/src/browser/default-browser.d.ts +7 -0
- package/dist/src/browser/default-browser.js +181 -0
- package/dist/src/browser/help.js +1 -1
- package/dist/src/browser/launcher.js +137 -14
- package/dist/src/cdp/client.js +2 -2
- package/dist/src/cdp/tabs.js +2 -2
- package/package.json +9 -9
- package/src/browser/default-browser.ts +217 -0
- package/src/browser/help.ts +1 -1
- package/src/browser/launcher.ts +169 -13
- package/src/cdp/client.ts +2 -2
- package/src/cdp/tabs.ts +2 -2
package/src/browser/launcher.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
|
+
import { isAbsolute } from "node:path";
|
|
2
3
|
import { probeDebugPort, sleep } from "../cdp/discovery.js";
|
|
4
|
+
import { asRecord } from "../cdp/types.js";
|
|
5
|
+
import { resolveDefaultBrowser } from "./default-browser.js";
|
|
3
6
|
|
|
4
7
|
const BROWSER_START_TIMEOUT_MS = 10_000;
|
|
5
8
|
const BROWSER_UNIT = "chrome-cdp-browser.service";
|
|
@@ -21,11 +24,13 @@ function runProcess(
|
|
|
21
24
|
command: string,
|
|
22
25
|
args: string[],
|
|
23
26
|
signal?: AbortSignal,
|
|
27
|
+
env?: NodeJS.ProcessEnv,
|
|
24
28
|
): Promise<ProcessResult> {
|
|
25
29
|
if (signal?.aborted) return Promise.reject(abortReason(signal));
|
|
26
30
|
return new Promise((resolveValue, reject) => {
|
|
27
31
|
const child = spawn(command, args, {
|
|
28
32
|
stdio: ["ignore", "pipe", "pipe"],
|
|
33
|
+
env,
|
|
29
34
|
});
|
|
30
35
|
let stdout = "";
|
|
31
36
|
let stderr = "";
|
|
@@ -106,10 +111,170 @@ async function waitForDebugEndpoint(
|
|
|
106
111
|
throw new Error(
|
|
107
112
|
`Browser did not expose CDP at ${host}:${port} within ${timeout}ms${
|
|
108
113
|
lastError instanceof Error ? ` (${lastError.message})` : ""
|
|
109
|
-
}
|
|
114
|
+
}. The browser may not support CDP startup flags or may have refused remote debugging for this profile. Enable remote debugging in the existing browser or set CDP_BROWSER to a compatible executable.`,
|
|
110
115
|
);
|
|
111
116
|
}
|
|
112
117
|
|
|
118
|
+
function hasGraphicalDesktop(env: NodeJS.ProcessEnv): boolean {
|
|
119
|
+
return Boolean(env["WAYLAND_DISPLAY"]?.trim() || env["DISPLAY"]?.trim());
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function graphicalEnvironment(
|
|
123
|
+
signal: AbortSignal,
|
|
124
|
+
): Promise<NodeJS.ProcessEnv> {
|
|
125
|
+
if (!process.env["SSH_CONNECTION"] && hasGraphicalDesktop(process.env)) {
|
|
126
|
+
return { ...process.env };
|
|
127
|
+
}
|
|
128
|
+
// The remote worker inherits SSH's environment, which can select a
|
|
129
|
+
// different MIME association from the graphical systemd user session.
|
|
130
|
+
const result = await runProcess(
|
|
131
|
+
"busctl",
|
|
132
|
+
[
|
|
133
|
+
"--user",
|
|
134
|
+
"--json=short",
|
|
135
|
+
"get-property",
|
|
136
|
+
"org.freedesktop.systemd1",
|
|
137
|
+
"/org/freedesktop/systemd1",
|
|
138
|
+
"org.freedesktop.systemd1.Manager",
|
|
139
|
+
"Environment",
|
|
140
|
+
],
|
|
141
|
+
signal,
|
|
142
|
+
);
|
|
143
|
+
if (result.code !== 0)
|
|
144
|
+
throw new Error("systemd user environment unavailable");
|
|
145
|
+
const reply = asRecord(JSON.parse(result.stdout), "systemd user environment");
|
|
146
|
+
if (reply["type"] !== "as" || !Array.isArray(reply["data"])) {
|
|
147
|
+
throw new Error("Invalid systemd user environment");
|
|
148
|
+
}
|
|
149
|
+
const entries: [string, string][] = [];
|
|
150
|
+
for (const assignment of reply["data"]) {
|
|
151
|
+
if (typeof assignment !== "string")
|
|
152
|
+
throw new Error("Invalid systemd environment variable");
|
|
153
|
+
const equals = assignment.indexOf("=");
|
|
154
|
+
if (equals <= 0) throw new Error("Invalid systemd environment variable");
|
|
155
|
+
entries.push([assignment.slice(0, equals), assignment.slice(equals + 1)]);
|
|
156
|
+
}
|
|
157
|
+
const env = Object.fromEntries(entries);
|
|
158
|
+
if (!hasGraphicalDesktop(env))
|
|
159
|
+
throw new Error("systemd has no graphical desktop environment");
|
|
160
|
+
return env;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async function configuredDefaultBrowser(signal?: AbortSignal) {
|
|
164
|
+
const timeout = AbortSignal.timeout(5_000);
|
|
165
|
+
const lookupSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
166
|
+
let env: NodeJS.ProcessEnv;
|
|
167
|
+
try {
|
|
168
|
+
env = await graphicalEnvironment(lookupSignal);
|
|
169
|
+
} catch (error) {
|
|
170
|
+
signal?.throwIfAborted();
|
|
171
|
+
throw new Error(
|
|
172
|
+
"Could not determine the graphical desktop environment. Set CDP_BROWSER or start a browser with CDP enabled yourself.",
|
|
173
|
+
{ cause: error },
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
// xdg-settings uses the shell's BROWSER setting ahead of desktop
|
|
177
|
+
// associations on generic desktops.
|
|
178
|
+
delete env["BROWSER"];
|
|
179
|
+
let id: string;
|
|
180
|
+
try {
|
|
181
|
+
const result = await runProcess(
|
|
182
|
+
"xdg-settings",
|
|
183
|
+
["get", "default-web-browser"],
|
|
184
|
+
lookupSignal,
|
|
185
|
+
env,
|
|
186
|
+
);
|
|
187
|
+
if (result.code !== 0)
|
|
188
|
+
throw new Error(result.stderr || `exit ${result.code}`);
|
|
189
|
+
id = result.stdout;
|
|
190
|
+
} catch (error) {
|
|
191
|
+
signal?.throwIfAborted();
|
|
192
|
+
throw new Error(
|
|
193
|
+
"Could not query the configured default browser with xdg-settings. Set CDP_BROWSER or start a browser with CDP enabled yourself.",
|
|
194
|
+
{ cause: error },
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
return resolveDefaultBrowser(id, env);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async function browserLaunchCommand(
|
|
201
|
+
host: string,
|
|
202
|
+
port: string,
|
|
203
|
+
signal?: AbortSignal,
|
|
204
|
+
): Promise<string[]> {
|
|
205
|
+
const switches = new Map([
|
|
206
|
+
["--remote-debugging-address", host],
|
|
207
|
+
["--remote-debugging-port", port],
|
|
208
|
+
]);
|
|
209
|
+
const profile = process.env["CDP_PROFILE_DIRECTORY"];
|
|
210
|
+
if (profile) switches.set("--profile-directory", profile);
|
|
211
|
+
const override = process.env["CDP_BROWSER"];
|
|
212
|
+
if (override === "") {
|
|
213
|
+
throw new Error("CDP_BROWSER must name a compatible executable.");
|
|
214
|
+
}
|
|
215
|
+
const desktop = override
|
|
216
|
+
? {
|
|
217
|
+
executable: override,
|
|
218
|
+
args: ["about:blank"],
|
|
219
|
+
workingDirectory: undefined,
|
|
220
|
+
}
|
|
221
|
+
: await configuredDefaultBrowser(signal);
|
|
222
|
+
const fromDesktop = new Set<string>();
|
|
223
|
+
for (const arg of desktop.args) {
|
|
224
|
+
if (arg === "--") {
|
|
225
|
+
throw new Error(
|
|
226
|
+
"The default browser's desktop command has an option separator, so CDP arguments cannot be appended safely. Set CDP_BROWSER or start the browser yourself with CDP enabled.",
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
const [name = ""] = arg.split("=", 1);
|
|
230
|
+
const key =
|
|
231
|
+
name.startsWith("-") && !name.startsWith("--") ? `-${name}` : name;
|
|
232
|
+
const value = arg.startsWith(name + "=") ? arg.slice(name.length + 1) : "";
|
|
233
|
+
const configured = switches.get(key);
|
|
234
|
+
if (
|
|
235
|
+
key === "--remote-debugging-pipe" ||
|
|
236
|
+
(configured !== undefined && configured !== value)
|
|
237
|
+
) {
|
|
238
|
+
throw new Error(
|
|
239
|
+
`The default browser's desktop arguments conflict with ${key}. Adjust the CDP configuration or start the browser yourself.`,
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
if (
|
|
243
|
+
key === "--user-data-dir" &&
|
|
244
|
+
!isAbsolute(value) &&
|
|
245
|
+
!desktop.workingDirectory
|
|
246
|
+
) {
|
|
247
|
+
throw new Error(
|
|
248
|
+
"The default browser uses a relative --user-data-dir without a desktop working directory. Start the browser yourself with CDP enabled.",
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
fromDesktop.add(key);
|
|
252
|
+
}
|
|
253
|
+
const args = [
|
|
254
|
+
// Only the selected entry knows its launcher's argument structure.
|
|
255
|
+
// Keep its complete argument prefix and attempt CDP, then probe the port.
|
|
256
|
+
...(override ? [] : desktop.args),
|
|
257
|
+
...[...switches]
|
|
258
|
+
.filter(([key]) => !fromDesktop.has(key))
|
|
259
|
+
.map(([key, value]) => `${key}=${value}`),
|
|
260
|
+
...(override ? desktop.args : []),
|
|
261
|
+
];
|
|
262
|
+
// systemd expands variables in ExecStart even without a shell. Preserve
|
|
263
|
+
// dollar signs in the executable path itself without changing which file runs.
|
|
264
|
+
const literalExecutable = desktop.executable.includes("$");
|
|
265
|
+
return [
|
|
266
|
+
...(desktop.workingDirectory
|
|
267
|
+
? [`--property=WorkingDirectory=${desktop.workingDirectory}`]
|
|
268
|
+
: []),
|
|
269
|
+
...(literalExecutable ? ["--expand-environment=no"] : []),
|
|
270
|
+
"--",
|
|
271
|
+
desktop.executable,
|
|
272
|
+
...(literalExecutable
|
|
273
|
+
? args
|
|
274
|
+
: args.map((arg) => arg.replaceAll("$", () => "$$"))),
|
|
275
|
+
];
|
|
276
|
+
}
|
|
277
|
+
|
|
113
278
|
async function unitExists(
|
|
114
279
|
systemctl: string,
|
|
115
280
|
signal?: AbortSignal,
|
|
@@ -156,7 +321,7 @@ export async function startBrowser(signal?: AbortSignal): Promise<string> {
|
|
|
156
321
|
}
|
|
157
322
|
const systemctl = process.env["CDP_SYSTEMCTL"] ?? "/usr/bin/systemctl";
|
|
158
323
|
const systemdRun = process.env["CDP_SYSTEMD_RUN"] ?? "/usr/bin/systemd-run";
|
|
159
|
-
|
|
324
|
+
let launchCommand: string[] | undefined;
|
|
160
325
|
let lastLaunchError = "";
|
|
161
326
|
for (let attempt = 0; attempt < 3; attempt++) {
|
|
162
327
|
const state = await waitForBrowserOrUnitRemoval(systemctl, signal);
|
|
@@ -168,20 +333,12 @@ export async function startBrowser(signal?: AbortSignal): Promise<string> {
|
|
|
168
333
|
`Browser unit ${BROWSER_UNIT} remained loaded without exposing CDP at ${host}:${port}`,
|
|
169
334
|
);
|
|
170
335
|
}
|
|
336
|
+
launchCommand ??= await browserLaunchCommand(host, port, signal);
|
|
171
337
|
await runProcess(
|
|
172
338
|
systemctl,
|
|
173
339
|
["--user", "reset-failed", BROWSER_UNIT],
|
|
174
340
|
signal,
|
|
175
341
|
);
|
|
176
|
-
const browserArgs = [
|
|
177
|
-
`--remote-debugging-address=${host}`,
|
|
178
|
-
`--remote-debugging-port=${port}`,
|
|
179
|
-
];
|
|
180
|
-
const profile = process.env["CDP_PROFILE_DIRECTORY"];
|
|
181
|
-
if (profile) {
|
|
182
|
-
browserArgs.push(`--profile-directory=${profile}`);
|
|
183
|
-
}
|
|
184
|
-
browserArgs.push("about:blank");
|
|
185
342
|
const launched = await runProcess(
|
|
186
343
|
systemdRun,
|
|
187
344
|
[
|
|
@@ -190,8 +347,7 @@ export async function startBrowser(signal?: AbortSignal): Promise<string> {
|
|
|
190
347
|
"--collect",
|
|
191
348
|
"--property=Type=exec",
|
|
192
349
|
"--property=Restart=no",
|
|
193
|
-
|
|
194
|
-
...browserArgs,
|
|
350
|
+
...launchCommand,
|
|
195
351
|
],
|
|
196
352
|
signal,
|
|
197
353
|
);
|
package/src/cdp/client.ts
CHANGED
|
@@ -28,12 +28,12 @@ function timeoutError(method: string, attempts: number): Error {
|
|
|
28
28
|
const seconds = CDP_TIMEOUT_MS / 1_000;
|
|
29
29
|
if (attempts > 1) {
|
|
30
30
|
return new Error(
|
|
31
|
-
|
|
31
|
+
`${method} timed out twice (${seconds}s each). Tab may be unresponsive or suspended.`,
|
|
32
32
|
);
|
|
33
33
|
}
|
|
34
34
|
if (method === "Runtime.evaluate") {
|
|
35
35
|
return new Error(
|
|
36
|
-
`
|
|
36
|
+
`Runtime.evaluate timed out (${seconds}s). Expression or awaited promise may still be running. Check effects before retrying.`,
|
|
37
37
|
);
|
|
38
38
|
}
|
|
39
39
|
return new Error(`Chrome did not answer ${method} within ${seconds}s.`);
|
package/src/cdp/tabs.ts
CHANGED
|
@@ -175,7 +175,7 @@ export class BrowserTabs {
|
|
|
175
175
|
);
|
|
176
176
|
} catch (error) {
|
|
177
177
|
throw new Error(
|
|
178
|
-
`
|
|
178
|
+
`Tab may have opened as shared. Run tabs before retrying: ${errorMessage(error)}`,
|
|
179
179
|
);
|
|
180
180
|
}
|
|
181
181
|
if (typeof response["targetId"] !== "string")
|
|
@@ -187,7 +187,7 @@ export class BrowserTabs {
|
|
|
187
187
|
await this.remember(created);
|
|
188
188
|
} catch (error) {
|
|
189
189
|
throw new Error(
|
|
190
|
-
`Opened tab ${created}
|
|
190
|
+
`Opened tab ${created}. Ownership save failed. Tab remains shared: ${errorMessage(error)}`,
|
|
191
191
|
);
|
|
192
192
|
}
|
|
193
193
|
return created;
|