import { copyFileSync, existsSync, mkdirSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { Database } from "bun:sqlite"; import type { SeedEntryInput } from "./cli"; import type { IndexStore } from "./store/store"; const BUNDLED_DATABASE_VERSION = "seed-db-v1"; type BundledSeedRow = { name: string; description: string | null; }; export class BundledDatabase { static fromPackage(): BundledDatabase { const here = dirname(fileURLToPath(import.meta.url)); return new BundledDatabase( join(here, "..", "assets", "tool-query.seed.sqlite3"), BUNDLED_DATABASE_VERSION, ); } constructor( private readonly sourcePath: string, private readonly version: string, ) {} ensureBootstrapped(targetPath: string): void { if (existsSync(targetPath)) { return; } mkdirSync(dirname(targetPath), { recursive: true }); copyFileSync(this.requireSourcePath(), targetPath); } needsSync(store: IndexStore): boolean { return store.metaValue("bundled_seed_version") !== this.version; } syncInto(store: IndexStore): void { if (!this.needsSync(store)) { return; } store.importSeedEntries(this.readSeedEntries(), "seed-import"); store.setMetaValue("bundled_seed_version", this.version); } private readSeedEntries(): SeedEntryInput[] { const database = new Database(this.requireSourcePath(), { readonly: true, strict: true, }); try { const rows = database .query( `SELECT command_name AS name, description FROM seed_metadata ORDER BY command_name ASC`, ) .all() as BundledSeedRow[]; return rows.map((row) => ({ name: row.name, ...(row.description === null ? {} : { description: row.description }), })); } finally { database.close(); } } private requireSourcePath(): string { if (!existsSync(this.sourcePath)) { throw new Error("bundled seed database is missing from the package"); } return this.sourcePath; } } export function bundledDatabaseVersion(): string { return BUNDLED_DATABASE_VERSION; }