@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
|
@@ -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
|
const BROWSER_START_TIMEOUT_MS = 10_000;
|
|
4
7
|
const BROWSER_UNIT = "chrome-cdp-browser.service";
|
|
5
8
|
const PROCESS_OUTPUT_LIMIT = 1 * 1_024 * 1_024;
|
|
@@ -8,12 +11,13 @@ function abortReason(signal) {
|
|
|
8
11
|
? signal.reason
|
|
9
12
|
: new Error("Browser launch aborted");
|
|
10
13
|
}
|
|
11
|
-
function runProcess(command, args, signal) {
|
|
14
|
+
function runProcess(command, args, signal, env) {
|
|
12
15
|
if (signal?.aborted)
|
|
13
16
|
return Promise.reject(abortReason(signal));
|
|
14
17
|
return new Promise((resolveValue, reject) => {
|
|
15
18
|
const child = spawn(command, args, {
|
|
16
19
|
stdio: ["ignore", "pipe", "pipe"],
|
|
20
|
+
env,
|
|
17
21
|
});
|
|
18
22
|
let stdout = "";
|
|
19
23
|
let stderr = "";
|
|
@@ -92,7 +96,135 @@ async function waitForDebugEndpoint(signal, timeout = BROWSER_START_TIMEOUT_MS)
|
|
|
92
96
|
}
|
|
93
97
|
await sleep(100, signal);
|
|
94
98
|
}
|
|
95
|
-
throw new Error(`Browser did not expose CDP at ${host}:${port} within ${timeout}ms${lastError instanceof Error ? ` (${lastError.message})` : ""}
|
|
99
|
+
throw new Error(`Browser did not expose CDP at ${host}:${port} within ${timeout}ms${lastError instanceof Error ? ` (${lastError.message})` : ""}. 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.`);
|
|
100
|
+
}
|
|
101
|
+
function hasGraphicalDesktop(env) {
|
|
102
|
+
return Boolean(env["WAYLAND_DISPLAY"]?.trim() || env["DISPLAY"]?.trim());
|
|
103
|
+
}
|
|
104
|
+
async function graphicalEnvironment(signal) {
|
|
105
|
+
if (!process.env["SSH_CONNECTION"] && hasGraphicalDesktop(process.env)) {
|
|
106
|
+
return { ...process.env };
|
|
107
|
+
}
|
|
108
|
+
// The remote worker inherits SSH's environment, which can select a
|
|
109
|
+
// different MIME association from the graphical systemd user session.
|
|
110
|
+
const result = await runProcess("busctl", [
|
|
111
|
+
"--user",
|
|
112
|
+
"--json=short",
|
|
113
|
+
"get-property",
|
|
114
|
+
"org.freedesktop.systemd1",
|
|
115
|
+
"/org/freedesktop/systemd1",
|
|
116
|
+
"org.freedesktop.systemd1.Manager",
|
|
117
|
+
"Environment",
|
|
118
|
+
], signal);
|
|
119
|
+
if (result.code !== 0)
|
|
120
|
+
throw new Error("systemd user environment unavailable");
|
|
121
|
+
const reply = asRecord(JSON.parse(result.stdout), "systemd user environment");
|
|
122
|
+
if (reply["type"] !== "as" || !Array.isArray(reply["data"])) {
|
|
123
|
+
throw new Error("Invalid systemd user environment");
|
|
124
|
+
}
|
|
125
|
+
const entries = [];
|
|
126
|
+
for (const assignment of reply["data"]) {
|
|
127
|
+
if (typeof assignment !== "string")
|
|
128
|
+
throw new Error("Invalid systemd environment variable");
|
|
129
|
+
const equals = assignment.indexOf("=");
|
|
130
|
+
if (equals <= 0)
|
|
131
|
+
throw new Error("Invalid systemd environment variable");
|
|
132
|
+
entries.push([assignment.slice(0, equals), assignment.slice(equals + 1)]);
|
|
133
|
+
}
|
|
134
|
+
const env = Object.fromEntries(entries);
|
|
135
|
+
if (!hasGraphicalDesktop(env))
|
|
136
|
+
throw new Error("systemd has no graphical desktop environment");
|
|
137
|
+
return env;
|
|
138
|
+
}
|
|
139
|
+
async function configuredDefaultBrowser(signal) {
|
|
140
|
+
const timeout = AbortSignal.timeout(5_000);
|
|
141
|
+
const lookupSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
142
|
+
let env;
|
|
143
|
+
try {
|
|
144
|
+
env = await graphicalEnvironment(lookupSignal);
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
signal?.throwIfAborted();
|
|
148
|
+
throw new Error("Could not determine the graphical desktop environment. Set CDP_BROWSER or start a browser with CDP enabled yourself.", { cause: error });
|
|
149
|
+
}
|
|
150
|
+
// xdg-settings uses the shell's BROWSER setting ahead of desktop
|
|
151
|
+
// associations on generic desktops.
|
|
152
|
+
delete env["BROWSER"];
|
|
153
|
+
let id;
|
|
154
|
+
try {
|
|
155
|
+
const result = await runProcess("xdg-settings", ["get", "default-web-browser"], lookupSignal, env);
|
|
156
|
+
if (result.code !== 0)
|
|
157
|
+
throw new Error(result.stderr || `exit ${result.code}`);
|
|
158
|
+
id = result.stdout;
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
signal?.throwIfAborted();
|
|
162
|
+
throw new Error("Could not query the configured default browser with xdg-settings. Set CDP_BROWSER or start a browser with CDP enabled yourself.", { cause: error });
|
|
163
|
+
}
|
|
164
|
+
return resolveDefaultBrowser(id, env);
|
|
165
|
+
}
|
|
166
|
+
async function browserLaunchCommand(host, port, signal) {
|
|
167
|
+
const switches = new Map([
|
|
168
|
+
["--remote-debugging-address", host],
|
|
169
|
+
["--remote-debugging-port", port],
|
|
170
|
+
]);
|
|
171
|
+
const profile = process.env["CDP_PROFILE_DIRECTORY"];
|
|
172
|
+
if (profile)
|
|
173
|
+
switches.set("--profile-directory", profile);
|
|
174
|
+
const override = process.env["CDP_BROWSER"];
|
|
175
|
+
if (override === "") {
|
|
176
|
+
throw new Error("CDP_BROWSER must name a compatible executable.");
|
|
177
|
+
}
|
|
178
|
+
const desktop = override
|
|
179
|
+
? {
|
|
180
|
+
executable: override,
|
|
181
|
+
args: ["about:blank"],
|
|
182
|
+
workingDirectory: undefined,
|
|
183
|
+
}
|
|
184
|
+
: await configuredDefaultBrowser(signal);
|
|
185
|
+
const fromDesktop = new Set();
|
|
186
|
+
for (const arg of desktop.args) {
|
|
187
|
+
if (arg === "--") {
|
|
188
|
+
throw new Error("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.");
|
|
189
|
+
}
|
|
190
|
+
const [name = ""] = arg.split("=", 1);
|
|
191
|
+
const key = name.startsWith("-") && !name.startsWith("--") ? `-${name}` : name;
|
|
192
|
+
const value = arg.startsWith(name + "=") ? arg.slice(name.length + 1) : "";
|
|
193
|
+
const configured = switches.get(key);
|
|
194
|
+
if (key === "--remote-debugging-pipe" ||
|
|
195
|
+
(configured !== undefined && configured !== value)) {
|
|
196
|
+
throw new Error(`The default browser's desktop arguments conflict with ${key}. Adjust the CDP configuration or start the browser yourself.`);
|
|
197
|
+
}
|
|
198
|
+
if (key === "--user-data-dir" &&
|
|
199
|
+
!isAbsolute(value) &&
|
|
200
|
+
!desktop.workingDirectory) {
|
|
201
|
+
throw new Error("The default browser uses a relative --user-data-dir without a desktop working directory. Start the browser yourself with CDP enabled.");
|
|
202
|
+
}
|
|
203
|
+
fromDesktop.add(key);
|
|
204
|
+
}
|
|
205
|
+
const args = [
|
|
206
|
+
// Only the selected entry knows its launcher's argument structure.
|
|
207
|
+
// Keep its complete argument prefix and attempt CDP, then probe the port.
|
|
208
|
+
...(override ? [] : desktop.args),
|
|
209
|
+
...[...switches]
|
|
210
|
+
.filter(([key]) => !fromDesktop.has(key))
|
|
211
|
+
.map(([key, value]) => `${key}=${value}`),
|
|
212
|
+
...(override ? desktop.args : []),
|
|
213
|
+
];
|
|
214
|
+
// systemd expands variables in ExecStart even without a shell. Preserve
|
|
215
|
+
// dollar signs in the executable path itself without changing which file runs.
|
|
216
|
+
const literalExecutable = desktop.executable.includes("$");
|
|
217
|
+
return [
|
|
218
|
+
...(desktop.workingDirectory
|
|
219
|
+
? [`--property=WorkingDirectory=${desktop.workingDirectory}`]
|
|
220
|
+
: []),
|
|
221
|
+
...(literalExecutable ? ["--expand-environment=no"] : []),
|
|
222
|
+
"--",
|
|
223
|
+
desktop.executable,
|
|
224
|
+
...(literalExecutable
|
|
225
|
+
? args
|
|
226
|
+
: args.map((arg) => arg.replaceAll("$", () => "$$"))),
|
|
227
|
+
];
|
|
96
228
|
}
|
|
97
229
|
async function unitExists(systemctl, signal) {
|
|
98
230
|
const result = await runProcess(systemctl, ["--user", "show", BROWSER_UNIT, "--property=LoadState", "--value"], signal);
|
|
@@ -129,7 +261,7 @@ export async function startBrowser(signal) {
|
|
|
129
261
|
}
|
|
130
262
|
const systemctl = process.env["CDP_SYSTEMCTL"] ?? "/usr/bin/systemctl";
|
|
131
263
|
const systemdRun = process.env["CDP_SYSTEMD_RUN"] ?? "/usr/bin/systemd-run";
|
|
132
|
-
|
|
264
|
+
let launchCommand;
|
|
133
265
|
let lastLaunchError = "";
|
|
134
266
|
for (let attempt = 0; attempt < 3; attempt++) {
|
|
135
267
|
const state = await waitForBrowserOrUnitRemoval(systemctl, signal);
|
|
@@ -139,24 +271,15 @@ export async function startBrowser(signal) {
|
|
|
139
271
|
if (state === "timeout") {
|
|
140
272
|
throw new Error(`Browser unit ${BROWSER_UNIT} remained loaded without exposing CDP at ${host}:${port}`);
|
|
141
273
|
}
|
|
274
|
+
launchCommand ??= await browserLaunchCommand(host, port, signal);
|
|
142
275
|
await runProcess(systemctl, ["--user", "reset-failed", BROWSER_UNIT], signal);
|
|
143
|
-
const browserArgs = [
|
|
144
|
-
`--remote-debugging-address=${host}`,
|
|
145
|
-
`--remote-debugging-port=${port}`,
|
|
146
|
-
];
|
|
147
|
-
const profile = process.env["CDP_PROFILE_DIRECTORY"];
|
|
148
|
-
if (profile) {
|
|
149
|
-
browserArgs.push(`--profile-directory=${profile}`);
|
|
150
|
-
}
|
|
151
|
-
browserArgs.push("about:blank");
|
|
152
276
|
const launched = await runProcess(systemdRun, [
|
|
153
277
|
"--user",
|
|
154
278
|
"--unit=chrome-cdp-browser",
|
|
155
279
|
"--collect",
|
|
156
280
|
"--property=Type=exec",
|
|
157
281
|
"--property=Restart=no",
|
|
158
|
-
|
|
159
|
-
...browserArgs,
|
|
282
|
+
...launchCommand,
|
|
160
283
|
], signal);
|
|
161
284
|
if (launched.code === 0) {
|
|
162
285
|
await waitForDebugEndpoint(signal);
|
package/dist/src/cdp/client.js
CHANGED
|
@@ -13,10 +13,10 @@ function cdpTimeoutAttempts(method) {
|
|
|
13
13
|
function timeoutError(method, attempts) {
|
|
14
14
|
const seconds = CDP_TIMEOUT_MS / 1_000;
|
|
15
15
|
if (attempts > 1) {
|
|
16
|
-
return new Error(
|
|
16
|
+
return new Error(`${method} timed out twice (${seconds}s each). Tab may be unresponsive or suspended.`);
|
|
17
17
|
}
|
|
18
18
|
if (method === "Runtime.evaluate") {
|
|
19
|
-
return new Error(`
|
|
19
|
+
return new Error(`Runtime.evaluate timed out (${seconds}s). Expression or awaited promise may still be running. Check effects before retrying.`);
|
|
20
20
|
}
|
|
21
21
|
return new Error(`Chrome did not answer ${method} within ${seconds}s.`);
|
|
22
22
|
}
|
package/dist/src/cdp/tabs.js
CHANGED
|
@@ -134,7 +134,7 @@ export class BrowserTabs {
|
|
|
134
134
|
response = asRecord(await this.cdp.send("Target.createTarget", { url, background: true }), "Target.createTarget response");
|
|
135
135
|
}
|
|
136
136
|
catch (error) {
|
|
137
|
-
throw new Error(`
|
|
137
|
+
throw new Error(`Tab may have opened as shared. Run tabs before retrying: ${errorMessage(error)}`);
|
|
138
138
|
}
|
|
139
139
|
if (typeof response["targetId"] !== "string")
|
|
140
140
|
throw new Error("Chrome did not return a new tab target; run tabs before retrying");
|
|
@@ -143,7 +143,7 @@ export class BrowserTabs {
|
|
|
143
143
|
await this.remember(created);
|
|
144
144
|
}
|
|
145
145
|
catch (error) {
|
|
146
|
-
throw new Error(`Opened tab ${created}
|
|
146
|
+
throw new Error(`Opened tab ${created}. Ownership save failed. Tab remains shared: ${errorMessage(error)}`);
|
|
147
147
|
}
|
|
148
148
|
return created;
|
|
149
149
|
}, signal);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@howaboua/pi-browser",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.17",
|
|
4
4
|
"description": "Logged-in browser inspection and control for Pi, Code Mode and Notebook Mode.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -45,10 +45,10 @@
|
|
|
45
45
|
"format:check": "oxfmt --check '**/*.{js,cjs,mjs,jsx,ts,cts,mts,tsx,json,jsonc,json5,css}'"
|
|
46
46
|
},
|
|
47
47
|
"peerDependencies": {
|
|
48
|
-
"@howaboua/pi-codex-conversion": ">=5.1.
|
|
49
|
-
"@earendil-works/pi-ai": ">=1.
|
|
50
|
-
"@earendil-works/pi-coding-agent": ">=1.
|
|
51
|
-
"@earendil-works/pi-tui": ">=1.
|
|
48
|
+
"@howaboua/pi-codex-conversion": ">=5.1.3",
|
|
49
|
+
"@earendil-works/pi-ai": ">=1.7.0",
|
|
50
|
+
"@earendil-works/pi-coding-agent": ">=1.7.0",
|
|
51
|
+
"@earendil-works/pi-tui": ">=1.7.0"
|
|
52
52
|
},
|
|
53
53
|
"peerDependenciesMeta": {
|
|
54
54
|
"@howaboua/pi-codex-conversion": {
|
|
@@ -56,9 +56,9 @@
|
|
|
56
56
|
}
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
59
|
-
"@howaboua/pi-codex-conversion": "5.1.
|
|
60
|
-
"@earendil-works/pi-ai": "1.
|
|
61
|
-
"@earendil-works/pi-coding-agent": "1.
|
|
59
|
+
"@howaboua/pi-codex-conversion": "5.1.3",
|
|
60
|
+
"@earendil-works/pi-ai": "1.7.0",
|
|
61
|
+
"@earendil-works/pi-coding-agent": "1.7.0",
|
|
62
62
|
"@types/node": "26.6.6",
|
|
63
63
|
"typescript": "7.0.2",
|
|
64
64
|
"oxfmt": "0.79.0"
|
|
@@ -90,6 +90,6 @@
|
|
|
90
90
|
"access": "public"
|
|
91
91
|
},
|
|
92
92
|
"dependencies": {
|
|
93
|
-
"@earendil-works/pi-schema": "1.
|
|
93
|
+
"@earendil-works/pi-schema": "1.7.0"
|
|
94
94
|
}
|
|
95
95
|
}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { access, readdir, readFile, stat } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { isAbsolute, join } from "node:path";
|
|
5
|
+
|
|
6
|
+
interface DesktopBrowser {
|
|
7
|
+
executable: string;
|
|
8
|
+
args: string[];
|
|
9
|
+
workingDirectory: string | undefined;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const RECOVERY =
|
|
13
|
+
"Set CDP_BROWSER to a compatible executable, or start a browser with CDP enabled yourself.";
|
|
14
|
+
|
|
15
|
+
async function missingIsUndefined<T>(
|
|
16
|
+
operation: Promise<T>,
|
|
17
|
+
): Promise<T | undefined> {
|
|
18
|
+
try {
|
|
19
|
+
return await operation;
|
|
20
|
+
} catch (error) {
|
|
21
|
+
if (
|
|
22
|
+
error &&
|
|
23
|
+
typeof error === "object" &&
|
|
24
|
+
"code" in error &&
|
|
25
|
+
(error.code === "ENOENT" || error.code === "ENOTDIR")
|
|
26
|
+
) {
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function desktopFiles(directory: string, id: string): Promise<string[]> {
|
|
34
|
+
const entries = await missingIsUndefined(
|
|
35
|
+
readdir(directory, { withFileTypes: true }),
|
|
36
|
+
);
|
|
37
|
+
const paths: string[] = [];
|
|
38
|
+
for (const entry of entries ?? []) {
|
|
39
|
+
const path = join(directory, entry.name);
|
|
40
|
+
if (entry.name === id && !entry.isDirectory()) {
|
|
41
|
+
paths.push(path);
|
|
42
|
+
} else if (entry.isDirectory() && id.startsWith(entry.name + "-")) {
|
|
43
|
+
// Nested entries derive their IDs by replacing '/' with '-'.
|
|
44
|
+
paths.push(
|
|
45
|
+
...(await desktopFiles(path, id.slice(entry.name.length + 1))),
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return paths;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function findDesktopFile(
|
|
53
|
+
id: string,
|
|
54
|
+
env: NodeJS.ProcessEnv,
|
|
55
|
+
): Promise<string> {
|
|
56
|
+
const userData = env["XDG_DATA_HOME"];
|
|
57
|
+
const home = env["HOME"];
|
|
58
|
+
const systemData = (env["XDG_DATA_DIRS"] || "/usr/local/share:/usr/share")
|
|
59
|
+
.split(":")
|
|
60
|
+
.filter(isAbsolute);
|
|
61
|
+
const roots = [
|
|
62
|
+
userData && isAbsolute(userData)
|
|
63
|
+
? userData
|
|
64
|
+
: join(home && isAbsolute(home) ? home : homedir(), ".local/share"),
|
|
65
|
+
...systemData,
|
|
66
|
+
];
|
|
67
|
+
for (const root of roots) {
|
|
68
|
+
const [path, ambiguous] = await desktopFiles(
|
|
69
|
+
join(root, "applications"),
|
|
70
|
+
id,
|
|
71
|
+
);
|
|
72
|
+
if (ambiguous) throw new Error("the desktop ID is ambiguous");
|
|
73
|
+
if (path) return path;
|
|
74
|
+
}
|
|
75
|
+
throw new Error("the desktop entry was not found");
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function desktopEntry(source: string): Map<string, string> {
|
|
79
|
+
const entry = new Map<string, string>();
|
|
80
|
+
let inDesktopEntry = false;
|
|
81
|
+
for (const line of source.split(/\r?\n/)) {
|
|
82
|
+
const trimmed = line.trim();
|
|
83
|
+
if (trimmed.startsWith("[")) {
|
|
84
|
+
if (inDesktopEntry) break;
|
|
85
|
+
inDesktopEntry = trimmed === "[Desktop Entry]";
|
|
86
|
+
} else if (inDesktopEntry && trimmed && !trimmed.startsWith("#")) {
|
|
87
|
+
const equals = trimmed.indexOf("=");
|
|
88
|
+
if (equals < 1) throw new Error("invalid desktop entry");
|
|
89
|
+
const key = trimmed.slice(0, equals).trimEnd();
|
|
90
|
+
if (entry.has(key)) throw new Error("duplicate desktop entry key");
|
|
91
|
+
entry.set(key, trimmed.slice(equals + 1).trimStart());
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return entry;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function desktopString(value: string): string {
|
|
98
|
+
const escapes: Record<string, string> = {
|
|
99
|
+
s: " ",
|
|
100
|
+
n: "\n",
|
|
101
|
+
t: "\t",
|
|
102
|
+
r: "\r",
|
|
103
|
+
"\\": "\\",
|
|
104
|
+
};
|
|
105
|
+
return value.replace(/\\(.|$)/g, (_match, char: string) => {
|
|
106
|
+
const replacement = escapes[char];
|
|
107
|
+
if (replacement === undefined)
|
|
108
|
+
throw new Error("invalid desktop entry escape");
|
|
109
|
+
return replacement;
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function execArguments(line: string): string[] {
|
|
114
|
+
// Desktop Entry quoting is not shell quoting. Accept literal words and
|
|
115
|
+
// whole double-quoted arguments only; leave nonliteral launchers unsupported.
|
|
116
|
+
const word =
|
|
117
|
+
/(?:"(?:[^"\\]|\\["`$\\])*"|[^ \t\n\r"'\\><~|&;$*?#()`]+)(?=[ \t]|$)/y;
|
|
118
|
+
const args: string[] = [];
|
|
119
|
+
let hasInputField = false;
|
|
120
|
+
for (let remaining = desktopString(line).trim(); remaining;) {
|
|
121
|
+
const match = word.exec(remaining)?.[0];
|
|
122
|
+
if (match === undefined)
|
|
123
|
+
throw new Error("unsupported desktop Exec quoting");
|
|
124
|
+
remaining = remaining.slice(match.length).trimStart();
|
|
125
|
+
word.lastIndex = 0;
|
|
126
|
+
if (args.length !== 0 && /^%[fFuU]$/.test(match)) {
|
|
127
|
+
if (hasInputField) throw new Error("multiple desktop Exec input fields");
|
|
128
|
+
hasInputField = true;
|
|
129
|
+
continue; // No URL or file was requested.
|
|
130
|
+
}
|
|
131
|
+
const unquoted = match.startsWith('"')
|
|
132
|
+
? match.slice(1, -1).replace(/\\(.)/gs, "$1")
|
|
133
|
+
: match;
|
|
134
|
+
args.push(
|
|
135
|
+
unquoted.replace(/%%|%/g, (percent) => {
|
|
136
|
+
if (percent === "%%") return "%";
|
|
137
|
+
throw new Error("unsupported desktop Exec field code");
|
|
138
|
+
}),
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
return args;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async function executablePath(
|
|
145
|
+
executable: string,
|
|
146
|
+
env: NodeJS.ProcessEnv,
|
|
147
|
+
): Promise<string | undefined> {
|
|
148
|
+
const candidates = isAbsolute(executable)
|
|
149
|
+
? [executable]
|
|
150
|
+
: executable.includes("/")
|
|
151
|
+
? []
|
|
152
|
+
: (env["PATH"] ?? "/usr/bin:/bin")
|
|
153
|
+
.split(":")
|
|
154
|
+
.filter(isAbsolute)
|
|
155
|
+
.map((directory) => join(directory, executable));
|
|
156
|
+
for (const path of candidates) {
|
|
157
|
+
try {
|
|
158
|
+
await access(path, constants.X_OK);
|
|
159
|
+
if ((await stat(path)).isFile()) return path;
|
|
160
|
+
} catch {
|
|
161
|
+
// Keep looking on PATH when a candidate isn't executable.
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return undefined;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export async function resolveDefaultBrowser(
|
|
168
|
+
id: string,
|
|
169
|
+
env: NodeJS.ProcessEnv,
|
|
170
|
+
): Promise<DesktopBrowser> {
|
|
171
|
+
if (!/^[A-Za-z0-9_.-]+\.desktop$/.test(id)) {
|
|
172
|
+
throw new Error(
|
|
173
|
+
"Could not determine the configured default browser. " + RECOVERY,
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
const path = await findDesktopFile(id, env);
|
|
178
|
+
if (!(await stat(path)).isFile())
|
|
179
|
+
throw new Error("invalid desktop entry file");
|
|
180
|
+
const entry = desktopEntry(await readFile(path, "utf8"));
|
|
181
|
+
if (
|
|
182
|
+
entry.get("Type") !== "Application" ||
|
|
183
|
+
entry.get("Hidden") === "true" ||
|
|
184
|
+
entry.get("Terminal") === "true" ||
|
|
185
|
+
entry.get("DBusActivatable") === "true"
|
|
186
|
+
) {
|
|
187
|
+
throw new Error(
|
|
188
|
+
"the desktop entry does not use direct application startup",
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
const [command, ...args] = execArguments(entry.get("Exec") ?? "");
|
|
192
|
+
if (!command || command.includes("=")) {
|
|
193
|
+
throw new Error("the desktop entry has no valid executable");
|
|
194
|
+
}
|
|
195
|
+
const executable = await executablePath(command, env);
|
|
196
|
+
const tryExec = desktopString(entry.get("TryExec") ?? "");
|
|
197
|
+
if (!executable || (tryExec && !(await executablePath(tryExec, env)))) {
|
|
198
|
+
throw new Error("the desktop executable is unavailable");
|
|
199
|
+
}
|
|
200
|
+
const workingDirectory =
|
|
201
|
+
desktopString(entry.get("Path") ?? "") || undefined;
|
|
202
|
+
if (workingDirectory && !isAbsolute(workingDirectory)) {
|
|
203
|
+
throw new Error("the desktop working directory is not absolute");
|
|
204
|
+
}
|
|
205
|
+
return { executable, args, workingDirectory };
|
|
206
|
+
} catch (error) {
|
|
207
|
+
throw new Error(
|
|
208
|
+
'Cannot start the default browser "' +
|
|
209
|
+
id +
|
|
210
|
+
'": ' +
|
|
211
|
+
(error instanceof Error ? error.message : String(error)) +
|
|
212
|
+
". " +
|
|
213
|
+
RECOVERY,
|
|
214
|
+
{ cause: error },
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
}
|
package/src/browser/help.ts
CHANGED
|
@@ -25,7 +25,7 @@ export function browserHelp(
|
|
|
25
25
|
type: "ref_id text id?; id focuses",
|
|
26
26
|
fill: "ref_id id|selector value; replace/clear text, select option value/label, boolean checks/unchecks",
|
|
27
27
|
press: "ref_id key; focused element, e.g. Enter or Control+a",
|
|
28
|
-
wait: "ref_id selector|text|url_includes timeout_ms?; DOM presence or substring
|
|
28
|
+
wait: "ref_id selector|text|url_includes timeout_ms?; DOM presence or substring",
|
|
29
29
|
screenshot: "ref_id id?|selector?; brings tab to foreground -> file",
|
|
30
30
|
navigate: "ref_id url",
|
|
31
31
|
html: "ref_id id?|selector?",
|