import type { ListEvent } from '@superlist/shared' type ListEventListener = (event: ListEvent) => void /** * In-process pub/sub used to fan out list changes to the SSE streams of every * member currently viewing a list. * * It only reaches the API instance that published the event, which is enough * for a single-instance deployment. Scaling horizontally would need a shared * bus (e.g. Postgres `LISTEN`/`NOTIFY`); this interface would stay the same. */ export class ListEvents { private readonly listeners = new Map>() /** Subscribes to one list's events; returns the unsubscribe function. */ subscribe(listId: string, listener: ListEventListener): () => void { const listeners = this.listeners.get(listId) ?? new Set() listeners.add(listener) this.listeners.set(listId, listeners) return () => { listeners.delete(listener) if (listeners.size === 0) this.listeners.delete(listId) } } /** Delivers the event to every subscriber of its list. */ publish(event: ListEvent): void { const listeners = this.listeners.get(event.listId) if (!listeners) return for (const listener of listeners) listener(event) } } /** Process-wide bus shared by the use cases and the SSE routes. */ export const listEvents = new ListEvents()