repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by admin
extensions/lsp/__tests__/registry-importer.test.ts
Rawimport {
cp,
mkdtemp,
readdir,
readFile,
rm,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, describe, expect, it } from "vitest";
import {
derive,
digest,
merge,
type Policy,
type Registry,
refresh,
serialize,
} from "../scripts/registry.js";
const source = fileURLToPath(new URL("../registry/", import.meta.url));
const policy = JSON.parse(
await readFile(join(source, "policy.json"), "utf8"),
) as Policy;
const fixture = await readFile(
join(source, "fixtures/helix-languages.toml"),
"utf8",
);
const license = await readFile(join(source, "HELIX-LICENSE"), "utf8");
const temporary: string[] = [];
afterEach(async () => {
await Promise.all(
temporary
.splice(0)
.map((path) => rm(path, { recursive: true, force: true })),
);
});
async function sandbox() {
const directory = await mkdtemp(join(tmpdir(), "lsp-registry-test-"));
temporary.push(directory);
await cp(source, directory, { recursive: true });
return directory;
}
const transport = async (url: string) =>
url.endsWith("/LICENSE") ? license : fixture;
async function snapshot(directory: string) {
return readFile(join(directory, "servers.json"), "utf8");
}
async function unchangedFailure(
options: Parameters<typeof refresh>[1],
pattern: RegExp,
) {
const directory = await sandbox();
const before = await snapshot(directory);
await expect(refresh(directory, options)).rejects.toThrow(pattern);
expect(await snapshot(directory)).toBe(before);
expect((await readdir(directory)).some((name) => name.endsWith(".tmp"))).toBe(
false,
);
}
describe("reviewed pinned registry maintenance", () => {
it("reproduces reviewed profiles and exact source/license integrity deterministically", async () => {
expect(digest(fixture)).toBe(policy.sha256);
expect(digest(license)).toBe(policy.licenseSha256);
const fresh = derive(fixture, policy);
expect(fresh).toEqual(policy.previousSource);
const result = merge(fresh, policy);
expect(
result.profiles.map((p) => [
p.id,
p.command,
p.args,
p.language,
p.extensions,
p.roots,
]),
).toEqual([
["gopls", "gopls", [], "go", [".go"], ["go.work", "go.mod"]],
[
"typescript-language-server",
"typescript-language-server",
["--stdio"],
"typescript",
[".ts"],
["package.json", "tsconfig.json"],
],
[
"clangd",
"clangd",
[],
"cpp",
[".cpp", ".cc", ".cxx", ".hpp"],
[".clangd", "compile_commands.json", "CMakeLists.txt"],
],
]);
expect(result.profiles[0]?.initializationOptions).toEqual({
fileWatcher: "fsnotify",
});
expect(result.profiles[0]?.settings).toEqual({
gopls: { fileWatcher: "fsnotify" },
});
expect(result.profiles[1]?.initializationOptions).toEqual({
tsserver: { useSyntaxServer: "never" },
});
for (const p of result.profiles)
expect(p.provenance).toMatchObject({
revision: policy.revision,
license: "MPL-2.0",
url: expect.stringContaining(policy.revision),
overrides: expect.any(Object),
});
expect(serialize(result)).toBe(await snapshot(source));
const directory = await sandbox();
const reports: string[] = [];
await refresh(directory, {
fetchText: transport,
report: (s) => reports.push(s),
});
await refresh(directory, { fetchText: transport });
expect(await snapshot(directory)).toBe(serialize(result));
expect(reports).toEqual(["Registry unchanged"]);
});
it("preserves direct reviewed local changes and explicit policy overrides", () => {
const fresh = derive(fixture, policy);
const current = merge(fresh, policy);
current.profiles[1]!.args = ["--stdio", "--log-level", "1"];
expect(merge(fresh, policy, current).profiles[1]?.args).toEqual([
"--stdio",
"--log-level",
"1",
]);
expect(merge(fresh, policy, current).profiles[2]?.roots).toContain(
"compile_commands.json",
);
});
it("imports nonconflicting upstream edits, reports field-level simultaneous changes, accepts identical changes", () => {
const fresh = derive(fixture, policy);
const current = merge(fresh, policy);
fresh[1]!.args = ["--stdio", "--log-level", "2"];
expect(merge(fresh, policy, current).profiles[1]?.args).toEqual(
fresh[1]!.args,
);
current.profiles[1]!.args = ["--stdio", "--log-level", "1"];
expect(() => merge(fresh, policy, current)).toThrow(
/typescript-language-server.args: previous=.*local=.*fresh=/,
);
current.profiles[1]!.args = fresh[1]!.args;
expect(merge(fresh, policy, current).profiles[1]?.args).toEqual(
fresh[1]!.args,
);
fresh[0]!.initializationOptions = { hints: { assignVariableTypes: false } };
expect(() => merge(fresh, policy, current)).toThrow(
/gopls.initializationOptions/,
);
});
it("resolves new explicit overrides before comparing simultaneous upstream edits", () => {
const fresh = derive(fixture, policy);
const current = merge(fresh, policy);
const changed = structuredClone(policy);
fresh[1]!.args = ["--stdio", "--log-level", "2"];
changed.overrides["typescript-language-server"]!["args"] = {
value: fresh[1]!.args,
reason: "Reviewed logging level",
};
expect(merge(fresh, changed, current).profiles[1]?.args).toEqual(
fresh[1]!.args,
);
current.profiles[1]!.args = ["--local"];
expect(() => merge(fresh, changed, current)).toThrow(/snapshot differs/);
});
it("publishes a complete deterministic replacement and reviewable diffs", async () => {
const directory = await sandbox();
const newer = fixture.replace(
'command = "typescript-language-server"\nargs = ["--stdio"]',
'command = "typescript-language-server"\nargs = ["--stdio", "--log-level", "2"]',
);
const changedPolicy = structuredClone(policy);
changedPolicy.sha256 = digest(newer);
await writeFile(join(directory, "policy.json"), serialize(changedPolicy));
const reports: string[] = [];
await refresh(directory, {
fetchText: async (url) => (url.endsWith("/LICENSE") ? license : newer),
report: (s) => reports.push(s),
});
expect(JSON.parse(await snapshot(directory)).profiles[1].args).toEqual([
"--stdio",
"--log-level",
"2",
]);
expect(
reports.some((s) => s.startsWith("typescript-language-server.args:")),
).toBe(true);
expect(
(await readdir(directory)).some((name) => name.endsWith(".tmp")),
).toBe(false);
});
it("rejects unresolved paths, placeholders, executable environments and malformed catalogs", () => {
for (const command of [
"/usr/bin/gopls",
"C:\\\\Tools\\\\gopls",
"${HOME}/gopls",
"~/bin/gopls",
"%APPDATA%/gopls",
"gopls;evil",
]) {
const input = fixture.replace(
'command = "gopls"',
`command = ${JSON.stringify(command)}`,
);
expect(() => merge(derive(input, policy), policy)).toThrow();
}
expect(() =>
derive(
fixture.replace(
"[language-server.gopls]",
'[language-server.gopls]\nenv = { TOKEN = "secret" }',
),
policy,
),
).toThrow(/environment/);
expect(() =>
derive(
fixture.replace(
'command = "gopls"',
'command = "gopls"\nargs = ["--path=<root>"]',
),
policy,
),
).toThrow(/Unsafe/);
expect(() => derive("not toml {{{", policy)).toThrow();
expect(() =>
derive(fixture.replace('"ts",', '"unsupported",'), policy),
).toThrow(/extension/);
});
it("preserves exact last-good bytes after unavailable network or corrupted pinned input", async () => {
await unchangedFailure(
{
fetchText: async () => {
throw new Error("Network unavailable");
},
},
/Network unavailable/,
);
await unchangedFailure({ fetchText: async () => "bad" }, /integrity/);
});
it("preserves last-good on malformed input even when deliberately repinned", async () => {
const directory = await sandbox();
const before = await snapshot(directory);
const p = structuredClone(policy);
p.sha256 = digest("bad = {");
await writeFile(join(directory, "policy.json"), serialize(p));
await expect(
refresh(directory, {
fetchText: async (url) =>
url.endsWith("/LICENSE") ? license : "bad = {",
}),
).rejects.toThrow();
expect(await snapshot(directory)).toBe(before);
});
it("rejects a license mismatch without replacing usable data", async () => {
const directory = await sandbox();
const before = await snapshot(directory);
await writeFile(join(directory, "HELIX-LICENSE"), "missing license notice");
await expect(refresh(directory, { fetchText: transport })).rejects.toThrow(
/license differs/,
);
expect(await snapshot(directory)).toBe(before);
});
it("preserves bytes on unresolved conflicts through the complete refresh route", async () => {
const directory = await sandbox();
const current = JSON.parse(await snapshot(directory)) as Registry;
current.profiles[1]!.args = ["--local"];
await writeFile(join(directory, "servers.json"), serialize(current));
const before = await snapshot(directory);
const newer = fixture.replace(
'command = "typescript-language-server"\nargs = ["--stdio"]',
'command = "typescript-language-server"\nargs = ["--upstream"]',
);
const p = structuredClone(policy);
p.sha256 = digest(newer);
await writeFile(join(directory, "policy.json"), serialize(p));
await expect(
refresh(directory, {
fetchText: async (url) => (url.endsWith("/LICENSE") ? license : newer),
}),
).rejects.toThrow(/conflicts/);
expect(await snapshot(directory)).toBe(before);
});
it("detects snapshot edits made while staging without overwriting them", async () => {
const directory = await sandbox();
await writeFile(
join(directory, "servers.json"),
` \n${await snapshot(directory)}`,
);
const edited = JSON.parse(await snapshot(directory)) as Registry;
edited.profiles[1]!.args = ["--local"];
const editedText = serialize(edited);
await expect(
refresh(directory, {
fetchText: transport,
beforeRename: async () => {
await writeFile(join(directory, "servers.json"), editedText);
},
}),
).rejects.toThrow(/changed during refresh/);
expect(await snapshot(directory)).toBe(editedText);
expect(
(await readdir(directory)).some((name) => name.endsWith(".tmp")),
).toBe(false);
});
it("cleans staged data on interrupted or failed publication, retaining exact usable snapshot", async () => {
for (const interrupt of [false, true]) {
const directory = await sandbox();
await writeFile(
join(directory, "servers.json"),
` \n${await snapshot(directory)}`,
);
const before = await snapshot(directory);
const controller = new AbortController();
await expect(
refresh(directory, {
fetchText: transport,
signal: controller.signal,
beforeRename: async () => {
if (interrupt)
controller.abort(new Error("Interrupted publication"));
else
for (const name of await readdir(directory))
if (name.endsWith(".tmp")) await rm(join(directory, name));
},
}),
).rejects.toThrow(interrupt ? /Interrupted/ : /ENOENT/);
expect(await snapshot(directory)).toBe(before);
expect(
(await readdir(directory)).some((name) => name.endsWith(".tmp")),
).toBe(false);
}
});
});