/** * 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/<app>/` * (`tools/<id>/manifest.json` and `tables/<id>.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";importtype { Role, Visibility } from"./protocol.ts";import { rule } from"./rules/index.ts";import { isSealedColumn, isSealedRow, parseSeal, SEAL_FIELDS, sealProblem, typeSealSpec } from"./seal.ts";exportinterfaceColumnDef { 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;}exportinterfaceTableDef { 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<string, unknown>;}/** * 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(<column>) is refused (null). */exportfunction parseVisibility(text: unknown): Visibility | null {if (text !== undefined && text !== null && typeof text !== "string") returnnull;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 | { refused: string }>("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 = newMap<string | null, Visibility | null>();/** Why a table's definition does not read, or null when it does. */exportfunction tableProblem(raw: Record<string, unknown>): 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);}exportfunction parseTable(raw: Record<string, unknown>): TableDef | null {const id = typeof raw.id === "string" ? raw.id : null;const visibility = parseVisibility(raw.visibility);if (!id || !visibility) returnnull;const columns: ColumnDef[] = Array.isArray(raw.columns) ? (raw.columns asRecord<string, unknown>[]) .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. */exportclassDefinitions {readonly tables: Map<string, TableDef>; constructor(tables: TableDef[]) {this.tables = newMap(tables.map((t) => [t.id, t])); } table(id: string): TableDef | undefined {returnthis.tables.get(id); } column(table: string, key: string): ColumnDef | undefined {returnthis.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 ofthis.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; }returnundefined; }/** The link columns of every table, for the store's links index. */ linkColumns(): Map<string, string[]> {const out = newMap<string, string[]>();for (const t ofthis.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<string, string> {const out = newMap<string, string>();for (const t ofthis.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<string> {// A table held as retired (src/retired.ts) is one no device holds either: its rows stay on the object, never synced.const out = newSet<string>(GONE_TABLES);for (const t ofthis.tables.values()) if (t.raw.internal === true) out.add(t.id);return out; }/** Tables a role may read whole. */ wholeTables(role: Role): Set<string> {const out = newSet<string>();for (const t ofthis.tables.values()) {const v = t.visibility.kind;if (v === "public") out.add(t.id);elseif ((v === "staff" || v === "mine" || v === "customer") && (role === "staff" || role === "owner")) out.add(t.id);elseif (v === "owner" && role === "owner") out.add(t.id); }return out; }/** Tables a member reads only their own rows of. */ ownTables(): Set<string> {const out = newSet<string>();for (const t ofthis.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. */exportfunction 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. */exportfunction storable(t: TableDef, data: Record<string, unknown>): Record<string, unknown> {const out: Record<string, unknown> = {};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. */exportfunction missingRequired(t: TableDef, data: Record<string, unknown>): 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. */exportfunction withDefaults(t: TableDef, data: Record<string, unknown>): Record<string, unknown> {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. */exportfunction 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 asRecord<string, unknown>;if (typeof d.id !== "string" || !d.id) return`every ${kind} needs an id`;if (kind === "theme") returnnull;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`;}exportasyncfunction etagOf(parts: unknown[]): Promise<string> {const text = JSON.stringify(parts);const digest = await crypto.subtle.digest("SHA-256", newTextEncoder().encode(text));return [...newUint8Array(digest)].slice(0, 12).map((b) => b.toString(16).padStart(2, "0")).join("");}