Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/lsp/src/registry.ts

Raw
import { constants } from "node:fs";
import { access, stat } from "node:fs/promises";
import {
	basename,
	delimiter,
	dirname,
	extname,
	isAbsolute,
	relative,
	resolve,
} from "node:path";
import { fileURLToPath } from "node:url";
import { LspFailure, snapshot } from "./source.ts";

export interface Profile {
	id: string;
	command: string;
	args: string[];
	language: string;
	extensions?: string[];
	roots?: string[];
	provenance?: Record<string, unknown>;
	initializationOptions: Record<string, unknown>;
	settings: Record<string, unknown>;
}

export async function profile(
	file?: string,
	server?: string,
): Promise<Profile> {
	try {
		const path = fileURLToPath(
			new URL(
				import.meta.url.endsWith("/src/registry.ts")
					? "../registry/servers.json"
					: "./registry/servers.json",
				import.meta.url,
			),
		);
		const value = JSON.parse(await snapshot(path));
		if (
			value.schemaVersion !== 1 ||
			!Array.isArray(value.profiles) ||
			value.profiles.length < 1 ||
			value.profiles.length > 16
		)
			throw new Error("Invalid registry");
		const ids = new Set<string>();
		for (const p of value.profiles) {
			if (
				!p ||
				typeof p.id !== "string" ||
				!/^[a-z0-9-]{1,64}$/u.test(p.id) ||
				ids.has(p.id) ||
				typeof p.command !== "string" ||
				!/^[a-zA-Z0-9_-]{1,128}$/u.test(p.command) ||
				!Array.isArray(p.args) ||
				p.args.length > 32 ||
				p.args.some((a: unknown) => typeof a !== "string" || a.length > 4096) ||
				typeof p.language !== "string" ||
				!Array.isArray(p.extensions) ||
				!p.extensions.length ||
				p.extensions.length > 32 ||
				p.extensions.some(
					(e: unknown) => typeof e !== "string" || !/^\.[a-zA-Z0-9]+$/u.test(e),
				) ||
				!Array.isArray(p.roots) ||
				p.roots.length > 32 ||
				p.roots.some(
					(r: unknown) =>
						typeof r !== "string" || !/^[a-zA-Z0-9_.-]{1,128}$/u.test(r),
				) ||
				!p.initializationOptions ||
				typeof p.initializationOptions !== "object" ||
				Array.isArray(p.initializationOptions) ||
				!p.settings ||
				typeof p.settings !== "object" ||
				Array.isArray(p.settings) ||
				!p.provenance
			)
				throw new Error("Invalid profile");
			ids.add(p.id);
		}
		const matches = (value.profiles as Profile[]).filter(
			(p) =>
				(!server || p.id === server) &&
				(!file || p.extensions?.includes(extname(file))),
		);
		if (matches.length !== 1)
			throw new LspFailure(
				matches.length ? "ambiguous" : "unsupported",
				matches.length
					? "Specify server: " + matches.map((p) => p.id).join(", ")
					: "No packaged server profile matches file/server selector.",
			);
		return matches[0] as Profile;
	} catch (error) {
		if (error instanceof LspFailure) throw error;
		throw new LspFailure(
			"invalid_config",
			"Invalid or unavailable packaged server registry; rebuild/reinstall package.",
		);
	}
}

export interface LaunchDescriptor {
	command: string;
	args: string[];
	identity: string;
}

interface ExecutableOptions {
	platform?: NodeJS.Platform;
	path?: string;
}

async function regularReadable(
	path: string,
	mode = constants.R_OK,
): Promise<boolean> {
	try {
		if (!(await stat(path)).isFile()) return false;
		await access(path, mode);
		return true;
	} catch {
		return false;
	}
}

function packagePath(directory: string, bin: string): string | undefined {
	if (
		typeof bin !== "string" ||
		bin.length < 1 ||
		bin.length > 4096 ||
		isAbsolute(bin)
	)
		return undefined;
	const path = resolve(directory, bin);
	const rel = relative(directory, path);
	return rel &&
		rel !== ".." &&
		!rel.startsWith("../") &&
		!rel.startsWith("..\\") &&
		!isAbsolute(rel)
		? path
		: undefined;
}

async function npmShim(
	directory: string,
	shim: string,
): Promise<LaunchDescriptor | undefined> {
	const packageDirs =
		basename(directory) === ".bin" &&
		basename(dirname(directory)) === "node_modules"
			? [resolve(directory, "..", "typescript-language-server")]
			: [resolve(directory, "node_modules", "typescript-language-server")];
	for (const packageDir of packageDirs) {
		const manifest = resolve(packageDir, "package.json");
		try {
			const value: unknown = JSON.parse(await snapshot(manifest));
			if (!value || typeof value !== "object" || Array.isArray(value)) continue;
			const record = value as { name?: unknown; bin?: unknown };
			const bin =
				typeof record.bin === "string"
					? record.bin
					: record.bin &&
							typeof record.bin === "object" &&
							!Array.isArray(record.bin)
						? (record.bin as Record<string, unknown>)[
								"typescript-language-server"
							]
						: undefined;
			const script = packagePath(packageDir, bin as string);
			if (
				record.name !== "typescript-language-server" ||
				!script ||
				!(await regularReadable(script))
			)
				throw new Error("invalid npm shim metadata");
			return {
				command: process.execPath,
				args: [script],
				identity: `${shim}:${script}`,
			};
		} catch (error) {
			if ((error as NodeJS.ErrnoException).code === "ENOENT") continue;
			throw error;
		}
	}
	return undefined;
}

export async function executable(
	command: string,
	options: ExecutableOptions = {},
): Promise<LaunchDescriptor> {
	const platform = options.platform ?? process.platform;
	const path =
		options.path ??
		Object.entries(process.env).find(
			([key]) => key.toLowerCase() === "path",
		)?.[1] ??
		"";
	const separator = platform === "win32" ? ";" : delimiter;
	for (const dir of path.split(separator).filter(Boolean).slice(0, 128)) {
		const native = resolve(
			dir,
			platform === "win32" ? `${command}.exe` : command,
		);
		if (
			await regularReadable(
				native,
				platform === "win32" ? constants.R_OK : constants.R_OK | constants.X_OK,
			)
		)
			return { command: native, args: [], identity: native };
		if (platform !== "win32" || command !== "typescript-language-server")
			continue;
		const shim = resolve(dir, "typescript-language-server.cmd");
		if (!(await regularReadable(shim))) continue;
		try {
			const launch = await npmShim(dir, shim);
			if (launch) return launch;
		} catch {
			throw new LspFailure(
				"missing_tool",
				"typescript-language-server.cmd has invalid npm metadata; repair it yourself, then retry; no auto-repair is performed.",
			);
		}
		throw new LspFailure(
			"missing_tool",
			"typescript-language-server.cmd has no adjacent readable npm package; repair it yourself, then retry; no auto-repair is performed.",
		);
	}
	throw new LspFailure(
		"missing_tool",
		`${command} not found on PATH. Install ${command} yourself, then retry; no auto-install is performed.`,
	);
}