// Chat presence + real-time delivery. A logged-in user opens a WebSocket and sends // `chat-hello`; signaling.js registers the socket here. Messages are persisted over HTTP // (routes.js) and pushed live to the recipient's sockets via pushToUser(). const { chatClients } = require('./presence'); function register(userId, ws) { if (!chatClients.has(userId)) chatClients.set(userId, new Set()); chatClients.get(userId).add(ws); ws._chatUserId = userId; } function unregister(ws) { const id = ws && ws._chatUserId; if (!id) return; const set = chatClients.get(id); if (set) { set.delete(ws); if (!set.size) chatClients.delete(id); } } function isOnline(userId) { const s = chatClients.get(userId); return !!(s && s.size); } function pushToUser(userId, obj) { const s = chatClients.get(userId); if (!s) return; const data = JSON.stringify(obj); for (const ws of s) { if (ws.readyState === 1) { try { ws.send(data); } catch (_) {} } } } module.exports = { register, unregister, isOnline, pushToUser };