#!/usr/bin/env bun import { existsSync, realpathSync } from "node:fs"; import { mkdir } from "node:fs/promises"; import { dirname, join, resolve, sep } from "node:path"; import { fileURLToPath } from "node:url"; import { BOOTSTRAP_MODEL_SCHEMA, compileModel, modelProcess } from "./model"; export type ModelToolCommand = { readonly executable: string; readonly args?: readonly string[]; }; export interface ModelToolchain { resolve(binary: "zen" | "prisma"): ModelToolCommand; } function defaultToolchain(root = process.cwd()): ModelToolchain { return { resolve: binary => ({ executable: resolve(root, "node_modules/.bin", binary) }) }; } export async function modelMain(argv: string[], toolchain = defaultToolchain()): Promise { const [command, ...flags] = argv; if (!["generate", "check", "diff", "pull"].includes(command ?? "")) throw new Error("Usage: supacloud-model generate|check|diff|pull [--schema file] [--output dir] [--candidate file]"); const options = new Map(); for (let index = 0; index < flags.length; index += 2) { const key = flags[index], value = flags[index + 1]; if (!key || !["--schema", "--output", "--candidate"].includes(key) || !value || value.startsWith("--") || options.has(key)) throw new Error("Invalid model command option"); options.set(key, value); } const schemaLabel = options.get("--schema") ?? "zenstack/schema.zmodel"; const schema = resolve(schemaLabel); const output = resolve(options.get("--output") ?? "zenstack/generated"); if (command === "generate" || command === "check") { if (options.has("--candidate")) throw new Error("--candidate is only supported by diff and pull"); if (!existsSync(schema)) throw new Error(`Maintain ${schemaLabel} before ${command}; adopt an existing database with supacloud-model pull first`); await compileModel(schema, output, command === "check"); return; } if (command !== "diff" && command !== "pull") throw new Error("Invalid model command"); const databaseUrl = process.env["SUPACLOUD_MODEL_DATABASE_URL"]; if (!databaseUrl) throw new Error("Select a read-only database explicitly with SUPACLOUD_MODEL_DATABASE_URL"); const rawCandidate = options.get("--candidate"); if (!rawCandidate) throw new Error("Supply a fresh --candidate file; review it before promotion into migration history"); const candidate = resolve(rawCandidate); if (existsSync(candidate) || candidate === schema) throw new Error("Candidate already exists; refusing to overwrite maintained files"); if (candidate === output || candidate.startsWith(output + sep) || !candidate.endsWith(command === "diff" ? ".sql" : ".zmodel")) throw new Error("Select a candidate file outside generated contracts with the correct extension"); // Validate the datasource even for pull so an embedded URL cannot override explicit selection. const { mkdtemp, rm, writeFile } = await import("node:fs/promises"); const { tmpdir } = await import("node:os"); const validation = await mkdtemp(resolve(tmpdir(), "supacloud-model-pull-")); try { // A project that has a database but no maintained model can still adopt it: // introspect through a temporary datasource-only model and never write it down. let source = schema; let bootstrap = false; if (command === "diff") { if (!existsSync(schema)) throw new Error(`Maintain ${schemaLabel} before diff; adopt an existing database with supacloud-model pull first`); await compileModel(schema, output, true); } else if (existsSync(schema)) await compileModel(schema, join(validation, "generated")); else { bootstrap = true; source = join(validation, "schema.zmodel"); await writeFile(source, BOOTSTRAP_MODEL_SCHEMA); await compileModel(source, join(validation, "generated")); } const operation = modelProcess(command, source, output, candidate); const tool = toolchain.resolve(operation.binary); if (!existsSync(tool.executable)) throw new Error(`Install the pinned ${operation.binary} tooling in the application`); await mkdir(dirname(candidate), { recursive: true }); const { SUPACLOUD_MODEL_DATABASE_URL: _selectedDatabaseUrl, ...parentEnv } = process.env; const child = Bun.spawn([tool.executable, ...(tool.args ?? []), ...operation.args], { env: { ...parentEnv, DATABASE_URL: databaseUrl }, stdio: ["ignore", "inherit", "inherit"], }); if (await child.exited !== 0) throw new Error("Model candidate generation failed; nothing was applied"); if (!bootstrap) return; // Prove the introspected candidate is a compilable model before recommending it. await compileModel(candidate, join(validation, "candidate")); console.log(`Wrote a review candidate to ${candidate} because ${schemaLabel} does not exist yet.`); console.log(`Review it, add the policy plugin and @@allow rules, move it to ${schemaLabel}, then run supacloud-model generate.`); } finally { await rm(validation, { recursive: true, force: true }); } } if (process.argv[1] && existsSync(process.argv[1]) && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) { try { await modelMain(process.argv.slice(2)); } catch (error) { console.error(error instanceof Error ? error.message : "Model command failed"); process.exitCode = 1; } }