/** * `scribase-migrate` writes into the exact same `supabase/migrations/` * convention `npx scribase migrate` reads (`edge-repos/scribase-cli`'s * `MIGRATIONS_DIR`), so a one-time migration and the app's ongoing * `scribase migrate` workflow share one history from day one. * * `POST .../migrations` is **not** additive: verified live (see README, * "Why every run resends the whole migrations folder") that it rejects a * request missing a version it has already recorded with * `409 migration_conflict`. So every call here reads the *entire* folder * fresh and resends it — new steps land as new files on disk first, then * the whole folder is submitted once. A later retry of the same step is * free: the file already exists, is skipped, and resending its unchanged * content is what the endpoint expects. */ import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; export const MIGRATIONS_DIR = 'supabase/migrations'; const FILE_PATTERN = /^(\d{14,20})_(.+)\.sql$/; export async function readMigrationFiles(dir) { let names; try { names = await readdir(dir); } catch { return []; } const files = []; for (const filename of names) { const match = FILE_PATTERN.exec(filename); if (!match) continue; const up = await readFile(join(dir, filename), 'utf8'); files.push({ version: match[1], name: match[2], up }); } files.sort((a, b) => (a.version < b.version ? -1 : a.version > b.version ? 1 : 0)); return files; } export function slugify(name) { return name.replace(/[^a-z0-9]+/gi, '_').replace(/^_+|_+$/g, '').toLowerCase(); } /** Writes one step, skipping (not overwriting) a version that already has a file. */ export async function writeMigrationFile(dir, { version, name, sql }) { await mkdir(dir, { recursive: true }); const slug = slugify(name); const filename = `${version}_${slug}.sql`; const path = join(dir, filename); const existing = await readMigrationFiles(dir); if (existing.some((f) => f.version === version)) { return { path, written: false }; } // Written byte-for-byte: the control plane checksums the exact `up` text, // so round-tripping through disk must never add or strip a trailing // newline (verified live — a re-send after that changed produced a real // `migration_conflict`, "an already-applied migration must never be // edited", for content a human would call identical). await writeFile(path, sql); return { path, written: true }; } /** Next free version strictly after every version already on disk, offset by `stepSeconds`. */ export function nextVersion(existing, stepSeconds = 0) { const base = Date.now() + stepSeconds * 1000; let candidate = formatVersion(new Date(base)); const used = new Set(existing.map((f) => f.version)); let bump = 0; while (used.has(candidate)) { bump += 1; candidate = formatVersion(new Date(base + bump * 1000)); } return candidate; } function formatVersion(date) { const pad = (n) => String(n).padStart(2, '0'); return `${date.getUTCFullYear()}${pad(date.getUTCMonth() + 1)}${pad(date.getUTCDate())}${pad(date.getUTCHours())}${pad(date.getUTCMinutes())}${pad(date.getUTCSeconds())}`; } /** Reads the whole folder and submits it in one call — the only safe way to call this endpoint more than once. */ export async function submitMigrationsDir(client, ref, dir, { apply = true } = {}) { const files = await readMigrationFiles(dir); if (files.length === 0) { return { plan: { steps: [] }, lintFindings: [], applied: [] }; } return client.migrations.run(ref, { apply, migrations: files.map((f) => ({ version: f.version, name: f.name, up: f.up })), }); }