botframework-streaming
Version:
Streaming library for the Microsoft Bot Framework
158 lines • 6.47 kB
JavaScript
;
/**
* @module botframework-streaming
*/
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NodeWebSocket = void 0;
const crypto = require("crypto");
const http_1 = require("http");
const WebSocket = require("ws");
const NONCE_LENGTH = 16;
/**
* An implementation of [ISocket](xref:botframework-streaming.ISocket) to use with a [NodeWebSocketFactory](xref:botframework-streaming.NodeWebSocketFactory) to create a WebSocket server.
*/
class NodeWebSocket {
/**
* Creates a new [NodeWebSocket](xref:botframework-streaming.NodeWebSocket) instance.
*
* @param wsSocket The `ws` WebSocket instance to build this connection on.
*/
constructor(wsSocket) {
this.wsSocket = wsSocket;
}
/**
* Create and set a `ws` WebSocket with an HTTP Request, Socket and Buffer.
*
* @param req An HTTP Request matching the [INodeIncomingMessage](xref:botframework-streaming.INodeIncomingMessage) interface.
* @param socket A Socket [INodeSocket](xref:botframework-streaming.INodeSocket) interface.
* @param head A Buffer [INodeBuffer](xref:botframework-streaming.INodeBuffer) interface.
* @returns A Promise that resolves after the WebSocket upgrade has been handled, otherwise rejects with a thrown error.
*/
create(req, socket, head) {
return __awaiter(this, void 0, void 0, function* () {
this.wsServer = new WebSocket.Server({ noServer: true });
return new Promise((resolve, reject) => {
try {
this.wsServer.handleUpgrade(req, socket, head, (websocket) => {
this.wsSocket = websocket;
resolve();
});
}
catch (err) {
reject(err);
}
});
});
}
/**
* Indicates if the 'ws' WebSocket is currently connected and ready to send messages.
*
* @returns `true` if the underlying websocket is ready and availble to send messages, otherwise `false`.
*/
get isConnected() {
return this.wsSocket && this.wsSocket.readyState === WebSocket.OPEN;
}
/**
* Writes a buffer to the socket and sends it.
*
* @param buffer The buffer of data to send across the connection.
*/
write(buffer) {
this.wsSocket.send(buffer);
}
/**
* Connects to the supporting socket using WebSocket protocol.
*
* @param serverAddress The address the server is listening on.
* @param port The port the server is listening on, defaults to 8082.
* @returns A Promise that resolves when the websocket connection is closed, or rejects on an error.
*/
connect(serverAddress, port = 8082) {
return __awaiter(this, void 0, void 0, function* () {
this.wsServer = new WebSocket.Server({ noServer: true });
// Key generation per https://tools.ietf.org/html/rfc6455#section-1.3 (pg. 7)
const wskey = crypto.randomBytes(NONCE_LENGTH).toString('base64');
const options = {
port: port,
hostname: serverAddress,
headers: {
connection: 'upgrade',
'Sec-WebSocket-Key': wskey,
'Sec-WebSocket-Version': '13',
},
};
const req = http_1.request(options);
req.end();
req.on('upgrade', (res, socket, head) => {
// @types/ws does not contain the signature for completeUpgrade
// https://github.com/websockets/ws/blob/0a612364e69fc07624b8010c6873f7766743a8e3/lib/websocket-server.js#L269
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this.wsServer.completeUpgrade(wskey, undefined, res, socket, head, (websocket) => {
this.wsSocket = websocket;
});
});
return new Promise((resolve, reject) => {
req.on('close', resolve);
req.on('error', reject);
});
});
}
/**
* Set the handler for `'data'` and `'message'` events received on the socket.
*
* @param handler The callback to handle the "message" event.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
setOnMessageHandler(handler) {
this.wsSocket.on('data', handler);
this.wsSocket.on('message', handler);
}
/**
* Close the socket.
*
* @remarks
* Optionally pass in a status code and string explaining why the connection is closing.
* @param code Optional status code to explain why the connection has closed.
* @param data Optional additional data to explain why the connection has closed.
*/
close(code, data) {
this.wsSocket.close(code, data);
}
/**
* Set the callback to call when encountering socket closures.
*
* @param handler The callback to handle the "close" event.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
setOnCloseHandler(handler) {
this.wsSocket.on('close', handler);
}
/**
* Set the callback to call when encountering errors.
*
* @param handler The callback to handle the "error" event.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
setOnErrorHandler(handler) {
this.wsSocket.on('error', (error) => {
if (error) {
handler(error);
}
});
}
}
exports.NodeWebSocket = NodeWebSocket;
//# sourceMappingURL=nodeWebSocket.js.map