repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/diff-review/open-browser.ts

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

export async function openBrowser(
	url: string,
): Promise<{ ok: boolean; command?: string; error?: string }> {
	if (
		process.env.NODE_ENV === "test" ||
		process.env.VITEST ||
		process.env.PI_DIFF_REVIEW_NO_OPEN
	)
		return { ok: false, error: "Browser opener disabled" };

	const candidates = openerCandidates(url);
	for (const candidate of candidates) {
		const result = await trySpawn(candidate.command, candidate.args);
		if (result.ok) return { ok: true, command: candidate.command };
	}
	return { ok: false, 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<{ ok: boolean; error?: string }> {
	return new Promise((resolve) => {
		const child = spawn(command, args, { detached: true, stdio: "ignore" });
		let settled = false;
		const done = (ok: boolean, error?: string) => {
			if (settled) return;
			settled = true;
			resolve({ ok, error });
		};
		child.once("error", (err) => done(false, err.message));
		child.once("spawn", () => {
			child.unref();
			done(true);
		});
		setTimeout(() => done(false, "timeout"), 1500).unref();
	});
}