import { afterEach, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { shipped } from "../scripts/declarations"; let root = ""; /** A types/ tree from { "pkg/file.d.ts": "contents" }. */ function tree(files: Record): string { root = mkdtempSync(join(tmpdir(), "declarations-")); for (const [path, contents] of Object.entries(files)) { mkdirSync(dirname(join(root, path)), { recursive: true }); writeFileSync(join(root, path), contents); } return root; } afterEach(() => rmSync(root, { recursive: true, force: true })); test("ships what index reaches, through every import form, and nothing else", () => { const types = tree({ "tablet/index.d.ts": `export { a } from "./a";\nexport type { B } from "./engine";\nimport "./side";`, "tablet/a.d.ts": `export type A = import("./deep").Deep;`, "tablet/deep.d.ts": `export type Deep = 1;`, "tablet/engine/index.d.ts": `export type B = 2;`, "tablet/side.d.ts": `export {};`, "tablet/dev.d.ts": `export declare const DEV: boolean;`, "toaster/index.d.ts": `export {};`, }); expect(shipped(types, "tablet", [])).toEqual(["a.d.ts", "deep.d.ts", "engine/index.d.ts", "index.d.ts", "side.d.ts"]); }); test("an unreached module's bare import does not ship, so it does not count", () => { const types = tree({ "toaster/index.d.ts": `export { announceToast } from "./announce";`, "toaster/announce.d.ts": `export declare function announceToast(): void;`, "toaster/lifetime.d.ts": `import { type Source } from "@pebble/pebble";`, }); expect(shipped(types, "toaster", [])).toEqual(["announce.d.ts", "index.d.ts"]); }); test("a reached bare import must be a declared dependency", () => { const types = tree({ "toaster/index.d.ts": `import { type Source } from "@pebble/pebble/rxcore";` }); expect(() => shipped(types, "toaster", [])).toThrow("@pebble/pebble is not a dependency"); expect(shipped(types, "toaster", ["@pebble/pebble"])).toEqual(["index.d.ts"]); }); test("a relative import out of the package fails", () => { const types = tree({ "tablet/index.d.ts": `export * from "../toaster/index";`, "toaster/index.d.ts": `export {};`, }); expect(() => shipped(types, "tablet", [])).toThrow("outside types/tablet/"); }); test("an import with no declaration fails", () => { const types = tree({ "tablet/index.d.ts": `export * from "./gone";` }); expect(() => shipped(types, "tablet", [])).toThrow(`"./gone", which has no declaration`); }); test("the library's own packages ship standalone declarations", () => { const built = Bun.spawnSync(["bunx", "tsc", "-p", "tsconfig.build.json", "--outDir", join(tree({}), "types")], { cwd: `${import.meta.dir}/..`, }); expect(built.exitCode).toBe(0); expect(shipped(join(root, "types"), "tablet", [])).not.toContain("dev.d.ts"); expect(shipped(join(root, "types"), "toaster", [])).not.toContain("lifetime.d.ts"); });