/**
 * Copyright (c) Microsoft Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { EventEmitter } from 'events';
export class WebSocketServerTransport {
    _ws;
    constructor(ws) {
        this._ws = ws;
    }
    send(message) {
        this._ws.send(message);
    }
    close(reason) {
        this._ws.close(reason?.code, reason?.reason);
    }
    on(event, handler) {
        this._ws.on(event, handler);
    }
    isClosed() {
        return this._ws.readyState === this._ws.CLOSING || this._ws.readyState === this._ws.CLOSED;
    }
}
export class SocketServerTransport extends EventEmitter {
    _socket;
    _closed = false;
    _pendingBuffers = [];
    constructor(socket) {
        super();
        this._socket = socket;
        socket.on('data', (buffer) => this._dispatch(buffer));
        socket.on('close', () => {
            this._closed = true;
            super.emit('close');
        });
        socket.on('error', (error) => {
            super.emit('error', error);
        });
    }
    send(message) {
        if (this._closed)
            return;
        this._socket.write(message);
        this._socket.write('\0');
    }
    close(reason) {
        if (this._closed)
            return;
        this._closed = true;
        this._socket.end();
    }
    isClosed() {
        return this._closed;
    }
    _dispatch(buffer) {
        let end = buffer.indexOf('\0');
        if (end === -1) {
            this._pendingBuffers.push(buffer);
            return;
        }
        this._pendingBuffers.push(buffer.slice(0, end));
        const message = Buffer.concat(this._pendingBuffers).toString();
        super.emit('message', message);
        let start = end + 1;
        end = buffer.indexOf('\0', start);
        while (end !== -1) {
            super.emit('message', buffer.toString(undefined, start, end));
            start = end + 1;
            end = buffer.indexOf('\0', start);
        }
        this._pendingBuffers = [buffer.slice(start)];
    }
}
//# sourceMappingURL=serverTransport.js.map