const clientsByUser = new Map(); export function addSseClient(userId, res) { const client = { userId, res, write: (payload) => { try { res.write(`data: ${JSON.stringify(payload)}\n\n`); } catch { } }, }; if (!clientsByUser.has(userId)) clientsByUser.set(userId, new Set()); clientsByUser.get(userId).add(client); // Initial hello client.write({ type: 'hello', at: Date.now() }); // Heartbeat to keep connections alive through proxies const heartbeat = setInterval(() => { try { res.write(`: ping\n\n`); } catch { } }, 25000); // Return cleanup return () => { clearInterval(heartbeat); try { res.end(); } catch { } clientsByUser.get(userId)?.delete(client); if (clientsByUser.get(userId)?.size === 0) clientsByUser.delete(userId); }; } export function sendEvent(userId, event) { const set = clientsByUser.get(userId); if (!set || set.size === 0) return; for (const client of set) client.write(event); } export function sendToBoth(userA, userB, event) { sendEvent(userA, event); if (userB !== userA) sendEvent(userB, event); }