Cotton code
220 lines · 8.1 KB · TypeScriptRaw
/** * One table as the generic record tools read its definition: the Rust * `TableDefinition` fields they decide on (crates/cotton-core/src/definitions), * read off the definition JSON the object holds verbatim — the personal * package's tables and the owner's own made tables (quota, machine), all in * the Rust shared format. * * Every table here is a made table in the Rust sense: its rows are the * object's generic rows, so a built-in's engine never answers for it. A * definition marked `internal` (mcp_token) is no table to these tools at all. */import { fail, type Data, type ToolContext } from "../../context.ts";import type { TableDef } from "../../../definitions.ts";import type { StoredRow } from "../../../store.ts";import { isSealedColumn } from "../../../seal.ts";/** One column as the definition JSON writes it. */export interface Column {  key: string;  type: string;  name?: string;  label?: string;  required?: boolean;  readonly?: boolean;  computed?: unknown;  choices?: string[];  choices_from?: unknown;  multiple?: boolean;  link_to?: string;  format?: string;  default?: unknown;  secret?: boolean;  /** A place column's read-only siblings, filled from the published place a person picks (./picks.ts). */  place?: { id: string; country: string; zone: string; lat?: string; lng?: string; version?: string };}export interface Sort {  column: string;  descending?: boolean;  tie?: string;  tie_descending?: boolean;  next?: boolean;}/** The columns a binned record keeps its day in: a record holding one is in the bin, out of every list. */const BIN_COLUMNS = ["trashed_at", "deleted_at"];/** * Columns no generic read answers whatever a definition declares * (`records::SENSITIVE_COLUMNS`), plus the vault's own `sealed`. */const SENSITIVE = new Set(["value_enc", "hint", "password", "secret_hash", "token_hash", "token_digest", "refresh_token_enc", "sync_token", "sealed", "wrapped_vmk", "public_key"]);export function isSensitiveColumn(key: string): boolean {  return SENSITIVE.has(key) || key.endsWith("_enc") || key.endsWith("_hash") || key.endsWith("_digest") || key.includes("password");}export const NO_TOOL_DRAWS = "No tool draws this table.";export class Table {  readonly def: TableDef;  readonly raw: Data;  readonly id: string;  readonly columns: Column[];  constructor(def: TableDef) {    this.def = def;    this.raw = def.raw;    this.id = def.id;    this.columns = Array.isArray(def.raw.columns) ? (def.raw.columns as Column[]).filter((c) => c && typeof c.key === "string") : [];  }  get plural(): string {    return typeof this.raw.plural === "string" && this.raw.plural ? this.raw.plural : this.id;  }  get name(): string {    return typeof this.raw.name === "string" && this.raw.name ? this.raw.name : this.id;  }  get title(): string {    return typeof this.raw.title === "string" ? this.raw.title : "";  }  get project(): string | null {    return stringKey(this.raw.project);  }  get order(): string | null {    return stringKey(this.raw.order);  }  get date(): string | null {    return stringKey(this.raw.date);  }  get sort(): Sort | null {    const s = this.raw.sort as Sort | null | undefined;    return s && typeof s === "object" && typeof s.column === "string" ? s : null;  }  /** The column a record is archived by, or "status" when a status choice reads `archived`, or null (`archive_of`). */  get archive(): { column: string } | { status: true } | null {    const archived = stringKey(this.raw.archived);    if (archived === "trashed_at") return null;    if (archived) return { column: archived };    const status = this.column("status");    return status?.choices?.includes("archived") ? { status: true } : null;  }  /** The column this table's bin keeps a record's day in, when it has one. */  get binColumn(): string | null {    return BIN_COLUMNS.find((key) => this.column(key)) ?? null;  }  get slip(): Data {    return this.raw.slip && typeof this.raw.slip === "object" ? (this.raw.slip as Data) : {};  }  /** The token whose writes may fill the readonly columns (`producer.token_id`). */  get producerToken(): string | null {    const p = this.raw.producer as { token_id?: unknown } | null | undefined;    return p && typeof p.token_id === "string" && p.token_id ? p.token_id : null;  }  column(key: string): Column | undefined {    return this.columns.find((c) => c.key === key);  }  /** Whether the table's `seal` block seals this column (src/seal.ts): no read filters, sums or searches it. */  sealed(key: string): boolean {    return isSealedColumn(this.def, key);  }  /** The day a record went to the bin, or null while it is live. */  binned(row: StoredRow): string | null {    const column = this.binColumn;    if (!column) return null;    const v = row.data[column];    return typeof v === "string" && v !== "" ? v : null;  }  /** Whether a record is in the archive (`archivedSql`, held against a row already read). */  archived(row: StoredRow): boolean {    const a = this.archive;    if (!a) return false;    const v = "status" in a ? row.data.status : row.data[a.column];    if ("status" in a) return v === "archived";    return !(v === null || v === undefined || v === "" || v === 0 || v === false);  }  /**   * The columns words are looked for in (`searchable_columns`): the title and   * every text column, less the project, an account number, a computed column,   * any column no generic read answers and any sealed column.   */  get searchable(): string[] {    const keys = new Set<string>();    if (this.title && this.column(this.title)) keys.add(this.title);    for (const c of this.columns) if (c.type === "text" || c.type === "longtext") keys.add(c.key);    return [...keys].filter((k) => {      const c = this.column(k)!;      return k !== this.project && c.type !== "account_number" && c.secret !== true && (c.computed === undefined || c.computed === null) && !isSensitiveColumn(k) && !this.sealed(k);    });  }  /** Words a person reads for a column: its name, else its key in words. */  label(c: Column): string {    const name = typeof c.name === "string" && c.name.trim() ? c.name : typeof c.label === "string" && c.label.trim() ? c.label : null;    return name ?? keyAsWords(c.key);  }}function stringKey(v: unknown): string | null {  return typeof v === "string" && v ? v : null;}export function keyAsWords(key: string): string {  const words = key.replace(/_/g, " ");  return words ? words[0]!.toUpperCase() + words.slice(1) : words;}export function lowerFirst(words: string): string {  return words ? words[0]!.toLowerCase() + words.slice(1) : words;}/** `table is required: …` — the generic verbs' own reading of the table argument (tables/mod.rs `table_arg`). */export function tableArg(args: Data): string {  const v = args.table;  if (typeof v !== "string" || !v.trim()) fail('table is required: the table\'s id, e.g. "todo"');  return v.trim();}/** * A table the object holds, or `No tool draws this table.` with its typed * code (tables/mod.rs `definition`). An internal table is answered exactly * as one that is not there. */export function resolveTable(ctx: Pick<ToolContext, "defs">, id: string, asked: unknown = id): Table {  const def = ctx.defs().table(id.trim());  if (!def || def.raw.internal === true) fail(NO_TOOL_DRAWS, { code: "no_tool_draws_this_table", table: typeof asked === "string" ? asked : null });  return new Table(def);}/** Every table the record tools may name: all the object holds, less the internal ones. */export function visibleTables(ctx: ToolContext): Table[] {  return [...ctx.defs().tables.values()].filter((t) => t.raw.internal !== true).map((t) => new Table(t));}/** `That {kind} is no longer here` — a record that is gone, never its id (receipts.json `no_longer_here`). */export function noLongerHere(t: Table): string {  return `That ${lowerFirst(t.name)} is no longer here`;}/** `id is required` — a record id argument, trimmed. */export function idArg(args: Data): string {  const v = args.id;  if (typeof v !== "string" || !v.trim()) fail("id is required");  return v.trim();}