teckos-client 0.2.3 → 0.3.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (55) hide show
  1. package/dist/index.js +456 -5
  2. package/dist/index.min.js +1 -0
  3. package/es/index.js +459 -0
  4. package/es/index.mjs +1 -0
  5. package/lib/index.js +484 -0
  6. package/package.json +63 -44
  7. package/src/ITeckosClient.js +2 -0
  8. package/src/ITeckosClient.js.map +1 -0
  9. package/src/ITeckosClient.ts +3 -3
  10. package/src/TeckosClient.js +235 -0
  11. package/src/TeckosClient.js.map +1 -0
  12. package/src/TeckosClient.ts +40 -32
  13. package/src/TeckosClientWithJWT.js +63 -0
  14. package/src/TeckosClientWithJWT.js.map +1 -0
  15. package/src/TeckosClientWithJWT.ts +8 -10
  16. package/src/index.js +8 -0
  17. package/src/index.js.map +1 -0
  18. package/src/index.ts +3 -3
  19. package/src/types/ConnectionState.js +9 -0
  20. package/src/types/ConnectionState.js.map +1 -0
  21. package/src/types/Options.js +2 -0
  22. package/src/types/Options.js.map +1 -0
  23. package/src/types/Packet.js +2 -0
  24. package/src/types/Packet.js.map +1 -0
  25. package/src/types/PacketType.js +7 -0
  26. package/src/types/PacketType.js.map +1 -0
  27. package/src/types/SocketEvent.js +2 -0
  28. package/src/types/SocketEvent.js.map +1 -0
  29. package/src/types/index.js +4 -0
  30. package/src/types/index.js.map +1 -0
  31. package/src/util/Converter.js +6 -0
  32. package/src/util/Converter.js.map +1 -0
  33. package/src/util/SocketEventEmitter.js +99 -0
  34. package/src/util/SocketEventEmitter.js.map +1 -0
  35. package/src/util/formatProdErrorMessage.ts +16 -0
  36. package/{dist → types}/ITeckosClient.d.ts +3 -3
  37. package/{dist → types}/TeckosClient.d.ts +6 -6
  38. package/{dist → types}/TeckosClientWithJWT.d.ts +0 -0
  39. package/types/index.d.ts +9 -0
  40. package/{dist → types}/types/ConnectionState.d.ts +0 -0
  41. package/{dist → types}/types/Options.d.ts +0 -0
  42. package/{dist → types}/types/Packet.d.ts +0 -0
  43. package/{dist → types}/types/PacketType.d.ts +0 -0
  44. package/{dist → types}/types/SocketEvent.d.ts +0 -0
  45. package/{dist → types}/types/index.d.ts +0 -0
  46. package/{dist → types}/util/Converter.d.ts +0 -0
  47. package/{dist → types}/util/SocketEventEmitter.d.ts +1 -1
  48. package/types/util/formatProdErrorMessage.d.ts +9 -0
  49. package/dist/index.d.ts +0 -9
  50. package/dist/teckos-client.cjs.development.js +0 -614
  51. package/dist/teckos-client.cjs.development.js.map +0 -1
  52. package/dist/teckos-client.cjs.production.min.js +0 -2
  53. package/dist/teckos-client.cjs.production.min.js.map +0 -1
  54. package/dist/teckos-client.esm.js +0 -611
  55. package/dist/teckos-client.esm.js.map +0 -1
