import { test, expect, beforeAll, afterAll } from "bun:test" import { Database } from "bun:sqlite" import { initDb, getEntriesData, saveEntry } from "./api" let server: ReturnType let db: Database let wsUrl: string beforeAll(() => { db = new Database(":memory:") initDb(db) const clients = new Set>() server = Bun.serve({ port: 0, fetch(req, server) { const { pathname } = new URL(req.url) if (pathname === "/ws") { if (server.upgrade(req)) return return new Response("WebSocket upgrade failed", { status: 400 }) } return new Response("app", { headers: { "Content-Type": "text/html; charset=utf-8" }, }) }, websocket: { open(ws) { clients.add(ws) ws.send(JSON.stringify({ type: "init", entries: getEntriesData(db) })) }, message(ws, msg) { const entry = JSON.parse(msg as string) saveEntry(db, entry) const payload = JSON.stringify({ type: "entry", entry }) for (const client of clients) client.send(payload) }, close(ws) { clients.delete(ws) }, }, }) wsUrl = `ws://localhost:${server.port}/ws` }) afterAll(() => { server.stop() db.close() }) const mockEntry = { id: "deadbeef", created: 1_000_000, item: { key: "k1", text: "hello", checked: null, created: 1_000_000 }, } function connectWS(): Promise<{ ws: WebSocket; messages: unknown[] }> { return new Promise((resolve, reject) => { const messages: unknown[] = [] const ws = new WebSocket(wsUrl) ws.onmessage = (e) => messages.push(JSON.parse(e.data as string)) ws.onopen = () => resolve({ ws, messages }) ws.onerror = reject }) } function waitFor(condition: () => boolean, timeout = 500): Promise { return new Promise((resolve, reject) => { const iv = setInterval(() => { if (condition()) { clearInterval(iv); resolve() } }, 10) setTimeout(() => { clearInterval(iv); reject(new Error("waitFor timeout")) }, timeout) }) } test("WS open sends init with empty entries", async () => { const { ws, messages } = await connectWS() await waitFor(() => messages.length >= 1) ws.close() expect(messages[0]).toEqual({ type: "init", entries: [] }) }) test("WS message saves entry and broadcasts to all subscribers", async () => { const { ws: ws1, messages: m1 } = await connectWS() const { ws: ws2, messages: m2 } = await connectWS() await waitFor(() => m1.length >= 1 && m2.length >= 1) ws1.send(JSON.stringify(mockEntry)) await waitFor(() => m1.length >= 2 && m2.length >= 2) ws1.close() ws2.close() const isBroadcast = (m: unknown) => (m as { type: string; entry: { id: string } }).type === "entry" && (m as { type: string; entry: { id: string } }).entry.id === "deadbeef" expect(m1.some(isBroadcast)).toBe(true) expect(m2.some(isBroadcast)).toBe(true) }) test("WS init includes previously saved entries", async () => { const { ws, messages } = await connectWS() await waitFor(() => messages.length >= 1) ws.close() const init = messages[0] as { type: string; entries: { id: string }[] } | undefined expect(init?.type).toBe("init") expect(init?.entries).toHaveLength(1) expect(init?.entries[0]?.id).toBe("deadbeef") }) test("GET / returns HTML fallback", async () => { const res = await fetch(`http://localhost:${server.port}/`) expect(res.status).toBe(200) expect(res.headers.get("content-type")).toContain("text/html") })