Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/devdocs/__serial__/settings.test.ts

Raw
import {
	existsSync,
	mkdirSync,
	mkdtempSync,
	readFileSync,
	rmSync,
	writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, expect, it, vi } from "vitest";
import {
	createPiSession,
	type PiSession,
} from "../../../test/fixture/create-pi-session.ts";
import { defaultDatabasePath } from "../src/settings.ts";

const extensionPaths = [fileURLToPath(new URL("../index.ts", import.meta.url))];
let box: PiSession | undefined;
const roots: string[] = [];
afterEach(async () => {
	await box?.dispose();
	box = undefined;
	vi.restoreAllMocks();
	for (const path of roots.splice(0))
		rmSync(path, { recursive: true, force: true });
});
it.each([
	{ trusted: false, environment: false, invalid: false, selected: "user.db" },
	{ trusted: true, environment: false, invalid: false, selected: "project.db" },
	{ trusted: true, environment: true, invalid: false, selected: "env.db" },
	{ trusted: true, environment: false, invalid: true, selected: null },
])(
	"honors db precedence and project trust: $trusted/$environment/$invalid",
	async ({ trusted, environment, invalid, selected }) => {
		const root = mkdtempSync(join(tmpdir(), "devdocs-settings-"));
		roots.push(root);
		mkdirSync(join(root, ".pi"));
		writeFileSync(
			join(root, ".pi", "settings.json"),
			JSON.stringify({
				devdocs: {
					databasePath: invalid ? "relative.db" : join(root, "project.db"),
				},
			}),
		);
		box = await createPiSession({
			cwd: root,
			projectTrusted: trusted,
			extensionPaths,
			env: {
				PI_DEVDOCS_DEBUG: "0",
				PI_DEVDOCS_DATABASE_PATH: environment
					? join(root, "env.db")
					: undefined,
			},
			userSettings: {
				devdocs: { databasePath: join(root, "user.db"), enabledSources: [] },
			},
		});
		expect(box.errors).toEqual([]);
		const tool = box.extensions[0]?.tools.get("devdocs")?.definition;
		if (!tool) throw new Error("missing devdocs");
		const result = tool.execute(
			"status",
			{ action: "status" },
			undefined,
			undefined,
			box.session.extensionRunner.createToolContext("fixture", undefined),
		);
		if (selected) {
			await result;
			expect(existsSync(join(root, selected))).toBe(true);
		} else {
			await expect(result).rejects.toThrow(/absolute/);
			expect(existsSync(join(root, "user.db"))).toBe(false);
		}
	},
);
it.each(["environment", "store"] as const)(
	"uses %s Context7 credentials only for that provider and never persists them in the cache",
	async (source) => {
		const secret = "test-key";
		vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
			expect(new URL(String(input)).origin).toBe("https://context7.com");
			expect(new Headers(init?.headers).get("authorization")).toBe(
				"Bearer " + secret,
			);
			return new Response(
				JSON.stringify(
					String(input).includes("libs/search")
						? { results: [{ id: "/example/widget", title: "Widget" }] }
						: {
								codeSnippets: [
									{
										codeTitle: "Transactions",
										codeDescription: "Atomic transactions " + secret,
										codeId:
											"https://github.com/example/widget/blob/main/docs.md",
										codeList: [],
									},
								],
							},
				),
			);
		});
		box = await createPiSession({
			extensionPaths,
			env: {
				PI_DEVDOCS_DEBUG: "0",
				PI_DEVDOCS_DATABASE_PATH: undefined,
				CONTEXT7_API_KEY: source === "environment" ? secret : undefined,
			},
			userSettings: { devdocs: { enabledSources: ["context7"] } },
		});
		if (source === "store")
			writeFileSync(
				join(box.agentDir, "auth.json"),
				JSON.stringify({ context7: { type: "api_key", key: secret } }),
			);
		const database = defaultDatabasePath();
		const tool = box.extensions[0]?.tools.get("devdocs")?.definition;
		if (!tool) throw new Error("missing devdocs");
		const ctx = box.session.extensionRunner.createToolContext(
			"fixture",
			undefined,
		);
		const result = await tool.execute(
			"search",
			{ action: "search", target: "Widget", query: "transactions" },
			undefined,
			undefined,
			ctx,
		);
		expect(JSON.stringify(result)).not.toContain(secret);
		expect(result.details).toMatchObject({ status: "ok" });
		const status = await tool.execute(
			"status",
			{ action: "status" },
			undefined,
			undefined,
			ctx,
		);
		expect(status.details).toMatchObject({ context7Mode: "keyed" });
		expect(readFileSync(database).includes(Buffer.from(secret))).toBe(false);
	},
);