Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/lsp/__tests__/launcher.test.ts

Raw
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, expect, it } from "vitest";
import { peer } from "../__serial__/peer.ts";
import { Client } from "../src/client.ts";
import { executable } from "../src/registry.ts";

const directories: string[] = [];
const clients: Client[] = [];
afterEach(async () => {
	await Promise.all(clients.splice(0).map((client) => client.close()));
	await Promise.all(
		directories
			.splice(0)
			.map((path) => rm(path, { recursive: true, force: true })),
	);
});

async function temp(): Promise<string> {
	const path = await mkdtemp(join(tmpdir(), "pi-lsp-win32-launcher-"));
	directories.push(path);
	return path;
}

async function npmPackage(
	base: string,
	layout: "local" | "global",
	peerScript: string,
	bin = "bin/owned-peer.mjs",
): Promise<string> {
	const prefix = join(base, "node_modules");
	const packageDir = join(prefix, "typescript-language-server");
	const shimDir = layout === "local" ? join(prefix, ".bin") : base;
	await mkdir(join(packageDir, "bin"), { recursive: true });
	await mkdir(shimDir, { recursive: true });
	await writeFile(
		join(packageDir, "package.json"),
		JSON.stringify({
			name: "typescript-language-server",
			bin: { "typescript-language-server": bin },
		}),
	);
	await writeFile(join(packageDir, "bin/owned-peer.mjs"), peerScript);
	await writeFile(
		join(shimDir, "typescript-language-server.cmd"),
		"@echo off\r\nnot executed\r\n",
	);
	return shimDir;
}

async function actualQuery(
	layout: "local" | "global",
): Promise<{ identity: string; pid: number }> {
	const root = await temp();
	const config = await peer(root, "normal");
	const script = config.args[0];
	if (!script) throw new Error("peer script missing");
	const path = await npmPackage(
		join(root, "npm space"),
		layout,
		await readFile(script, "utf8"),
	);
	const launch = await executable("typescript-language-server", {
		platform: "win32",
		path,
	});
	expect(launch.command).toBe(process.execPath);
	expect(launch.args).toHaveLength(1);
	const scriptArg = launch.args[0];
	if (!scriptArg) throw new Error("npm launcher script missing");
	const client = new Client(root, { ...config, args: ["--sentinel"] }, launch);
	clients.push(client);
	expect(client.child.spawnargs.slice(-2)).toEqual([scriptArg, "--sentinel"]);
	const file = join(root, "main.go");
	await writeFile(file, "package fixture\nvar Value = 1\n");
	const response = (await client.query(
		"hover",
		file,
		2,
		5,
		AbortSignal.timeout(3000),
	)) as { contents: string };
	const state = JSON.parse(response.contents) as { pid: number };
	await client.close();
	await client.exited;
	return { identity: launch.identity, pid: state.pid };
}

it("launches local and global npm shims through Node without executing cmd", async () => {
	const local = await actualQuery("local");
	const global = await actualQuery("global");
	expect(local.pid).not.toBe(global.pid);
	expect(local.identity).not.toBe(global.identity);
});

it("keeps PATH precedence and native executable precedence", async () => {
	const root = await temp();
	const config = await peer(root, "normal");
	const script = config.args[0];
	if (!script) throw new Error("peer script missing");
	const first = await npmPackage(
		join(root, "first"),
		"local",
		await readFile(script, "utf8"),
	);
	const second = await npmPackage(
		join(root, "second"),
		"global",
		await readFile(script, "utf8"),
	);
	const selected = await executable("typescript-language-server", {
		platform: "win32",
		path: `${first};${second}`,
	});
	expect(selected.identity).toContain(first);
	await writeFile(join(first, "typescript-language-server.exe"), "native");
	const native = await executable("typescript-language-server", {
		platform: "win32",
		path: `${first};${second}`,
	});
	expect(native.command).toBe(join(first, "typescript-language-server.exe"));
	expect(native.args).toEqual([]);
});

it.each([
	[
		"broken metadata",
		async (root: string, _shim: string) =>
			writeFile(
				join(root, "node_modules/typescript-language-server/package.json"),
				"{",
			),
		"invalid npm metadata",
	],
	[
		"escaping bin",
		async (root: string) =>
			writeFile(
				join(root, "node_modules/typescript-language-server/package.json"),
				JSON.stringify({
					name: "typescript-language-server",
					bin: "../escape.mjs",
				}),
			),
		"invalid npm metadata",
	],
	[
		"package without shim",
		async (root: string) =>
			rm(join(root, "node_modules/.bin/typescript-language-server.cmd")),
		"not found on PATH",
	],
] as const)(
	"rejects %s rather than repairing or bypassing npm launcher",
	async (_name, mutate, message) => {
		const root = await temp();
		const shim = await npmPackage(root, "local", "process.exit(0)");
		await mutate(root, shim);
		await expect(
			executable("typescript-language-server", {
				platform: "win32",
				path: shim,
			}),
		).rejects.toMatchObject({
			status: "missing_tool",
			message: expect.stringContaining(message),
		});
	},
);

it("does not search ancestor npm package decoys", async () => {
	const root = await temp();
	const shim = join(root, "project/node_modules/.bin");
	await mkdir(shim, { recursive: true });
	await writeFile(
		join(shim, "typescript-language-server.cmd"),
		"@echo off\r\n",
	);
	await npmPackage(root, "local", "process.exit(0)");
	await expect(
		executable("typescript-language-server", { platform: "win32", path: shim }),
	).rejects.toMatchObject({ status: "missing_tool" });
});

it("does not accept cmd shims for unrelated servers", async () => {
	const root = await temp();
	const shim = await npmPackage(root, "local", "process.exit(0)");
	await expect(
		executable("clangd", { platform: "win32", path: shim }),
	).rejects.toMatchObject({ status: "missing_tool" });
});