import { db } from '../db/index.js'; import type { BetaRevision } from '../../beta-revision.js'; export function currentBetaRevision(id: number): { revision: number; started_at: string } { return ( (db() .prepare( `SELECT revision, started_at FROM beta_revisions WHERE beta_id = ? ORDER BY revision DESC LIMIT 1` ) .get(id) as { revision: number; started_at: string } | undefined) ?? { revision: 1, started_at: ( db().prepare('SELECT opened_at FROM betas WHERE id = ?').get(id) as { opened_at: string; } ).opened_at } ); } /** Called in the revision transaction, before replacing the pinned bundle. */ export function archiveBetaRevision( id: number, revision: number, startedAt: string, notes: string | null ): void { db() .prepare( 'INSERT OR IGNORE INTO beta_revisions (beta_id, revision, started_at, notes) VALUES (?, ?, ?, ?)' ) .run(id, revision, startedAt, notes); db() .prepare( `INSERT OR IGNORE INTO beta_revision_files (beta_id, revision, script_id, name, kind, path, version_id, version, release_version, sha256, content_hash) SELECT bs.beta_id, ?, s.id, s.name, s.kind, s.target_rel_path, v.id, v.version, v.release_version, v.sha256, v.content_hash FROM beta_scripts bs JOIN scripts s ON s.id = bs.script_id JOIN script_versions v ON v.id = bs.script_version_id WHERE bs.beta_id = ?` ) .run(revision, id); } export function betaRevisionHistory(id: number): BetaRevision[] { const rows = db() .prepare( 'SELECT revision, started_at, notes, results_json FROM beta_revisions WHERE beta_id = ? ORDER BY revision DESC' ) .all(id) as Array<{ revision: number; started_at: string; notes: string | null; results_json: string | null; }>; const files = db() .prepare( `SELECT revision, script_id, name, kind, path, version_id, version, release_version, sha256 FROM beta_revision_files WHERE beta_id = ? ORDER BY script_id` ) .all(id) as Array; return rows.map(({ results_json, ...row }) => ({ ...row, results: results_json ? JSON.parse(results_json) : null, files: files .filter((file) => file.revision === row.revision) .map(({ revision, ...file }) => file) })); }