import { createHash } from 'node:crypto'; import { db } from '../db/index.js'; import { config, type ArtifactKind } from '../config.js'; export type { ArtifactKind }; export const ARTIFACT_KINDS: ReadonlyArray = ['script', 'config', 'plugin', 'baseline']; export function isArtifactKind(v: unknown): v is ArtifactKind { return typeof v === 'string' && (ARTIFACT_KINDS as readonly string[]).includes(v); } export type ScopeType = 'game' | 'map'; export interface ScriptRow { id: number; name: string; target_rel_path: string; scope_type: ScopeType | null; scope_value: string | null; current_version_id: number | null; kind: ArtifactKind; created_at: string; } export type ScriptVersionState = 'untested' | 'tested' | 'test-failed'; export interface ScriptVersionRow { id: number; script_id: number; version: number; sha256: string; size: number; content: Buffer; notes: string | null; state: ScriptVersionState; kind: ArtifactKind; uploaded_at: string; } // The script name is the primary user-facing identifier; slugify to derive a // URL-safe form. Same rules as the old beta slugify — lowercase, letters + digits. export function slugify(name: string): string { return name .toLowerCase() .replace(/[^a-z0-9]+/g, '-') .replace(/^-+|-+$/g, ''); } export class ScriptError extends Error { constructor( message: string, public readonly kind: | 'name-empty' | 'name-taken' | 'path-empty' | 'no-such-script' | 'no-such-version' | 'scope-requires-beta' | 'invalid-scope' | 'in-use-current' | 'in-use-beta' | 'has-scope' | 'has-active-beta' | 'invalid-kind' | 'baseline-requires-scope' | 'baseline-exists' | 'empty-overlay' ) { super(message); } } function sha256(buf: Buffer): string { return createHash('sha256').update(buf).digest('hex'); } export function getScript(id: number): ScriptRow | undefined { return db().prepare('SELECT * FROM scripts WHERE id = ?').get(id) as ScriptRow | undefined; } export function getScriptByName(name: string): ScriptRow | undefined { return db().prepare('SELECT * FROM scripts WHERE name = ?').get(name) as ScriptRow | undefined; } export function listScripts(kind?: ArtifactKind): ScriptRow[] { if (kind) { return db().prepare('SELECT * FROM scripts WHERE kind = ? ORDER BY name').all(kind) as ScriptRow[]; } return db().prepare('SELECT * FROM scripts ORDER BY name').all() as ScriptRow[]; } // Look up the current baseline for a given scope. Baselines have exactly one // current_version_id after their first promote; before that they are still // gated through the beta pipeline. `includeUntested` returns the baseline row // even without a promoted version (used at beta-open time when the baseline is // being introduced in the same beta as the overlays). export function getBaselineForScope(scopeType: ScopeType, scopeValue: string): ScriptRow | undefined { return db() .prepare( `SELECT * FROM scripts WHERE kind = 'baseline' AND scope_type = ? AND scope_value = ? LIMIT 1` ) .get(scopeType, scopeValue) as ScriptRow | undefined; } // All promoted config overlays for a scope. `exceptScriptIds` lets callers // skip overlays whose new version is bundled in a beta — avoids applying the // prior version twice when composing. export function listPromotedOverlaysForScope( scopeType: ScopeType, scopeValue: string, exceptScriptIds: number[] = [] ): ScriptRow[] { const rows = db() .prepare( `SELECT * FROM scripts WHERE kind = 'config' AND scope_type = ? AND scope_value = ? AND current_version_id IS NOT NULL ORDER BY id` ) .all(scopeType, scopeValue) as ScriptRow[]; if (exceptScriptIds.length === 0) return rows; const skip = new Set(exceptScriptIds); return rows.filter((r) => !skip.has(r.id)); } export function listVersions(scriptId: number): ScriptVersionRow[] { return db() .prepare('SELECT * FROM script_versions WHERE script_id = ? ORDER BY version DESC') .all(scriptId) as ScriptVersionRow[]; } export function getVersion(id: number): ScriptVersionRow | undefined { return db().prepare('SELECT * FROM script_versions WHERE id = ?').get(id) as | ScriptVersionRow | undefined; } // Latest version is 'max(version)' — used everywhere we want the freshest // upload, whether or not it has been promoted (current_version_id). export function getLatestVersion(scriptId: number): ScriptVersionRow | undefined { return db() .prepare('SELECT * FROM script_versions WHERE script_id = ? ORDER BY version DESC LIMIT 1') .get(scriptId) as ScriptVersionRow | undefined; } export interface CreateScriptInput { name: string; /** Optional: defaults to the upload filename for script/plugin, and to * the configured config target file for config/baseline. */ targetRelPath?: string; scopeType?: ScopeType | null; scopeValue?: string | null; content: Buffer; notes?: string; /** Defaults to 'script' for back-compat with existing callers. */ kind?: ArtifactKind; } // Insert script + version 1 in one transaction. Scope may be set at creation // because the script has no current_version_id yet (nothing to gate). export function createScript(input: CreateScriptInput): { script: ScriptRow; version: ScriptVersionRow } { if (!input.name.trim()) throw new ScriptError('script name is required', 'name-empty'); const kind: ArtifactKind = input.kind ?? 'script'; if (!isArtifactKind(kind)) throw new ScriptError(`invalid kind: ${input.kind}`, 'invalid-kind'); // Target file defaulting per kind. Configs and baselines all compose into // the same on-disk cfg file, so the operator never picks it. let targetRelPath = input.targetRelPath?.trim() ?? ''; if (!targetRelPath && (kind === 'config' || kind === 'baseline')) { targetRelPath = config.configTargetFile; } if (!targetRelPath) throw new ScriptError('target rel path is required', 'path-empty'); // Kind-specific validation. if (kind === 'baseline') { if (!input.scopeType || !input.scopeValue) { throw new ScriptError('baselines require a scope (game or map)', 'baseline-requires-scope'); } if (getBaselineForScope(input.scopeType, input.scopeValue)) { throw new ScriptError( `a baseline already exists for ${input.scopeType}=${input.scopeValue}`, 'baseline-exists' ); } } if (kind === 'config') { if (!input.scopeType || !input.scopeValue) { throw new ScriptError('config overlays require a scope', 'invalid-scope'); } // Reject empty or comment-only overlays — nothing to apply. const text = input.content.toString('utf8'); if (!/^\s*set\s+\S+\s+/m.test(text)) { throw new ScriptError( 'config overlay must contain at least one `set KEY VALUE` line', 'empty-overlay' ); } } validateScope(input.scopeType ?? null, input.scopeValue ?? null); if (getScriptByName(input.name)) throw new ScriptError(`script "${input.name}" already exists`, 'name-taken'); const sha = sha256(input.content); const size = input.content.byteLength; const insertScript = db().prepare( `INSERT INTO scripts (name, target_rel_path, scope_type, scope_value, kind) VALUES (?, ?, ?, ?, ?)` ); const insertVersion = db().prepare( `INSERT INTO script_versions (script_id, version, sha256, size, content, notes, kind) VALUES (?, 1, ?, ?, ?, ?, ?)` ); let scriptId!: number; let versionId!: number; db().transaction(() => { const s = insertScript.run(input.name, targetRelPath, input.scopeType ?? null, input.scopeValue ?? null, kind); scriptId = Number(s.lastInsertRowid); const v = insertVersion.run(scriptId, sha, size, input.content, input.notes ?? null, kind); versionId = Number(v.lastInsertRowid); })(); return { script: getScript(scriptId)!, version: getVersion(versionId)! }; } export function uploadNewVersion(scriptId: number, content: Buffer, notes?: string): ScriptVersionRow { const script = getScript(scriptId); if (!script) throw new ScriptError(`no such script (id=${scriptId})`, 'no-such-script'); if (script.kind === 'config') { const text = content.toString('utf8'); if (!/^\s*set\s+\S+\s+/m.test(text)) { throw new ScriptError( 'config overlay must contain at least one `set KEY VALUE` line', 'empty-overlay' ); } } const latest = getLatestVersion(scriptId); const nextVersion = (latest?.version ?? 0) + 1; const sha = sha256(content); const res = db() .prepare( `INSERT INTO script_versions (script_id, version, sha256, size, content, notes, kind) VALUES (?, ?, ?, ?, ?, ?, ?)` ) .run(scriptId, nextVersion, sha, content.byteLength, content, notes ?? null, script.kind); return getVersion(Number(res.lastInsertRowid))!; } function validateScope(scopeType: ScopeType | null, scopeValue: string | null): void { if (scopeType === null && scopeValue === null) return; if (scopeType === 'game' || scopeType === 'map') { if (!scopeValue || !scopeValue.trim()) { throw new ScriptError(`scope_value required for scope_type=${scopeType}`, 'invalid-scope'); } return; } throw new ScriptError(`unknown scope_type: ${scopeType}`, 'invalid-scope'); } export interface SetScopeInput { scriptId: number; scopeType: ScopeType | null; scopeValue: string | null; } // Setting or changing a scope while the script already has a promoted version // requires a beta first (per plan §"Beta trigger"). Un-scoping is free. export function setScope(input: SetScopeInput): ScriptRow { const script = getScript(input.scriptId); if (!script) throw new ScriptError(`no such script (id=${input.scriptId})`, 'no-such-script'); validateScope(input.scopeType, input.scopeValue); const changed = input.scopeType !== script.scope_type || (input.scopeValue ?? null) !== (script.scope_value ?? null); const isSetOrChange = input.scopeType !== null && changed; if (isSetOrChange && script.current_version_id !== null) { throw new ScriptError( 'setting or changing scope requires opening a beta first', 'scope-requires-beta' ); } db() .prepare('UPDATE scripts SET scope_type = ?, scope_value = ? WHERE id = ?') .run(input.scopeType, input.scopeValue, input.scriptId); return getScript(input.scriptId)!; } // Version delete is metadata-only: it never touches server disks. But deleting // the current version or a version referenced by a running beta would break // downstream state, so those are blocked. export function deleteVersion(versionId: number): void { const version = getVersion(versionId); if (!version) throw new ScriptError(`no such version (id=${versionId})`, 'no-such-version'); const script = getScript(version.script_id)!; if (script.current_version_id === versionId) { throw new ScriptError('cannot delete the current version', 'in-use-current'); } const beta = db() .prepare( `SELECT b.id FROM betas b JOIN beta_scripts bs ON bs.beta_id = b.id WHERE bs.script_version_id = ? AND b.state = 'running' LIMIT 1` ) .get(versionId) as { id: number } | undefined; if (beta) throw new ScriptError(`beta ${beta.id} is still running against this version`, 'in-use-beta'); db().prepare('DELETE FROM script_versions WHERE id = ?').run(versionId); } export function deleteScript(scriptId: number): void { const script = getScript(scriptId); if (!script) throw new ScriptError(`no such script (id=${scriptId})`, 'no-such-script'); if (script.scope_type !== null) { throw new ScriptError('un-set scope before deleting a script', 'has-scope'); } const beta = db() .prepare( `SELECT b.id FROM betas b JOIN beta_scripts bs ON bs.beta_id = b.id WHERE bs.script_id = ? AND b.state = 'running' LIMIT 1` ) .get(scriptId) as { id: number } | undefined; if (beta) throw new ScriptError(`beta ${beta.id} is still running against this script`, 'has-active-beta'); db().prepare('DELETE FROM scripts WHERE id = ?').run(scriptId); } // Servers that match a script's scope. Empty for unscoped scripts — those are // only ever pushed to explicitly chosen beta targets. export function serversMatchingScope(scopeType: ScopeType | null, scopeValue: string | null): string[] { if (scopeType === null || scopeValue === null) return []; const rows = db() .prepare(`SELECT name FROM servers WHERE ${scopeType} = ? ORDER BY name`) .all(scopeValue) as Array<{ name: string }>; return rows.map((r) => r.name); } // Distinct game IDs present in the registered fleet. Powers the scope=game // dropdown so operators can only pick values that will match at least one // server. export function listDistinctGames(): string[] { const rows = db() .prepare(`SELECT DISTINCT game FROM servers WHERE game IS NOT NULL AND game <> '' ORDER BY game`) .all() as Array<{ game: string }>; return rows.map((r) => r.game); } // Distinct maps grouped by their game. Scope=map is chained (pick game → pick // map) so the UI can filter map options to those valid under the selected game. export function listMapsByGame(): Record { const rows = db() .prepare( `SELECT DISTINCT game, map FROM servers WHERE game IS NOT NULL AND game <> '' AND map IS NOT NULL AND map <> '' ORDER BY game, map` ) .all() as Array<{ game: string; map: string }>; const out: Record = {}; for (const r of rows) { (out[r.game] ??= []).push(r.map); } return out; }