@@ -1,2 +0,0 @@
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
@@ -1 +0,0 @@
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\n\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 // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\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-argument\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 // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n clearTimeout(this.connectionTimeout)\n }\n // Stop reconnection timeout\n if (this.reconnectionTimeout) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\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,S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8B,IAC/B3E,EAAK6B,QAAQX,OAAOD,MAAMjB,EAAK4B,wBAC9Bb,UAAU,aAAaC,SAAQ,SAACnB,UAAaA,SAE7C+E,sBAAwB5E,EAAK6B,QAAQR,oBACrCsD,4BAA8B,KAElC5D,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"}
@@ -1,611 +0,0 @@
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
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
309
- _this.acks.set(_this.fnId, args.pop());
310
-
311
- packet.id = _this.fnId;
312
- _this.fnId += 1;
313
- }
314
-
315
- return _this.sendPackage(packet);
316
- };
317
-
318
- _this.send = function () {
319
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
320
- args[_key2] = arguments[_key2];
321
- }
322
-
323
- args.unshift('message');
324
- return _this.sendPackage({
325
- type: PacketType.EVENT,
326
- data: args
327
- });
328
- };
329
-
330
- _this.sendPackage = function (packet) {
331
- if (_this.ws !== undefined && _this.ws.readyState === WebSocket.OPEN) {
332
- var buffer = encodePacket(packet);
333
- if (_this.options.debug) d("[" + _this.url + "] Send packet: " + JSON.stringify(packet));
334
-
335
- _this.ws.send(buffer);
336
-
337
- return true;
338
- }
339
-
340
- return false;
341
- };
342
-
343
- _this.handleMessage = function (msg) {
344
- var packet = typeof msg.data === 'string' ? JSON.parse(msg.data) : decodePacket(msg.data);
345
- if (_this.options.debug) d("[" + _this.url + "] Got packet: " + JSON.stringify(packet));
346
-
347
- if (packet.type === PacketType.EVENT) {
348
- var event = packet.data[0];
349
- var args = packet.data.slice(1);
350
-
351
- if (event) {
352
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
353
- _this.listeners(event).forEach(function (listener) {
354
- return listener.apply(void 0, args);
355
- });
356
- } else {
357
- throw new Error("[teckos-client@" + _this.url + "] Got invalid event message: " + JSON.stringify(msg.data));
358
- }
359
- } else if (packet.type === PacketType.ACK && packet.id !== undefined) {
360
- // Call assigned function
361
- var ack = _this.acks.get(packet.id);
362
-
363
- if (typeof ack === 'function') {
364
- ack.apply(_assertThisInitialized(_this), packet.data);
365
-
366
- _this.acks["delete"](packet.id);
367
- }
368
- } else {
369
- throw new Error("[teckos-client@" + _this.url + "] Got invalid message type: " + packet.type);
370
- }
371
- };
372
-
373
- _this.handleOpen = function () {
374
- if (_this.currentReconnectionAttempts > 0) {
375
- // Reset reconnection settings to default
376
- _this.currentReconnectDelay = _this.options.reconnectionDelay;
377
- _this.currentReconnectionAttempts = 0; // Inform listeners
378
-
379
- if (_this.options.debug) d("[" + _this.url + "] Reconnected!"); // eslint-disable-next-line @typescript-eslint/no-unsafe-return
380
-
381
- _this.listeners('reconnect').forEach(function (listener) {
382
- return listener();
383
- });
384
- } // Inform listeners
385
-
386
-
387
- if (_this.options.debug) d("[" + _this.url + "] Connected!");
388
-
389
- _this.listeners('connect').forEach(function (listener) {
390
- return listener();
391
- });
392
- };
393
-
394
- _this.handleError = function (error) {
395
- if (_this.handlers && _this.handlers.error) {
396
- if (_this.options.debug) d("[" + _this.url + "] Got error from server: " + JSON.stringify(error));
397
-
398
- _this.handlers.error.forEach(function (listener) {
399
- return listener(error);
400
- });
401
- }
402
- };
403
-
404
- _this.handleClose = function () {
405
- // Stop connection timeout
406
- if (_this.connectionTimeout) {
407
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
408
- clearTimeout(_this.connectionTimeout);
409
- } // Stop reconnection timeout
410
-
411
-
412
- if (_this.reconnectionTimeout) {
413
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
414
- clearTimeout(_this.reconnectionTimeout);
415
- } // Inform listeners
416
-
417
-
418
- if (_this.currentReconnectionAttempts > 0) {
419
- if (_this.options.debug) d("[" + _this.url + "] Reconnect #" + _this.currentReconnectionAttempts + " failed!");
420
-
421
- _this.listeners('reconnect_error').forEach(function (listener) {
422
- if (listener) listener();
423
- });
424
- } else {
425
- if (_this.options.debug) d("[" + _this.url + "] Disconnected!");
426
-
427
- _this.listeners('disconnect').forEach(function (listener) {
428
- if (listener) listener();
429
- });
430
- }
431
-
432
- if (_this.options.reconnection) {
433
- // Apply reconnection logic
434
- _this.currentReconnectionAttempts += 1;
435
-
436
- if (_this.options.reconnectionAttempts === Infinity || _this.currentReconnectionAttempts <= _this.options.reconnectionAttempts) {
437
- var timeout = Math.min(_this.options.reconnectionDelayMax, _this.currentReconnectDelay); // Increase reconnection delay
438
-
439
- _this.currentReconnectDelay = Math.round(_this.currentReconnectDelay + _this.currentReconnectDelay * _this.options.randomizationFactor);
440
- if (_this.options.debug) d("[" + _this.url + "] Try reconnecting (" + _this.currentReconnectionAttempts + "/" + _this.options.reconnectionAttempts + ") in " + timeout + "ms to " + _this.url + "...");
441
- _this.reconnectionTimeout = setTimeout(function () {
442
- _this.reconnect();
443
- }, timeout);
444
- } else {
445
- if (_this.options.debug) d("[" + _this.url + "] Reconnection maximum of " + _this.options.reconnectionAttempts + " reached");
446
-
447
- _this.listeners('reconnect_failed').forEach(function (listener) {
448
- return listener();
449
- });
450
- }
451
- }
452
- };
453
-
454
- _this.close = function () {
455
- if (_this.options.debug) d("[" + _this.url + "] Closing connection (client-side)");
456
-
457
- if (_this.ws !== undefined) {
458
- _this.ws.onclose = function () {};
459
-
460
- _this.ws.close();
461
-
462
- _this.listeners('disconnect').forEach(function (listener) {
463
- return listener();
464
- });
465
- }
466
- };
467
-
468
- _this.disconnect = function () {
469
- _this.close();
470
- };
471
-
472
- _this.options = _extends({}, DEFAULT_OPTIONS, options);
473
- _this.currentReconnectDelay = _this.options.reconnectionDelay;
474
- _this.url = url;
475
- return _this;
476
- }
477
-
478
- var _proto = TeckosClient.prototype;
479
-
480
- _proto.getConnectionState = function getConnectionState() {
481
- if (this.ws) {
482
- switch (this.ws.readyState) {
483
- case WebSocket.OPEN:
484
- return ConnectionState.CONNECTED;
485
-
486
- case WebSocket.CONNECTING:
487
- return ConnectionState.CONNECTING;
488
-
489
- case WebSocket.CLOSING:
490
- return ConnectionState.DISCONNECTING;
491
-
492
- default:
493
- return ConnectionState.DISCONNECTED;
494
- }
495
- }
496
-
497
- return ConnectionState.DISCONNECTED;
498
- };
499
-
500
- _createClass(TeckosClient, [{
501
- key: "webSocket",
502
- get: function get() {
503
- return this.ws;
504
- }
505
- }, {
506
- key: "state",
507
- get: function get() {
508
- return this.getConnectionState();
509
- }
510
- }, {
511
- key: "connected",
512
- get: function get() {
513
- return this.getConnectionState() === ConnectionState.CONNECTED;
514
- }
515
- }, {
516
- key: "disconnected",
517
- get: function get() {
518
- return this.getConnectionState() === ConnectionState.DISCONNECTED;
519
- }
520
- }]);
521
-
522
- return TeckosClient;
523
- }(SocketEventEmitter);
524
-
525
- var d$1 = /*#__PURE__*/debug('teckos:client');
526
-
527
- var TeckosClientWithJWT = /*#__PURE__*/function (_TeckosClient) {
528
- _inheritsLoose(TeckosClientWithJWT, _TeckosClient);
529
-
530
- // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
531
- function TeckosClientWithJWT(url, options, token, initialData) {
532
- var _this;
533
-
534
- _this = _TeckosClient.call(this, url, options) || this;
535
- _this.receivedReady = false;
536
-
537
- _this.handleReadyEvent = function () {
538
- if (_this.options.debug) d$1("[" + _this.url + "] Connected!");
539
- _this.receivedReady = true;
540
-
541
- if (_this.currentReconnectionAttempts > 0) {
542
- if (_this.options.debug) d$1("[" + _this.url + "] Reconnected!");
543
-
544
- _this.listeners('reconnect').forEach(function (listener) {
545
- return listener();
546
- }); // Reset reconnection settings to default
547
-
548
-
549
- _this.currentReconnectDelay = _this.options.reconnectionDelay;
550
- _this.currentReconnectionAttempts = 0;
551
- }
552
-
553
- _this.listeners('connect').forEach(function (listener) {
554
- return listener();
555
- });
556
- };
557
-
558
- _this.handleOpen = function () {
559
- _this.receivedReady = false;
560
-
561
- _this.once('ready', _this.handleReadyEvent);
562
-
563
- if (_this.options.debug) d$1('Connection opened, sending token now');
564
-
565
- _this.emit('token', _extends({
566
- token: _this.token
567
- }, _this.initialData));
568
- };
569
-
570
- _this.token = token; // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
571
-
572
- _this.initialData = initialData;
573
-
574
- _this.on('disconnect', function () {
575
- _this.receivedReady = false;
576
- });
577
-
578
- return _this;
579
- }
580
-
581
- var _proto = TeckosClientWithJWT.prototype;
582
-
583
- _proto.getConnectionState = function getConnectionState() {
584
- if (this.ws) {
585
- switch (this.ws.readyState) {
586
- case WebSocket.OPEN:
587
- if (this.receivedReady) {
588
- return ConnectionState.CONNECTED;
589
- }
590
-
591
- return ConnectionState.CONNECTING;
592
-
593
- case WebSocket.CONNECTING:
594
- return ConnectionState.CONNECTING;
595
-
596
- case WebSocket.CLOSING:
597
- return ConnectionState.DISCONNECTING;
598
-
599
- default:
600
- return ConnectionState.DISCONNECTED;
601
- }
602
- }
603
-
604
- return ConnectionState.DISCONNECTED;
605
- };
606
-
607
- return TeckosClientWithJWT;
608
- }(TeckosClient);
609
-
610
- export { ConnectionState, PacketType, TeckosClient, TeckosClientWithJWT };
611
- //# sourceMappingURL=teckos-client.esm.js.map