"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MCPWebSocketTransport = void 0;
const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
const ws_1 = require("ws");
class MCPWebSocketTransport {
    _socket;
    onmessage;
    onerror;
    onclose;
    constructor(socket) {
        this._socket = socket;
    }
    async start() {
        this._socket.on("message", (data) => {
            try {
                let parsed;
                if (typeof data === "string") {
                    parsed = JSON.parse(data);
                }
                else if (Buffer.isBuffer(data)) {
                    parsed = JSON.parse(data.toString("utf-8"));
                }
                else {
                    parsed = JSON.parse(data.toString());
                }
                console.log("MCPW Message received", JSON.stringify(parsed));
                const message = types_js_1.JSONRPCMessageSchema.parse(parsed);
                setImmediate(() => {
                    this.onmessage?.(message);
                });
            }
            catch (error) {
                this.onerror?.(error);
            }
        });
        this._socket.on("close", () => {
            this.onclose?.();
        });
        this._socket.on("error", (err) => {
            this.onerror?.(err);
        });
    }
    async send(message) {
        return new Promise((resolve, reject) => {
            const json = JSON.stringify(message);
            console.log("MCPWs sending", json);
            if (this._socket.readyState !== ws_1.WebSocket.OPEN) {
                return reject(new Error(`WebSocket is not open: readyState ${this._socket.readyState}`));
            }
            try {
                this._socket.send(json, (error) => {
                    if (error) {
                        this.onerror?.(error);
                        return reject(error);
                    }
                    resolve();
                });
            }
            catch (error) {
                this.onerror?.(error);
                reject(error);
            }
        });
    }
    async close() {
        this._socket.close();
    }
}
exports.MCPWebSocketTransport = MCPWebSocketTransport;
//# sourceMappingURL=McpWebsocketTransport.js.map