import type { ListEvent } from '@superlist/shared' import { Hono } from 'hono' import { streamSSE } from 'hono/streaming' import { requireSession } from '@/lib/auth-session' import { listEvents } from '@/lib/events' import { requireListMembership } from '@/lib/list-access' import { validate } from '@/lib/validate' import { ListParamsSchema } from '@/modules/lists/schema' import type { AppEnv } from '@/types' /** Maximum silence between frames; a comment heartbeat is sent in between. */ const HEARTBEAT_MS = 20_000 /** * GET /lists/:listId/events — Server-Sent Events stream with the changes * happening on a list (items, members, invitations). Members only. * * Events are buffered and written as they arrive; while the list is quiet a * comment heartbeat keeps the connection open through Bun's idle timeout and * any proxy in between. */ export const listEventsRoute = new Hono().get( '/', requireSession, validate.param(ListParamsSchema), requireListMembership, (c) => { const { listId } = c.req.valid('param') return streamSSE(c, async (stream) => { const pending: ListEvent[] = [] // Resolves a pending wait as soon as an event is buffered, so nothing has // to wait for the heartbeat interval. let wake: (() => void) | undefined const unsubscribe = listEvents.subscribe(listId, (event) => { pending.push(event) wake?.() }) stream.onAbort(() => unsubscribe()) const waitForEvent = () => new Promise((resolve) => { wake = resolve }) await stream.writeSSE({ event: 'ready', data: JSON.stringify({ listId }) }) while (!stream.aborted) { const event = pending.shift() if (event) { await stream.writeSSE({ event: event.type, data: JSON.stringify(event) }) continue } let timer: ReturnType | undefined await Promise.race([ waitForEvent(), new Promise((resolve) => { timer = setTimeout(resolve, HEARTBEAT_MS) }), ]) clearTimeout(timer) wake = undefined if (pending.length === 0 && !stream.aborted) { await stream.write(': ping\n\n') } } }) }, )