/** * Reading the kit definitions the object holds: a table's visibility, its * columns, which row a `mine()` row belongs to. * * The definitions are a kit's JSON from `crates/cotton-core/kits//` * (`tools//manifest.json` and `tables/.json`), stored verbatim and * served to the phone verbatim; this module reads only what the object must * decide on. */ import { GONE_TABLES } from "./retired.ts"; import { faceProblem } from "./faces.ts"; import type { Role, Visibility } from "./protocol.ts"; import { rule } from "./rules/index.ts"; import { isSealedColumn, isSealedRow, parseSeal, SEAL_FIELDS, sealProblem, type SealSpec } from "./seal.ts"; export interface ColumnDef { key: string; type: string; link_to?: string; required?: boolean; default?: unknown; computed?: unknown; readonly?: boolean; /** Several values: a link of several records holds a list of their ids. */ multiple?: boolean; } export interface TableDef { id: string; visibility: Visibility; columns: ColumnDef[]; /** The column that dates a row (`"date"` in the JSON), if any. */ date?: string | null; /** The `seal` block (src/seal.ts): the columns kept clear, every other one sealed. Absent on an open table. */ seal?: SealSpec | null; raw: Record; } /** * A table's visibility word, read by the phone's own rule (cotton-rules * visibility.rs, as WASM; vectors in crates/cotton-rules/vectors/visibility.json): * absent is `owner`; any other word than public, staff, customer, owner or * mine() is refused (null). */ export function parseVisibility(text: unknown): Visibility | null { if (text !== undefined && text !== null && typeof text !== "string") return null; const word = text ?? null; // The rule is pure and its words few: each is asked of the WASM once per isolate, where every // definitions rebuild used to ask it once per table (about 1,200 calls a sign-up, 12 Nov 2026). if (VISIBILITIES.has(word)) return VISIBILITIES.get(word)!; const read = rule("visibility.parse", { word }); const answer = "refused" in read ? null : Object.freeze(read); VISIBILITIES.set(word, answer); return answer; } /** parseVisibility's answers by word, frozen: shared by every table that says the word. */ const VISIBILITIES = new Map(); /** Why a table's definition does not read, or null when it does. */ export function tableProblem(raw: Record): string | null { if (typeof raw.id !== "string" || !raw.id) return "every table needs an id"; if (!parseVisibility(raw.visibility)) return "visibility must be public, mine(person_column), staff, customer or owner"; return sealProblem(raw); } export function parseTable(raw: Record): TableDef | null { const id = typeof raw.id === "string" ? raw.id : null; const visibility = parseVisibility(raw.visibility); if (!id || !visibility) return null; const columns: ColumnDef[] = Array.isArray(raw.columns) ? (raw.columns as Record[]) .filter((c) => typeof c.key === "string") .map((c) => ({ key: c.key as string, type: typeof c.type === "string" ? c.type : "text", link_to: typeof c.link_to === "string" ? c.link_to : undefined, required: c.required === true, default: c.default, computed: c.computed, readonly: c.readonly === true, multiple: c.multiple === true, })) : []; return { id, visibility, columns, date: typeof raw.date === "string" ? raw.date : null, seal: parseSeal(raw), raw, }; } /** The definitions of one business, indexed. */ export class Definitions { readonly tables: Map; constructor(tables: TableDef[]) { this.tables = new Map(tables.map((t) => [t.id, t])); } table(id: string): TableDef | undefined { return this.tables.get(id); } column(table: string, key: string): ColumnDef | undefined { return this.tables.get(table)?.columns.find((c) => c.key === key); } /** The table whose rows are a person's own card: the package's `mine(person)` table with a `person` link (yoga_member, kitchen_customer); never a built-in one (messages). */ personTable(): TableDef | undefined { for (const t of this.tables.values()) { if (t.raw.builtin === true) continue; if (t.visibility.kind === "mine" && t.visibility.through === "person" && t.columns.some((c) => c.key === "person")) return t; } return undefined; } /** The link columns of every table, for the store's links index. */ linkColumns(): Map { const out = new Map(); for (const t of this.tables.values()) out.set(t.id, t.columns.filter((c) => c.type === "link" && !c.computed).map((c) => c.key)); return out; } /** Each dated table's date column: what a sync window keeps the table by. */ dateColumns(): Map { const out = new Map(); for (const t of this.tables.values()) if (t.date) out.set(t.id, t.date); return out; } /** The object's own tables (`internal: true`: tokens, OAuth state) that no device syncs and no record tool names. */ internalTables(): Set { // A table held as retired (src/retired.ts) is one no device holds either: its rows stay on the object, never synced. const out = new Set(GONE_TABLES); for (const t of this.tables.values()) if (t.raw.internal === true) out.add(t.id); return out; } /** Tables a role may read whole. */ wholeTables(role: Role): Set { const out = new Set(); for (const t of this.tables.values()) { const v = t.visibility.kind; if (v === "public") out.add(t.id); else if ((v === "staff" || v === "mine" || v === "customer") && (role === "staff" || role === "owner")) out.add(t.id); else if (v === "owner" && role === "owner") out.add(t.id); } return out; } /** Tables a member reads only their own rows of. */ ownTables(): Set { const out = new Set(); for (const t of this.tables.values()) if (t.visibility.kind === "mine" || t.visibility.kind === "customer") out.add(t.id); return out; } /** The floor role that may write rows of a table directly (create/update/delete acts). Members never write rows directly; they act. */ writeFloor(table: string): Role { const t = this.tables.get(table); if (!t) return "owner"; return t.visibility.kind === "owner" ? "owner" : "staff"; } } /** The columns a photo id may sit in, so an export or a cache knows which keys to fetch. */ export function photoColumns(t: TableDef): string[] { return t.columns.filter((c) => c.type === "photo" && !c.computed).map((c) => c.key); } /** * Drop computed and unknown keys from data someone wrote; the object stores * only what the definition names and never a computed value. A sealed table * also stores the sealer's own three columns (src/seal.ts), which no * definition declares. */ export function storable(t: TableDef, data: Record): Record { const out: Record = {}; for (const c of t.columns) { if (c.computed) continue; if (c.key in data) out[c.key] = data[c.key]; } if (t.seal) for (const k of SEAL_FIELDS) if (k in data) out[k] = data[k]; return out; } /** Required columns a write left empty. A sealed row holds its sealed columns in its blob, so only its clear ones are asked for. */ export function missingRequired(t: TableDef, data: Record): string[] { const sealed = isSealedRow(data); return t.columns .filter((c) => c.required && !c.computed && !(sealed && isSealedColumn(t, c.key)) && (data[c.key] === undefined || data[c.key] === null || data[c.key] === "")) .map((c) => c.key); } /** Defaults the definition gives, applied where a write said nothing; never a sealed column's on a sealed row, whose blob says it. */ export function withDefaults(t: TableDef, data: Record): Record { const out = { ...data }; const sealed = isSealedRow(data); for (const c of t.columns) { if (c.computed) continue; if (sealed && isSealedColumn(t, c.key)) continue; if (!(c.key in out) && c.default !== undefined) out[c.key] = c.default; } return out; } /** A stable hash of the definitions, for the phone's etag. */ /** * What is wrong with a tool, board or theme definition merged in by id, or * null. Each needs an id; a tool also needs a name, and its automations — * which the engine reads on every write — each a `when` object and a `then` * list, and each card its views hold names a face the app draws * (src/faces.ts); a board's parts are a list. */ export function definitionProblem(kind: "tool" | "board" | "theme", doc: unknown): string | null { if (!doc || typeof doc !== "object" || Array.isArray(doc)) return `every ${kind} is an object`; const d = doc as Record; if (typeof d.id !== "string" || !d.id) return `every ${kind} needs an id`; if (kind === "theme") return null; if (kind === "board") return d.parts === undefined || Array.isArray(d.parts) ? null : `the board ${d.id}'s parts are a list`; if (typeof d.name !== "string" || !d.name) return `the tool ${d.id} needs a name`; const automations = d.automations; const ok = automations === undefined || (Array.isArray(automations) && automations.every((a) => a && typeof a === "object" && a.when && typeof a.when === "object" && Array.isArray(a.then))); return ok ? faceProblem(d) : `the tool ${d.id}'s automations are each a when and a then`; } export async function etagOf(parts: unknown[]): Promise { const text = JSON.stringify(parts); const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)); return [...new Uint8Array(digest)].slice(0, 12).map((b) => b.toString(16).padStart(2, "0")).join(""); }