import path from 'path'; import { SynthOSConfig } from '../init'; /** * Schema sidecar IO + additive-merge logic. Used by both shared-table and * per-page-table routes — the only difference is the parent folder where the * `.schema.json` file lives. * * Spec: docs/specs/shared-tables-schema-sidecar.md */ export interface SchemaWrapper { version: number; schema: Record; createdAt: string; updatedAt: string; definedBy?: string; } export type MergeMode = 'additive' | 'replace'; export interface MergeConflict { field: string; existing: unknown; incoming: unknown; } const SCHEMA_VERSION = 1; /** Sidecar file path: `/
.schema.json`. */ export function schemaFile(parent: string, table: string): string { return path.join(parent, `${table}.schema.json`); } /** Load the wrapper. Returns undefined if missing or unparsable. */ export async function loadSchema(config: SynthOSConfig, parent: string, table: string): Promise { const sp = config.storageProvider; const file = schemaFile(parent, table); if (!await sp.checkIfExists(file)) return undefined; try { const parsed = JSON.parse(await sp.loadFile(file)); if (parsed && typeof parsed === 'object' && parsed.schema && typeof parsed.schema === 'object') { return parsed as SchemaWrapper; } } catch { // fall through } return undefined; } /** Persist a wrapper to disk. */ export async function saveSchema(config: SynthOSConfig, parent: string, table: string, wrapper: SchemaWrapper): Promise { const sp = config.storageProvider; await sp.ensureFolderExists(parent); await sp.saveFile(schemaFile(parent, table), JSON.stringify(wrapper, null, 4)); } /** Delete the schema sidecar. No-op if it doesn't exist. */ export async function deleteSchema(config: SynthOSConfig, parent: string, table: string): Promise { const sp = config.storageProvider; const file = schemaFile(parent, table); if (await sp.checkIfExists(file)) { await sp.deleteFile(file); } } /** * Apply `incoming` against `existing` per `mode`: * - 'replace' → drop existing entirely; incoming wins. * - 'additive' → union of `properties` (existing wins on overlap if types match; * conflicting types reported via `conflicts`); union of `required`. * * Returns the merged schema and any conflicts. On conflict, callers should * surface them as a 409 and NOT persist the result. */ export function mergeSchema( existing: Record | undefined, incoming: Record, mode: MergeMode, ): { merged: Record; conflicts: MergeConflict[] } { if (mode === 'replace' || !existing) { return { merged: incoming, conflicts: [] }; } const conflicts: MergeConflict[] = []; const existingProps = isPlainObject(existing.properties) ? existing.properties as Record : {}; const incomingProps = isPlainObject(incoming.properties) ? incoming.properties as Record : {}; const mergedProps: Record = { ...existingProps }; for (const [field, def] of Object.entries(incomingProps)) { if (!(field in existingProps)) { mergedProps[field] = def; continue; } const existingDef = existingProps[field]; if (typesAreCompatible(existingDef, def)) { // Existing wins on overlap (preserves enum/required/format choices). continue; } conflicts.push({ field, existing: existingDef, incoming: def }); } if (conflicts.length > 0) { return { merged: existing, conflicts }; } const existingRequired = Array.isArray(existing.required) ? existing.required as unknown[] : []; const incomingRequired = Array.isArray(incoming.required) ? incoming.required as unknown[] : []; const mergedRequired = Array.from(new Set([...existingRequired, ...incomingRequired] .filter(r => typeof r === 'string'))); const merged: Record = { ...existing, properties: mergedProps, }; if (mergedRequired.length > 0) { merged.required = mergedRequired; } return { merged, conflicts: [] }; } /** * Validate the structural shape of an incoming JSON Schema. Strict-mode * validation against the meta-schema is out of scope; we only check that the * payload is a plain object so we don't persist garbage. */ export function isValidSchemaPayload(s: unknown): s is Record { return isPlainObject(s); } function isPlainObject(v: unknown): v is Record { return !!v && typeof v === 'object' && !Array.isArray(v); } /** * Type-compatibility check used by additive merge. Two definitions are * compatible when their `type` fields match (or both are absent). We * intentionally tolerate other field differences (description, enum widening, * format changes) — incoming-vs-existing field-level diffs aren't surfaced * as conflicts in v1; only top-level type mismatches block the merge. */ function typesAreCompatible(existing: unknown, incoming: unknown): boolean { if (!isPlainObject(existing) || !isPlainObject(incoming)) return existing === incoming; const et = existing.type; const it = incoming.type; if (et === undefined && it === undefined) return true; if (et === undefined || it === undefined) return true; if (Array.isArray(et) || Array.isArray(it)) { const ea = Array.isArray(et) ? et : [et]; const ia = Array.isArray(it) ? it : [it]; return ea.some(x => ia.includes(x)); } return et === it; } /** * Build a SchemaWrapper from a plain JSON Schema, using `now` for both * timestamps when no existing wrapper is being preserved. */ export function newSchemaWrapper(schema: Record, now: string, definedBy?: string): SchemaWrapper { const wrapper: SchemaWrapper = { version: SCHEMA_VERSION, schema, createdAt: now, updatedAt: now, }; if (definedBy) wrapper.definedBy = definedBy; return wrapper; } /** * Update an existing wrapper, preserving createdAt and bumping updatedAt. */ export function updateSchemaWrapper( existing: SchemaWrapper, schema: Record, now: string, definedBy?: string, ): SchemaWrapper { const wrapper: SchemaWrapper = { version: existing.version || SCHEMA_VERSION, schema, createdAt: existing.createdAt, updatedAt: now, }; if (definedBy) wrapper.definedBy = definedBy; else if (existing.definedBy) wrapper.definedBy = existing.definedBy; return wrapper; } /** * Enumerate tables in a namespace folder. A "table" is either: * - a subfolder containing record files, OR * - a `.schema.json` sidecar (table may be schemaless until first save). * * Returns one entry per unique table name, with hasSchema + recordCount. * * `reserved` filters out names that occupy the namespace for non-table use * (e.g. `files`, the per-page uploads folder). */ export async function listTables( config: SynthOSConfig, parent: string, reserved: ReadonlySet = new Set(), ): Promise> { const sp = config.storageProvider; if (!await sp.checkIfExists(parent)) return []; const folders = await sp.listFolders(parent); const files = await sp.listFiles(parent); const known = new Map(); for (const folder of folders) { if (reserved.has(folder)) continue; const recs = (await sp.listFiles(path.join(parent, folder))) .filter(f => f.endsWith('.json')).length; known.set(folder, { hasSchema: false, recordCount: recs }); } for (const file of files) { const m = file.match(/^(.+)\.schema\.json$/); if (!m) continue; const name = m[1]; if (reserved.has(name)) continue; const existing = known.get(name); if (existing) { existing.hasSchema = true; } else { known.set(name, { hasSchema: true, recordCount: 0 }); } } return Array.from(known.entries()) .map(([name, info]) => ({ name, ...info })) .sort((a, b) => a.name.localeCompare(b.name)); }