"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MAX_SOCKET_PAYLOAD_BYTES = void 0;
exports.connectWebSocket = connectWebSocket;
const isomorphic_ws_1 = __importDefault(require("isomorphic-ws"));
/**
 * Maximum websocket frame size, in bytes, for sockets on both ends of the
 * editor <-> dev server connection. 100 MiB matches the `ws` library default;
 * it is set explicitly so the limit is a deliberate choice rather than an
 * inherited default. Inbound frames over the limit make `ws` close that
 * single socket with 1009 (Message Too Big).
 *
 * Only applies where `ws` is the implementation (Node). Browsers ignore the
 * option and don't enforce a receive limit.
 */
exports.MAX_SOCKET_PAYLOAD_BYTES = 100 * 1024 * 1024;
/**
 * If the connection is not established within the timeout, the promise will be rejected.
 * This can happen with bad network conditions, but is very rare.
 */
function connectWebSocket(wsUrl, protocol, timeout = 30_000) {
    return new Promise((resolve, reject) => {
        const ws = new isomorphic_ws_1.default(wsUrl, protocol, { maxPayload: exports.MAX_SOCKET_PAYLOAD_BYTES });
        const timeoutId = setTimeout(() => {
            reject(new Error('[internal] WebSocket connection timeout'));
        }, timeout);
        ws.addEventListener('open', () => {
            clearTimeout(timeoutId);
            // Resolve the promise with the WebSocket instance when the connection is open
            resolve(ws);
        });
        ws.addEventListener('error', (event) => {
            clearTimeout(timeoutId);
            // Wrap browser WebSocket errors with [internal] tag so they can be filtered
            // from Clark's context (raw browser errors don't have useful stack traces)
            const message = 'message' in event && typeof event.message === 'string' ? event.message : 'WebSocket connection failed';
            reject(new Error(`[internal] ${message}`));
        });
    });
}
//# sourceMappingURL=util.js.map