/** * The dev seed end to end against `wrangler dev`, as the coordinator runs it * against the dev Worker: * * cd apps/business && pnpm -s exec tsx scripts/__tests__/e2e-dev-seed.ts [--scale small|medium] * * Starts the Worker with nothing onboarded (`dev-worker.ts startWrangler`, * the fixed code 123456 in DEV_OTP), then runs `pnpm -s dev-seed` as a * person would: a stand-in number signs up on the open host and its new * object is filled. The object's own count of live rows per table * (GET /v1/admin/export) must be the life's; a portrait and a book cover must * come back from /v1/media. A second run must write nothing and bring no message; * a run with --reset must empty the object and make the same database again. * wrangler dev is stopped and the temp dir removed however it ends. */import { spawnSync, typeChildProcess } from"node:child_process";import { mkdtempSync, rmSync } from"node:fs";import { tmpdir } from"node:os";import { join } from"node:path";import { counts, leave, signIn, typeSession } from"../dev-seed/client.ts";import { generateLife, typeScale } from"../dev-seed/life.ts";import { APP, check, startWrangler, stop } from"./dev-worker.ts";const NUMBER = "+919000000019";const CODE = "123456";const TODAY = "2026-10-29";const scale = (process.argv.includes("--scale") ? process.argv[process.argv.indexOf("--scale") + 1] : "small") asScale;const tmp = mkdtempSync(join(tmpdir(), "e2e-dev-seed-"));let wrangler: ChildProcess | null = null;const cleanup = (): void => { stop(wrangler); wrangler = null; rmSync(tmp, { recursive: true, force: true });};process.on("SIGINT", () => { cleanup(); process.exit(130);});function seed(base: string, ...more: string[]): { out: string; seconds: number } {const started = Date.now();const r = spawnSync("pnpm", ["-s", "dev-seed", "--base", base, "--number", NUMBER, "--scale", scale, "--today", TODAY, ...more], { cwd: APP, encoding: "utf8", env: { ...process.env, DEV_OTP: CODE }, }); check(r.status === 0, `pnpm dev-seed ${more.join(" ")}${r.status ? `\n${r.stdout}${r.stderr}` : ""}`); check(!r.stdout.includes(CODE) && !r.stderr.includes(CODE), "the code is never printed");return { out: r.stdout, seconds: (Date.now() - started) / 1000 };}/** * The seed's tables as the object counts them, beside what the life brings * and the owner's own person with their number, which the object makes for * the number that signed in (src/owner.ts). */function differences(held: Record<string, number>, life: Record<string, number>): string[] {const brought = { ...life, person: life.person! + 1, person_handle: life.person_handle! + 1 };returnObject.entries(brought) .filter(([table, n]) => (held[table] ?? 0) !== n) .map(([table, n]) => `${table}: the object holds ${held[table] ?? 0}, the seed brings ${n}`);}/** One table's live rows, read off the object's export. */asyncfunction rowsOf(s: Session, table: string): Promise<{ id: string; data: Record<string, unknown> }[]> {const out: { id: string; data: Record<string, unknown> }[] = [];for (let after: string | null = `${table}/`; after; ) {const r = await fetch(`${s.base}/v1/admin/export?limit=1000&after=${encodeURIComponent(after)}`, { headers: { authorization: `Bearer ${s.token}` } });const page = (await r.json()) as { rows: { table: string; id: string; data: Record<string, unknown> }[]; next: string | null };const mine = page.rows.filter((row) => row.table === table); out.push(...mine); after = mine.length === page.rows.length ? page.next : null; }return out;}try {const { base } = await startWrangler(tmp, (child) => { wrangler = child; });const first = seed(base); console.log(first.out.trimEnd());let s: Session = await signIn(base, NUMBER, CODE);try {const life = generateLife({ seed: "cotton-dev-1", scale, today: TODAY, databaseId: s.databaseId });const held = await counts(s); check(differences(held, life.counts).length === 0, `every table holds what the seed brings\n${differences(held, life.counts).join("\n")}`);const portrait = life.rows.find((r) => r.table === "person")!.data.avatar_key as string;const bookCover = life.rows.find((r) => r.table === "book")!.data.cover as string;for (const [what, key, type] of [["a portrait", portrait, "image/png"], ["a book cover", bookCover, "image/png"]] asconst) {const r = await fetch(`${base}/v1/media/${key.split("/").map(encodeURIComponent).join("/")}`, { headers: { authorization: `Bearer ${s.token}` } });const bytes = newUint8Array(await r.arrayBuffer());const sent = life.media.find((m) => m.key === key)!.bytes; check(r.ok && r.headers.get("content-type") === type && Buffer.compare(bytes, sent) === 0, `${what} comes back from /v1/media as it was sent`); }// Every chat's numbers are the seed's people: the import matched each contact to the person holding it.const contacts = await rowsOf(s, "message_contact");const people = newSet((await rowsOf(s, "person")).map((r) => r.id)); check(contacts.length > 0 && contacts.every((c) => people.has(c.data.person_id as string)), `every chat contact is one of the seed's people (${contacts.length})`); console.log(`first run: ${first.seconds.toFixed(1)} s; ${Object.values(life.counts).reduce((a, b) => a + b, 0)} rows and messages, ${life.media.length} files`);const second = seed(base); check(/rows: 0 written, \d+ unchanged/.test(second.out), `a second run writes no row\n${second.out}`); check(/chats: \d+, 0 messages brought/.test(second.out), "a second run brings no message"); check(/media: 0 sent/.test(second.out), "a second run sends no file"); check(differences(await counts(s), life.counts).length === 0, "and the object holds the same rows"); console.log(`second run: ${second.seconds.toFixed(1)} s`); } finally {await leave(s).catch(() => {}); }const third = seed(base, "--reset"); check(/reset: every row of .* gone \(POST \/v1\/admin\/reset/.test(third.out), "--reset empties the object through its admin reset route"); s = await signIn(base, NUMBER, CODE);try {const life = generateLife({ seed: "cotton-dev-1", scale, today: TODAY, databaseId: s.databaseId }); check(differences(await counts(s), life.counts).length === 0, "after --reset the object holds the seed's rows again"); console.log(`reset run: ${third.seconds.toFixed(1)} s`); } finally {await leave(s).catch(() => {}); } console.log("e2e dev seed: passed");} catch (error) { console.error((error asError).message); process.exitCode = 1;} finally { cleanup();}