#!/usr/bin/env node
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
const require_server_server = require('./server.cjs');
let __modelcontextprotocol_sdk_server_sse_js = require("@modelcontextprotocol/sdk/server/sse.js");
let dotenv = require("dotenv");
dotenv = require_rolldown_runtime.__toESM(dotenv);
let express = require("express");
express = require_rolldown_runtime.__toESM(express);

//#region src/server/sse.ts
/******* Server Set Up ************/
const server = require_server_server.loadServer({ isLocal: false });
/******* Express App Set Up *******/
const app = (0, express.default)();
const env = app.get("env");
dotenv.default.config({ path: [
	`.env.${env}.local`,
	`.env.${env}`,
	".env.local",
	".env"
] });
app.use((req, res, next) => {
	res.header("Access-Control-Allow-Origin", "*");
	res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
	res.header("Access-Control-Allow-Headers", "Content-Type");
	if (req.method === "OPTIONS") {
		res.sendStatus(200);
		return;
	}
	next();
});
app.use(express.default.json());
const router = express.default.Router();
const transports = {};
const POST_ENDPOINT = "/messages";
router.post(POST_ENDPOINT, async (req, res) => {
	console.info("message request received: ", req.body);
	const sessionId = req.query.sessionId;
	if (typeof sessionId !== "string") {
		res.status(400).send({ messages: "Bad session id." });
		return;
	}
	const transport = transports[sessionId];
	if (!transport) {
		res.status(400).send({ messages: "No transport found for sessionId." });
		return;
	}
	await transport.handlePostMessage(req, res, req.body);
});
router.get("/", async (_req, res) => {
	console.info("connection request received");
	const transport = new __modelcontextprotocol_sdk_server_sse_js.SSEServerTransport(POST_ENDPOINT, res);
	console.info("new transport created with session id: ", transport.sessionId);
	transports[transport.sessionId] = transport;
	console.info(`${Object.keys(transports).length} sessions active`);
	res.on("close", () => {
		console.info("SSE connection closed");
		delete transports[transport.sessionId];
	});
	await server.connect(transport);
	await sendMessages(transport);
});
const sendMessages = async (transport) => {
	try {
		await transport.send({
			jsonrpc: "2.0",
			method: "sse/connection",
			params: { message: "Stream started" }
		});
		console.info("Stream started");
		let messageCount = 0;
		const interval = setInterval(async () => {
			messageCount++;
			const message = `Message ${messageCount} at ${(/* @__PURE__ */ new Date()).toISOString()}`;
			try {
				await transport.send({
					jsonrpc: "2.0",
					method: "sse/message",
					params: { data: message }
				});
				console.info(`Sent: ${message}`);
				if (messageCount === 2) {
					clearInterval(interval);
					await transport.send({
						jsonrpc: "2.0",
						method: "sse/complete",
						params: { message: "Stream completed" }
					});
					console.info("Stream completed");
				}
			} catch (error) {
				console.error("Error sending message:", error);
				clearInterval(interval);
			}
		}, 1e3);
	} catch (error) {
		console.error("Error in startSending:", error);
	}
};
app.use("/", router);
app.use("/health", (_req, res) => {
	res.send("OK");
});
const PORT = process.env.PORT ?? 3e3;
app.listen(PORT, () => {
	console.info(`MCP Streamable HTTP Server listening on port ${PORT}`);
});

//#endregion
//# sourceMappingURL=sse.cjs.map