import assert from "node:assert/strict"; import { test } from "node:test"; import type { Actor } from "../contract/actor.ts"; import { hinting, pullStream, recordEvent, repoStream, taskStream, type Hint } from "../events.ts"; import { d1, migrated } from "./d1.ts"; const human: Actor = { kind: "human", person: { id: "u1", name: "Aman", email: "a@example.com", role: "owner" }, via: "session" }; function setup() { const sqlite = migrated(); sqlite.exec("INSERT INTO tasks (id, repo_id, number, title, body, author_id, created_at, updated_at) VALUES (5, 'r1', 1, 't', '', 'u1', 0, 0)"); sqlite.exec("INSERT INTO pulls (id, repo_id, number, title, author_id, base_ref, head_ref, created_at, updated_at) VALUES (9, 'r2', 1, 't', 'u1', 'main', 'tasks/1', 0, 0)"); const hints: Hint[] = []; return { db: hinting(d1(sqlite), (hint) => hints.push(hint)), hints, sqlite }; } test("a committed batch hints each stream's repository once, with its newest event", async () => { const { db, hints } = setup(); const [first] = await db.batch([ recordEvent(db, human, taskStream(5), "task.renamed", { from: "a", to: "b" }, 0), recordEvent(db, human, taskStream(5), "task.closed", {}, 0), db.prepare("UPDATE tasks SET title = 'b' WHERE id = 5"), recordEvent(db, human, pullStream(9), "pull.closed", {}, 0), recordEvent(db, human, "org", "invitation.revoked", { email: "x@example.com" }, 0), ]); assert.equal(first.meta.last_row_id, 1); assert.deepEqual(hints, [ { latestId: 2, stream: "task:5", repoId: "r1" }, { latestId: 3, stream: "pull:9", repoId: "r2" }, ]); }); test("a single recorded event hints after it runs", async () => { const { db, hints } = setup(); const statement = recordEvent(db, human, repoStream("r3"), "repo.updated", { description: "x" }, 0); assert.deepEqual(hints, []); await statement.run(); assert.deepEqual(hints, [{ latestId: 1, stream: "repo:r3", repoId: "r3" }]); }); test("a failed batch hints nothing", async () => { const { db, hints } = setup(); await assert.rejects(db.batch([recordEvent(db, human, taskStream(5), "task.closed", {}, 0), db.prepare("INSERT INTO nowhere VALUES (1)")])); assert.deepEqual(hints, []); }); test("reading an event statement with first() fails instead of skipping its hint", async () => { const { db, hints } = setup(); await assert.rejects(recordEvent(db, human, repoStream("r4"), "repo.updated", { description: "x" }, 0).first(), /run\(\) or db\.batch\(\)/); assert.deepEqual(hints, []); });