// express-router — Express integration for @kyneta/sse-transport. // // Creates Express routes that integrate with SseServerTransport: // - GET endpoint for clients to open an SSE stream. Its first event carries // the connection's key. // - POST endpoint for clients to send binary wire frames, naming their // connection by that key in the `X-Kyneta-Connection` header. // // Design: Imperative Shell — delegates POST body parsing to // SseConnection.handlePostBody() and message delivery to SseConnection.receive(). import { maxBinaryFrameSize } from "@kyneta/transport" import type { Request, Response, Router } from "express" import express from "express" import { CONNECTION_KEY_EVENT, CONNECTION_KEY_HEADER, } from "./connection-key.js" import type { SseServerTransport } from "./server-transport.js" // --------------------------------------------------------------------------- // Options // --------------------------------------------------------------------------- export interface SseExpressRouterOptions { /** * Path for the sync endpoint where clients POST messages. * @default "/sync" */ syncPath?: string /** * Path for the events endpoint where clients connect via SSE. * @default "/events" */ eventsPath?: string /** * Interval in milliseconds for sending heartbeat comments to keep connections alive. * @default 30000 (30 seconds) */ heartbeatInterval?: number } // --------------------------------------------------------------------------- // createSseExpressRouter // --------------------------------------------------------------------------- /** * Create an Express router for SSE server endpoints. * * This factory function creates Express routes that integrate with * SseServerTransport. It handles: * - POST endpoint for clients to send messages to the server * - GET endpoint for clients to receive messages via SSE * - Heartbeat mechanism to detect stale connections * * @param transport The SseServerTransport instance * @param options Configuration options for the router * @returns An Express Router ready to be mounted * * @example * ```typescript * import { SseServerTransport } from "@kyneta/sse-transport/server" * import { createSseExpressRouter } from "@kyneta/sse-transport/express" * * const serverTransport = new SseServerTransport() * app.use("/sse", createSseExpressRouter(serverTransport)) * ``` */ export function createSseExpressRouter( transport: SseServerTransport, options: SseExpressRouterOptions = {}, ): Router { const { syncPath = "/sync", eventsPath = "/events", heartbeatInterval = 30000, } = options const router = express.Router() // --------------------------------------------------------------------------- // POST /sync — clients send binary wire frames TO the server // --------------------------------------------------------------------------- router.post( syncPath, // One POST carries one wire frame, so its body is capped by the largest // frame a message within the transport's cap can need. express.raw({ type: "application/octet-stream", limit: maxBinaryFrameSize(transport.maxMessageSize), }), (req: Request, res: Response) => { const key = req.get(CONNECTION_KEY_HEADER) const connection = key === undefined ? undefined : transport.connectionFor(key) if (!connection) { res.status(404).json({ error: "Unknown connection" }) return } // Ensure we have binary data if (!(req.body instanceof Uint8Array)) { res.status(400).json({ error: "Expected binary body" }) return } // Connection owns the full inbound pipeline: // Uint8Array → Pipeline.receive() → ChannelMsg const body = req.body as Uint8Array const result = connection.handlePostBody(body) // Imperative shell: execute side effects based on result if (result.type === "messages") { for (const msg of result.messages) { connection.receive(msg) } } // "pending" type means fragment received, waiting for more — no action needed // "error" type is logged implicitly by the response status res.status(result.response.status).json(result.response.body) }, ) // --------------------------------------------------------------------------- // GET /events — clients connect and listen for events FROM the server // --------------------------------------------------------------------------- router.get(eventsPath, (req: Request, res: Response) => { // Register before writing headers: a transport that is not accepting // (stopping or stopped) refuses, and the client backs off on the 503. // Every stream gets a fresh key, so it never replaces another. const connection = transport.registerConnection() if (!connection) { res.status(503).end("transport not accepting connections") return } // Set headers for SSE res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive", }) res.flushHeaders() // `flush` is added by compression middleware and some environments. const flushable: Response & { flush?: () => void } = res const flush = () => flushable.flush?.() // The connection's send() encodes and fragments; the send function only // wraps each pre-encoded text frame in SSE data syntax. connection.setSendFunction((textFrame: string) => { res.write(`data: ${textFrame}\n\n`) flush() }) // Heartbeat comments (ignored by EventSource) detect a dead connection. const heartbeat = setInterval(() => { try { res.write(": heartbeat\n\n") } catch (_err) { clearInterval(heartbeat) transport.unregisterConnection(connection) } }, heartbeatInterval) connection.setDisconnectHandler(() => { clearInterval(heartbeat) res.end() }) req.on("close", () => { clearInterval(heartbeat) transport.unregisterConnection(connection) }) // The key opens the client's gate, so it goes last, once everything it // may trigger is in place. res.write(`event: ${CONNECTION_KEY_EVENT}\ndata: ${connection.key}\n\n`) flush() }) return router }