import type { Context } from 'hono'; import { streamSSE } from 'hono/streaming'; import { onChange, type ChangeTopic } from '../services/events.ts'; /** GET /api/events: a long-lived stream of `{type: 'change', topics}` messages for the owner's tabs. */ export function liveChanges(c: Context) { c.header('X-Accel-Buffering', 'no'); c.header('Cache-Control', 'no-cache, no-transform'); return streamSSE(c, async (stream) => { let chain: Promise = Promise.resolve(); const send = (data: unknown) => { chain = chain.then(() => stream.writeSSE({ data: JSON.stringify(data) })).catch(() => undefined); }; const off = onChange((topics: ChangeTopic[]) => send({ type: 'change', topics })); const ping = setInterval(() => send({ type: 'ping' }), 25_000); send({ type: 'ready' }); await new Promise((resolve) => stream.onAbort(() => resolve())); clearInterval(ping); off(); await chain; }); }