export class SSEManager {
    constructor(heartbeatMs = 30000) {
        this.heartbeatMs = heartbeatMs;
        this.connections = new Set();
        this.heartbeatInterval = null;
    }
    /** Add a new SSE connection */
    addConnection(res) {
        res.writeHead(200, {
            'Content-Type': 'text/event-stream',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Access-Control-Allow-Origin': '*',
        });
        // Send initial connected event
        this.send(res, 'heartbeat', { timestamp: new Date().toISOString(), connected: true });
        this.connections.add(res);
        res.on('close', () => this.connections.delete(res));
        // Start heartbeat if this is the first connection
        if (!this.heartbeatInterval && this.connections.size === 1) {
            this.startHeartbeat();
        }
    }
    /** Broadcast event to all connected clients */
    broadcast(type, data) {
        const message = this.formatMessage(type, data);
        for (const conn of this.connections) {
            if (conn.destroyed) {
                this.connections.delete(conn);
                continue;
            }
            conn.write(message);
        }
    }
    /** Send event to a single connection */
    send(res, type, data) {
        if (!res.destroyed) {
            res.write(this.formatMessage(type, data));
        }
    }
    /** Format SSE message */
    formatMessage(type, data) {
        return `event: ${type}\ndata: ${JSON.stringify(data)}\n\n`;
    }
    /** Start heartbeat timer */
    startHeartbeat() {
        this.heartbeatInterval = setInterval(() => {
            if (this.connections.size === 0) {
                this.stopHeartbeat();
                return;
            }
            this.broadcast('heartbeat', { timestamp: new Date().toISOString() });
        }, this.heartbeatMs);
    }
    /** Stop heartbeat timer */
    stopHeartbeat() {
        if (this.heartbeatInterval) {
            clearInterval(this.heartbeatInterval);
            this.heartbeatInterval = null;
        }
    }
    /** Get number of active connections */
    get connectionCount() {
        return this.connections.size;
    }
    /** Close all connections and stop heartbeat */
    closeAll() {
        this.stopHeartbeat();
        for (const conn of this.connections) {
            if (!conn.destroyed) {
                conn.end();
            }
        }
        this.connections.clear();
    }
}
//# sourceMappingURL=sse-manager.js.map