repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/the-system/open-browser.ts

Raw
File outline
import { spawn } from "node:child_process";
import { pathToFileURL } from "node:url";

export type BrowserOpenResult =
	| { ok: true; url: string; command: string }
	| { ok: false; url: string; error: string };

export async function openHtmlFile(file: string): Promise<BrowserOpenResult> {
	const url = pathToFileURL(file).href;
	if (process.env.NODE_ENV === "test" || process.env.VITEST)
		return { ok: false, url, error: "Browser opener disabled" };
	for (const candidate of openerCandidates(url)) {
		const ok = await trySpawn(candidate.command, candidate.args);
		if (ok) return { ok: true, url, command: candidate.command };
	}
	return { ok: false, url, error: "No browser opener found" };
}

function openerCandidates(
	url: string,
): Array<{ command: string; args: string[] }> {
	if (process.env.TERMUX_VERSION)
		return [{ command: "termux-open-url", args: [url] }];
	if (process.platform === "darwin") return [{ command: "open", args: [url] }];
	if (process.platform === "win32")
		return [{ command: "cmd.exe", args: ["/c", "start", "", url] }];
	return [
		{ command: "xdg-open", args: [url] },
		{ command: "wslview", args: [url] },
		{ command: "gio", args: ["open", url] },
	];
}

function trySpawn(command: string, args: string[]): Promise<boolean> {
	return new Promise((resolve) => {
		const child = spawn(command, args, { detached: true, stdio: "ignore" });
		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();
	});
}