import { cp, lstat, mkdir, mkdtemp, readFile, realpath, rm, symlink, writeFile, } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; /** * Generated module fixtures for the packager's tests: a built module directory in a temporary * location, whose `node_modules` links to the real Module SDK and Drizzle this package depends on. * Everything a development module directory holds is there, including what must never ship * (`src/`, `tests/`, declarations, source maps, `workspace:` ranges), so a test can prove the * packager leaves it out. */ const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); export interface FakePackage { readonly name: string; readonly version?: string; readonly packageJson?: Record; /** Files relative to the fake package's root. */ readonly files?: Record; } export interface FixtureModuleOptions { readonly databaseAbi?: 1; readonly id?: string; readonly license?: unknown; readonly licenseText?: string | Uint8Array; readonly version?: string; readonly serverSource?: string; readonly withModuleDatabase?: boolean; readonly withSchema?: boolean; /** The module's `engines` field; omitted from `package.json` when `null`. */ readonly engines?: Record | null; /** How the module's `@ekklesia/*` dependencies are installed: linked to this workspace's packages * (the default), or copied as real directories into a flat `node_modules`, as a registry install * lays them out. */ readonly ekklesiaInstall?: "workspace" | "registry"; readonly fakePackages?: readonly FakePackage[]; readonly manifest?: (manifest: Record) => Record; } const temporaryDirectories: string[] = []; export async function cleanupFixtures(): Promise { await Promise.all( temporaryDirectories .splice(0) .map((directory) => rm(directory, { force: true, recursive: true })), ); } export async function scratchDirectory(prefix = "ekklesia-pack-"): Promise { const directory = await realpath(await mkdtemp(path.join(tmpdir(), prefix))); temporaryDirectories.push(directory); return directory; } async function write(file: string, contents: string | Uint8Array): Promise { await mkdir(path.dirname(file), { recursive: true }); await writeFile(file, contents); } const defaultServer = ( id: string, version: string, databaseAbi?: 1, ) => `import { defineModuleRuntime } from "@ekklesia/module-sdk"; export default defineModuleRuntime({ ${databaseAbi === 1 ? "database: { abi: 1 }, " : ""}id: ${JSON.stringify(id)}, version: ${JSON.stringify(version)}, register() {} }); `; const schemaSource = (id: string, databaseAbi?: 1) => `import { createModuleTable${ databaseAbi === 1 ? ", moduleDrizzleSchemaMetadata" : "" } } from "@ekklesia/module-database/drizzle"; import { text, uuid } from "drizzle-orm/pg-core"; export const records = createModuleTable(${JSON.stringify(id)})("records", { id: uuid("id").primaryKey(), value: text("value").notNull(), }); export default ${ databaseAbi === 1 ? `moduleDrizzleSchemaMetadata(${JSON.stringify(id)}, { records })` : `{ moduleId: ${JSON.stringify(id)}, tables: { records } }` }; `; export async function fixtureModule(options: FixtureModuleOptions = {}): Promise { const id = options.id ?? "example"; const version = options.version ?? "0.1.0"; const root = await scratchDirectory("ekklesia-pack-fixture-"); const moduleDirectory = path.join(root, id); const tableName = `${id.replaceAll("-", "_")}_records`; const usesModuleDatabase = options.withModuleDatabase || options.withSchema || options.databaseAbi === 1; const engines = options.engines === undefined ? { node: ">=24.11.0 <25" } : options.engines; const baseManifest: Record = { manifestVersion: 8, id, name: `${id} module`, version, compatibility: { platform: "^0.1.0", moduleSdk: "^0.1.0" }, ...(options.databaseAbi === 1 ? { database: { abi: 1 } } : {}), capabilities: [], permissions: [], entrypoints: { server: "./dist/server/index.js", ...(options.withSchema ? { schema: "./dist/schema/index.js" } : {}), migrations: "./drizzle", }, }; const manifest = options.manifest ? options.manifest(baseManifest) : baseManifest; await write( path.join(moduleDirectory, "ekklesia.module.json"), `${JSON.stringify(manifest, null, 2)}\n`, ); await write( path.join(moduleDirectory, "package.json"), `${JSON.stringify( { name: `@test/module-${id}`, version, license: Object.hasOwn(options, "license") ? options.license : "MIT", private: true, type: "module", ...(engines === null ? {} : { engines }), scripts: { build: "tsc" }, dependencies: { "@ekklesia/module-sdk": "workspace:*", ...(usesModuleDatabase ? { "@ekklesia/module-database": "workspace:*" } : {}), "drizzle-orm": "0.45.2", }, devDependencies: { typescript: "7.0.2" }, exports: { ".": "./dist/server/index.js" }, ekklesia: { layer: "module" }, }, null, 2, )}\n`, ); await write( path.join(moduleDirectory, "LICENSE"), options.licenseText ?? "MIT License\n\nCopyright (c) 2026 Example Module\n", ); await write( path.join(moduleDirectory, "dist/server/index.js"), options.serverSource ?? defaultServer(id, version, options.databaseAbi), ); await write(path.join(moduleDirectory, "dist/server/index.js.map"), '{"version":3}\n'); await write(path.join(moduleDirectory, "dist/server/index.d.ts"), "export {};\n"); if (options.withSchema) { await write( path.join(moduleDirectory, "dist/schema/index.js"), schemaSource(id, options.databaseAbi), ); } await write(path.join(moduleDirectory, "src/server/index.ts"), "export {};\n"); await write(path.join(moduleDirectory, "tests/server.test.ts"), "export {};\n"); await write(path.join(moduleDirectory, "README.md"), "# Development notes\n"); await write( path.join(moduleDirectory, "drizzle/0000_initial.sql"), `CREATE TABLE "${tableName}" ("id" uuid PRIMARY KEY NOT NULL, "value" text NOT NULL);\n`, ); await write( path.join(moduleDirectory, "drizzle/meta/_journal.json"), JSON.stringify({ version: "7", dialect: "postgresql", entries: [ { idx: 0, version: "7", when: 1_700_000_000_000, tag: "0000_initial", breakpoints: true }, ], }), ); await write( path.join(moduleDirectory, "drizzle/meta/_ekklesia.json"), JSON.stringify({ version: 1, moduleId: id, entries: [{ tag: "0000_initial", destructive: { mode: "none" } }], }), ); await write( path.join(moduleDirectory, "drizzle/meta/0000_snapshot.json"), JSON.stringify({ version: "7", dialect: "postgresql", id: "10000000-0000-4000-8000-000000000001", prevId: "00000000-0000-0000-0000-000000000000", }), ); // The module's dependencies: the real packages this package depends on, either linked as a // workspace links them, or copied as a registry install would place them. const modules = path.join(moduleDirectory, "node_modules"); await mkdir(path.join(modules, "@ekklesia"), { recursive: true }); const ekklesiaPackages = [ "module-sdk", ...(usesModuleDatabase ? ["module-database"] : []), ] as const; if (options.ekklesiaInstall === "registry") { await installLikeARegistry(modules, [...ekklesiaPackages, "contracts"]); } else { for (const name of ekklesiaPackages) { await symlink( await realpath(path.join(packageRoot, "node_modules", "@ekklesia", name)), path.join(modules, "@ekklesia", name), ); } } await symlink( await realpath(path.join(packageRoot, "node_modules", "drizzle-orm")), path.join(modules, "drizzle-orm"), ); for (const fake of options.fakePackages ?? []) { const fakeRoot = path.join(modules, ...fake.name.split("/")); await write( path.join(fakeRoot, "package.json"), JSON.stringify({ name: fake.name, version: fake.version ?? "1.0.0", type: "module", main: "index.js", license: "MIT", ...fake.packageJson, }), ); for (const [relative, contents] of Object.entries(fake.files ?? {})) { await write(path.join(fakeRoot, relative), contents); } } return moduleDirectory; } /** * Copies each `@ekklesia/*` package's published files (`package.json`, `dist`, `LICENSE`) into a flat * `node_modules` as real directories, and links the third-party packages they depend on beside them: * the layout a registry install produces, with nothing pointing back into the workspace's sources. */ async function installLikeARegistry(modules: string, names: readonly string[]): Promise { for (const name of names) { const source = await realpath(path.join(packageRoot, "..", name)); const target = path.join(modules, "@ekklesia", name); await mkdir(target, { recursive: true }); for (const entry of ["package.json", "dist", "LICENSE"]) { await cp(path.join(source, entry), path.join(target, entry), { force: false, recursive: true, }).catch((error: NodeJS.ErrnoException) => { if (error.code !== "ENOENT") throw error; }); } const manifest = JSON.parse( await readFile(path.join(source, "package.json"), "utf8"), ) as Record | undefined>; for (const dependency of Object.keys(manifest.dependencies ?? {})) { const link = path.join(modules, ...dependency.split("/")); if (dependency.startsWith("@ekklesia/") || (await exists(link))) continue; await mkdir(path.dirname(link), { recursive: true }); await symlink(await realpath(path.join(source, "node_modules", dependency)), link); } } } async function exists(file: string): Promise { try { await lstat(file); return true; } catch { return false; } } export const SOURCE_REVISION = "86ae907f59458508e3277666cdd214f5bd7c1078"; const nativeFixtureSource = path.join(packageRoot, "tests", "fixtures", "native-module"); /** * The checked-in native proof module (`tests/fixtures/native-module`), copied to a fresh, unrelated * temporary directory with `node_modules` linking the real sharp and Module SDK this package's * workspace installed, as a module's own install would provide them. */ export async function nativeFixtureModule(): Promise { // Inside this package, beside its own node_modules, as a module checkout sits beside its own: a // bundle's module keys are paths relative to the module, so a copy in the system temporary // directory would bundle paths that climb out of it and into this checkout. const fixtures = path.join(packageRoot, ".fixtures"); await mkdir(fixtures, { recursive: true }); const root = await realpath(await mkdtemp(path.join(fixtures, "native-"))); temporaryDirectories.push(root); const moduleDirectory = path.join(root, "native-proof"); await cp(nativeFixtureSource, moduleDirectory, { recursive: true }); const modules = path.join(moduleDirectory, "node_modules"); await mkdir(path.join(modules, "@ekklesia"), { recursive: true }); await symlink( await realpath(path.join(packageRoot, "node_modules", "sharp")), path.join(modules, "sharp"), ); await symlink( await realpath(path.join(packageRoot, "node_modules", "@ekklesia", "module-sdk")), path.join(modules, "@ekklesia", "module-sdk"), ); return moduleDirectory; } /** The workspace's real installed package, for tests that build fake native packages from it. */ export async function installedPackageFile(...segments: string[]): Promise { return realpath(path.join(packageRoot, "node_modules", ...segments)); }