/** * The seed's side of the Worker's front door, on the open host (OPEN_HOST: * cottondb.com, the dev Worker's workers.dev host, 127.0.0.1 under wrangler * dev), where nothing in the URL names an object: * * POST /v1/code, POST /v1/sign-in the number signs up (the directory makes * its object) or in, with the fixed code * POST /v1/act mint_token an owner `ctn_` token for the seed's own * calls, revoked when the seed is done * POST /v1/admin/reset --reset: every row goes (the admin reset * route, which an owner token of a * personal object may call); sessions and * tokens with them, so the seed signs in again * POST /v1/media/missing, PUT /v1/media/<key> the pictures and songs * POST /v1/admin/import the rows, `put` with their own ids * POST /v1/import/messages the chats, as the WhatsApp import * GET /v1/admin/export?limit=1 the live rows per table afterwards * * A refusal is thrown with its status and the object's words; no secret (the * code, a credential, a token) is ever in a message. */importtype { ImportBatch } from"../../src/import/envelope.ts";importtype { SeedMedia, SeedRow } from"./life.ts";exportclassSeedRefusalextendsError {}exportinterfaceSession { base: string; databaseId: string;/** The seed's device credential (`ctd_…`). */ credential: string;/** An owner token the seed minted (`ctn_…`), and its row's id. */ token: string; tokenId: string;}exportconst DEVICE_ID = "dev-seed";asyncfunction call<T = Record<string, unknown>>(base: string, method: string, path: string, body?: unknown, bearer?: string): Promise<T> {let r: Response;try { r = await fetch(`${base}${path}`, { method, headers: { ...(body !== undefined ? { "content-type": "application/json" } : {}), ...(bearer ? { authorization: `Bearer ${bearer}` } : {}) }, body: body !== undefined ? JSON.stringify(body) : undefined, }); } catch (error) {thrownewSeedRefusal(`${method} ${base}${path}: ${(error as Error).message}`); }const text = await r.text();if (!r.ok) thrownewSeedRefusal(`${method} ${path} → ${r.status} ${text.slice(0, 400)}`);return (text ? JSON.parse(text) : {}) as T;}/** Sign the number up or in with the code, and mint the seed's owner token. */exportasyncfunction signIn(base: string, phone: string, code: string): Promise<Session> {const asked = await call<{ challenge_id: string; database_id: string }>(base, "POST", "/v1/code", { phone, device_id: DEVICE_ID });const signed = await call<{ credential: string; person: { role: string } }>(base, "POST", "/v1/sign-in", { database_id: asked.database_id, challenge_id: asked.challenge_id, code, device_id: DEVICE_ID });if (signed.person.role !== "owner") thrownewSeedRefusal(`${phone} signed in as ${signed.person.role}, not as the owner of its database`);const minted = await call<{ token?: string; made?: { id: string } }>(base, "POST", "/v1/act", { act: "mint_token", args: { name: "dev seed", scopes: ["owner"], expires_in_days: 1, allow: "all" } }, signed.credential);if (!minted.token || !minted.made?.id) thrownewSeedRefusal("mint_token answered no token");return { base, databaseId: asked.database_id, credential: signed.credential, token: minted.token, tokenId: minted.made.id };}/** The object's own account of itself: its database id and kind, and that it holds the personal kit. */exportasyncfunction describe(s: Session): Promise<{ databaseId: string | null; kind: string | null; tables: number }> {const defs = await call<{ business?: { database_id?: string; kind?: string }; tables?: unknown[] }>(s.base, "GET", "/v1/definitions", undefined, s.credential);return { databaseId: defs.business?.database_id ?? null, kind: defs.business?.kind ?? null, tables: defs.tables?.length ?? 0 };}/** Every row goes; the object signs nobody in afterwards until they sign in again. */exportasyncfunction reset(s: Session): Promise<number> {const answer = await call<{ version: number }>(s.base, "POST", "/v1/admin/reset", {}, s.token);return answer.version;}/** Media the object lacks, then each sent: `{ sent, held }`. *//** How often one media PUT is sent again after the Worker answered 5xx (the seed's own retry, `putOnce`). */exportconst PUT_TRIES = 3;/** * One media PUT, sent again (after 1 s, then 2 s) while the Worker answers * 5xx: R2 or the object now and then fails one write under the seed's six at * once (1 in 540 synthetic PUTs on cottondb-dev, 12 Nov 2026, never the same * key twice), and a PUT of the same bytes is idempotent (`stored: false`). * A 4xx, or a 5xx every try, refuses the seed, saying what failed. */exportasyncfunction putOnce(s: Session, path: string, m: SeedMedia, sent: number, wait: (ms: number) => Promise<void> = (ms) => newPromise((done) => setTimeout(done, ms))): Promise<Response> {for (let attempt = 1; ; attempt += 1) {let r: Response;try { r = await fetch(`${s.base}${path}`, { method: "PUT", headers: { authorization: `Bearer ${s.credential}`, "content-type": m.contentType }, body: m.bytes }); } catch (error) {thrownewSeedRefusal(`PUT ${path}: ${(error as Error).message}; ${sent} sent before it, and a re-run sends only what is still missing`); }if (r.status === 200 || r.status === 201) return r;const said = `PUT ${path} → ${r.status} ${(await r.text()).slice(0, 200)}`;if (r.status < 500 || attempt >= PUT_TRIES) thrownewSeedRefusal(attempt > 1 ? `${said} (tried ${attempt} times)` : said); console.error(`${said}; sending it again`);await wait(1000 * attempt); }}exportasyncfunction upload(s: Session, media: SeedMedia[]): Promise<{ sent: number; held: number; bytes: number }> {const missing = newSet<string>();for (let i = 0; i < media.length; i += 500) {const answer = await call<{ missing: string[] }>(s.base, "POST", "/v1/media/missing", { keys: media.slice(i, i + 500).map((m) => m.key) }, s.credential);for (const key of answer.missing) missing.add(key); }let sent = 0;let bytes = 0;const queue = media.filter((m) => missing.has(m.key));const worker = async (): Promise<void> => {for (let m = queue.shift(); m; m = queue.shift()) {const path = `/v1/media/${m.key.split("/").map(encodeURIComponent).join("/")}`;await putOnce(s, path, m, sent); sent += 1; bytes += m.bytes.length; } };awaitPromise.all(Array.from({ length: 6 }, worker));return { sent, held: media.length - sent, bytes };}exportinterfaceBrought { written: number; unchanged: number; deleted: number;}/** The rows, in their order (a link's target before the row naming it), a thousand a call. */exportasyncfunction importRows(s: Session, rows: SeedRow[]): Promise<Brought> {const total: Brought = { written: 0, unchanged: 0, deleted: 0 };for (let i = 0; i < rows.length; i += 1000) {const batch = rows.slice(i, i + 1000).map((r) => ({ verb: "put", ...r }));const answer = await call<{ puts: Record<string, Brought> }>(s.base, "POST", "/v1/admin/import", { rows: batch }, s.token);for (const t ofObject.values(answer.puts ?? {})) { total.written += t.written; total.unchanged += t.unchanged; total.deleted += t.deleted; } }return total;}/** Each chat as one WhatsApp import batch: `{ messages, skipped }` (a re-run skips every message it brought before). */exportasyncfunction importChats(s: Session, chats: ImportBatch[]): Promise<{ messages: number; skipped: number }> {let messages = 0;let skipped = 0;for (const chat of chats) {const answer = await call<{ applied: { messages: number }; skipped: number }>(s.base, "POST", "/v1/import/messages", chat, s.token); messages += answer.applied.messages; skipped += answer.skipped; }return { messages, skipped };}/** Live rows per table, as the object counts them. */exportasyncfunction counts(s: Session): Promise<Record<string, number>> {const answer = await call<{ counts: Record<string, number> }>(s.base, "GET", "/v1/admin/export?limit=1", undefined, s.token);return answer.counts;}/** The seed's token revoked and its device signed out: it leaves no way in behind. */exportasyncfunction leave(s: Session): Promise<void> {await call(s.base, "POST", "/v1/act", { act: "revoke_token", args: { id: s.tokenId } }, s.credential);await call(s.base, "POST", "/v1/sign-out", {}, s.credential);}