const express = require('express'); const router = express.Router(); // List of connected SSE clients let clients = []; router.get('/stream', (req, res) => { res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' }); const clientId = Date.now() + '-' + Math.random().toString(36).substring(2, 7); const newClient = { id: clientId, res }; clients.push(newClient); // Send initial connection event res.write(`data: ${JSON.stringify({ type: 'connected', clientId })}\n\n`); req.on('close', () => { clients = clients.filter(c => c.id !== clientId); }); }); function broadcastEvent(eventData) { const dataString = `data: ${JSON.stringify(eventData)}\n\n`; clients.forEach(client => { try { client.res.write(dataString); } catch (e) { // client might have disconnected } }); } module.exports = { router, broadcastEvent };