UNPKG

jaysonic

Version:

A feature rich JSON-RPC 1.0/2.0 compliant client and server library

183 lines (135 loc) 9.25 kB
"use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var WebSocket = require("ws"); var JsonRpcServerFactory = require("."); var WSServerProtocol = require("./protocol/ws"); /** * Creates and instance of WsServerFactory * @extends JsonRpcServerFactory * @requires ws */ var WsServerFactory = /*#__PURE__*/function (_JsonRpcServerFactory) { _inherits(WsServerFactory, _JsonRpcServerFactory); var _super = _createSuper(WsServerFactory); function WsServerFactory(options) { var _this; _classCallCheck(this, WsServerFactory); _this = _super.call(this, options); var defaults = { path: null, // all the ws options on the github page perMessageDeflate: { zlibDeflateOptions: { // See zlib defaults. chunkSize: 1024, memLevel: 7, level: 3 }, zlibInflateOptions: { chunkSize: 10 * 1024 } } }; _this.options = _objectSpread(_objectSpread({}, defaults), _this.options || {}); _this.protocol = WSServerProtocol; return _this; } /** @inheritdoc */ _createClass(WsServerFactory, [{ key: "setSever", value: function setSever() { this.server = new WebSocket.Server(this.options); } /** @inheritdoc */ }, { key: "listen", value: function listen() { var _this2 = this; return new Promise(function (resolve, reject) { if (_this2.listening) { // not having this caused MaxEventListeners error return reject(Error("server already listening")); } var _this2$options = _this2.options, host = _this2$options.host, port = _this2$options.port, path = _this2$options.path; _this2.setSever(); _this2._setupListeners(reject); _this2.server.on("listening", function () { _this2.listening = true; _this2.buildProtocol(); resolve({ host: host, port: port, path: path }); }); }); } /** @inheritdoc */ }, { key: "buildProtocol", value: function buildProtocol() { var _this3 = this; this.server.on("connection", function (client) { var pcol = new _this3.protocol(_this3, client, _this3.options.version, _this3.options.delimiter); pcol.clientConnected(); _this3.clients.push(pcol); _this3.clientConnected(pcol); _this3.clientConnected(pcol); client.on("close", function () { _this3.clientDisconnected(pcol); }); }); } /** @inheritdoc */ }, { key: "_removeClients", value: function _removeClients() { var _iterator = _createForOfIteratorHelper(this.clients), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var pcol = _step.value; pcol.client.close(); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } this.clients = []; } /** * Send notification to client * * @param {class} client Client instance * @param {string} response Stringified JSON-RPC message to sent to client * @throws Will throw an error if client is not defined */ }, { key: "sendNotification", value: function sendNotification(client, response) { return client.send(response); } }]); return WsServerFactory; }(JsonRpcServerFactory); module.exports = WsServerFactory;