"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transport = void 0;
const buffer_1 = require("buffer");
exports.transport = {
    isReady(socket) {
        return !socket.pending;
    },
    onReady(socket, callback) {
        socket.on('ready', callback);
        return () => socket.off('ready', callback);
    },
    onMessage(socket, callback) {
        const handler = (data) => splitMessages(data).forEach(data => callback(data));
        socket.on('data', handler);
        return () => socket.off('data', handler);
    },
    onClose(socket, callback) {
        socket.on('close', callback);
        return () => socket.off('close', callback);
    },
    onError(socket, callback) {
        socket.on('error', callback);
        return () => socket.off('error', callback);
    },
    send(socket, data) {
        socket.write(data);
    },
    serialize(data) {
        const header = buffer_1.Buffer.allocUnsafe(4);
        const buffer = buffer_1.Buffer.from(JSON.stringify(data));
        header.writeUint32BE(buffer.byteLength);
        const format = buffer_1.Buffer.concat([header, buffer]);
        return format;
    },
    deserialize(data) {
        return JSON.parse(buffer_1.Buffer.from(data).toString());
    },
};
function splitMessages(data) {
    const buffer = buffer_1.Buffer.from(data);
    const messages = [];
    let offset = 0;
    while (offset < buffer.length) {
        const messageLength = buffer.readUInt32BE(offset);
        offset += 4;
        messages.push(buffer.slice(offset, offset + messageLength));
        offset += messageLength;
    }
    return messages;
}
exports.default = exports.transport;
