├── .github ├── CODE_OF_CONDUCT.md ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md └── README.md ├── .gitignore ├── LICENSE ├── dist ├── LICENSE ├── README.md ├── browser │ ├── clusterws.js │ └── clusterws.min.js ├── index.js └── package.json ├── package.json ├── src ├── index.ts ├── modules │ ├── channels.ts │ └── parser.ts └── utils │ ├── emitter.ts │ ├── helpers.ts │ └── types.ts ├── tests └── manual │ ├── index.html │ └── main.js ├── tsbuild.json └── tslint.json /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team . The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Submitting 2 | 3 | - [ ] Bug 4 | - [ ] Question 5 | - [ ] Suggestion 6 | - [ ] Other 7 | 8 | ### Details 9 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Submitting 2 | 3 | - [ ] Bug fix 4 | - [ ] Feature 5 | - [ ] Other 6 | 7 | ### Details 8 | -------------------------------------------------------------------------------- /.github/README.md: -------------------------------------------------------------------------------- 1 |

ClusterWS JavaScript Client

2 |
Build Scalable Node.js WebSockets Applications
3 | 4 |

5 | 6 |

7 | 8 |

9 | NPM Version 10 | Maintain 11 | GitHub license 12 |

13 | 14 |

15 | Official JavaScript Client library for ClusterWS - lightweight, fast and powerful framework for building scalable WebSockets applications in Node.js. 16 |

17 | 18 |

19 |

20 | Find more about ClusterWS JavaScript Client in Wiki Documentation 21 |

22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # TODO: clean up git ignore 2 | .npm 3 | .idea/ 4 | .vscode/ 5 | 6 | old/ 7 | play.js 8 | node_modules/ 9 | package-lock.json 10 | 11 | manual-test/ 12 | 13 | # Tests 14 | coverage/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 ClusterWS 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /dist/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 ClusterWS 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /dist/README.md: -------------------------------------------------------------------------------- 1 |

ClusterWS JavaScript Client

2 |
Build Scalable Node.js WebSockets Applications
3 | 4 |

5 | 6 |

7 | 8 |

9 | NPM Version 10 | Maintain 11 | GitHub license 12 |

13 | 14 |

15 | Official JavaScript Client library for ClusterWS - lightweight, fast and powerful framework for building scalable WebSockets applications in Node.js. 16 |

17 | 18 |

19 |

20 | Find more about ClusterWS JavaScript Client in Wiki Documentation 21 |

