Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/the-system/__tests__/open-browser.test.ts

Raw
import assert from "node:assert/strict";
import {
	chmodSync,
	copyFileSync,
	existsSync,
	mkdtempSync,
	readFileSync,
	realpathSync,
	rmSync,
	writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, it } from "vitest";
import { openUrl } from "../open-browser.ts";

const roots: string[] = [];

afterEach(() => {
	for (const root of roots.splice(0))
		rmSync(root, { recursive: true, force: true });
});

describe("System browser opener", () => {
	it("opens through the native win32 URL handler without cmd", async () => {
		const root = mkdtempSync(path.join(tmpdir(), "system-browser-"));
		roots.push(root);
		const executable = path.join(root, "rundll32.exe");
		const preload = path.join(root, "record.cjs");
		const record = path.join(root, "args.json");
		const temporaryRecord = path.join(root, "args.json.tmp");
		const url = "http://127.0.0.1:12345/board.html?k=token";
		copyFileSync(process.execPath, executable);
		chmodSync(executable, 0o755);
		writeFileSync(
			preload,
			`const fs = require("node:fs"); fs.writeFileSync(${JSON.stringify(temporaryRecord)}, JSON.stringify({ args: process.argv.slice(1), cwd: process.cwd() })); fs.renameSync(${JSON.stringify(temporaryRecord)}, ${JSON.stringify(record)});`,
		);
		const opened = await openUrl(url, {
			platform: "win32",
			env: {
				...process.env,
				PATH: root,
				NODE_ENV: "",
				TERMUX_VERSION: "",
				VITEST: "",
				NODE_OPTIONS: `--require=${preload}`,
			},
		});
		assert.equal(opened.ok, true);
		if (!opened.ok) return;
		assert.equal(opened.command, "rundll32.exe");
		for (let attempt = 0; attempt < 500 && !existsSync(record); attempt++)
			await new Promise((resolve) => setTimeout(resolve, 10));
		const result = JSON.parse(readFileSync(record, "utf8")) as {
			args: string[];
			cwd: string;
		};
		assert.equal(
			path.basename(result.args[0] ?? ""),
			"url.dll,FileProtocolHandler",
		);
		assert.equal(result.args[1], opened.url);
		assert.equal(realpathSync(result.cwd), realpathSync("/"));
	});
});