repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/ui/open.ts
Rawimport { spawn } from "node:child_process";
import { uiError } from "./errors";
export type OpenerCandidate = {
command: string;
args: string[];
windowsHide?: boolean;
};
export function openerCandidates(
url: string,
options: { platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv } = {},
): OpenerCandidate[] {
const platform = options.platform ?? process.platform;
const env = options.env ?? process.env;
if (env.TERMUX_VERSION) return [{ command: "termux-open-url", args: [url] }];
if (platform === "darwin") return [{ command: "open", args: [url] }];
if (platform === "win32") {
return [{ command: "explorer.exe", args: [url], windowsHide: true }];
}
return [
{ command: "xdg-open", args: [url] },
{ command: "wslview", args: [url] },
{ command: "gio", args: ["open", url] },
];
}
export async function openBrowser(url: string): Promise<void> {
if (
process.env.NODE_ENV === "test" ||
process.env.VITEST ||
process.env.PI_UI_NO_AUTO_OPEN === "1"
)
return;
for (const candidate of openerCandidates(url)) {
if (await trySpawn(candidate.command, candidate.args)) return;
}
throw uiError("open_failed", "Could not open browser", {
action:
"Open the /ui link manually from the terminal widget or scan the QR code.",
retryable: true,
});
}
function trySpawn(command: string, args: string[]): Promise<boolean> {
return new Promise((resolve) => {
const child = spawn(command, args, {
detached: true,
stdio: "ignore",
windowsHide: true,
});
let settled = false;
const done = (ok: boolean) => {
if (settled) return;
settled = true;
resolve(ok);
};
child.once("error", () => done(false));
child.once("spawn", () => {
child.unref();
done(true);
});
setTimeout(() => done(false), 1500).unref();
});
}