Created
December 17, 2018 11:33
-
-
Save matheus1lva/832f008a3a3cb056b537ca715cb15d60 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
eval("/*\n Copyright © 2018 Andrew Powell\n\n This Source Code Form is subject to the terms of the Mozilla Public\n License, v. 2.0. If a copy of the MPL was not distributed with this\n file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n The above copyright notice and this permission notice shall be\n included in all copies or subsantial portions of this Source Code Form.\n*/\nconst { error, refresh, warn } = __webpack_require__(/*! ./log */ \"./node_modules/webpack-plugin-serve/lib/client/log.js\");\n\n// ignore 1008 (HTTP 400 equivalent) and 1011 (HTTP 500 equivalent)\nconst ignoreCodes = [1008, 1011];\nconst maxAttempts = 10;\n\nclass ClientSocket {\n constructor(options, ...args) {\n this.args = args;\n this.attempts = 0;\n this.eventHandlers = [];\n this.options = options;\n this.retrying = false;\n\n this.connect();\n }\n\n addEventListener(...args) {\n this.eventHandlers.push(args);\n this.socket.addEventListener(...args);\n }\n\n connect() {\n if (this.socket) {\n delete this.socket;\n }\n\n this.connecting = true;\n\n this.socket = new WebSocket(...this.args);\n\n if (this.options.retry) {\n this.socket.addEventListener('close', (event) => {\n if (ignoreCodes.includes(event.code)) {\n return;\n }\n\n if (!this.retrying) {\n warn(`The WebSocket was closed and will attempt to reconnect`);\n }\n\n this.reconnect();\n });\n } else {\n this.socket.onclose = () => warn(`The client WebSocket was closed. ${refresh}`);\n }\n\n this.socket.addEventListener('open', () => {\n this.attempts = 0;\n this.retrying = false;\n });\n\n if (this.eventHandlers.length) {\n for (const [name, fn] of this.eventHandlers) {\n this.socket.addEventListener(name, fn);\n }\n }\n }\n\n reconnect() {\n this.attempts += 1;\n this.retrying = true;\n\n if (this.attempts > maxAttempts) {\n error(`The WebSocket could not be reconnected. ${refresh}`);\n this.retrying = false;\n return;\n }\n\n const timeout = 1000 * this.attempts ** 2;\n\n setTimeout(() => this.connect(this.args), timeout);\n }\n\n removeEventListener(...args) {\n const [, handler] = args;\n this.eventHandlers = this.eventHandlers.filter(([, fn]) => fn === handler);\n this.socket.removeEventListener(...args);\n }\n}\n\nmodule.exports = { ClientSocket };\n\n\n//# sourceURL=webpack:///(webpack)-plugin-serve/lib/client/ClientSocket.js?"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment