Cotton code
137 lines · 6.9 KB · TypeScriptRaw
/** * Onboard a database onto its Worker object: its meta and its kit's * definitions (the flavour's tools and their tables, read from the * repository). No business ships a seed now: Sharmila's and Nancy's apps and * their seeds left the tree (22 Nov 2026). * * Flags: --base <url> (where the Worker answers; a workers.dev host gets the * /b/<slug> prefix, a named host does not), --owner <phone> (who signs in as * the owner), --upi <id>, --today YYYY-MM-DD, --database-id <uuid> (the personal database keeps its * Rust workspace id). The personal database (`pnpm onboard <slug> --owner * +91… --database-id <uuid>`) takes its flavour from apps/business/flavours * The admin token is BUSINESS_ADMIN_TOKEN or the file * ~/.cotton-credentials/cloudflare/business-admin-token, or for the dev * Worker (cottondb-dev.…workers.dev) business-dev-admin-token. */import { readFileSync, existsSync } from "node:fs";import { homedir } from "node:os";import { join, resolve, dirname } from "node:path";import { fileURLToPath } from "node:url";import { KITS } from "../src/kits.ts";const here = dirname(fileURLToPath(import.meta.url));const repo = resolve(here, "../../..");const FLAVOURS = join(repo, "apps/cotton/App/Flavours");type Data = Record<string, unknown>;// ── arguments ───────────────────────────────────────────────────────────────const argv = process.argv.slice(2);const slug = argv.find((a) => !a.startsWith("--"));if (!slug) fail("usage: pnpm onboard <slug> --base <url> [--owner +91…] [--upi id] [--today YYYY-MM-DD]");const flag = (name: string): string | undefined => {  const i = argv.indexOf(`--${name}`);  return i >= 0 ? argv[i + 1] : undefined;};const base = (flag("base") ?? "http://127.0.0.1:8787").replace(/\/$/, "");const prefix = /workers\.dev$|localhost|127\.0\.0\.1/.test(new URL(base).hostname) ? `/b/${slug}` : "";const token = process.env.BUSINESS_ADMIN_TOKEN ?? readToken();const today = flag("today") ?? localToday("Asia/Kolkata");function readToken(): string {  // The dev Worker (wrangler.jsonc `env.dev`) holds an admin token of its own.  const name = /^cottondb-dev\./.test(new URL(base).hostname) ? "business-dev-admin-token" : "business-admin-token";  const file = join(homedir(), ".cotton-credentials/cloudflare", name);  if (!existsSync(file)) fail(`no admin token: set BUSINESS_ADMIN_TOKEN or write ${file}`);  return readFileSync(file, "utf8").trim();}function fail(message: string): never {  console.error(message);  process.exit(1);}// ── the Worker ──────────────────────────────────────────────────────────────async function admin<T = Data>(method: string, path: string, body?: unknown): Promise<T> {  const r = await fetch(`${base}${prefix}${path}`, {    method,    headers: { authorization: `Bearer ${token}`, ...(body !== undefined ? { "content-type": "application/json" } : {}) },    body: body !== undefined ? JSON.stringify(body) : undefined,  });  const text = await r.text();  if (!r.ok) fail(`${method} ${path} → ${r.status} ${text.slice(0, 500)}`);  return JSON.parse(text) as T;}// ── definitions from the repository ─────────────────────────────────────────function readJson<T = Data>(path: string): T {  return JSON.parse(readFileSync(path, "utf8")) as T;}/** * The flavour's tools as the kits ship them (src/kits.ts, from * crates/cotton-core/kits), each with the tables it names. A kit that is a * tool of its own (personal) is sent as that tool alone: its other tools and * its boards reach every personal object from the kit (src/kit_keep.ts). A * flavour's tool no kit sends (people, messages) is the phone's own. */function definitionsOf(flavour: Data): { tools: Data[]; tables: Data[] } {  const tools: Data[] = [];  const tables = new Map<string, Data>();  for (const id of flavour.tools as string[]) {    for (const kit of Object.values(KITS)) {      const tool = (kit.own.length ? kit.own : kit.tools).find((t) => t.id === id);      if (!tool) continue;      tools.push(tool);      const named = new Set(tool.tables as string[]);      for (const table of kit.tables) if (named.has(String(table.id))) tables.set(String(table.id), table);    }  }  return { tools, tables: [...tables.values()] };}// ── dates ───────────────────────────────────────────────────────────────────function localToday(zone: string): string {  const parts = new Intl.DateTimeFormat("en-CA", { timeZone: zone, year: "numeric", month: "2-digit", day: "2-digit" }).formatToParts(new Date());  const get = (type: string) => parts.find((p) => p.type === type)!.value;  return `${get("year")}-${get("month")}-${get("day")}`;}// ── run ─────────────────────────────────────────────────────────────────────// A business app's flavour is the phone app's manifest; a database with no app of its own (the owner's personal one) keeps its flavour beside the Worker.const flavourFile = [join(FLAVOURS, slug, "flavour.json"), join(here, "../flavours", `${slug}.json`)].find((f) => existsSync(f));if (!flavourFile) fail(`no flavour for ${slug} in ${FLAVOURS} or apps/business/flavours`);const flavour = readJson(flavourFile);const { tools, tables } = definitionsOf(flavour);console.log(`${slug} at ${base}${prefix}, today ${today}`);const business = await admin("PUT", "/v1/admin/business", {  name: flavour.name,  currency: "INR",  timezone: "Asia/Kolkata",  kind: flavour.kind === "personal" ? "personal" : "business",  ...(flag("owner") ? { owner_phone: flag("owner") } : {}),  ...(flag("database-id") ? { database_id: flag("database-id") } : {}),  ...(flag("upi") ? { upi_id: flag("upi") } : {}),});console.log(`  business: ${JSON.stringify(business.business)}`);const defs = await admin("PUT", "/v1/admin/definitions", {  tools,  tables,  flavour: { flavour: flavour.flavour, name: flavour.name, public_views: flavour.public_views ?? {}, fan: flavour.fan ?? null },});console.log(`  definitions: ${String(defs.tools)} tools, ${String(defs.tables)} tables, version ${String(defs.version)}`);if (flavour.kind === "personal") {  // The personal database is not seeded: `pnpm import-personal` brings the owner's rows from their Mac.  console.log("  personal: no seed; pnpm import-personal brings the rows");} else {  // No business ships a seed now (the Sharmila and Nancy apps left the tree, 22 Nov 2026): a business is its meta and definitions.  console.log("  business: no seed");}