/** * The pure rules, run from the phone's own Rust (crates/cotton-rules) as WASM * (`pnpm rules:wasm` builds src/rules/wasm/; the module is checked in beside a * stamp of its sources). One door: a rule's name and its input, both JSON; * the answer, or a refusal in the rule's words. * * The module is instantiated on the first call, once per isolate. */import { refuse } from"../http.ts";import { call, initSync, mail_arrive, mail_attachment, plan } from"./wasm/cotton_rules.js";import rulesModule from"./wasm/cotton_rules_bg.wasm";let ready = false;function init(): void {if (!ready) { initSync({ module: rulesModule }); ready = true; }}/** Run `name` over `input`: its answer, or its refusal in the rule's words. */exportfunction tryRule<T>(name: string, input: unknown): { ok: T } | { error: string } { init();return JSON.parse(call(name, JSON.stringify(input))) as { ok: T } | { error: string };}/** * Run the messages engine's `name` over `input` (cotton_rules::import::asked), * answering each read it asks with `ask(question, args)` — synchronously, from * inside the plan: the plan, or the engine's refusal (its words and code). */exportfunction tryPlan<T>(name: string, input: unknown, ask: (question: string, args: Record<string, unknown>) => unknown): { ok: T } | { error: string; code: string } { init();const answer = (question: string, args: string): string => JSON.stringify(ask(question, JSON.parse(args) asRecord<string, unknown>) ?? null);return JSON.parse(plan(name, JSON.stringify(input), answer)) as { ok: T } | { error: string; code: string };}/** Run `name` over `input`; a refusal is a 400 (`code`) in the rule's words. */exportfunction rule<T>(name: string, input: unknown, code = "bad_request"): T {const out = tryRule<T>(name, input);if ("error"in out) refuse(400, code, out.error);return out.ok;}/** * Mail that arrived on a person's own domain, read as the Mac reads mail * (cotton_rules::mail::arrive): the raw bytes go in as bytes. Its rows, or * its refusal in words. *//** What Cotton's fetcher read of a message over IMAP (Post CONTRACT row 13): Gmail's ids as decimal strings, its labels and flags as IMAP spells them, and whether it came from the Inbox. */exportinterfaceFetched { msgid?: string; thrid?: string; labels: string[]; flags: string[]; inbox: boolean;}exportfunction mailArrive<T>(raw: Uint8Array, input: { database: string; account: string; received: number; fetched?: Fetched }): { ok: T } | { error: string } { init();return JSON.parse(mail_arrive(raw, JSON.stringify(input))) as { ok: T } | { error: string };}/** The `index`th attachment's decoded bytes, in mailArrive's order; undefined past the last. */exportfunction mailAttachment(raw: Uint8Array, index: number): Uint8Array | undefined { init();return mail_attachment(raw, index);}