teckos-client 0.3.3 → 0.3.6

Sign up to get free protection for your applications and to get access to all the features.
Files changed (56) hide show
  1. package/dist/ITeckosClient.d.ts +18 -0
  2. package/dist/TeckosClient.d.ts +35 -0
  3. package/dist/TeckosClientWithJWT.d.ts +12 -0
  4. package/dist/index.d.ts +9 -0
  5. package/dist/index.js +40 -43
  6. package/dist/index.js.map +1 -0
  7. package/dist/index.min.js +1 -1
  8. package/dist/teckos-client.cjs.development.js +611 -0
  9. package/dist/teckos-client.cjs.development.js.map +1 -0
  10. package/dist/teckos-client.cjs.production.min.js +2 -0
  11. package/dist/teckos-client.cjs.production.min.js.map +1 -0
  12. package/dist/teckos-client.esm.js +608 -0
  13. package/dist/teckos-client.esm.js.map +1 -0
  14. package/dist/types/ConnectionState.d.ts +7 -0
  15. package/dist/types/Options.d.ts +10 -0
  16. package/dist/types/Packet.d.ts +6 -0
  17. package/dist/types/PacketType.d.ts +5 -0
  18. package/dist/types/SocketEvent.d.ts +10 -0
  19. package/dist/types/index.d.ts +7 -0
  20. package/dist/util/Converter.d.ts +4 -0
  21. package/dist/util/SocketEventEmitter.d.ts +23 -0
  22. package/es/index.js +34 -39
  23. package/es/index.mjs +1 -1
  24. package/lib/index.js +37 -58
  25. package/package.json +6 -7
  26. package/src/ITeckosClient.ts +2 -3
  27. package/src/TeckosClient.ts +29 -29
  28. package/src/TeckosClientWithJWT.ts +6 -6
  29. package/src/index.ts +3 -3
  30. package/types/ITeckosClient.d.ts +2 -3
  31. package/types/TeckosClient.d.ts +5 -5
  32. package/types/index.d.ts +3 -3
  33. package/src/ITeckosClient.js +0 -2
  34. package/src/ITeckosClient.js.map +0 -1
  35. package/src/TeckosClient.js +0 -235
  36. package/src/TeckosClient.js.map +0 -1
  37. package/src/TeckosClientWithJWT.js +0 -63
  38. package/src/TeckosClientWithJWT.js.map +0 -1
  39. package/src/index.js +0 -8
  40. package/src/index.js.map +0 -1
  41. package/src/types/ConnectionState.js +0 -9
  42. package/src/types/ConnectionState.js.map +0 -1
  43. package/src/types/Options.js +0 -2
  44. package/src/types/Options.js.map +0 -1
  45. package/src/types/Packet.js +0 -2
  46. package/src/types/Packet.js.map +0 -1
  47. package/src/types/PacketType.js +0 -7
  48. package/src/types/PacketType.js.map +0 -1
  49. package/src/types/SocketEvent.js +0 -2
  50. package/src/types/SocketEvent.js.map +0 -1
  51. package/src/types/index.js +0 -4
  52. package/src/types/index.js.map +0 -1
  53. package/src/util/Converter.js +0 -6
  54. package/src/util/Converter.js.map +0 -1
  55. package/src/util/SocketEventEmitter.js +0 -99
  56. package/src/util/SocketEventEmitter.js.map +0 -1