22 | -------------------------------------------------------------------------------- /dist/browser/clusterws.js: -------------------------------------------------------------------------------- 1 | var ClusterWS = (function () { 2 | 'use strict'; 3 | 4 | function isFunction(fn) { 5 | return typeof fn === 'function'; 6 | } 7 | 8 | var EventEmitter = (function () { 9 | function EventEmitter() { 10 | this.events = {}; 11 | } 12 | EventEmitter.prototype.on = function (event, listener) { 13 | if (!isFunction(listener)) { 14 | throw new Error('Listener must be a function'); 15 | } 16 | this.events[event] = listener; 17 | }; 18 | EventEmitter.prototype.emit = function (event) { 19 | var args = []; 20 | for (var _i = 1; _i < arguments.length; _i++) { 21 | args[_i - 1] = arguments[_i]; 22 | } 23 | var listener = this.events[event]; 24 | listener && listener.apply(void 0, args); 25 | }; 26 | EventEmitter.prototype.exist = function (event) { 27 | return !!this.events[event]; 28 | }; 29 | EventEmitter.prototype.off = function (event) { 30 | delete this.events[event]; 31 | }; 32 | EventEmitter.prototype.removeEvents = function () { 33 | this.events = {}; 34 | }; 35 | return EventEmitter; 36 | }()); 37 | 38 | function decode(socket, data) { 39 | var msgType = data[0], param = data[1], message = data[2]; 40 | if (msgType === 'e') { 41 | return socket.emitter.emit(param, message); 42 | } 43 | if (msgType === 'p') { 44 | var channels = Object.keys(message); 45 | for (var i = 0, len = channels.length; i < len; i++) { 46 | var channel = channels[i]; 47 | var messages = message[channel]; 48 | for (var j = 0, msgLen = messages.length; j < msgLen; j++) { 49 | socket.channels.channelNewMessage(channel, messages[j]); 50 | } 51 | } 52 | } 53 | if (msgType === 's') { 54 | if (param === 's') { 55 | var channels = Object.keys(message); 56 | for (var i = 0, len = channels.length; i < len; i++) { 57 | var channel = channels[i]; 58 | socket.channels.channelSetStatus(channel, message[channel]); 59 | } 60 | } 61 | if (param === 'c') { 62 | socket.autoPing = message.autoPing; 63 | socket.pingInterval = message.pingInterval; 64 | socket.resetPing(); 65 | } 66 | } 67 | } 68 | function encode(event, data, eventType) { 69 | var message = { 70 | emit: ['e', event, data], 71 | publish: ['p', event, data], 72 | system: { 73 | subscribe: ['s', 's', data], 74 | unsubscribe: ['s', 'u', data], 75 | configuration: ['s', 'c', data] 76 | } 77 | }; 78 | if (eventType === 'system') { 79 | return JSON.stringify(message[eventType][event]); 80 | } 81 | return JSON.stringify(message[eventType]); 82 | } 83 | 84 | var Channel = (function () { 85 | function Channel(client, name) { 86 | this.client = client; 87 | this.name = name; 88 | this.READY = 1; 89 | this.status = 0; 90 | this.events = {}; 91 | this.watchers = []; 92 | if (this.client.readyState === this.client.OPEN) { 93 | this.client.send('subscribe', [this.name], 'system'); 94 | } 95 | } 96 | Channel.prototype.on = function (event, listener) { 97 | this.events[event] = listener; 98 | }; 99 | Channel.prototype.publish = function (message) { 100 | if (this.status === this.READY) { 101 | this.client.send(this.name, message, 'publish'); 102 | } 103 | }; 104 | Channel.prototype.setWatcher = function (listener) { 105 | this.watchers.push(listener); 106 | }; 107 | Channel.prototype.removeWatcher = function (listener) { 108 | for (var i = 0, len = this.watchers.length; i < len; i++) { 109 | if (this.watchers[i] === listener) { 110 | this.watchers.splice(i, 1); 111 | break; 112 | } 113 | } 114 | }; 115 | Channel.prototype.unsubscribe = function () { 116 | this.status = 0; 117 | this.emit('unsubscribed'); 118 | this.client.channels.removeChannel(this.name); 119 | this.client.send('unsubscribe', this.name, 'system'); 120 | }; 121 | Channel.prototype.emit = function (event) { 122 | var listener = this.events[event]; 123 | listener && listener(); 124 | }; 125 | Channel.prototype.broadcast = function (message) { 126 | for (var i = 0, len = this.watchers.length; i < len; i++) { 127 | this.watchers[i](message); 128 | } 129 | }; 130 | return Channel; 131 | }()); 132 | var Channels = (function () { 133 | function Channels(client) { 134 | this.client = client; 135 | this.channels = {}; 136 | } 137 | Channels.prototype.subscribe = function (channelName) { 138 | if (!this.channels[channelName]) { 139 | var channel = new Channel(this.client, channelName); 140 | this.channels[channelName] = channel; 141 | return channel; 142 | } 143 | }; 144 | Channels.prototype.resubscribe = function () { 145 | var allChannels = Object.keys(this.channels); 146 | if (allChannels.length) { 147 | this.client.send('subscribe', allChannels, 'system'); 148 | } 149 | }; 150 | Channels.prototype.getChannelByName = function (channelName) { 151 | return this.channels[channelName] || null; 152 | }; 153 | Channels.prototype.channelNewMessage = function (channelName, message) { 154 | var channel = this.channels[channelName]; 155 | if (channel && channel.status === channel.READY) { 156 | channel.broadcast(message); 157 | } 158 | }; 159 | Channels.prototype.channelSetStatus = function (channelName, pass) { 160 | var channel = this.channels[channelName]; 161 | if (channel) { 162 | if (!pass) { 163 | channel.emit('canceled'); 164 | return this.removeChannel(channelName); 165 | } 166 | channel.status = 1; 167 | channel.emit('subscribed'); 168 | } 169 | }; 170 | Channels.prototype.removeChannel = function (channelName) { 171 | delete this.channels[channelName]; 172 | }; 173 | Channels.prototype.removeAllChannels = function () { 174 | this.channels = {}; 175 | }; 176 | return Channels; 177 | }()); 178 | 179 | var Socket = window.MozWebSocket || window.WebSocket; 180 | var PONG = new Uint8Array(['A'.charCodeAt(0)]).buffer; 181 | var ClusterWS = (function () { 182 | function ClusterWS(configurations) { 183 | this.reconnectAttempts = 0; 184 | this.options = { 185 | url: configurations.url, 186 | autoConnect: configurations.autoConnect !== false, 187 | autoReconnect: configurations.autoReconnect || false, 188 | autoResubscribe: configurations.autoResubscribe !== false, 189 | autoReconnectOptions: { 190 | attempts: configurations.autoReconnectOptions ? 191 | configurations.autoReconnectOptions.attempts || 0 : 0, 192 | minInterval: configurations.autoReconnectOptions ? 193 | configurations.autoReconnectOptions.minInterval || 500 : 500, 194 | maxInterval: configurations.autoReconnectOptions ? 195 | configurations.autoReconnectOptions.maxInterval || 2000 : 2000 196 | } 197 | }; 198 | if (!this.options.url) { 199 | throw new Error('url must be provided'); 200 | } 201 | this.emitter = new EventEmitter(); 202 | this.channels = new Channels(this); 203 | this.reconnectAttempts = this.options.autoReconnectOptions.attempts; 204 | if (this.options.autoConnect) { 205 | this.connect(); 206 | } 207 | } 208 | Object.defineProperty(ClusterWS.prototype, "OPEN", { 209 | get: function () { 210 | return this.socket.OPEN; 211 | }, 212 | enumerable: true, 213 | configurable: true 214 | }); 215 | Object.defineProperty(ClusterWS.prototype, "CLOSED", { 216 | get: function () { 217 | return this.socket.CLOSED; 218 | }, 219 | enumerable: true, 220 | configurable: true 221 | }); 222 | Object.defineProperty(ClusterWS.prototype, "readyState", { 223 | get: function () { 224 | return this.socket ? this.socket.readyState : 0; 225 | }, 226 | enumerable: true, 227 | configurable: true 228 | }); 229 | Object.defineProperty(ClusterWS.prototype, "binaryType", { 230 | get: function () { 231 | return this.socket.binaryType; 232 | }, 233 | set: function (binaryType) { 234 | this.socket.binaryType = binaryType; 235 | }, 236 | enumerable: true, 237 | configurable: true 238 | }); 239 | ClusterWS.prototype.connect = function () { 240 | var _this = this; 241 | if (this.isCreated) { 242 | throw new Error('Connect event has been called multiple times'); 243 | } 244 | this.isCreated = true; 245 | this.socket = new Socket(this.options.url); 246 | this.socket.onopen = function () { 247 | _this.reconnectAttempts = _this.options.autoReconnectOptions.attempts; 248 | _this.options.autoResubscribe ? 249 | _this.channels.resubscribe() : 250 | _this.channels.removeAllChannels(); 251 | _this.emitter.emit('open'); 252 | }; 253 | this.socket.onclose = function (codeEvent, reason) { 254 | clearTimeout(_this.pingTimeout); 255 | _this.isCreated = false; 256 | var closeCode = typeof codeEvent === 'number' ? codeEvent : codeEvent.code; 257 | var closeReason = typeof codeEvent === 'number' ? reason : codeEvent.reason; 258 | _this.emitter.emit('close', closeCode, closeReason); 259 | if (_this.options.autoReconnect && closeCode !== 1000) { 260 | if (_this.readyState === _this.CLOSED) { 261 | if (_this.options.autoReconnectOptions.attempts === 0 || _this.reconnectAttempts > 0) { 262 | _this.reconnectAttempts--; 263 | return setTimeout(function () { 264 | _this.connect(); 265 | }, Math.floor(Math.random() * (_this.options.autoReconnectOptions.maxInterval - _this.options.autoReconnectOptions.minInterval + 1))); 266 | } 267 | } 268 | } 269 | _this.emitter.removeEvents(); 270 | _this.channels.removeAllChannels(); 271 | }; 272 | this.socket.onmessage = function (message) { 273 | var messageToProcess = message; 274 | if (message.data) { 275 | messageToProcess = message.data; 276 | } 277 | _this.parsePing(messageToProcess, function () { 278 | if (_this.emitter.exist('message')) { 279 | return _this.emitter.emit('message', messageToProcess); 280 | } 281 | _this.processMessage(messageToProcess); 282 | }); 283 | }; 284 | this.socket.onerror = function (error) { 285 | if (_this.emitter.exist('error')) { 286 | return _this.emitter.emit('error', error); 287 | } 288 | _this.close(); 289 | throw new Error('Connect event has been called multiple times'); 290 | }; 291 | }; 292 | ClusterWS.prototype.on = function (event, listener) { 293 | this.emitter.on(event, listener); 294 | }; 295 | ClusterWS.prototype.send = function (event, message, eventType) { 296 | if (eventType === void 0) { eventType = 'emit'; } 297 | if (message === undefined) { 298 | return this.socket.send(event); 299 | } 300 | return this.socket.send(encode(event, message, eventType)); 301 | }; 302 | ClusterWS.prototype.close = function (code, reason) { 303 | this.socket.close(code || 1000, reason); 304 | }; 305 | ClusterWS.prototype.subscribe = function (channelName) { 306 | return this.channels.subscribe(channelName); 307 | }; 308 | ClusterWS.prototype.getChannelByName = function (channelName) { 309 | return this.channels.getChannelByName(channelName); 310 | }; 311 | ClusterWS.prototype.processMessage = function (message) { 312 | try { 313 | if (message instanceof Array) { 314 | return decode(this, message); 315 | } 316 | if (typeof message !== 'string') { 317 | var err = new Error('processMessage accepts only string or array types'); 318 | if (this.emitter.exist('error')) { 319 | return this.emitter.emit('error', err); 320 | } 321 | throw err; 322 | } 323 | if (message[0] !== '[') { 324 | var err = new Error('processMessage received incorrect message'); 325 | if (this.emitter.exist('error')) { 326 | return this.emitter.emit('error', err); 327 | } 328 | throw err; 329 | } 330 | return decode(this, JSON.parse(message)); 331 | } 332 | catch (err) { 333 | if (this.emitter.exist('error')) { 334 | return this.emitter.emit('error', err); 335 | } 336 | this.close(); 337 | throw err; 338 | } 339 | }; 340 | ClusterWS.prototype.parsePing = function (message, next) { 341 | var _this = this; 342 | if (message.size === 1 || message.byteLength === 1) { 343 | var parser_1 = function (possiblePingMessage) { 344 | if (new Uint8Array(possiblePingMessage)[0] === 57) { 345 | _this.resetPing(); 346 | _this.socket.send(PONG); 347 | return _this.emitter.emit('ping'); 348 | } 349 | return next(); 350 | }; 351 | if (!(message instanceof ArrayBuffer)) { 352 | var reader = new FileReader(); 353 | reader.onload = function (event) { return parser_1(event.srcElement.result); }; 354 | return reader.readAsArrayBuffer(message); 355 | } 356 | return parser_1(message); 357 | } 358 | return next(); 359 | }; 360 | ClusterWS.prototype.resetPing = function () { 361 | var _this = this; 362 | clearTimeout(this.pingTimeout); 363 | if (this.pingInterval && this.autoPing) { 364 | this.pingTimeout = setTimeout(function () { 365 | _this.close(4001, "No ping received in " + (_this.pingInterval + 500) + "ms"); 366 | }, this.pingInterval + 500); 367 | } 368 | }; 369 | return ClusterWS; 370 | }()); 371 | 372 | return ClusterWS; 373 | 374 | }()); 375 | -------------------------------------------------------------------------------- /dist/browser/clusterws.min.js: -------------------------------------------------------------------------------- 1 | var ClusterWS=function(){"use strict";var t=function(){function t(){this.events={}}return t.prototype.on=function(t,e){if("function"!=typeof e)throw new Error("Listener must be a function");this.events[t]=e},t.prototype.emit=function(t){for(var e=[],n=1;n0))return t.reconnectAttempts--,setTimeout(function(){t.connect()},Math.floor(Math.random()*(t.options.autoReconnectOptions.maxInterval-t.options.autoReconnectOptions.minInterval+1)));t.emitter.removeEvents(),t.channels.removeAllChannels()},this.socket.onmessage=function(e){var n=e;e.data&&(n=e.data),t.parsePing(n,function(){if(t.emitter.exist("message"))return t.emitter.emit("message",n);t.processMessage(n)})},this.socket.onerror=function(e){if(t.emitter.exist("error"))return t.emitter.emit("error",e);throw t.close(),new Error("Connect event has been called multiple times")}},n.prototype.on=function(t,e){this.emitter.on(t,e)},n.prototype.send=function(t,e,n){return void 0===n&&(n="emit"),void 0===e?this.socket.send(t):this.socket.send(function(t,e,n){var s={emit:["e",t,e],publish:["p",t,e],system:{subscribe:["s","s",e],unsubscribe:["s","u",e],configuration:["s","c",e]}};return"system"===n?JSON.stringify(s[n][t]):JSON.stringify(s[n])}(t,e,n))},n.prototype.close=function(t,e){this.socket.close(t||1e3,e)},n.prototype.subscribe=function(t){return this.channels.subscribe(t)},n.prototype.getChannelByName=function(t){return this.channels.getChannelByName(t)},n.prototype.processMessage=function(t){try{if(t instanceof Array)return e(this,t);if("string"!=typeof t){var n=new Error("processMessage accepts only string or array types");if(this.emitter.exist("error"))return this.emitter.emit("error",n);throw n}if("["!==t[0]){n=new Error("processMessage received incorrect message");if(this.emitter.exist("error"))return this.emitter.emit("error",n);throw n}return e(this,JSON.parse(t))}catch(n){if(this.emitter.exist("error"))return this.emitter.emit("error",n);throw this.close(),n}},n.prototype.parsePing=function(t,e){var n=this;if(1===t.size||1===t.byteLength){var s=function(t){return 57===new Uint8Array(t)[0]?(n.resetPing(),n.socket.send(r),n.emitter.emit("ping")):e()};if(!(t instanceof ArrayBuffer)){var i=new FileReader;return i.onload=function(t){return s(t.srcElement.result)},i.readAsArrayBuffer(t)}return s(t)}return e()},n.prototype.resetPing=function(){var t=this;clearTimeout(this.pingTimeout),this.pingInterval&&this.autoPing&&(this.pingTimeout=setTimeout(function(){t.close(4001,"No ping received in "+(t.pingInterval+500)+"ms")},this.pingInterval+500))},n}()}(); 2 | -------------------------------------------------------------------------------- /dist/index.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | function isFunction(t) { 4 | return "function" == typeof t; 5 | } 6 | 7 | var EventEmitter = function() { 8 | function t() { 9 | this.events = {}; 10 | } 11 | return t.prototype.on = function(t, e) { 12 | if (!isFunction(e)) throw new Error("Listener must be a function"); 13 | this.events[t] = e; 14 | }, t.prototype.emit = function(t) { 15 | for (var e = [], n = 1; n < arguments.length; n++) e[n - 1] = arguments[n]; 16 | var s = this.events[t]; 17 | s && s.apply(void 0, e); 18 | }, t.prototype.exist = function(t) { 19 | return !!this.events[t]; 20 | }, t.prototype.off = function(t) { 21 | delete this.events[t]; 22 | }, t.prototype.removeEvents = function() { 23 | this.events = {}; 24 | }, t; 25 | }(); 26 | 27 | function decode(t, e) { 28 | var n = e[0], s = e[1], i = e[2]; 29 | if ("e" === n) return t.emitter.emit(s, i); 30 | if ("p" === n) for (var o = 0, r = (h = Object.keys(i)).length; o < r; o++) for (var c = i[p = h[o]], a = 0, u = c.length; a < u; a++) t.channels.channelNewMessage(p, c[a]); 31 | if ("s" === n) { 32 | if ("s" === s) { 33 | var h; 34 | for (o = 0, r = (h = Object.keys(i)).length; o < r; o++) { 35 | var p = h[o]; 36 | t.channels.channelSetStatus(p, i[p]); 37 | } 38 | } 39 | "c" === s && (t.autoPing = i.autoPing, t.pingInterval = i.pingInterval, t.resetPing()); 40 | } 41 | } 42 | 43 | function encode(t, e, n) { 44 | var s = { 45 | emit: [ "e", t, e ], 46 | publish: [ "p", t, e ], 47 | system: { 48 | subscribe: [ "s", "s", e ], 49 | unsubscribe: [ "s", "u", e ], 50 | configuration: [ "s", "c", e ] 51 | } 52 | }; 53 | return "system" === n ? JSON.stringify(s[n][t]) : JSON.stringify(s[n]); 54 | } 55 | 56 | var Channel = function() { 57 | function t(t, e) { 58 | this.client = t, this.name = e, this.READY = 1, this.status = 0, this.events = {}, 59 | this.watchers = [], this.client.readyState === this.client.OPEN && this.client.send("subscribe", [ this.name ], "system"); 60 | } 61 | return t.prototype.on = function(t, e) { 62 | this.events[t] = e; 63 | }, t.prototype.publish = function(t) { 64 | this.status === this.READY && this.client.send(this.name, t, "publish"); 65 | }, t.prototype.setWatcher = function(t) { 66 | this.watchers.push(t); 67 | }, t.prototype.removeWatcher = function(t) { 68 | for (var e = 0, n = this.watchers.length; e < n; e++) if (this.watchers[e] === t) { 69 | this.watchers.splice(e, 1); 70 | break; 71 | } 72 | }, t.prototype.unsubscribe = function() { 73 | this.status = 0, this.emit("unsubscribed"), this.client.channels.removeChannel(this.name), 74 | this.client.send("unsubscribe", this.name, "system"); 75 | }, t.prototype.emit = function(t) { 76 | var e = this.events[t]; 77 | e && e(); 78 | }, t.prototype.broadcast = function(t) { 79 | for (var e = 0, n = this.watchers.length; e < n; e++) this.watchers[e](t); 80 | }, t; 81 | }(), Channels = function() { 82 | function t(t) { 83 | this.client = t, this.channels = {}; 84 | } 85 | return t.prototype.subscribe = function(t) { 86 | if (!this.channels[t]) { 87 | var e = new Channel(this.client, t); 88 | return this.channels[t] = e, e; 89 | } 90 | }, t.prototype.resubscribe = function() { 91 | var t = Object.keys(this.channels); 92 | t.length && this.client.send("subscribe", t, "system"); 93 | }, t.prototype.getChannelByName = function(t) { 94 | return this.channels[t] || null; 95 | }, t.prototype.channelNewMessage = function(t, e) { 96 | var n = this.channels[t]; 97 | n && n.status === n.READY && n.broadcast(e); 98 | }, t.prototype.channelSetStatus = function(t, e) { 99 | var n = this.channels[t]; 100 | if (n) { 101 | if (!e) return n.emit("canceled"), this.removeChannel(t); 102 | n.status = 1, n.emit("subscribed"); 103 | } 104 | }, t.prototype.removeChannel = function(t) { 105 | delete this.channels[t]; 106 | }, t.prototype.removeAllChannels = function() { 107 | this.channels = {}; 108 | }, t; 109 | }(), Socket = window.MozWebSocket || window.WebSocket, PONG = new Uint8Array([ "A".charCodeAt(0) ]).buffer, ClusterWS = function() { 110 | function t(t) { 111 | if (this.reconnectAttempts = 0, this.options = { 112 | url: t.url, 113 | autoConnect: !1 !== t.autoConnect, 114 | autoReconnect: t.autoReconnect || !1, 115 | autoResubscribe: !1 !== t.autoResubscribe, 116 | autoReconnectOptions: { 117 | attempts: t.autoReconnectOptions && t.autoReconnectOptions.attempts || 0, 118 | minInterval: t.autoReconnectOptions && t.autoReconnectOptions.minInterval || 500, 119 | maxInterval: t.autoReconnectOptions && t.autoReconnectOptions.maxInterval || 2e3 120 | } 121 | }, !this.options.url) throw new Error("url must be provided"); 122 | this.emitter = new EventEmitter(), this.channels = new Channels(this), this.reconnectAttempts = this.options.autoReconnectOptions.attempts, 123 | this.options.autoConnect && this.connect(); 124 | } 125 | return Object.defineProperty(t.prototype, "OPEN", { 126 | get: function() { 127 | return this.socket.OPEN; 128 | }, 129 | enumerable: !0, 130 | configurable: !0 131 | }), Object.defineProperty(t.prototype, "CLOSED", { 132 | get: function() { 133 | return this.socket.CLOSED; 134 | }, 135 | enumerable: !0, 136 | configurable: !0 137 | }), Object.defineProperty(t.prototype, "readyState", { 138 | get: function() { 139 | return this.socket ? this.socket.readyState : 0; 140 | }, 141 | enumerable: !0, 142 | configurable: !0 143 | }), Object.defineProperty(t.prototype, "binaryType", { 144 | get: function() { 145 | return this.socket.binaryType; 146 | }, 147 | set: function(t) { 148 | this.socket.binaryType = t; 149 | }, 150 | enumerable: !0, 151 | configurable: !0 152 | }), t.prototype.connect = function() { 153 | var t = this; 154 | if (this.isCreated) throw new Error("Connect event has been called multiple times"); 155 | this.isCreated = !0, this.socket = new Socket(this.options.url), this.socket.onopen = function() { 156 | t.reconnectAttempts = t.options.autoReconnectOptions.attempts, t.options.autoResubscribe ? t.channels.resubscribe() : t.channels.removeAllChannels(), 157 | t.emitter.emit("open"); 158 | }, this.socket.onclose = function(e, n) { 159 | clearTimeout(t.pingTimeout), t.isCreated = !1; 160 | var s = "number" == typeof e ? e : e.code, i = "number" == typeof e ? n : e.reason; 161 | if (t.emitter.emit("close", s, i), t.options.autoReconnect && 1e3 !== s && t.readyState === t.CLOSED && (0 === t.options.autoReconnectOptions.attempts || t.reconnectAttempts > 0)) return t.reconnectAttempts--, 162 | setTimeout(function() { 163 | t.connect(); 164 | }, Math.floor(Math.random() * (t.options.autoReconnectOptions.maxInterval - t.options.autoReconnectOptions.minInterval + 1))); 165 | t.emitter.removeEvents(), t.channels.removeAllChannels(); 166 | }, this.socket.onmessage = function(e) { 167 | var n = e; 168 | e.data && (n = e.data), t.parsePing(n, function() { 169 | if (t.emitter.exist("message")) return t.emitter.emit("message", n); 170 | t.processMessage(n); 171 | }); 172 | }, this.socket.onerror = function(e) { 173 | if (t.emitter.exist("error")) return t.emitter.emit("error", e); 174 | throw t.close(), new Error("Connect event has been called multiple times"); 175 | }; 176 | }, t.prototype.on = function(t, e) { 177 | this.emitter.on(t, e); 178 | }, t.prototype.send = function(t, e, n) { 179 | return void 0 === n && (n = "emit"), void 0 === e ? this.socket.send(t) : this.socket.send(encode(t, e, n)); 180 | }, t.prototype.close = function(t, e) { 181 | this.socket.close(t || 1e3, e); 182 | }, t.prototype.subscribe = function(t) { 183 | return this.channels.subscribe(t); 184 | }, t.prototype.getChannelByName = function(t) { 185 | return this.channels.getChannelByName(t); 186 | }, t.prototype.processMessage = function(t) { 187 | try { 188 | if (t instanceof Array) return decode(this, t); 189 | if ("string" != typeof t) { 190 | var e = new Error("processMessage accepts only string or array types"); 191 | if (this.emitter.exist("error")) return this.emitter.emit("error", e); 192 | throw e; 193 | } 194 | if ("[" !== t[0]) { 195 | e = new Error("processMessage received incorrect message"); 196 | if (this.emitter.exist("error")) return this.emitter.emit("error", e); 197 | throw e; 198 | } 199 | return decode(this, JSON.parse(t)); 200 | } catch (e) { 201 | if (this.emitter.exist("error")) return this.emitter.emit("error", e); 202 | throw this.close(), e; 203 | } 204 | }, t.prototype.parsePing = function(t, e) { 205 | var n = this; 206 | if (1 === t.size || 1 === t.byteLength) { 207 | var s = function(t) { 208 | return 57 === new Uint8Array(t)[0] ? (n.resetPing(), n.socket.send(PONG), n.emitter.emit("ping")) : e(); 209 | }; 210 | if (!(t instanceof ArrayBuffer)) { 211 | var i = new FileReader(); 212 | return i.onload = function(t) { 213 | return s(t.srcElement.result); 214 | }, i.readAsArrayBuffer(t); 215 | } 216 | return s(t); 217 | } 218 | return e(); 219 | }, t.prototype.resetPing = function() { 220 | var t = this; 221 | clearTimeout(this.pingTimeout), this.pingInterval && this.autoPing && (this.pingTimeout = setTimeout(function() { 222 | t.close(4001, "No ping received in " + (t.pingInterval + 500) + "ms"); 223 | }, this.pingInterval + 500)); 224 | }, t; 225 | }(); 226 | 227 | module.exports = ClusterWS; module.exports.default = ClusterWS; 228 | -------------------------------------------------------------------------------- /dist/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@clusterws/client-js", 3 | "version": "4.0.0-alpha.2", 4 | "description": "Official JavaScript Client for ClusterWS", 5 | "main": "index.js", 6 | "types": "index.d.ts", 7 | "author": "Dmitrii Goriunov", 8 | "license": "MIT", 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/ClusterWS/ClusterWS-Client-JS" 12 | }, 13 | "keywords": [ 14 | "clusterws", 15 | "websocket", 16 | "scale", 17 | "cws", 18 | "cluster", 19 | "ws client", 20 | "javascript" 21 | ] 22 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@clusterws/client-js", 3 | "version": "4.0.0-alpha.2", 4 | "description": "Official JavaScript Client for ClusterWS", 5 | "main": "index.js", 6 | "types": "index.d.ts", 7 | "author": "Dmitrii Goriunov", 8 | "scripts": { 9 | "build": "ts-builder -c ./tsbuild.json", 10 | "release": "npm run build && cd dist && npm publish --tag alpha --access public" 11 | }, 12 | "license": "MIT", 13 | "repository": { 14 | "type": "git", 15 | "url": "https://github.com/ClusterWS/ClusterWS-Client-JS" 16 | }, 17 | "devDependencies": { 18 | "ts-builder": "^0.10.0" 19 | }, 20 | "keywords": [ 21 | "clusterws", 22 | "websocket", 23 | "scale", 24 | "cws", 25 | "cluster", 26 | "ws client", 27 | "javascript" 28 | ] 29 | } -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { EventEmitter } from './utils/emitter'; 2 | import { decode, encode } from './modules/parser'; 3 | import { Channels, Channel } from './modules/channels'; 4 | import { Listener, Configurations, Options, Message } from './utils/types'; 5 | 6 | declare const window: any; 7 | const Socket: any = window.MozWebSocket || window.WebSocket; 8 | const PONG: any = new Uint8Array(['A'.charCodeAt(0)]).buffer; 9 | 10 | // TODO: 11 | // - implement d.ts file 12 | 13 | export default class ClusterWS { 14 | private socket: WebSocket; 15 | private emitter: EventEmitter; 16 | private options: Options; 17 | private channels: Channels; 18 | 19 | private isCreated: boolean; 20 | private reconnectAttempts: number = 0; 21 | 22 | private autoPing: boolean; 23 | private pingInterval: number; 24 | private pingTimeout: any; 25 | 26 | constructor(configurations: Configurations) { 27 | this.options = { 28 | url: configurations.url, 29 | autoConnect: configurations.autoConnect !== false, 30 | autoReconnect: configurations.autoReconnect || false, 31 | autoResubscribe: configurations.autoResubscribe !== false, 32 | autoReconnectOptions: { 33 | attempts: configurations.autoReconnectOptions ? 34 | configurations.autoReconnectOptions.attempts || 0 : 0, 35 | minInterval: configurations.autoReconnectOptions ? 36 | configurations.autoReconnectOptions.minInterval || 500 : 500, 37 | maxInterval: configurations.autoReconnectOptions ? 38 | configurations.autoReconnectOptions.maxInterval || 2000 : 2000 39 | } 40 | }; 41 | 42 | if (!this.options.url) { 43 | throw new Error('url must be provided'); 44 | } 45 | 46 | this.emitter = new EventEmitter(); 47 | this.channels = new Channels(this); 48 | this.reconnectAttempts = this.options.autoReconnectOptions.attempts; 49 | 50 | if (this.options.autoConnect) { 51 | this.connect(); 52 | } 53 | } 54 | 55 | public get OPEN(): number { 56 | return this.socket.OPEN; 57 | } 58 | 59 | public get CLOSED(): number { 60 | return this.socket.CLOSED; 61 | } 62 | 63 | public get readyState(): number { 64 | return this.socket ? this.socket.readyState : 0; 65 | } 66 | 67 | public set binaryType(binaryType: BinaryType) { 68 | this.socket.binaryType = binaryType; 69 | } 70 | 71 | public get binaryType(): BinaryType { 72 | return this.socket.binaryType; 73 | } 74 | 75 | public connect(): void { 76 | if (this.isCreated) { 77 | throw new Error('Connect event has been called multiple times'); 78 | } 79 | 80 | this.isCreated = true; 81 | this.socket = new Socket(this.options.url); 82 | 83 | this.socket.onopen = (): void => { 84 | this.reconnectAttempts = this.options.autoReconnectOptions.attempts; 85 | this.options.autoResubscribe ? 86 | this.channels.resubscribe() : 87 | this.channels.removeAllChannels(); 88 | 89 | this.emitter.emit('open'); 90 | }; 91 | 92 | this.socket.onclose = (codeEvent: CloseEvent | number, reason?: string): any => { 93 | clearTimeout(this.pingTimeout); 94 | this.isCreated = false; 95 | const closeCode: number = typeof codeEvent === 'number' ? codeEvent : codeEvent.code; 96 | const closeReason: string = typeof codeEvent === 'number' ? reason : codeEvent.reason; 97 | 98 | this.emitter.emit('close', closeCode, closeReason); 99 | 100 | if (this.options.autoReconnect && closeCode !== 1000) { 101 | if (this.readyState === this.CLOSED) { 102 | if (this.options.autoReconnectOptions.attempts === 0 || this.reconnectAttempts > 0) { 103 | this.reconnectAttempts--; 104 | return setTimeout(() => { 105 | this.connect(); 106 | }, Math.floor(Math.random() * (this.options.autoReconnectOptions.maxInterval - this.options.autoReconnectOptions.minInterval + 1))); 107 | } 108 | } 109 | } 110 | 111 | // clean up connection events if we are done with this socket 112 | this.emitter.removeEvents(); 113 | this.channels.removeAllChannels(); 114 | }; 115 | 116 | this.socket.onmessage = (message: MessageEvent | Message): void => { 117 | let messageToProcess: Message = message; 118 | if (message.data) { 119 | // this means we run in browser 120 | messageToProcess = message.data; 121 | } 122 | 123 | this.parsePing(messageToProcess, () => { 124 | if (this.emitter.exist('message')) { 125 | return this.emitter.emit('message', messageToProcess); 126 | } 127 | 128 | this.processMessage(messageToProcess); 129 | }); 130 | }; 131 | 132 | this.socket.onerror = (error: ErrorEvent): void => { 133 | if (this.emitter.exist('error')) { 134 | return this.emitter.emit('error', error); 135 | } 136 | // if error catch is not there then we can close connection on any error 137 | this.close(); 138 | throw new Error('Connect event has been called multiple times'); 139 | }; 140 | } 141 | 142 | // TODO: make sure we implement on message event properly 143 | // on message, on ping, on close, on error are reserved events 144 | public on(event: string, listener: Listener): void { 145 | this.emitter.on(event, listener); 146 | } 147 | 148 | // TODO: add overload to this function in d.ts file 149 | public send(event: string, message: Message, eventType: string = 'emit'): void { 150 | // we swap to default websocket send if no event and message provided correctly 151 | if (message === undefined) { 152 | return this.socket.send(event); 153 | } 154 | 155 | return this.socket.send(encode(event, message, eventType)); 156 | } 157 | 158 | public close(code?: number, reason?: string): void { 159 | this.socket.close(code || 1000, reason); 160 | } 161 | 162 | public subscribe(channelName: string): Channel { 163 | return this.channels.subscribe(channelName); 164 | } 165 | 166 | public getChannelByName(channelName: string): Channel { 167 | return this.channels.getChannelByName(channelName); 168 | } 169 | 170 | public processMessage(message: Message): void { 171 | // write message processor 172 | try { 173 | if (message instanceof Array) { 174 | return decode(this as any, message); 175 | } 176 | 177 | if (typeof message !== 'string') { 178 | const err: Error = new Error('processMessage accepts only string or array types'); 179 | if (this.emitter.exist('error')) { 180 | return this.emitter.emit('error', err); 181 | } 182 | 183 | throw err; 184 | } 185 | 186 | if (message[0] !== '[') { 187 | const err: Error = new Error('processMessage received incorrect message'); 188 | if (this.emitter.exist('error')) { 189 | return this.emitter.emit('error', err); 190 | } 191 | 192 | throw err; 193 | } 194 | 195 | return decode(this as any, JSON.parse(message)); 196 | } catch (err) { 197 | // This will parse the rest of the errors 198 | if (this.emitter.exist('error')) { 199 | return this.emitter.emit('error', err); 200 | } 201 | 202 | this.close(); 203 | throw err; 204 | } 205 | } 206 | 207 | private parsePing(message: Message, next: Listener): void { 208 | // we should handle ping before emitting on message 209 | if (message.size === 1 || message.byteLength === 1) { 210 | const parser: Listener = (possiblePingMessage: Message): void => { 211 | if (new Uint8Array(possiblePingMessage)[0] === 57) { 212 | // this is our ping need to send pong response and trigger ping 213 | this.resetPing(); 214 | this.socket.send(PONG); 215 | return this.emitter.emit('ping'); 216 | } 217 | 218 | return next(); 219 | }; 220 | 221 | if (!(message instanceof ArrayBuffer)) { 222 | // transform blob to arrayBuffer 223 | const reader: FileReader = new FileReader(); 224 | reader.onload = (event: any): void => parser(event.srcElement.result); 225 | return reader.readAsArrayBuffer(message); 226 | } 227 | 228 | return parser(message); 229 | } 230 | 231 | return next(); 232 | } 233 | 234 | private resetPing(): void { 235 | clearTimeout(this.pingTimeout); 236 | if (this.pingInterval && this.autoPing) { 237 | this.pingTimeout = setTimeout(() => { 238 | this.close(4001, `No ping received in ${this.pingInterval + 500}ms`); 239 | }, this.pingInterval + 500); 240 | } 241 | } 242 | } -------------------------------------------------------------------------------- /src/modules/channels.ts: -------------------------------------------------------------------------------- 1 | import ClusterWS from '../index'; 2 | import { Message, Listener } from '../utils/types'; 3 | 4 | // TODO: channel logic can be improved for better performance 5 | // Single channel 6 | export class Channel { 7 | public READY: number = 1; 8 | public status: number = 0; 9 | 10 | private events: any = {}; 11 | private watchers: any[] = []; 12 | 13 | constructor(private client: ClusterWS, public name: string) { 14 | if (this.client.readyState === this.client.OPEN) { 15 | this.client.send('subscribe', [this.name], 'system'); 16 | } 17 | } 18 | 19 | public on(event: string, listener: Listener): void { 20 | this.events[event] = listener; 21 | } 22 | 23 | public publish(message: Message): void { 24 | if (this.status === this.READY) { 25 | this.client.send(this.name, message, 'publish'); 26 | } 27 | } 28 | 29 | public setWatcher(listener: Listener): void { 30 | this.watchers.push(listener); 31 | } 32 | 33 | public removeWatcher(listener: Listener): void { 34 | for (let i: number = 0, len: number = this.watchers.length; i < len; i++) { 35 | if (this.watchers[i] === listener) { 36 | this.watchers.splice(i, 1); 37 | break; 38 | } 39 | } 40 | } 41 | 42 | public unsubscribe(): any { 43 | this.status = 0; 44 | this.emit('unsubscribed'); 45 | (this.client as any).channels.removeChannel(this.name); 46 | this.client.send('unsubscribe', this.name, 'system'); 47 | } 48 | 49 | private emit(event: string): void { 50 | const listener: Listener = this.events[event]; 51 | listener && listener(); 52 | } 53 | 54 | private broadcast(message: Message): void { 55 | for (let i: number = 0, len: number = this.watchers.length; i < len; i++) { 56 | this.watchers[i](message); 57 | } 58 | } 59 | } 60 | 61 | // Channels manager 62 | export class Channels { 63 | private channels: { [key: string]: Channel } = {}; 64 | 65 | constructor(private client: ClusterWS) { } 66 | 67 | public subscribe(channelName: string): Channel { 68 | if (!this.channels[channelName]) { 69 | const channel: Channel = new Channel(this.client, channelName); 70 | this.channels[channelName] = channel; 71 | return channel; 72 | } 73 | } 74 | 75 | public resubscribe(): void { 76 | const allChannels: string[] = Object.keys(this.channels); 77 | if (allChannels.length) { 78 | this.client.send('subscribe', allChannels, 'system'); 79 | } 80 | } 81 | 82 | public getChannelByName(channelName: string): Channel { 83 | return this.channels[channelName] || null; 84 | } 85 | 86 | // This is used internally when new message is received 87 | public channelNewMessage(channelName: string, message: Message): void { 88 | const channel: Channel = this.channels[channelName]; 89 | if (channel && channel.status === channel.READY) { 90 | (channel as any).broadcast(message); 91 | } 92 | } 93 | 94 | // This is used internally when we get status for this channel from server 95 | public channelSetStatus(channelName: string, pass: boolean): void { 96 | const channel: Channel = this.channels[channelName]; 97 | if (channel) { 98 | if (!pass) { 99 | // if subscription fail we delete event 100 | (channel as any).emit('canceled'); 101 | return this.removeChannel(channelName); 102 | } 103 | channel.status = 1; 104 | (channel as any).emit('subscribed'); 105 | } 106 | } 107 | 108 | public removeChannel(channelName: string): void { 109 | delete this.channels[channelName]; 110 | } 111 | 112 | public removeAllChannels(): void { 113 | this.channels = {}; 114 | } 115 | } -------------------------------------------------------------------------------- /src/modules/parser.ts: -------------------------------------------------------------------------------- 1 | import ClusterWS from '../index'; 2 | import { Message } from '../utils/types'; 3 | 4 | export function decode(socket: ClusterWS, data: Message): void { 5 | // handle all the stuff 6 | const [msgType, param, message]: [string, string, Message] = data; 7 | 8 | if (msgType === 'e') { 9 | return (socket as any).emitter.emit(param, message); 10 | } 11 | 12 | if (msgType === 'p') { 13 | const channels: string[] = Object.keys(message); 14 | for (let i: number = 0, len: number = channels.length; i < len; i++) { 15 | const channel: string = channels[i]; 16 | const messages: Message[] = message[channel]; 17 | for (let j: number = 0, msgLen: number = messages.length; j < msgLen; j++) { 18 | (socket as any).channels.channelNewMessage(channel, messages[j]); 19 | } 20 | } 21 | } 22 | 23 | if (msgType === 's') { 24 | if (param === 's') { 25 | const channels: string[] = Object.keys(message); 26 | for (let i: number = 0, len: number = channels.length; i < len; i++) { 27 | const channel: string = channels[i]; 28 | (socket as any).channels.channelSetStatus(channel, message[channel]); 29 | } 30 | } 31 | 32 | if (param === 'c') { 33 | (socket as any).autoPing = message.autoPing; 34 | (socket as any).pingInterval = message.pingInterval; 35 | (socket as any).resetPing(); 36 | } 37 | } 38 | } 39 | 40 | export function encode(event: string, data: Message, eventType: string): string { 41 | const message: { [key: string]: any } = { 42 | emit: ['e', event, data], 43 | publish: ['p', event, data], 44 | system: { 45 | subscribe: ['s', 's', data], 46 | unsubscribe: ['s', 'u', data], 47 | configuration: ['s', 'c', data] 48 | } 49 | }; 50 | 51 | if (eventType === 'system') { 52 | return JSON.stringify(message[eventType][event]); 53 | } 54 | 55 | return JSON.stringify(message[eventType]); 56 | } -------------------------------------------------------------------------------- /src/utils/emitter.ts: -------------------------------------------------------------------------------- 1 | import { Listener } from './types'; 2 | import { isFunction } from './helpers'; 3 | 4 | export class EventEmitter { 5 | private events: { [key: string]: Listener } = {}; 6 | 7 | public on(event: string, listener: Listener): void { 8 | if (!isFunction(listener)) { 9 | throw new Error('Listener must be a function'); 10 | } 11 | 12 | this.events[event] = listener; 13 | } 14 | 15 | public emit(event: string, ...args: any[]): void { 16 | const listener: Listener = this.events[event]; 17 | listener && listener(...args); 18 | } 19 | 20 | public exist(event: string): boolean { 21 | return !!this.events[event]; 22 | } 23 | 24 | public off(event: string): void { 25 | delete this.events[event]; 26 | } 27 | 28 | public removeEvents(): void { 29 | this.events = {}; 30 | } 31 | } -------------------------------------------------------------------------------- /src/utils/helpers.ts: -------------------------------------------------------------------------------- 1 | export function isFunction(fn: T): boolean { 2 | return typeof fn === 'function'; 3 | } -------------------------------------------------------------------------------- /src/utils/types.ts: -------------------------------------------------------------------------------- 1 | // for SocketMessage use string | Buffer 2 | export type Message = any; 3 | export type Listener = (...args: any[]) => void; 4 | 5 | export type Options = { 6 | url: string; 7 | autoConnect: boolean; 8 | autoReconnect: boolean; 9 | autoResubscribe: boolean; 10 | autoReconnectOptions: { 11 | attempts: number; 12 | minInterval: number; 13 | maxInterval: number; 14 | } 15 | }; 16 | 17 | export type Configurations = { 18 | url: string; 19 | autoConnect?: boolean; 20 | autoReconnect?: boolean; 21 | autoResubscribe?: boolean; 22 | autoReconnectOptions?: { 23 | attempts?: number; 24 | minInterval?: number; 25 | maxInterval?: number; 26 | } 27 | }; -------------------------------------------------------------------------------- /tests/manual/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Document 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /tests/manual/main.js: -------------------------------------------------------------------------------- 1 | let socket = new ClusterWS({ 2 | url: "ws://localhost:3001", 3 | autoReconnect: true, 4 | autoReconnectOptions: { 5 | attempts: 10, 6 | minInterval: 10000, 7 | maxInterval: 100000 8 | } 9 | }); 10 | 11 | // socket.binaryType = 'arraybuffer'; 12 | socket.on('open', () => { 13 | console.log('Socket has been open'); 14 | }); 15 | 16 | // socket.on('message', async (message) => { 17 | // console.log(message); 18 | // socket.processMessage(message); 19 | // }); 20 | 21 | socket.on('ping', () => { 22 | console.log('Received ping'); 23 | }); 24 | 25 | socket.on('close', (code, reason) => { 26 | console.log(code, reason); 27 | }); 28 | 29 | 30 | let helloWorldChannel = socket.subscribe('hello world'); 31 | 32 | helloWorldChannel.on('subscribed', () => { 33 | console.log('Channels hello world has been subscribed'); 34 | 35 | setInterval(() => { 36 | helloWorldChannel.publish('My super message'); 37 | }, 5000); 38 | }); 39 | 40 | 41 | let watcherOne = (message) => { 42 | console.log("Received message watcher 1 in hello world", message); 43 | }; 44 | 45 | let watcherTwo = (message) => { 46 | console.log("Received message watcher 2 in hello world", message); 47 | } 48 | 49 | helloWorldChannel.setWatcher(watcherOne); 50 | helloWorldChannel.setWatcher(watcherTwo); 51 | 52 | setTimeout(() => { 53 | helloWorldChannel.removeWatcher(watcherTwo); 54 | }, 15000) 55 | 56 | -------------------------------------------------------------------------------- /tsbuild.json: -------------------------------------------------------------------------------- 1 | { 2 | "src": "./src/", 3 | "main": "index.ts", 4 | "tslint": "./tslint.json", 5 | "builds": [ 6 | { 7 | "distFolder": "./dist/", 8 | "output": { 9 | "format": "cjs", 10 | "file": "index.js", 11 | "name": "ClusterWS" 12 | }, 13 | "uglify": { 14 | "mangle": true, 15 | "output": { 16 | "beautify": true 17 | } 18 | }, 19 | "copy": [ 20 | { 21 | "src": "./LICENSE", 22 | "dist": "./dist/LICENSE" 23 | }, 24 | { 25 | "src": "./src/index.d.ts", 26 | "dist": "./dist/index.d.ts" 27 | }, 28 | { 29 | "src": "./.github/README.md", 30 | "dist": "./dist/README.md" 31 | }, 32 | { 33 | "src": "./package.json", 34 | "dist": "./dist/package.json", 35 | "remove": [ 36 | "devDependencies", 37 | "scripts" 38 | ] 39 | } 40 | ] 41 | }, 42 | { 43 | "distFolder": "./dist/browser/", 44 | "output": { 45 | "format": "iife", 46 | "file": "clusterws.min.js", 47 | "name": "ClusterWS" 48 | }, 49 | "uglify": { 50 | "mangle": true 51 | } 52 | }, 53 | { 54 | "distFolder": "./dist/browser/", 55 | "output": { 56 | "format": "iife", 57 | "file": "clusterws.js", 58 | "name": "ClusterWS" 59 | } 60 | } 61 | ], 62 | "tsConfigs": { 63 | "compilerOptions": { 64 | "target": "es5", 65 | "module": "ES2015", 66 | "removeComments": true, 67 | "declaration": false 68 | }, 69 | "exclude": [ 70 | "./src/**/*.test.ts" 71 | ], 72 | "include": [ 73 | "./src/**/*" 74 | ] 75 | } 76 | } -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "tslint:recommended", 4 | "tslint-eslint-rules" 5 | ], 6 | "rules": { 7 | "no-string-literal": false, 8 | "typedef": [ 9 | true, 10 | "call-signature", 11 | "arrow-call-signature", 12 | "parameter", 13 | "arrow-parameter", 14 | "property-declaration", 15 | "variable-declaration", 16 | "member-variable-declaration", 17 | "object-destructuring", 18 | "array-destructuring" 19 | ], 20 | "object-literal-shorthand": true, 21 | "interface-over-type-literal": false, 22 | "no-unused-expression": false, 23 | "eofline": false, 24 | "object-literal-sort-keys": false, 25 | "ordered-imports": false, 26 | "prefer-const": [ 27 | true, 28 | { 29 | "destructuring": "all" 30 | } 31 | ], 32 | "no-var-keyword": true, 33 | "quotemark": [ 34 | true, 35 | "single", 36 | "jsx-double" 37 | ], 38 | "trailing-comma": [ 39 | false 40 | ], 41 | "semicolon": [ 42 | true, 43 | "always" 44 | ], 45 | "no-console": false, 46 | "curly": true, 47 | "brace-style": [ 48 | true, 49 | "1tbs", 50 | { 51 | "allowSingleLine": true 52 | } 53 | ], 54 | "max-classes-per-file": [ 55 | true, 56 | 2 57 | ], 58 | "max-line-length": [ 59 | true, 60 | 180 61 | ] 62 | } 63 | } --------------------------------------------------------------------------------