@@ -0,0 +1,2 @@
1
+ "use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var n=e(require("debug")),t=e(require("isomorphic-ws"));function r(){return(r=Object.assign||function(e){for(var n=1;n<arguments.length;n++){var t=arguments[n];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])}return e}).apply(this,arguments)}function o(e,n){e.prototype=Object.create(n.prototype),e.prototype.constructor=e,(Object.setPrototypeOf||function(e,n){return e.__proto__=n,e})(e,n)}var i,c,s=new TextEncoder,a=new TextDecoder;(i=exports.PacketType||(exports.PacketType={}))[i.EVENT=0]="EVENT",i[i.ACK=1]="ACK",(c=exports.ConnectionState||(exports.ConnectionState={})).DISCONNECTED="disconnected",c.CONNECTING="connecting",c.CONNECTED="connected",c.DISCONNECTING="disconnecting";var u=function(){var e=this;this.maxListeners=50,this.handlers={},this.addListener=function(n,t){if(Object.keys(e.handlers).length===e.maxListeners)throw new Error("Max listeners reached");if("function"!=typeof t)throw new Error("The given listener is not a function");return e.handlers[n]=e.handlers[n]||[],e.handlers[n].push(t),e},this.once=function(n,t){if(Object.keys(e.handlers).length===e.maxListeners)throw new Error("Max listeners reached");if("function"!=typeof t)throw new Error("The given listener is not a function");return e.handlers[n]=e.handlers[n]||[],e.handlers[n].push((function r(){t(),e.off(n,r)})),e},this.removeListener=function(n,t){return e.handlers[n]&&(e.handlers[n]=e.handlers[n].filter((function(e){return e!==t}))),e},this.off=function(n,t){return e.removeListener(n,t)},this.removeAllListeners=function(n){return n?delete e.handlers[n]:e.handlers={},e},this.setMaxListeners=function(n){return e.maxListeners=n,e},this.getMaxListeners=function(){return e.maxListeners},this.listeners=function(n){return e.handlers[n]?[].concat(e.handlers[n]):[]},this.rawListeners=function(n){return[].concat(e.handlers[n])},this.listenerCount=function(n){return e.handlers[n]?Object.keys(e.handlers[n]).length:0},this.prependListener=function(n,t){if(Object.keys(e.handlers).length===e.maxListeners)throw new Error("Max listeners reached");return e.handlers[n]=e.handlers[n]||[],e.handlers[n].unshift(t),e},this.prependOnceListener=function(n,t){if(Object.keys(e.handlers).length===e.maxListeners)throw new Error("Max listeners reached");return e.handlers[n]=e.handlers[n]||[],e.handlers[n].unshift((function r(){t(),e.off(n,r)})),e},this.eventNames=function(){return Object.keys(e.handlers)},this.on=function(n,t){return e.addListener(n,t)},this.emit=function(n){for(var t=arguments.length,r=new Array(t>1?t-1:0),o=1;o<t;o++)r[o-1]=arguments[o];var i=e.listeners(n);return i.length>0&&(i.forEach((function(e){e&&e(r)})),!0)}},l=n("teckos:client"),d={reconnection:!0,reconnectionDelay:1e3,reconnectionDelayMax:5e3,reconnectionAttempts:Infinity,randomizationFactor:.5,timeout:5e3,debug:!1},f=function(e){function n(n,o){var i;return(i=e.call(this)||this).currentReconnectionAttempts=0,i.acks=new Map,i.fnId=0,i.attachHandler=function(){i.ws&&(i.ws.onopen=i.handleOpen,i.ws.onerror=i.handleError,i.ws.onclose=i.handleClose,i.ws.onmessage=i.handleMessage)},i.connect=function(){i.options.debug&&l("Connecting to "+i.url+"..."),i.ws=new t(i.url),i.attachHandler(),i.connectionTimeout=setTimeout((function(){i.ws&&i.ws.readyState===t.CONNECTING&&i.ws.close()}),i.options.timeout)},i.reconnect=function(){i.listeners("reconnect_attempt").forEach((function(e){return e()})),i.connect()},i.emit=function(e){for(var n=arguments.length,t=new Array(n>1?n-1:0),r=1;r<n;r++)t[r-1]=arguments[r];t.unshift(e);var o={type:exports.PacketType.EVENT,data:t};return"function"==typeof t[t.length-1]&&(i.acks.set(i.fnId,t.pop()),o.id=i.fnId,i.fnId+=1),i.sendPackage(o)},i.send=function(){for(var e=arguments.length,n=new Array(e),t=0;t<e;t++)n[t]=arguments[t];return n.unshift("message"),i.sendPackage({type:exports.PacketType.EVENT,data:n})},i.sendPackage=function(e){if(void 0!==i.ws&&i.ws.readyState===t.OPEN){var n=function(e){return s.encode(JSON.stringify(e))}(e);return i.options.debug&&l("["+i.url+"] Send packet: "+JSON.stringify(e)),i.ws.send(n),!0}return!1},i.handleMessage=function(e){var n="string"==typeof e.data?JSON.parse(e.data):JSON.parse(a.decode(e.data).toString());if(i.options.debug&&l("["+i.url+"] Got packet: "+JSON.stringify(n)),n.type===exports.PacketType.EVENT){var t=n.data[0],r=n.data.slice(1);if(!t)throw new Error("[teckos-client@"+i.url+"] Got invalid event message: "+JSON.stringify(e.data));i.listeners(t).forEach((function(e){return e.apply(void 0,r)}))}else{if(n.type!==exports.PacketType.ACK||void 0===n.id)throw new Error("[teckos-client@"+i.url+"] Got invalid message type: "+n.type);var o=i.acks.get(n.id);"function"==typeof o&&(o.apply(function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(i),n.data),i.acks.delete(n.id))}},i.handleOpen=function(){i.currentReconnectionAttempts>0&&(i.currentReconnectDelay=i.options.reconnectionDelay,i.currentReconnectionAttempts=0,i.options.debug&&l("["+i.url+"] Reconnected!"),i.listeners("reconnect").forEach((function(e){return e()}))),i.options.debug&&l("["+i.url+"] Connected!"),i.listeners("connect").forEach((function(e){return e()}))},i.handleError=function(e){i.handlers&&i.handlers.error&&(i.options.debug&&l("["+i.url+"] Got error from server: "+JSON.stringify(e)),i.handlers.error.forEach((function(n){return n(e)})))},i.handleClose=function(){if(i.connectionTimeout&&clearTimeout(i.connectionTimeout),i.reconnectionTimeout&&clearTimeout(i.reconnectionTimeout),i.currentReconnectionAttempts>0?(i.options.debug&&l("["+i.url+"] Reconnect #"+i.currentReconnectionAttempts+" failed!"),i.listeners("reconnect_error").forEach((function(e){e&&e()}))):(i.options.debug&&l("["+i.url+"] Disconnected!"),i.listeners("disconnect").forEach((function(e){e&&e()}))),i.options.reconnection)if(i.currentReconnectionAttempts+=1,Infinity===i.options.reconnectionAttempts||i.currentReconnectionAttempts<=i.options.reconnectionAttempts){var e=Math.min(i.options.reconnectionDelayMax,i.currentReconnectDelay);i.currentReconnectDelay=Math.round(i.currentReconnectDelay+i.currentReconnectDelay*i.options.randomizationFactor),i.options.debug&&l("["+i.url+"] Try reconnecting ("+i.currentReconnectionAttempts+"/"+i.options.reconnectionAttempts+") in "+e+"ms to "+i.url+"..."),i.reconnectionTimeout=setTimeout((function(){i.reconnect()}),e)}else i.options.debug&&l("["+i.url+"] Reconnection maximum of "+i.options.reconnectionAttempts+" reached"),i.listeners("reconnect_failed").forEach((function(e){return e()}))},i.close=function(){i.options.debug&&l("["+i.url+"] Closing connection (client-side)"),void 0!==i.ws&&(i.ws.onclose=function(){},i.ws.close(),i.listeners("disconnect").forEach((function(e){return e()})))},i.disconnect=function(){i.close()},i.options=r({},d,o),i.currentReconnectDelay=i.options.reconnectionDelay,i.url=n,i}var i;return o(n,e),n.prototype.getConnectionState=function(){if(this.ws)switch(this.ws.readyState){case t.OPEN:return exports.ConnectionState.CONNECTED;case t.CONNECTING:return exports.ConnectionState.CONNECTING;case t.CLOSING:return exports.ConnectionState.DISCONNECTING;default:return exports.ConnectionState.DISCONNECTED}return exports.ConnectionState.DISCONNECTED},(i=[{key:"webSocket",get:function(){return this.ws}},{key:"state",get:function(){return this.getConnectionState()}},{key:"connected",get:function(){return this.getConnectionState()===exports.ConnectionState.CONNECTED}},{key:"disconnected",get:function(){return this.getConnectionState()===exports.ConnectionState.DISCONNECTED}}])&&function(e,n){for(var t=0;t<n.length;t++){var r=n[t];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}(n.prototype,i),n}(u),h=n("teckos:client"),p=function(e){function n(n,t,o,i){var c;return(c=e.call(this,n,t)||this).receivedReady=!1,c.handleReadyEvent=function(){c.options.debug&&h("["+c.url+"] Connected!"),c.receivedReady=!0,c.currentReconnectionAttempts>0&&(c.options.debug&&h("["+c.url+"] Reconnected!"),c.listeners("reconnect").forEach((function(e){return e()})),c.currentReconnectDelay=c.options.reconnectionDelay,c.currentReconnectionAttempts=0),c.listeners("connect").forEach((function(e){return e()}))},c.handleOpen=function(){c.receivedReady=!1,c.once("ready",c.handleReadyEvent),c.options.debug&&h("Connection opened, sending token now"),c.emit("token",r({token:c.token},c.initialData))},c.token=o,c.initialData=i,c.on("disconnect",(function(){c.receivedReady=!1})),c}return o(n,e),n.prototype.getConnectionState=function(){if(this.ws)switch(this.ws.readyState){case t.OPEN:return this.receivedReady?exports.ConnectionState.CONNECTED:exports.ConnectionState.CONNECTING;case t.CONNECTING:return exports.ConnectionState.CONNECTING;case t.CLOSING:return exports.ConnectionState.DISCONNECTING;default:return exports.ConnectionState.DISCONNECTED}return exports.ConnectionState.DISCONNECTED},n}(f);exports.TeckosClient=f,exports.TeckosClientWithJWT=p;
2
+ //# sourceMappingURL=teckos-client.cjs.production.min.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"teckos-client.cjs.production.min.js","sources":["../src/util/Converter.ts","../src/types/PacketType.ts","../src/types/ConnectionState.ts","../src/util/SocketEventEmitter.ts","../src/TeckosClient.ts","../src/TeckosClientWithJWT.ts"],"sourcesContent":["import { Packet } from '../types'\n\nconst enc = new TextEncoder()\nconst dec = new TextDecoder()\n\nconst encodePacket = (packet: Packet): ArrayBufferLike => enc.encode(JSON.stringify(packet))\nconst decodePacket = (buffer: ArrayBuffer): Packet =>\n JSON.parse(dec.decode(buffer).toString()) as Packet\nexport { encodePacket, decodePacket }\n","enum PacketType {\n EVENT,\n ACK,\n}\nexport { PacketType }\n","enum ConnectionState {\n DISCONNECTED = 'disconnected',\n CONNECTING = 'connecting',\n CONNECTED = 'connected',\n DISCONNECTING = 'disconnecting',\n}\nexport { ConnectionState }\n","export type Listener = (...args: any[]) => void\n\nclass SocketEventEmitter<T extends string> {\n protected maxListeners = 50\n\n protected handlers: {\n [event: string]: ((...args: any[]) => void)[]\n } = {}\n\n public addListener = (event: T, listener: (...args: any[]) => void): this => {\n if (Object.keys(this.handlers).length === this.maxListeners) {\n throw new Error('Max listeners reached')\n }\n if (typeof listener !== 'function') {\n throw new Error('The given listener is not a function')\n }\n this.handlers[event] = this.handlers[event] || []\n this.handlers[event].push(listener)\n return this\n }\n\n public once = (event: T, listener: (...args: any[]) => void): this => {\n if (Object.keys(this.handlers).length === this.maxListeners) {\n throw new Error('Max listeners reached')\n }\n if (typeof listener !== 'function') {\n throw new Error('The given listener is not a function')\n }\n this.handlers[event] = this.handlers[event] || []\n const onceWrapper = () => {\n listener()\n this.off(event, onceWrapper)\n }\n this.handlers[event].push(onceWrapper)\n return this\n }\n\n public removeListener = (event: T, listener: (...args: any[]) => void): this => {\n if (this.handlers[event]) {\n this.handlers[event] = this.handlers[event].filter((handler) => handler !== listener)\n }\n return this\n }\n\n public off = (event: T, listener: (...args: any[]) => void): this =>\n this.removeListener(event, listener)\n\n public removeAllListeners = (event?: T): this => {\n if (event) {\n delete this.handlers[event]\n } else {\n this.handlers = {}\n }\n return this\n }\n\n public setMaxListeners = (n: number): this => {\n this.maxListeners = n\n return this\n }\n\n public getMaxListeners = (): number => this.maxListeners\n\n public listeners = (event: T): Listener[] => {\n if (this.handlers[event]) {\n return [...this.handlers[event]]\n }\n return []\n }\n\n public rawListeners = (event: T): Listener[] => [...this.handlers[event]]\n\n public listenerCount = (event: T): number => {\n if (this.handlers[event]) {\n return Object.keys(this.handlers[event]).length\n }\n return 0\n }\n\n public prependListener = (event: T, listener: (...args: any[]) => void): this => {\n if (Object.keys(this.handlers).length === this.maxListeners) {\n throw new Error('Max listeners reached')\n }\n this.handlers[event] = this.handlers[event] || []\n this.handlers[event].unshift(listener)\n return this\n }\n\n public prependOnceListener = (event: T, listener: (...args: any[]) => void): this => {\n if (Object.keys(this.handlers).length === this.maxListeners) {\n throw new Error('Max listeners reached')\n }\n this.handlers[event] = this.handlers[event] || []\n const onceWrapper = () => {\n listener()\n this.off(event, onceWrapper)\n }\n this.handlers[event].unshift(onceWrapper)\n return this\n }\n\n public eventNames = (): T[] => Object.keys(this.handlers) as T[]\n\n public on = (event: T, listener: (...args: any[]) => void): this =>\n this.addListener(event, listener)\n\n public emit = (event: T, ...args: any[]): boolean => {\n const listeners = this.listeners(event)\n if (listeners.length > 0) {\n listeners.forEach((listener) => {\n if (listener) listener(args)\n })\n return true\n }\n return false\n }\n}\n\nexport { SocketEventEmitter }\n","import debug from 'debug'\nimport WebSocket from 'isomorphic-ws'\nimport { decodePacket, encodePacket } from './util/Converter'\nimport { ConnectionState, OptionalOptions, Options, Packet, PacketType, SocketEvent } from './types'\nimport { ITeckosClient } from './ITeckosClient'\nimport { SocketEventEmitter } from './util/SocketEventEmitter'\n\nconst d = debug('teckos:client')\n\nconst DEFAULT_OPTIONS: Options = {\n reconnection: true,\n reconnectionDelay: 1000,\n reconnectionDelayMax: 5000,\n reconnectionAttempts: Infinity,\n randomizationFactor: 0.5,\n timeout: 5000,\n debug: false,\n}\n\nclass TeckosClient extends SocketEventEmitter<SocketEvent> implements ITeckosClient {\n protected readonly url: string\n\n protected readonly options: Options\n\n ws: WebSocket | undefined\n\n protected currentReconnectDelay: number\n\n protected currentReconnectionAttempts = 0\n\n protected acks: Map<number, (...args: any[]) => void> = new Map()\n\n protected fnId = 0\n\n protected connectionTimeout: any | undefined\n\n protected reconnectionTimeout: any | undefined\n\n constructor(url: string, options?: OptionalOptions) {\n super()\n this.options = {\n ...DEFAULT_OPTIONS,\n ...options,\n }\n this.currentReconnectDelay = this.options.reconnectionDelay\n this.url = url\n }\n\n protected attachHandler = (): void => {\n if (this.ws) {\n this.ws.onopen = this.handleOpen\n this.ws.onerror = this.handleError\n this.ws.onclose = this.handleClose\n this.ws.onmessage = this.handleMessage\n }\n }\n\n public get webSocket(): WebSocket | undefined {\n return this.ws\n }\n\n public connect = (): void => {\n if (this.options.debug) d(`Connecting to ${this.url}...`)\n\n // This will try to connect immediately\n this.ws = new WebSocket(this.url)\n // Attach handlers\n this.attachHandler()\n // Handle timeout\n this.connectionTimeout = setTimeout(() => {\n if (this.ws && this.ws.readyState === WebSocket.CONNECTING) {\n this.ws.close()\n }\n }, this.options.timeout)\n }\n\n protected reconnect = (): void => {\n this.listeners('reconnect_attempt').forEach((listener) => listener())\n this.connect()\n }\n\n protected getConnectionState(): ConnectionState {\n if (this.ws) {\n switch (this.ws.readyState) {\n case WebSocket.OPEN:\n return ConnectionState.CONNECTED\n case WebSocket.CONNECTING:\n return ConnectionState.CONNECTING\n case WebSocket.CLOSING:\n return ConnectionState.DISCONNECTING\n default:\n return ConnectionState.DISCONNECTED\n }\n }\n return ConnectionState.DISCONNECTED\n }\n\n public get state(): ConnectionState {\n return this.getConnectionState()\n }\n\n get connected(): boolean {\n return this.getConnectionState() === ConnectionState.CONNECTED\n }\n\n get disconnected(): boolean {\n return this.getConnectionState() === ConnectionState.DISCONNECTED\n }\n\n public emit = (event: SocketEvent, ...args: any[]): boolean => {\n args.unshift(event)\n\n const packet: Packet = {\n type: PacketType.EVENT,\n data: args,\n }\n\n if (typeof args[args.length - 1] === 'function') {\n this.acks.set(this.fnId, args.pop())\n packet.id = this.fnId\n this.fnId += 1\n }\n\n return this.sendPackage(packet)\n }\n\n public send = (...args: any[]): boolean => {\n args.unshift('message')\n return this.sendPackage({\n type: PacketType.EVENT,\n data: args,\n })\n }\n\n public sendPackage = (packet: Packet): boolean => {\n if (this.ws !== undefined && this.ws.readyState === WebSocket.OPEN) {\n const buffer = encodePacket(packet)\n if (this.options.debug) d(`[${this.url}] Send packet: ${JSON.stringify(packet)}`)\n this.ws.send(buffer)\n return true\n }\n return false\n }\n\n protected handleMessage = (msg: WebSocket.MessageEvent): void => {\n const packet =\n typeof msg.data === 'string'\n ? (JSON.parse(msg.data) as Packet)\n : decodePacket(msg.data as ArrayBuffer)\n if (this.options.debug) d(`[${this.url}] Got packet: ${JSON.stringify(packet)}`)\n if (packet.type === PacketType.EVENT) {\n const event = packet.data[0] as SocketEvent\n const args = packet.data.slice(1)\n if (event) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n this.listeners(event).forEach((listener) => listener(...args))\n } else {\n throw new Error(\n `[teckos-client@${this.url}] Got invalid event message: ${JSON.stringify(\n msg.data\n )}`\n )\n }\n } else if (packet.type === PacketType.ACK && packet.id !== undefined) {\n // Call assigned function\n const ack = this.acks.get(packet.id)\n if (typeof ack === 'function') {\n ack.apply(this, packet.data)\n this.acks.delete(packet.id)\n }\n } else {\n throw new Error(`[teckos-client@${this.url}] Got invalid message type: ${packet.type}`)\n }\n }\n\n protected handleOpen = (): void => {\n if (this.currentReconnectionAttempts > 0) {\n // Reset reconnection settings to default\n this.currentReconnectDelay = this.options.reconnectionDelay\n this.currentReconnectionAttempts = 0\n\n // Inform listeners\n if (this.options.debug) d(`[${this.url}] Reconnected!`)\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n this.listeners('reconnect').forEach((listener) => listener())\n }\n // Inform listeners\n if (this.options.debug) d(`[${this.url}] Connected!`)\n this.listeners('connect').forEach((listener) => listener())\n }\n\n protected handleError = (error: WebSocket.ErrorEvent): void => {\n if (this.handlers && this.handlers.error) {\n if (this.options.debug)\n d(`[${this.url}] Got error from server: ${JSON.stringify(error)}`)\n this.handlers.error.forEach((listener) => listener(error))\n }\n }\n\n protected handleClose = (): void => {\n // Stop connection timeout\n if (this.connectionTimeout) {\n clearTimeout(this.connectionTimeout)\n }\n // Stop reconnection timeout\n if (this.reconnectionTimeout) {\n clearTimeout(this.reconnectionTimeout)\n }\n\n // Inform listeners\n if (this.currentReconnectionAttempts > 0) {\n if (this.options.debug)\n d(`[${this.url}] Reconnect #${this.currentReconnectionAttempts} failed!`)\n this.listeners('reconnect_error').forEach((listener) => {\n if (listener) listener()\n })\n } else {\n if (this.options.debug) d(`[${this.url}] Disconnected!`)\n this.listeners('disconnect').forEach((listener) => {\n if (listener) listener()\n })\n }\n\n if (this.options.reconnection) {\n // Apply reconnection logic\n this.currentReconnectionAttempts += 1\n\n if (\n this.options.reconnectionAttempts === Infinity ||\n this.currentReconnectionAttempts <= this.options.reconnectionAttempts\n ) {\n const timeout = Math.min(\n this.options.reconnectionDelayMax,\n this.currentReconnectDelay\n )\n // Increase reconnection delay\n this.currentReconnectDelay = Math.round(\n this.currentReconnectDelay +\n this.currentReconnectDelay * this.options.randomizationFactor\n )\n\n if (this.options.debug)\n d(\n `[${this.url}] Try reconnecting (${this.currentReconnectionAttempts}/${this.options.reconnectionAttempts}) in ${timeout}ms to ${this.url}...`\n )\n this.reconnectionTimeout = setTimeout(() => {\n this.reconnect()\n }, timeout)\n } else {\n if (this.options.debug)\n d(\n `[${this.url}] Reconnection maximum of ${this.options.reconnectionAttempts} reached`\n )\n this.listeners('reconnect_failed').forEach((listener) => listener())\n }\n }\n }\n\n public close = (): void => {\n if (this.options.debug) d(`[${this.url}] Closing connection (client-side)`)\n if (this.ws !== undefined) {\n this.ws.onclose = () => {}\n this.ws.close()\n this.listeners('disconnect').forEach((listener) => listener())\n }\n }\n\n public disconnect = (): void => {\n this.close()\n }\n}\n\nexport { TeckosClient }\n","import debug from 'debug'\nimport WebSocket from 'isomorphic-ws'\nimport { TeckosClient } from './TeckosClient'\nimport { OptionalOptions, ConnectionState } from './types'\n\nconst d = debug('teckos:client')\n\nclass TeckosClientWithJWT extends TeckosClient {\n protected readonly token: string\n\n protected readonly initialData: any\n\n protected receivedReady = false\n\n // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\n constructor(url: string, options: OptionalOptions, token: string, initialData?: any) {\n super(url, options)\n this.token = token\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n this.initialData = initialData\n this.on('disconnect', () => {\n this.receivedReady = false\n })\n }\n\n protected getConnectionState(): ConnectionState {\n if (this.ws) {\n switch (this.ws.readyState) {\n case WebSocket.OPEN:\n if (this.receivedReady) {\n return ConnectionState.CONNECTED\n }\n return ConnectionState.CONNECTING\n case WebSocket.CONNECTING:\n return ConnectionState.CONNECTING\n case WebSocket.CLOSING:\n return ConnectionState.DISCONNECTING\n default:\n return ConnectionState.DISCONNECTED\n }\n }\n return ConnectionState.DISCONNECTED\n }\n\n protected handleReadyEvent = (): void => {\n if (this.options.debug) d(`[${this.url}] Connected!`)\n this.receivedReady = true\n if (this.currentReconnectionAttempts > 0) {\n if (this.options.debug) d(`[${this.url}] Reconnected!`)\n this.listeners('reconnect').forEach((listener) => listener())\n // Reset reconnection settings to default\n this.currentReconnectDelay = this.options.reconnectionDelay\n this.currentReconnectionAttempts = 0\n }\n this.listeners('connect').forEach((listener) => listener())\n }\n\n protected handleOpen = (): void => {\n this.receivedReady = false\n this.once('ready', this.handleReadyEvent)\n if (this.options.debug) d('Connection opened, sending token now')\n this.emit('token', {\n token: this.token,\n ...this.initialData,\n })\n }\n}\n\nexport { TeckosClientWithJWT }\n"],"names":["PacketType","ConnectionState","enc","TextEncoder","dec","TextDecoder","SocketEventEmitter","event","listener","Object","keys","_this","handlers","length","maxListeners","Error","push","onceWrapper","off","filter","handler","removeListener","n","unshift","addListener","args","listeners","forEach","d","debug","DEFAULT_OPTIONS","reconnection","reconnectionDelay","reconnectionDelayMax","reconnectionAttempts","Infinity","randomizationFactor","timeout","TeckosClient","url","options","Map","ws","onopen","handleOpen","onerror","handleError","onclose","handleClose","onmessage","handleMessage","WebSocket","attachHandler","connectionTimeout","setTimeout","readyState","CONNECTING","close","connect","packet","type","EVENT","data","acks","set","fnId","pop","id","sendPackage","undefined","OPEN","buffer","encode","JSON","stringify","encodePacket","send","msg","parse","decode","toString","slice","ACK","ack","get","apply","currentReconnectionAttempts","currentReconnectDelay","error","clearTimeout","reconnectionTimeout","Math","min","round","reconnect","getConnectionState","this","CONNECTED","CLOSING","DISCONNECTING","DISCONNECTED","TeckosClientWithJWT","token","initialData","receivedReady","once","handleReadyEvent","emit","on"],"mappings":"siBAEA,ICFKA,ECAAC,EFECC,EAAM,IAAIC,YACVC,EAAM,IAAIC,aCHXL,EAAAA,qBAAAA,2CAEDA,kBCFCC,EAAAA,0BAAAA,yDAEDA,0BACAA,wBACAA,oCCFEK,EAAN,wCAC6B,iBAIrB,oBAEiB,SAACC,EAAUC,MACxBC,OAAOC,KAAKC,EAAKC,UAAUC,SAAWF,EAAKG,mBACrC,IAAIC,MAAM,4BAEI,mBAAbP,QACD,IAAIO,MAAM,+CAEpBJ,EAAKC,SAASL,GAASI,EAAKC,SAASL,IAAU,GAC/CI,EAAKC,SAASL,GAAOS,KAAKR,GACnBG,aAGG,SAACJ,EAAUC,MACjBC,OAAOC,KAAKC,EAAKC,UAAUC,SAAWF,EAAKG,mBACrC,IAAIC,MAAM,4BAEI,mBAAbP,QACD,IAAIO,MAAM,+CAEpBJ,EAAKC,SAASL,GAASI,EAAKC,SAASL,IAAU,GAK/CI,EAAKC,SAASL,GAAOS,MAJD,SAAdC,IACFT,IACAG,EAAKO,IAAIX,EAAOU,MAGbN,uBAGa,SAACJ,EAAUC,UAC3BG,EAAKC,SAASL,KACdI,EAAKC,SAASL,GAASI,EAAKC,SAASL,GAAOY,QAAO,SAACC,UAAYA,IAAYZ,MAEzEG,YAGE,SAACJ,EAAUC,UACpBG,EAAKU,eAAed,EAAOC,4BAEH,SAACD,UACrBA,SACOI,EAAKC,SAASL,GAErBI,EAAKC,SAAW,GAEbD,wBAGc,SAACW,UACtBX,EAAKG,aAAeQ,EACbX,wBAGc,kBAAcA,EAAKG,6BAEzB,SAACP,UACZI,EAAKC,SAASL,aACHI,EAAKC,SAASL,IAEtB,sBAGW,SAACA,mBAA6BI,EAAKC,SAASL,wBAE3C,SAACA,UAChBI,EAAKC,SAASL,GACPE,OAAOC,KAAKC,EAAKC,SAAS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ElC5D,UAAU,WAAWC,SAAQ,SAACnB,UAAaA,qBAG7B,aACdgG,eAAgB,IAChBC,KAAK,QAAS9F,EAAK+F,kBACpB/F,EAAK6B,QAAQX,OAAOD,EAAE,0CACrB+E,KAAK,WACNL,MAAO3F,EAAK2F,OACT3F,EAAK4F,iBA9CPD,MAAQA,IAERC,YAAcA,IACdK,GAAG,cAAc,aACbJ,eAAgB,iCAInBT,mBAAA,cACFC,KAAKtD,UACGsD,KAAKtD,GAAGa,iBACPJ,EAAUmB,YACP0B,KAAKQ,cACEvG,wBAAgBgG,UAEpBhG,wBAAgBuD,gBACtBL,EAAUK,kBACJvD,wBAAgBuD,gBACtBL,EAAU+C,eACJjG,wBAAgBkG,6BAEhBlG,wBAAgBmG,oBAG5BnG,wBAAgBmG,iBAlCG9D"}
@@ -0,0 +1,608 @@
1
+ import debug from 'debug';
2
+ import WebSocket from 'isomorphic-ws';
3
+
4
+ function _defineProperties(target, props) {
5
+ for (var i = 0; i < props.length; i++) {
6
+ var descriptor = props[i];
7
+ descriptor.enumerable = descriptor.enumerable || false;
8
+ descriptor.configurable = true;
9
+ if ("value" in descriptor) descriptor.writable = true;
10
+ Object.defineProperty(target, descriptor.key, descriptor);
11
+ }
12
+ }
13
+
14
+ function _createClass(Constructor, protoProps, staticProps) {
15
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
16
+ if (staticProps) _defineProperties(Constructor, staticProps);
17
+ return Constructor;
18
+ }
19
+
20
+ function _extends() {
21
+ _extends = Object.assign || function (target) {
22
+ for (var i = 1; i < arguments.length; i++) {
23
+ var source = arguments[i];
24
+
25
+ for (var key in source) {
26
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
27
+ target[key] = source[key];
28
+ }
29
+ }
30
+ }
31
+
32
+ return target;
33
+ };
34
+
35
+ return _extends.apply(this, arguments);
36
+ }
37
+
38
+ function _inheritsLoose(subClass, superClass) {
39
+ subClass.prototype = Object.create(superClass.prototype);
40
+ subClass.prototype.constructor = subClass;
41
+
42
+ _setPrototypeOf(subClass, superClass);
43
+ }
44
+
45
+ function _setPrototypeOf(o, p) {
46
+ _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
47
+ o.__proto__ = p;
48
+ return o;
49
+ };
50
+
51
+ return _setPrototypeOf(o, p);
52
+ }
53
+
54
+ function _assertThisInitialized(self) {
55
+ if (self === void 0) {
56
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
57
+ }
58
+
59
+ return self;
60
+ }
61
+
62
+ var enc = /*#__PURE__*/new TextEncoder();
63
+ var dec = /*#__PURE__*/new TextDecoder();
64
+
65
+ var encodePacket = function encodePacket(packet) {
66
+ return enc.encode(JSON.stringify(packet));
67
+ };
68
+
69
+ var decodePacket = function decodePacket(buffer) {
70
+ return JSON.parse(dec.decode(buffer).toString());
71
+ };
72
+
73
+ var PacketType;
74
+
75
+ (function (PacketType) {
76
+ PacketType[PacketType["EVENT"] = 0] = "EVENT";
77
+ PacketType[PacketType["ACK"] = 1] = "ACK";
78
+ })(PacketType || (PacketType = {}));
79
+
80
+ var ConnectionState;
81
+
82
+ (function (ConnectionState) {
83
+ ConnectionState["DISCONNECTED"] = "disconnected";
84
+ ConnectionState["CONNECTING"] = "connecting";
85
+ ConnectionState["CONNECTED"] = "connected";
86
+ ConnectionState["DISCONNECTING"] = "disconnecting";
87
+ })(ConnectionState || (ConnectionState = {}));
88
+
89
+ var SocketEventEmitter = function SocketEventEmitter() {
90
+ var _this = this;
91
+
92
+ this.maxListeners = 50;
93
+ this.handlers = {};
94
+
95
+ this.addListener = function (event, listener) {
96
+ if (Object.keys(_this.handlers).length === _this.maxListeners) {
97
+ throw new Error('Max listeners reached');
98
+ }
99
+
100
+ if (typeof listener !== 'function') {
101
+ throw new Error('The given listener is not a function');
102
+ }
103
+
104
+ _this.handlers[event] = _this.handlers[event] || [];
105
+
106
+ _this.handlers[event].push(listener);
107
+
108
+ return _this;
109
+ };
110
+
111
+ this.once = function (event, listener) {
112
+ if (Object.keys(_this.handlers).length === _this.maxListeners) {
113
+ throw new Error('Max listeners reached');
114
+ }
115
+
116
+ if (typeof listener !== 'function') {
117
+ throw new Error('The given listener is not a function');
118
+ }
119
+
120
+ _this.handlers[event] = _this.handlers[event] || [];
121
+
122
+ var onceWrapper = function onceWrapper() {
123
+ listener();
124
+
125
+ _this.off(event, onceWrapper);
126
+ };
127
+
128
+ _this.handlers[event].push(onceWrapper);
129
+
130
+ return _this;
131
+ };
132
+
133
+ this.removeListener = function (event, listener) {
134
+ if (_this.handlers[event]) {
135
+ _this.handlers[event] = _this.handlers[event].filter(function (handler) {
136
+ return handler !== listener;
137
+ });
138
+ }
139
+
140
+ return _this;
141
+ };
142
+
143
+ this.off = function (event, listener) {
144
+ return _this.removeListener(event, listener);
145
+ };
146
+
147
+ this.removeAllListeners = function (event) {
148
+ if (event) {
149
+ delete _this.handlers[event];
150
+ } else {
151
+ _this.handlers = {};
152
+ }
153
+
154
+ return _this;
155
+ };
156
+
157
+ this.setMaxListeners = function (n) {
158
+ _this.maxListeners = n;
159
+ return _this;
160
+ };
161
+
162
+ this.getMaxListeners = function () {
163
+ return _this.maxListeners;
164
+ };
165
+
166
+ this.listeners = function (event) {
167
+ if (_this.handlers[event]) {
168
+ return [].concat(_this.handlers[event]);
169
+ }
170
+
171
+ return [];
172
+ };
173
+
174
+ this.rawListeners = function (event) {
175
+ return [].concat(_this.handlers[event]);
176
+ };
177
+
178
+ this.listenerCount = function (event) {
179
+ if (_this.handlers[event]) {
180
+ return Object.keys(_this.handlers[event]).length;
181
+ }
182
+
183
+ return 0;
184
+ };
185
+
186
+ this.prependListener = function (event, listener) {
187
+ if (Object.keys(_this.handlers).length === _this.maxListeners) {
188
+ throw new Error('Max listeners reached');
189
+ }
190
+
191
+ _this.handlers[event] = _this.handlers[event] || [];
192
+
193
+ _this.handlers[event].unshift(listener);
194
+
195
+ return _this;
196
+ };
197
+
198
+ this.prependOnceListener = function (event, listener) {
199
+ if (Object.keys(_this.handlers).length === _this.maxListeners) {
200
+ throw new Error('Max listeners reached');
201
+ }
202
+
203
+ _this.handlers[event] = _this.handlers[event] || [];
204
+
205
+ var onceWrapper = function onceWrapper() {
206
+ listener();
207
+
208
+ _this.off(event, onceWrapper);
209
+ };
210
+
211
+ _this.handlers[event].unshift(onceWrapper);
212
+
213
+ return _this;
214
+ };
215
+
216
+ this.eventNames = function () {
217
+ return Object.keys(_this.handlers);
218
+ };
219
+
220
+ this.on = function (event, listener) {
221
+ return _this.addListener(event, listener);
222
+ };
223
+
224
+ this.emit = function (event) {
225
+ for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
226
+ args[_key - 1] = arguments[_key];
227
+ }
228
+
229
+ var listeners = _this.listeners(event);
230
+
231
+ if (listeners.length > 0) {
232
+ listeners.forEach(function (listener) {
233
+ if (listener) listener(args);
234
+ });
235
+ return true;
236
+ }
237
+
238
+ return false;
239
+ };
240
+ };
241
+
242
+ var d = /*#__PURE__*/debug('teckos:client');
243
+ var DEFAULT_OPTIONS = {
244
+ reconnection: true,
245
+ reconnectionDelay: 1000,
246
+ reconnectionDelayMax: 5000,
247
+ reconnectionAttempts: Infinity,
248
+ randomizationFactor: 0.5,
249
+ timeout: 5000,
250
+ debug: false
251
+ };
252
+
253
+ var TeckosClient = /*#__PURE__*/function (_SocketEventEmitter) {
254
+ _inheritsLoose(TeckosClient, _SocketEventEmitter);
255
+
256
+ function TeckosClient(url, options) {
257
+ var _this;
258
+
259
+ _this = _SocketEventEmitter.call(this) || this;
260
+ _this.currentReconnectionAttempts = 0;
261
+ _this.acks = new Map();
262
+ _this.fnId = 0;
263
+
264
+ _this.attachHandler = function () {
265
+ if (_this.ws) {
266
+ _this.ws.onopen = _this.handleOpen;
267
+ _this.ws.onerror = _this.handleError;
268
+ _this.ws.onclose = _this.handleClose;
269
+ _this.ws.onmessage = _this.handleMessage;
270
+ }
271
+ };
272
+
273
+ _this.connect = function () {
274
+ if (_this.options.debug) d("Connecting to " + _this.url + "..."); // This will try to connect immediately
275
+
276
+ _this.ws = new WebSocket(_this.url); // Attach handlers
277
+
278
+ _this.attachHandler(); // Handle timeout
279
+
280
+
281
+ _this.connectionTimeout = setTimeout(function () {
282
+ if (_this.ws && _this.ws.readyState === WebSocket.CONNECTING) {
283
+ _this.ws.close();
284
+ }
285
+ }, _this.options.timeout);
286
+ };
287
+
288
+ _this.reconnect = function () {
289
+ _this.listeners('reconnect_attempt').forEach(function (listener) {
290
+ return listener();
291
+ });
292
+
293
+ _this.connect();
294
+ };
295
+
296
+ _this.emit = function (event) {
297
+ for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
298
+ args[_key - 1] = arguments[_key];
299
+ }
300
+
301
+ args.unshift(event);
302
+ var packet = {
303
+ type: PacketType.EVENT,
304
+ data: args
305
+ };
306
+
307
+ if (typeof args[args.length - 1] === 'function') {
308
+ _this.acks.set(_this.fnId, args.pop());
309
+
310
+ packet.id = _this.fnId;
311
+ _this.fnId += 1;
312
+ }
313
+
314
+ return _this.sendPackage(packet);
315
+ };
316
+
317
+ _this.send = function () {
318
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
319
+ args[_key2] = arguments[_key2];
320
+ }
321
+
322
+ args.unshift('message');
323
+ return _this.sendPackage({
324
+ type: PacketType.EVENT,
325
+ data: args
326
+ });
327
+ };
328
+
329
+ _this.sendPackage = function (packet) {
330
+ if (_this.ws !== undefined && _this.ws.readyState === WebSocket.OPEN) {
331
+ var buffer = encodePacket(packet);
332
+ if (_this.options.debug) d("[" + _this.url + "] Send packet: " + JSON.stringify(packet));
333
+
334
+ _this.ws.send(buffer);
335
+
336
+ return true;
337
+ }
338
+
339
+ return false;
340
+ };
341
+
342
+ _this.handleMessage = function (msg) {
343
+ var packet = typeof msg.data === 'string' ? JSON.parse(msg.data) : decodePacket(msg.data);
344
+ if (_this.options.debug) d("[" + _this.url + "] Got packet: " + JSON.stringify(packet));
345
+
346
+ if (packet.type === PacketType.EVENT) {
347
+ var event = packet.data[0];
348
+ var args = packet.data.slice(1);
349
+
350
+ if (event) {
351
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
352
+ _this.listeners(event).forEach(function (listener) {
353
+ return listener.apply(void 0, args);
354
+ });
355
+ } else {
356
+ throw new Error("[teckos-client@" + _this.url + "] Got invalid event message: " + JSON.stringify(msg.data));
357
+ }
358
+ } else if (packet.type === PacketType.ACK && packet.id !== undefined) {
359
+ // Call assigned function
360
+ var ack = _this.acks.get(packet.id);
361
+
362
+ if (typeof ack === 'function') {
363
+ ack.apply(_assertThisInitialized(_this), packet.data);
364
+
365
+ _this.acks["delete"](packet.id);
366
+ }
367
+ } else {
368
+ throw new Error("[teckos-client@" + _this.url + "] Got invalid message type: " + packet.type);
369
+ }
370
+ };
371
+
372
+ _this.handleOpen = function () {
373
+ if (_this.currentReconnectionAttempts > 0) {
374
+ // Reset reconnection settings to default
375
+ _this.currentReconnectDelay = _this.options.reconnectionDelay;
376
+ _this.currentReconnectionAttempts = 0; // Inform listeners
377
+
378
+ if (_this.options.debug) d("[" + _this.url + "] Reconnected!"); // eslint-disable-next-line @typescript-eslint/no-unsafe-return
379
+
380
+ _this.listeners('reconnect').forEach(function (listener) {
381
+ return listener();
382
+ });
383
+ } // Inform listeners
384
+
385
+
386
+ if (_this.options.debug) d("[" + _this.url + "] Connected!");
387
+
388
+ _this.listeners('connect').forEach(function (listener) {
389
+ return listener();
390
+ });
391
+ };
392
+
393
+ _this.handleError = function (error) {
394
+ if (_this.handlers && _this.handlers.error) {
395
+ if (_this.options.debug) d("[" + _this.url + "] Got error from server: " + JSON.stringify(error));
396
+
397
+ _this.handlers.error.forEach(function (listener) {
398
+ return listener(error);
399
+ });
400
+ }
401
+ };
402
+
403
+ _this.handleClose = function () {
404
+ // Stop connection timeout
405
+ if (_this.connectionTimeout) {
406
+ clearTimeout(_this.connectionTimeout);
407
+ } // Stop reconnection timeout
408
+
409
+
410
+ if (_this.reconnectionTimeout) {
411
+ clearTimeout(_this.reconnectionTimeout);
412
+ } // Inform listeners
413
+
414
+
415
+ if (_this.currentReconnectionAttempts > 0) {
416
+ if (_this.options.debug) d("[" + _this.url + "] Reconnect #" + _this.currentReconnectionAttempts + " failed!");
417
+
418
+ _this.listeners('reconnect_error').forEach(function (listener) {
419
+ if (listener) listener();
420
+ });
421
+ } else {
422
+ if (_this.options.debug) d("[" + _this.url + "] Disconnected!");
423
+
424
+ _this.listeners('disconnect').forEach(function (listener) {
425
+ if (listener) listener();
426
+ });
427
+ }
428
+
429
+ if (_this.options.reconnection) {
430
+ // Apply reconnection logic
431
+ _this.currentReconnectionAttempts += 1;
432
+
433
+ if (_this.options.reconnectionAttempts === Infinity || _this.currentReconnectionAttempts <= _this.options.reconnectionAttempts) {
434
+ var timeout = Math.min(_this.options.reconnectionDelayMax, _this.currentReconnectDelay); // Increase reconnection delay
435
+
436
+ _this.currentReconnectDelay = Math.round(_this.currentReconnectDelay + _this.currentReconnectDelay * _this.options.randomizationFactor);
437
+ if (_this.options.debug) d("[" + _this.url + "] Try reconnecting (" + _this.currentReconnectionAttempts + "/" + _this.options.reconnectionAttempts + ") in " + timeout + "ms to " + _this.url + "...");
438
+ _this.reconnectionTimeout = setTimeout(function () {
439
+ _this.reconnect();
440
+ }, timeout);
441
+ } else {
442
+ if (_this.options.debug) d("[" + _this.url + "] Reconnection maximum of " + _this.options.reconnectionAttempts + " reached");
443
+
444
+ _this.listeners('reconnect_failed').forEach(function (listener) {
445
+ return listener();
446
+ });
447
+ }
448
+ }
449
+ };
450
+
451
+ _this.close = function () {
452
+ if (_this.options.debug) d("[" + _this.url + "] Closing connection (client-side)");
453
+
454
+ if (_this.ws !== undefined) {
455
+ _this.ws.onclose = function () {};
456
+
457
+ _this.ws.close();
458
+
459
+ _this.listeners('disconnect').forEach(function (listener) {
460
+ return listener();
461
+ });
462
+ }
463
+ };
464
+
465
+ _this.disconnect = function () {
466
+ _this.close();
467
+ };
468
+
469
+ _this.options = _extends({}, DEFAULT_OPTIONS, options);
470
+ _this.currentReconnectDelay = _this.options.reconnectionDelay;
471
+ _this.url = url;
472
+ return _this;
473
+ }
474
+
475
+ var _proto = TeckosClient.prototype;
476
+
477
+ _proto.getConnectionState = function getConnectionState() {
478
+ if (this.ws) {
479
+ switch (this.ws.readyState) {
480
+ case WebSocket.OPEN:
481
+ return ConnectionState.CONNECTED;
482
+
483
+ case WebSocket.CONNECTING:
484
+ return ConnectionState.CONNECTING;
485
+
486
+ case WebSocket.CLOSING:
487
+ return ConnectionState.DISCONNECTING;
488
+
489
+ default:
490
+ return ConnectionState.DISCONNECTED;
491
+ }
492
+ }
493
+
494
+ return ConnectionState.DISCONNECTED;
495
+ };
496
+
497
+ _createClass(TeckosClient, [{
498
+ key: "webSocket",
499
+ get: function get() {
500
+ return this.ws;
501
+ }
502
+ }, {
503
+ key: "state",
504
+ get: function get() {
505
+ return this.getConnectionState();
506
+ }
507
+ }, {
508
+ key: "connected",
509
+ get: function get() {
510
+ return this.getConnectionState() === ConnectionState.CONNECTED;
511
+ }
512
+ }, {
513
+ key: "disconnected",
514
+ get: function get() {
515
+ return this.getConnectionState() === ConnectionState.DISCONNECTED;
516
+ }
517
+ }]);
518
+
519
+ return TeckosClient;
520
+ }(SocketEventEmitter);
521
+
522
+ var d$1 = /*#__PURE__*/debug('teckos:client');
523
+
524
+ var TeckosClientWithJWT = /*#__PURE__*/function (_TeckosClient) {
525
+ _inheritsLoose(TeckosClientWithJWT, _TeckosClient);
526
+
527
+ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
528
+ function TeckosClientWithJWT(url, options, token, initialData) {
529
+ var _this;
530
+
531
+ _this = _TeckosClient.call(this, url, options) || this;
532
+ _this.receivedReady = false;
533
+
534
+ _this.handleReadyEvent = function () {
535
+ if (_this.options.debug) d$1("[" + _this.url + "] Connected!");
536
+ _this.receivedReady = true;
537
+
538
+ if (_this.currentReconnectionAttempts > 0) {
539
+ if (_this.options.debug) d$1("[" + _this.url + "] Reconnected!");
540
+
541
+ _this.listeners('reconnect').forEach(function (listener) {
542
+ return listener();
543
+ }); // Reset reconnection settings to default
544
+
545
+
546
+ _this.currentReconnectDelay = _this.options.reconnectionDelay;
547
+ _this.currentReconnectionAttempts = 0;
548
+ }
549
+
550
+ _this.listeners('connect').forEach(function (listener) {
551
+ return listener();
552
+ });
553
+ };
554
+
555
+ _this.handleOpen = function () {
556
+ _this.receivedReady = false;
557
+
558
+ _this.once('ready', _this.handleReadyEvent);
559
+
560
+ if (_this.options.debug) d$1('Connection opened, sending token now');
561
+
562
+ _this.emit('token', _extends({
563
+ token: _this.token
564
+ }, _this.initialData));
565
+ };
566
+
567
+ _this.token = token; // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
568
+
569
+ _this.initialData = initialData;
570
+
571
+ _this.on('disconnect', function () {
572
+ _this.receivedReady = false;
573
+ });
574
+
575
+ return _this;
576
+ }
577
+
578
+ var _proto = TeckosClientWithJWT.prototype;
579
+
580
+ _proto.getConnectionState = function getConnectionState() {
581
+ if (this.ws) {
582
+ switch (this.ws.readyState) {
583
+ case WebSocket.OPEN:
584
+ if (this.receivedReady) {
585
+ return ConnectionState.CONNECTED;
586
+ }
587
+
588
+ return ConnectionState.CONNECTING;
589
+
590
+ case WebSocket.CONNECTING:
591
+ return ConnectionState.CONNECTING;
592
+
593
+ case WebSocket.CLOSING:
594
+ return ConnectionState.DISCONNECTING;
595
+
596
+ default:
597
+ return ConnectionState.DISCONNECTED;
598
+ }
599
+ }
600
+
601
+ return ConnectionState.DISCONNECTED;
602
+ };
603
+
604
+ return TeckosClientWithJWT;
605
+ }(TeckosClient);
606
+
607
+ export { ConnectionState, PacketType, TeckosClient, TeckosClientWithJWT };
608
+ //# sourceMappingURL=teckos-client.esm.js.map