topgun-socket
Advanced tools
Comparing version 1.1.10 to 1.1.11
@@ -80,3 +80,3 @@ import { A as AuthToken, C as CodecEngine, E as EventObject, a as EventObjectCallback, b as AsyncStreamEmitter, T as TGChannelClient, S as SocketProtocolIgnoreStatuses, c as SocketProtocolErrorStatuses, d as TGChannel, D as DemuxedConsumableStream, e as ConsumerStats, f as ChannelState } from './channel-f08c2f18.js'; | ||
authTokenName?: string | undefined; | ||
binaryType?: string | undefined; | ||
binaryType?: string | undefined | BinaryType; | ||
cloneData?: boolean | undefined; | ||
@@ -397,21 +397,5 @@ autoSubscribeOnConnect?: boolean | undefined; | ||
/** | ||
* WebSocket constructor. | ||
* | ||
* The third `opts` options object gets ignored in web browsers, since it's | ||
* non-standard, and throws a TypeError if passed to the constructor. | ||
* See: https://github.com/einaros/ws/issues/227 | ||
* | ||
* @param {String} uri | ||
* @param {Array} protocols (optional) | ||
* @api public | ||
*/ | ||
declare function ws(uri: string, protocols?: string[]): WebSocket; | ||
declare namespace ws { | ||
var prototype: any; | ||
} | ||
declare const version = "1.0.0"; | ||
declare function create(options: ClientOptions): TGClientSocket; | ||
export { AuthEngine, AuthStates, AuthStatus, AutoReconnectOptions, CallIdGenerator, ClientOptions, InvokeOptions, KickOutData, OnCloseValue, OnErrorValue, OnEventValue, OnInboundInvokeValue, OnInboundTransmitValue, OnOpenAbortValue, OnOpenValue, ProtocolVersions, SignedAuthToken, States, SubscribeFailData, SubscribeOptions, TGAuthEngine, TGClientSocket, TGTransport, TransmitOptions, TransportHandlers, create, version, ws }; | ||
export { AuthEngine, AuthStates, AuthStatus, AutoReconnectOptions, CallIdGenerator, ClientOptions, InvokeOptions, KickOutData, OnCloseValue, OnErrorValue, OnEventValue, OnInboundInvokeValue, OnInboundTransmitValue, OnOpenAbortValue, OnOpenValue, ProtocolVersions, SignedAuthToken, States, SubscribeFailData, SubscribeOptions, TGAuthEngine, TGClientSocket, TGTransport, TransmitOptions, TransportHandlers, create, version }; |
@@ -1,1 +0,1 @@ | ||
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunk2WJ4JSQRjs = require('./chunk-2WJ4JSQR.js');var _chunkZARTXZMYjs = require('./chunk-ZARTXZMY.js');require('./chunk-S7SIMXGM.js');require('./chunk-XXDCE5O3.js');function F(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,a=>{let n=Math.random()*16|0;return(a==="x"?n:n&3|8).toString(16)})}var _2 = require('buffer/');function E(a,n){if(!n)return a;if(n[Symbol.iterator]){let e=n[Symbol.iterator](),t;for(;(t=e.next())&&!t.done;)a.append(t.value)}else{let e=-1;for(;++e<n.length;){let t=n[e];a.append(t)}}return a}var A=class{constructor(){this.next=null,this.prev=null,this.list=null}append(n){let e=this.list;if(!n||!n.append||!n.prepend||!n.detach)throw new Error("An argument without append, prepend, or detach methods was given to `Item#append`.");return!e||this===n?!1:(n.detach(),this.next&&(n.next=this.next,this.next.prev=n),n.prev=this,n.list=e,this.next=n,(this===e.tail||!e.tail)&&(e.tail=n),e.size++,n)}prepend(n){let e=this.list;if(!n||!n.append||!n.prepend||!n.detach)throw new Error("An argument without append, prepend, or detach methods was given to `Item#prepend`.");return!e||this===n?!1:(n.detach(),this.prev&&(n.prev=this.prev,this.prev.next=n),n.next=this,n.list=e,this.prev=n,this===e.head&&(e.head=n),e.tail||(e.tail=this),e.size++,n)}detach(){let n=this.list;return n?(n.tail===this&&(n.tail=this.prev),n.head===this&&(n.head=this.next),n.tail===n.head&&(n.tail=null),this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=null,this.next=null,this.list=null,n.size--,this):this}};var x=class{constructor(n){this.item=null;this.item=n}next(){let n=this.item;return n?(this.item=n.next,{value:n,done:!1}):{value:null,done:!0}}};var D=class{static from(n){let e=new this;return E(e,n)}static of(...n){let e=new this;return E(e,n)}constructor(...n){this.size=0,this.tail=null,this.head=null,E(this,n)}append(n){if(!n)return!1;if(!n.append||!n.prepend||!n.detach)throw new Error("An argument without append, prepend, or detach methods was given to `List#append`.");return this.tail?this.tail.append(n):this.head?this.head.append(n):(n.detach(),n.list=this,this.head=n,this.size++,n)}prepend(n){if(!n)return!1;if(!n.append||!n.prepend||!n.detach)throw new Error("An argument without append, prepend, or detach methods was given to `List#prepend`.");return this.head?this.head.prepend(n):(n.detach(),n.list=this,this.head=n,this.size++,n)}toArray(){let n=this.head,e=[];for(;n;)e.push(n),n=n.next;return e}[Symbol.iterator](){return new x(this.head)}};function O(a=0){return new Promise(n=>{setTimeout(()=>n(),a)})}var g=_chunk2WJ4JSQRjs.t.call(void 0, ),B= exports.AuthEngine =class{constructor(){this._internalStorage={},this.isLocalStorageEnabled=this._checkLocalStorageEnabled()}saveToken(n,e,t){return this.isLocalStorageEnabled&&g.localStorage?g.localStorage.setItem(n,e):this._internalStorage[n]=e,Promise.resolve(e)}removeToken(n){let e=this.loadToken(n);return this.isLocalStorageEnabled&&g.localStorage?g.localStorage.removeItem(n):delete this._internalStorage[n],e}loadToken(n){let e;return this.isLocalStorageEnabled&&g.localStorage?e=g.localStorage.getItem(n):e=this._internalStorage[n]||null,Promise.resolve(e)}_checkLocalStorageEnabled(){let n;try{g.localStorage,g.localStorage.setItem("__scLocalStorageTest",1),g.localStorage.removeItem("__scLocalStorageTest")}catch(e){n=e}return!n}};var _ws = require('ws'); var _ws2 = _interopRequireDefault(_ws);var q=_chunk2WJ4JSQRjs.t.call(void 0, ),I,L;_optionalChain([q, 'optionalAccess', _4 => _4.WebSocket])?(I=q.WebSocket,L=function(a,n){return new I(a)}):(I=_ws2.default,L=function(a,n){return new I(a,[],n)});var u=class{constructor(n,e,t,s,i){this.state=u.CLOSED,this.auth=n,this.codec=e,this.options=t,this.wsOptions=s,this.protocolVersion=t.protocolVersion,this.connectTimeout=t.connectTimeout,this.pingTimeout=t.pingTimeout,this.pingTimeoutDisabled=!!t.pingTimeoutDisabled,this.callIdGenerator=t.callIdGenerator,this.authTokenName=t.authTokenName,this.isBufferingBatch=!1,this._pingTimeoutTicker=null,this._callbackMap={},this._batchBuffer=[],i||(i={}),this._onOpenHandler=i.onOpen||function(){},this._onOpenAbortHandler=i.onOpenAbort||function(){},this._onCloseHandler=i.onClose||function(){},this._onEventHandler=i.onEvent||function(){},this._onErrorHandler=i.onError||function(){},this._onInboundInvokeHandler=i.onInboundInvoke||function(){},this._onInboundTransmitHandler=i.onInboundTransmit||function(){},this.state=u.CONNECTING;let r=this.uri(),o=L(r,s);o.binaryType=this.options.binaryType,this.socket=o,o.onopen=()=>{this._onOpen()},o.onclose=async l=>{let p;l.code==null?p=1005:p=l.code,this._destroy(p,l.reason)},o.onmessage=(l,p)=>{this._onMessage(l.data)},o.onerror=l=>{this.state===u.CONNECTING&&this._destroy(1006)},this._connectTimeoutRef=setTimeout(()=>{this._destroy(4007),this.socket.close(4007)},this.connectTimeout),this.protocolVersion===1?this._handlePing=l=>l==="#1"?(this._resetPingTimeout(),this.socket.readyState===this.socket.OPEN&&this.send("#2"),!0):!1:this._handlePing=l=>l===""?(this._resetPingTimeout(),this.socket.readyState===this.socket.OPEN&&this.send(""),!0):!1}uri(){let n=this.options.query||{},e;this.options.protocolScheme==null?e=this.options.secure?"wss":"ws":e=this.options.protocolScheme,this.options.timestampRequests&&(n[this.options.timestampParam]=new Date().getTime());let t=new URLSearchParams;for(let[r,o]of Object.entries(n))if(Array.isArray(o))for(let l of o)t.append(r,l);else t.set(r,`${o}`);n=t.toString(),n.length&&(n="?"+n);let s,i;if(this.options.socketPath==null){if(this.options.host)s=this.options.host;else{let r="";this.options.port&&(e==="wss"&&this.options.port!==443||e==="ws"&&this.options.port!==80)&&(r=":"+this.options.port),s=this.options.hostname+r}i=this.options.path}else s=this.options.socketPath,i=`:${this.options.path}`;return e+"://"+s+i+n}clearAllListeners(){this._onOpenHandler=function(){},this._onOpenAbortHandler=function(){},this._onCloseHandler=function(){},this._onEventHandler=function(){},this._onErrorHandler=function(){},this._onInboundInvokeHandler=function(){},this._onInboundTransmitHandler=function(){}}startBatch(){this.isBufferingBatch=!0,this._batchBuffer=[]}flushBatch(){if(this.isBufferingBatch=!1,!this._batchBuffer.length)return;let n=this.serializeObject(this._batchBuffer);this._batchBuffer=[],this.send(n)}cancelBatch(){this.isBufferingBatch=!1,this._batchBuffer=[]}getBytesReceived(){return this.socket.bytesReceived}close(n,e){(this.state===u.OPEN||this.state===u.CONNECTING)&&(n=n||1e3,this._destroy(n,e),this.socket.close(n,e))}transmitObject(n){let e={event:n.event,data:n.data};return n.callback&&(e.cid=n.cid=this.callIdGenerator(),this._callbackMap[n.cid]=n),this.sendObject(e),n.cid||null}transmit(n,e,t){let s={event:n,data:e};return(this.state===u.OPEN||t.force)&&this.transmitObject(s),Promise.resolve()}invokeRaw(n,e,t,s){let i={event:n,data:e,callback:s};t.noTimeout||(i.timeout=setTimeout(()=>{this._handleEventAckTimeout(i)},this.options.ackTimeout));let r=null;return(this.state===u.OPEN||t.force)&&(r=this.transmitObject(i)),r}invoke(n,e,t){return new Promise((s,i)=>{this.invokeRaw(n,e,t,(r,o)=>{if(r){i(r);return}s(o)})})}cancelPendingResponse(n){delete this._callbackMap[n]}decode(n){return this.codec.decode(n)}encode(n){return this.codec.encode(n)}send(n){this.socket.readyState!==this.socket.OPEN?this._destroy(1005):this.socket.send(n)}serializeObject(n){let e;try{e=this.encode(n)}catch(t){return this._onError(t),null}return e}sendObject(n){if(this.isBufferingBatch){this._batchBuffer.push(n);return}let e=this.serializeObject(n);e!=null&&this.send(e)}_handleEventAckTimeout(n){n.cid&&delete this._callbackMap[n.cid],delete n.timeout;let e=n.callback;if(e){delete n.callback;let t=new (0, _chunk2WJ4JSQRjs.m)(`Event response for "${n.event}" timed out`);e.call(n,t,n)}}async _onOpen(){clearTimeout(this._connectTimeoutRef),this._resetPingTimeout();let n;try{n=await this._handshake()}catch(e){e.statusCode==null&&(e.statusCode=4003),this._onError(e),this._destroy(e.statusCode,e.toString()),this.socket.close(e.statusCode);return}this.state=u.OPEN,n&&(this.pingTimeout=n.pingTimeout),this._resetPingTimeout(),this._onOpenHandler(n)}async _handshake(){let n=await this.auth.loadToken(this.authTokenName),e={force:!0},t=await this.invoke("#handshake",{authToken:n},e);return t&&(t.authToken=n,t.authError&&(t.authError=_chunk2WJ4JSQRjs.s.call(void 0, t.authError))),t}_abortAllPendingEventsDueToBadConnection(n){Object.keys(this._callbackMap||{}).forEach(e=>{let t=this._callbackMap[e];delete this._callbackMap[e],clearTimeout(t.timeout),delete t.timeout;let s=`Event "${t.event}" was aborted due to a bad connection`,i=new (0, _chunk2WJ4JSQRjs.n)(s,n),r=t.callback;r&&(delete t.callback,r.call(t,i,t))})}_destroy(n,e){!e&&_chunk2WJ4JSQRjs.p[n]&&(e=_chunk2WJ4JSQRjs.p[n]),delete this.socket.onopen,delete this.socket.onclose,delete this.socket.onmessage,delete this.socket.onerror,clearTimeout(this._connectTimeoutRef),clearTimeout(this._pingTimeoutTicker),this.state===u.OPEN?(this.state=u.CLOSED,this._abortAllPendingEventsDueToBadConnection("disconnect"),this._onCloseHandler({code:n,reason:e})):this.state===u.CONNECTING?(this.state=u.CLOSED,this._abortAllPendingEventsDueToBadConnection("connectAbort"),this._onOpenAbortHandler({code:n,reason:e})):this.state===u.CLOSED&&this._abortAllPendingEventsDueToBadConnection("connectAbort")}_processInboundPacket(n,e){if(n&&n.event!=null)if(n.cid==null)this._onInboundTransmitHandler({...n});else{let t=new (0, _chunk2WJ4JSQRjs.y)(this,n.cid,n.event,n.data);this._onInboundInvokeHandler(t)}else if(n&&n.rid!=null){let t=this._callbackMap[n.rid];if(t&&(clearTimeout(t.timeout),delete t.timeout,delete this._callbackMap[n.rid],t.callback)){let s=_chunk2WJ4JSQRjs.s.call(void 0, n.error);t.callback(s,n.data)}}else this._onEventHandler({event:"raw",data:{message:e}})}_onMessage(n){if(this._onEventHandler({event:"message",data:{message:n}}),this._handlePing(n))return;let e=this.decode(n);if(Array.isArray(e)){let t=e.length;for(let s=0;s<t;s++)this._processInboundPacket(e[s],n)}else this._processInboundPacket(e,n)}_onError(n){this._onErrorHandler({error:n})}_resetPingTimeout(){this.pingTimeoutDisabled||(clearTimeout(this._pingTimeoutTicker),this._pingTimeoutTicker=setTimeout(()=>{this._destroy(4e3),this.socket.close(4e3)},this.pingTimeout))}},b= exports.TGTransport =u;b.CONNECTING="connecting",b.OPEN="open",b.CLOSED="closed";var X=typeof window<"u",P=_chunk2WJ4JSQRjs.t.call(void 0, ),h=class extends _chunk2WJ4JSQRjs.v{constructor(e){super();this._privateDataHandlerMap={"#publish":e=>{let t=this._undecorateChannelName(e.channel);this.isSubscribed(t,!0)&&this._channelDataDemux.write(t,e.data)},"#kickOut":e=>{let t=this._undecorateChannelName(e.channel),s=this._channelMap[t];s&&(this.emit("kickOut",{channel:t,message:e.message}),this._channelEventDemux.write(`${t}/kickOut`,{message:e.message}),this._triggerChannelUnsubscribe(s))},"#setAuthToken":e=>{e&&this._setAuthToken(e)},"#removeAuthToken":e=>{this._removeAuthToken()}};this._privateRPCHandlerMap={"#setAuthToken":(e,t)=>{e?(this._setAuthToken(e),t.end()):t.error(new (0, _chunk2WJ4JSQRjs.j)("No token data provided by #setAuthToken event"))},"#removeAuthToken":(e,t)=>{this._removeAuthToken(),t.end()}};let s=Object.assign({path:"/topgunsocket/",secure:!1,protocolScheme:null,socketPath:null,autoConnect:!0,autoReconnect:!0,autoSubscribeOnConnect:!0,connectTimeout:2e4,ackTimeout:1e4,timestampRequests:!1,timestampParam:"t",authTokenName:"topgunsocket.authToken",binaryType:"arraybuffer",batchOnHandshake:!1,batchOnHandshakeDuration:100,batchInterval:50,protocolVersion:2,wsOptions:{},cloneData:!1},e);this.id=null,this.version=s.version||null,this.protocolVersion=s.protocolVersion,this.state=h.CLOSED,this.authState=h.UNAUTHENTICATED,this.signedAuthToken=null,this.authToken=null,this.pendingReconnect=!1,this.pendingReconnectTimeout=null,this.preparingPendingSubscriptions=!1,this.clientId=s.clientId,this.wsOptions=s.wsOptions,this.connectTimeout=s.connectTimeout,this.ackTimeout=s.ackTimeout,this.channelPrefix=s.channelPrefix||null,this.disconnectOnUnload=s.disconnectOnUnload==null?!0:s.disconnectOnUnload,this.authTokenName=s.authTokenName,s.pingTimeout=s.connectTimeout,this.pingTimeout=s.pingTimeout,this.pingTimeoutDisabled=!!s.pingTimeoutDisabled;let i=Math.pow(2,31)-1,r=o=>{if(this[o]>i)throw new (0, _chunk2WJ4JSQRjs.h)(`The ${o} value provided exceeded the maximum amount allowed`)};if(r("connectTimeout"),r("ackTimeout"),r("pingTimeout"),this.connectAttempts=0,this.isBatching=!1,this.batchOnHandshake=s.batchOnHandshake,this.batchOnHandshakeDuration=s.batchOnHandshakeDuration,this._batchingIntervalId=null,this._outboundBuffer=new D,this._channelMap={},this._channelEventDemux=new _chunk2WJ4JSQRjs.u,this._channelDataDemux=new _chunk2WJ4JSQRjs.u,this._receiverDemux=new _chunk2WJ4JSQRjs.u,this._procedureDemux=new _chunk2WJ4JSQRjs.u,this.options=s,this._cid=1,this.options.callIdGenerator=()=>this._cid++,this.options.autoReconnect){this.options.autoReconnectOptions==null&&(this.options.autoReconnectOptions={});let o=this.options.autoReconnectOptions;o.initialDelay==null&&(o.initialDelay=1e4),o.randomness==null&&(o.randomness=1e4),o.multiplier==null&&(o.multiplier=1.5),o.maxDelay==null&&(o.maxDelay=6e4)}if(this.options.subscriptionRetryOptions==null&&(this.options.subscriptionRetryOptions={}),this.options.authEngine?this.auth=this.options.authEngine:this.auth=new B,this.options.codecEngine?this.codec=this.options.codecEngine:this.codec=_chunk2WJ4JSQRjs.w,this.options.protocol){let o=new (0, _chunk2WJ4JSQRjs.h)('The "protocol" option does not affect socketcluster-client - If you want to utilize SSL/TLS, use "secure" option instead');this._onError(o)}if(this.options.query=s.query||{},typeof this.options.query=="string"){let o=new URLSearchParams(this.options.query),l={};o.forEach((p,v)=>{let k=l[v];k==null?l[v]=p:(Array.isArray(k)||(l[v]=[k]),l[v].push(p))}),this.options.query=l}X&&this.disconnectOnUnload&&P.addEventListener&&P.removeEventListener&&this._handleBrowserUnload(),this.options.autoConnect&&this.connect()}get isBufferingBatch(){return this.transport.isBufferingBatch}getBackpressure(){return Math.max(this.getAllListenersBackpressure(),this.getAllReceiversBackpressure(),this.getAllProceduresBackpressure(),this.getAllChannelsBackpressure())}getState(){return this.state}getBytesReceived(){return this.transport.getBytesReceived()}async deauthenticate(){(async()=>{let e;try{e=await this.auth.removeToken(this.authTokenName)}catch(t){this._onError(t);return}this.emit("removeAuthToken",{oldAuthToken:e})})(),this.state!==h.CLOSED&&this.transmit("#removeAuthToken"),this._changeToUnauthenticatedStateAndClearTokens(),await O(0)}connect(){if(this.state===h.CLOSED){this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef),this.state=h.CONNECTING,this.emit("connecting",{}),this.transport&&this.transport.clearAllListeners();let e={onOpen:t=>{this.state=h.OPEN,this._onOpen(t)},onOpenAbort:t=>{this.state!==h.CLOSED&&(this.state=h.CLOSED,this._destroy(t.code,t.reason,!0))},onClose:t=>{this.state!==h.CLOSED&&(this.state=h.CLOSED,this._destroy(t.code,t.reason))},onEvent:t=>{this.emit(t.event,t.data)},onError:t=>{this._onError(t.error)},onInboundInvoke:t=>{this._onInboundInvoke(t)},onInboundTransmit:t=>{this._onInboundTransmit(t.event,t.data)}};this.transport=new b(this.auth,this.codec,this.options,this.wsOptions,e)}}reconnect(e,t){this.disconnect(e,t),this.connect()}disconnect(e,t){if(e=e||1e3,typeof e!="number")throw new (0, _chunk2WJ4JSQRjs.h)("If specified, the code argument must be a number");let s=this.state===h.CONNECTING;s||this.state===h.OPEN?(this.state=h.CLOSED,this._destroy(e,t,s),this.transport.close(e,t)):(this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef))}decodeBase64(e){return _2.Buffer.from(e,"base64").toString("utf8")}encodeBase64(e){return _2.Buffer.from(e,"utf8").toString("base64")}getAuthToken(){return this.authToken}getSignedAuthToken(){return this.signedAuthToken}async authenticate(e){let t;try{t=await this.invoke("#authenticate",e)}catch(s){throw s.name!=="BadConnectionError"&&s.name!=="TimeoutError"&&this._changeToUnauthenticatedStateAndClearTokens(),await O(0),s}return t&&t.isAuthenticated!=null?t.authError&&(t.authError=_chunk2WJ4JSQRjs.s.call(void 0, t.authError)):t={isAuthenticated:this.authState,authError:null},t.isAuthenticated?this._changeToAuthenticatedState(e):this._changeToUnauthenticatedStateAndClearTokens(),(async()=>{try{await this.auth.saveToken(this.authTokenName,e,{})}catch(s){this._onError(s)}})(),await O(0),t}decode(e){return this.transport.decode(e)}encode(e){return this.transport.encode(e)}send(e){this.transport.send(e)}transmit(e,t,s){return this._processOutboundEvent(e,t,s)}invoke(e,t,s){return this._processOutboundEvent(e,t,s,!0)}transmitPublish(e,t){let s={channel:this._decorateChannelName(e),data:t};return this.transmit("#publish",s)}invokePublish(e,t){let s={channel:this._decorateChannelName(e),data:t};return this.invoke("#publish",s)}startBatch(){this.transport.startBatch()}flushBatch(){this.transport.flushBatch()}cancelBatch(){this.transport.cancelBatch()}startBatching(){this.isBatching=!0,this._startBatching()}stopBatching(){this.isBatching=!1,this._stopBatching()}cancelBatching(){this.isBatching=!1,this._cancelBatching()}subscribe(e,t){t=t||{};let s=this._channelMap[e],i={waitForAuth:!!t.waitForAuth};return t.priority!=null&&(i.priority=t.priority),t.data!==void 0&&(i.data=t.data),s?t&&(s.options=i):(s={name:e,state:_chunkZARTXZMYjs.a.PENDING,options:i},this._channelMap[e]=s,this._trySubscribe(s)),new (0, _chunkZARTXZMYjs.a)(e,this,this._channelEventDemux,this._channelDataDemux)}async unsubscribe(e){let t=this._channelMap[e];t&&(this._triggerChannelUnsubscribe(t),this._tryUnsubscribe(t))}receiver(e){return this._receiverDemux.stream(e)}closeReceiver(e){this._receiverDemux.close(e)}closeAllReceivers(){this._receiverDemux.closeAll()}killReceiver(e){this._receiverDemux.kill(e)}killAllReceivers(){this._receiverDemux.killAll()}killReceiverConsumer(e){this._receiverDemux.killConsumer(e)}getReceiverConsumerStats(e){return this._receiverDemux.getConsumerStats(e)}getReceiverConsumerStatsList(e){return this._receiverDemux.getConsumerStatsList(e)}getAllReceiversConsumerStatsList(){return this._receiverDemux.getConsumerStatsListAll()}getReceiverBackpressure(e){return this._receiverDemux.getBackpressure(e)}getAllReceiversBackpressure(){return this._receiverDemux.getBackpressureAll()}getReceiverConsumerBackpressure(e){return this._receiverDemux.getConsumerBackpressure(e)}hasReceiverConsumer(e,t){return this._receiverDemux.hasConsumer(e,t)}hasAnyReceiverConsumer(e){return this._receiverDemux.hasConsumerAll(e)}procedure(e){return this._procedureDemux.stream(e)}closeProcedure(e){this._procedureDemux.close(e)}closeAllProcedures(){this._procedureDemux.closeAll()}killProcedure(e){this._procedureDemux.kill(e)}killAllProcedures(){this._procedureDemux.killAll()}killProcedureConsumer(e){this._procedureDemux.killConsumer(e)}getProcedureConsumerStats(e){return this._procedureDemux.getConsumerStats(e)}getProcedureConsumerStatsList(e){return this._procedureDemux.getConsumerStatsList(e)}getAllProceduresConsumerStatsList(){return this._procedureDemux.getConsumerStatsListAll()}getProcedureBackpressure(e){return this._procedureDemux.getBackpressure(e)}getAllProceduresBackpressure(){return this._procedureDemux.getBackpressureAll()}getProcedureConsumerBackpressure(e){return this._procedureDemux.getConsumerBackpressure(e)}hasProcedureConsumer(e,t){return this._procedureDemux.hasConsumer(e,t)}hasAnyProcedureConsumer(e){return this._procedureDemux.hasConsumerAll(e)}channel(e){return new (0, _chunkZARTXZMYjs.a)(e,this,this._channelEventDemux,this._channelDataDemux)}closeChannel(e){this.channelCloseOutput(e),this.channelCloseAllListeners(e)}closeAllChannelOutputs(){this._channelDataDemux.closeAll()}closeAllChannelListeners(){this._channelEventDemux.closeAll()}closeAllChannels(){this.closeAllChannelOutputs(),this.closeAllChannelListeners()}killChannel(e){this.channelKillOutput(e),this.channelKillAllListeners(e)}killAllChannelOutputs(){this._channelDataDemux.killAll()}killAllChannelListeners(){this._channelEventDemux.killAll()}killAllChannels(){this.killAllChannelOutputs(),this.killAllChannelListeners()}killChannelOutputConsumer(e){this._channelDataDemux.killConsumer(e)}killChannelListenerConsumer(e){this._channelEventDemux.killConsumer(e)}getChannelOutputConsumerStats(e){return this._channelDataDemux.getConsumerStats(e)}getChannelListenerConsumerStats(e){return this._channelEventDemux.getConsumerStats(e)}getAllChannelOutputsConsumerStatsList(){return this._channelDataDemux.getConsumerStatsListAll()}getAllChannelListenersConsumerStatsList(){return this._channelEventDemux.getConsumerStatsListAll()}getChannelBackpressure(e){return Math.max(this.channelGetOutputBackpressure(e),this.channelGetAllListenersBackpressure(e))}getAllChannelOutputsBackpressure(){return this._channelDataDemux.getBackpressureAll()}getAllChannelListenersBackpressure(){return this._channelEventDemux.getBackpressureAll()}getAllChannelsBackpressure(){return Math.max(this.getAllChannelOutputsBackpressure(),this.getAllChannelListenersBackpressure())}getChannelListenerConsumerBackpressure(e){return this._channelEventDemux.getConsumerBackpressure(e)}getChannelOutputConsumerBackpressure(e){return this._channelDataDemux.getConsumerBackpressure(e)}hasAnyChannelOutputConsumer(e){return this._channelDataDemux.hasConsumerAll(e)}hasAnyChannelListenerConsumer(e){return this._channelEventDemux.hasConsumerAll(e)}getChannelState(e){let t=this._channelMap[e];return t?t.state:_chunkZARTXZMYjs.a.UNSUBSCRIBED}getChannelOptions(e){let t=this._channelMap[e];return t?{...t.options}:{}}channelCloseOutput(e){this._channelDataDemux.close(e)}channelCloseListener(e,t){this._channelEventDemux.close(`${e}/${t}`)}channelCloseAllListeners(e){this._getAllChannelStreamNames(e).forEach(t=>{this._channelEventDemux.close(t)})}channelKillOutput(e){this._channelDataDemux.kill(e)}channelKillListener(e,t){this._channelEventDemux.kill(`${e}/${t}`)}channelKillAllListeners(e){this._getAllChannelStreamNames(e).forEach(t=>{this._channelEventDemux.kill(t)})}channelGetOutputConsumerStatsList(e){return this._channelDataDemux.getConsumerStatsList(e)}channelGetListenerConsumerStatsList(e,t){return this._channelEventDemux.getConsumerStatsList(`${e}/${t}`)}channelGetAllListenersConsumerStatsList(e){return this._getAllChannelStreamNames(e).map(t=>this._channelEventDemux.getConsumerStatsList(t)).reduce((t,s)=>(s.forEach(i=>{t.push(i)}),t),[])}channelGetOutputBackpressure(e){return this._channelDataDemux.getBackpressure(e)}channelGetListenerBackpressure(e,t){return this._channelEventDemux.getBackpressure(`${e}/${t}`)}channelGetAllListenersBackpressure(e){let t=this._getAllChannelStreamNames(e).map(s=>this._channelEventDemux.getBackpressure(s));return Math.max(...t.concat(0))}channelHasOutputConsumer(e,t){return this._channelDataDemux.hasConsumer(e,t)}channelHasListenerConsumer(e,t,s){return this._channelEventDemux.hasConsumer(`${e}/${t}`,s)}channelHasAnyListenerConsumer(e,t){return this._getAllChannelStreamNames(e).some(s=>this._channelEventDemux.hasConsumer(s,t))}subscriptions(e){let t=[];return Object.keys(this._channelMap).forEach(s=>{(e||this._channelMap[s].state===_chunkZARTXZMYjs.a.SUBSCRIBED)&&t.push(s)}),t}isSubscribed(e,t){let s=this._channelMap[e];return t?!!s:!!s&&s.state===_chunkZARTXZMYjs.a.SUBSCRIBED}processPendingSubscriptions(){this.preparingPendingSubscriptions=!1;let e=[];Object.keys(this._channelMap).forEach(t=>{let s=this._channelMap[t];s.state===_chunkZARTXZMYjs.a.PENDING&&e.push(s)}),e.sort((t,s)=>{let i=t.options.priority||0,r=s.options.priority||0;return i>r?-1:i<r?1:0}),e.forEach(t=>{this._trySubscribe(t)})}_getAllChannelStreamNames(e){let t=this._channelEventDemux.getConsumerStatsListAll().filter(s=>s.stream.indexOf(`${e}/`)===0).reduce((s,i)=>(s[i.stream]=!0,s),{});return Object.keys(t)}_tryUnsubscribe(e){if(this.state===h.OPEN){let t={noTimeout:!0};this._cancelPendingSubscribeCallback(e);let s=this._decorateChannelName(e.name);this.transport.transmit("#unsubscribe",s,t)}}_triggerChannelUnsubscribe(e,t){let s=e.name;if(this._cancelPendingSubscribeCallback(e),e.state===_chunkZARTXZMYjs.a.SUBSCRIBED){let i={oldChannelState:e.state,newChannelState:t?_chunkZARTXZMYjs.a.PENDING:_chunkZARTXZMYjs.a.UNSUBSCRIBED};this._channelEventDemux.write(`${s}/subscribeStateChange`,i),this._channelEventDemux.write(`${s}/unsubscribe`,{}),this.emit("subscribeStateChange",{channel:s,...i}),this.emit("unsubscribe",{channel:s})}t?e.state=_chunkZARTXZMYjs.a.PENDING:delete this._channelMap[s]}_trySubscribe(e){let t=!e.options.waitForAuth||this.authState===h.AUTHENTICATED;if(this.state===h.OPEN&&!this.preparingPendingSubscriptions&&e._pendingSubscriptionCid==null&&t){let s={noTimeout:!0},i={};e.options.waitForAuth&&(s.waitForAuth=!0,i.waitForAuth=s.waitForAuth),e.options.data&&(i.data=e.options.data),e._pendingSubscriptionCid=this.transport.invokeRaw("#subscribe",{channel:this._decorateChannelName(e.name),...i},s,r=>{if(r){if(r.name==="BadConnectionError")return;delete e._pendingSubscriptionCid,this._triggerChannelSubscribeFail(r,e,i)}else delete e._pendingSubscriptionCid,this._triggerChannelSubscribe(e,i)}),this.emit("subscribeRequest",{channel:e.name,subscriptionOptions:i})}}_cancelBatching(){this._batchingIntervalId!=null&&clearInterval(this._batchingIntervalId),this._batchingIntervalId=null,this.cancelBatch()}_stopBatching(){this._batchingIntervalId!=null&&clearInterval(this._batchingIntervalId),this._batchingIntervalId=null,this.flushBatch()}_startBatching(){this._batchingIntervalId==null&&(this.startBatch(),this._batchingIntervalId=setInterval(()=>{this.flushBatch(),this.startBatch()},this.options.batchInterval))}_undecorateChannelName(e){return this.channelPrefix&&e.indexOf(this.channelPrefix)===0?e.replace(this.channelPrefix,""):e}_decorateChannelName(e){return this.channelPrefix&&(e=this.channelPrefix+e),e}_cancelPendingSubscribeCallback(e){e._pendingSubscriptionCid!=null&&(this.transport.cancelPendingResponse(e._pendingSubscriptionCid),delete e._pendingSubscriptionCid)}_triggerChannelSubscribeFail(e,t,s){let i=t.name,r=!t.options.waitForAuth||this.authState===h.AUTHENTICATED;!!this._channelMap[i]&&r&&(delete this._channelMap[i],this._channelEventDemux.write(`${i}/subscribeFail`,{error:e,subscriptionOptions:s}),this.emit("subscribeFail",{error:e,channel:i,subscriptionOptions:s}))}_triggerChannelSubscribe(e,t){let s=e.name;if(e.state!==_chunkZARTXZMYjs.a.SUBSCRIBED){let i=e.state;e.state=_chunkZARTXZMYjs.a.SUBSCRIBED;let r={oldChannelState:i,newChannelState:e.state,subscriptionOptions:t};this._channelEventDemux.write(`${s}/subscribeStateChange`,r),this._channelEventDemux.write(`${s}/subscribe`,{subscriptionOptions:t}),this.emit("subscribeStateChange",{channel:s,...r}),this.emit("subscribe",{channel:s,subscriptionOptions:t})}}_processOutboundEvent(e,t,s,i){s=s||{},this.state===h.CLOSED&&this.connect();let r={event:e,data:null},o;i?o=new Promise((v,k)=>{r.callback=(R,J)=>{if(R){k(R);return}v(J)}}):o=Promise.resolve();let l=new A;this.options.cloneData?r.data=_chunk2WJ4JSQRjs.x.call(void 0, t):r.data=t,l.data=r;let p=s.ackTimeout==null?this.ackTimeout:s.ackTimeout;return r.timeout=setTimeout(()=>{this._handleEventAckTimeout(r,l)},p),this._outboundBuffer.append(l),this.state===h.OPEN&&this._flushOutboundBuffer(),o}_handleEventAckTimeout(e,t){t&&t.detach(),delete e.timeout;let s=e.callback;if(s){delete e.callback;let i=new (0, _chunk2WJ4JSQRjs.m)(`Event response for "${e.event}" timed out`);s.call(e,i,e)}e.cid&&this.transport.cancelPendingResponse(e.cid)}_flushOutboundBuffer(){let e=this._outboundBuffer.head,t;for(;e;){t=e.next;let s=e.data;e.detach(),this.transport.transmitObject(s),e=t}}_onInboundInvoke(e){let{procedure:t,data:s}=e,i=this._privateRPCHandlerMap[t];i?i.call(this,s,e):this._procedureDemux.write(t,e)}_onInboundTransmit(e,t){let s=this._privateDataHandlerMap[e];s?s.call(this,t):this._receiverDemux.write(e,t)}_destroy(e,t,s){if(this.id=null,this._cancelBatching(),this.transport&&this.transport.clearAllListeners(),this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef),this._suspendSubscriptions(),s?this.emit("connectAbort",{code:e,reason:t}):this.emit("disconnect",{code:e,reason:t}),this.emit("close",{code:e,reason:t}),!h.ignoreStatuses[e]){let i;t?i="Socket connection closed with status code "+e+" and reason: "+t:i="Socket connection closed with status code "+e;let r=new (0, _chunk2WJ4JSQRjs.k)(h.errorStatuses[e]||i,e);this._onError(r)}this._abortAllPendingEventsDueToBadConnection(s?"connectAbort":"disconnect"),this.options.autoReconnect&&(e===4e3||e===4001||e===1005?this._tryReconnect(0):e!==1e3&&e<4500&&this._tryReconnect())}_abortAllPendingEventsDueToBadConnection(e){let t=this._outboundBuffer.head,s;for(;t;){s=t.next;let i=t.data;clearTimeout(i.timeout),delete i.timeout,t.detach(),t=s;let r=i.callback;if(r){delete i.callback;let o=`Event "${i.event}" was aborted due to a bad connection`,l=new (0, _chunk2WJ4JSQRjs.n)(o,e);r.call(i,l,i)}i.cid&&this.transport.cancelPendingResponse(i.cid)}}_suspendSubscriptions(){Object.keys(this._channelMap).forEach(e=>{let t=this._channelMap[e];this._triggerChannelUnsubscribe(t,!0)})}_onError(e){this.emit("error",{error:e})}_tryReconnect(e){let t=this.connectAttempts++,s=this.options.autoReconnectOptions,i;if(e==null||t>0){let r=Math.round(s.initialDelay+(s.randomness||0)*Math.random());i=Math.round(r*Math.pow(s.multiplier,t))}else i=e;i>s.maxDelay&&(i=s.maxDelay),clearTimeout(this._reconnectTimeoutRef),this.pendingReconnect=!0,this.pendingReconnectTimeout=i,this._reconnectTimeoutRef=setTimeout(()=>{this.connect()},i)}_onOpen(e){this.isBatching?this._startBatching():this.batchOnHandshake&&(this._startBatching(),setTimeout(()=>{this.isBatching||this._stopBatching()},this.batchOnHandshakeDuration)),this.preparingPendingSubscriptions=!0,e?(this.id=e.id,this.pingTimeout=e.pingTimeout,e.isAuthenticated?this._changeToAuthenticatedState(e.authToken):this._changeToUnauthenticatedStateAndClearTokens()):this._changeToUnauthenticatedStateAndClearTokens(),this.connectAttempts=0,this.options.autoSubscribeOnConnect&&this.processPendingSubscriptions(),this.emit("connect",{...e,processPendingSubscriptions:()=>{this.processPendingSubscriptions()}}),this.state===h.OPEN&&this._flushOutboundBuffer()}_extractAuthTokenData(e){let s=(e||"").split(".")[1];if(s!=null){let i=s;try{return i=this.decodeBase64(i),JSON.parse(i)}catch (e2){return i}}return null}_changeToAuthenticatedState(e){if(this.signedAuthToken=e,this.authToken=this._extractAuthTokenData(e),this.authState!==h.AUTHENTICATED){let t=this.authState;this.authState=h.AUTHENTICATED;let s={oldAuthState:t,newAuthState:this.authState,signedAuthToken:e,authToken:this.authToken};this.preparingPendingSubscriptions||this.processPendingSubscriptions(),this.emit("authStateChange",s)}this.emit("authenticate",{signedAuthToken:e,authToken:this.authToken})}_changeToUnauthenticatedStateAndClearTokens(){if(this.authState!==h.UNAUTHENTICATED){let e=this.authState,t=this.authToken,s=this.signedAuthToken;this.authState=h.UNAUTHENTICATED,this.signedAuthToken=null,this.authToken=null;let i={oldAuthState:e,newAuthState:this.authState};this.emit("authStateChange",i),this.emit("deauthenticate",{oldSignedAuthToken:s,oldAuthToken:t})}}async _handleBrowserUnload(){let e=()=>{this.disconnect()},t=!1,s=()=>{t||(t=!0,P.addEventListener("beforeunload",e,!1))},i=()=>{t&&(t=!1,P.removeEventListener("beforeunload",e,!1))};(async()=>{let r=this.listener("connecting").createConsumer();for(;!(await r.next()).done;)s()})(),(async()=>{let r=this.listener("close").createConsumer();for(;!(await r.next()).done;)i()})()}_setAuthToken(e){this._changeToAuthenticatedState(e.token),(async()=>{try{await this.auth.saveToken(this.authTokenName,e.token,{})}catch(t){this._onError(t)}})()}_removeAuthToken(){(async()=>{let e;try{e=await this.auth.removeToken(this.authTokenName)}catch(t){this._onError(t);return}this.emit("removeAuthToken",{oldAuthToken:e})})(),this._changeToUnauthenticatedStateAndClearTokens()}},d= exports.TGClientSocket =h;d.CONNECTING="connecting",d.OPEN="open",d.CLOSED="closed",d.AUTHENTICATED="authenticated",d.UNAUTHENTICATED="unauthenticated",d.SUBSCRIBED="subscribed",d.PENDING="pending",d.UNSUBSCRIBED="unsubscribed",d.ignoreStatuses=_chunk2WJ4JSQRjs.q,d.errorStatuses=_chunk2WJ4JSQRjs.p;var N=_chunk2WJ4JSQRjs.t.call(void 0, );function Y(){return N.location&&location.protocol==="https:"}function Z(a,n){let e=a.secure==null?n:a.secure;return a.port||(N.location&&location.port?parseFloat(location.port):e?443:80)}function W(a){if(a=a||{},a.host&&!a.host.match(/[^:]+:\d{2,5}/))throw new (0, _chunk2WJ4JSQRjs.h)('The host option should include both the hostname and the port number in the format "hostname:port"');if(a.host&&a.hostname)throw new (0, _chunk2WJ4JSQRjs.h)('The host option should already include the hostname and the port number in the format "hostname:port" - Because of this, you should never use host and hostname options together');if(a.host&&a.port)throw new (0, _chunk2WJ4JSQRjs.h)('The host option should already include the hostname and the port number in the format "hostname:port" - Because of this, you should never use host and port options together');let n=Y(),e={clientId:F(),port:Z(a,n),hostname:N.location&&location.hostname||"localhost",secure:n};return Object.assign(e,a),new d(e)}var K=_chunk2WJ4JSQRjs.t.call(void 0, ),w=_optionalChain([K, 'optionalAccess', _5 => _5.WebSocket])||_optionalChain([K, 'optionalAccess', _6 => _6.MozWebSocket]);function ee(a,n){let e;return n?e=new w(a,n):e=new w(a),e}w&&(ee.prototype=w.prototype);var te="1.0.0";function We(a){return W({...a,version:te})}exports.AuthEngine = B; exports.TGClientSocket = d; exports.TGTransport = b; exports.create = We; exports.version = te; exports.ws = ee; | ||
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _chunk2WJ4JSQRjs = require('./chunk-2WJ4JSQR.js');var _chunkZARTXZMYjs = require('./chunk-ZARTXZMY.js');require('./chunk-S7SIMXGM.js');require('./chunk-XXDCE5O3.js');function V(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,a=>{let n=Math.random()*16|0;return(a==="x"?n:n&3|8).toString(16)})}var _2 = require('buffer/'); var _3 = _interopRequireDefault(_2);function E(a,n){if(!n)return a;if(n[Symbol.iterator]){let e=n[Symbol.iterator](),t;for(;(t=e.next())&&!t.done;)a.append(t.value)}else{let e=-1;for(;++e<n.length;){let t=n[e];a.append(t)}}return a}var A=class{constructor(){this.next=null,this.prev=null,this.list=null}append(n){let e=this.list;if(!n||!n.append||!n.prepend||!n.detach)throw new Error("An argument without append, prepend, or detach methods was given to `Item#append`.");return!e||this===n?!1:(n.detach(),this.next&&(n.next=this.next,this.next.prev=n),n.prev=this,n.list=e,this.next=n,(this===e.tail||!e.tail)&&(e.tail=n),e.size++,n)}prepend(n){let e=this.list;if(!n||!n.append||!n.prepend||!n.detach)throw new Error("An argument without append, prepend, or detach methods was given to `Item#prepend`.");return!e||this===n?!1:(n.detach(),this.prev&&(n.prev=this.prev,this.prev.next=n),n.next=this,n.list=e,this.prev=n,this===e.head&&(e.head=n),e.tail||(e.tail=this),e.size++,n)}detach(){let n=this.list;return n?(n.tail===this&&(n.tail=this.prev),n.head===this&&(n.head=this.next),n.tail===n.head&&(n.tail=null),this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=null,this.next=null,this.list=null,n.size--,this):this}};var x=class{constructor(n){this.item=null;this.item=n}next(){let n=this.item;return n?(this.item=n.next,{value:n,done:!1}):{value:null,done:!0}}};var D=class{static from(n){let e=new this;return E(e,n)}static of(...n){let e=new this;return E(e,n)}constructor(...n){this.size=0,this.tail=null,this.head=null,E(this,n)}append(n){if(!n)return!1;if(!n.append||!n.prepend||!n.detach)throw new Error("An argument without append, prepend, or detach methods was given to `List#append`.");return this.tail?this.tail.append(n):this.head?this.head.append(n):(n.detach(),n.list=this,this.head=n,this.size++,n)}prepend(n){if(!n)return!1;if(!n.append||!n.prepend||!n.detach)throw new Error("An argument without append, prepend, or detach methods was given to `List#prepend`.");return this.head?this.head.prepend(n):(n.detach(),n.list=this,this.head=n,this.size++,n)}toArray(){let n=this.head,e=[];for(;n;)e.push(n),n=n.next;return e}[Symbol.iterator](){return new x(this.head)}};function O(a=0){return new Promise(n=>{setTimeout(()=>n(),a)})}var p=_chunk2WJ4JSQRjs.t.call(void 0, ),B= exports.AuthEngine =class{constructor(){this._internalStorage={},this.isLocalStorageEnabled=this._checkLocalStorageEnabled()}saveToken(n,e,t){return this.isLocalStorageEnabled&&p.localStorage?p.localStorage.setItem(n,e):this._internalStorage[n]=e,Promise.resolve(e)}removeToken(n){let e=this.loadToken(n);return this.isLocalStorageEnabled&&p.localStorage?p.localStorage.removeItem(n):delete this._internalStorage[n],e}loadToken(n){let e;return this.isLocalStorageEnabled&&p.localStorage?e=p.localStorage.getItem(n):e=this._internalStorage[n]||null,Promise.resolve(e)}_checkLocalStorageEnabled(){let n;try{p.localStorage,p.localStorage.setItem("__scLocalStorageTest",1),p.localStorage.removeItem("__scLocalStorageTest")}catch(e){n=e}return!n}};var _ws = require('ws'); var _ws2 = _interopRequireDefault(_ws);function $(a){return typeof a=="function"}function j(a,n){let e=_chunk2WJ4JSQRjs.t.call(void 0, );return e&&$(e.WebSocket)?new e.WebSocket(a):new (0, _ws2.default)(a,[],n)}var u=class{constructor(n,e,t,s,i){this.state=u.CLOSED,this.auth=n,this.codec=e,this.options=t,this.wsOptions=s,this.protocolVersion=t.protocolVersion,this.connectTimeout=t.connectTimeout,this.pingTimeout=t.pingTimeout,this.pingTimeoutDisabled=!!t.pingTimeoutDisabled,this.callIdGenerator=t.callIdGenerator,this.authTokenName=t.authTokenName,this.isBufferingBatch=!1,this._pingTimeoutTicker=null,this._callbackMap={},this._batchBuffer=[],i||(i={}),this._onOpenHandler=i.onOpen||function(){},this._onOpenAbortHandler=i.onOpenAbort||function(){},this._onCloseHandler=i.onClose||function(){},this._onEventHandler=i.onEvent||function(){},this._onErrorHandler=i.onError||function(){},this._onInboundInvokeHandler=i.onInboundInvoke||function(){},this._onInboundTransmitHandler=i.onInboundTransmit||function(){},this.state=u.CONNECTING;let r=this.uri(),o=j(r,s);o.binaryType=this.options.binaryType,this.socket=o,o.onopen=()=>{this._onOpen()},o.onclose=async l=>{let m;l.code==null?m=1005:m=l.code,this._destroy(m,l.reason)},o.onmessage=(l,m)=>{this._onMessage(l.data)},o.onerror=()=>{this.state===u.CONNECTING&&this._destroy(1006)},this._connectTimeoutRef=setTimeout(()=>{this._destroy(4007),this.socket.close(4007)},this.connectTimeout),this.protocolVersion===1?this._handlePing=l=>l==="#1"?(this._resetPingTimeout(),this.socket.readyState===this.socket.OPEN&&this.send("#2"),!0):!1:this._handlePing=l=>l===""?(this._resetPingTimeout(),this.socket.readyState===this.socket.OPEN&&this.send(""),!0):!1}uri(){let n=this.options.query||{},e;this.options.protocolScheme==null?e=this.options.secure?"wss":"ws":e=this.options.protocolScheme,this.options.timestampRequests&&(n[this.options.timestampParam]=new Date().getTime());let t=new URLSearchParams;for(let[r,o]of Object.entries(n))if(Array.isArray(o))for(let l of o)t.append(r,l);else t.set(r,`${o}`);n=t.toString(),n.length&&(n="?"+n);let s,i;if(this.options.socketPath==null){if(this.options.host)s=this.options.host;else{let r="";this.options.port&&(e==="wss"&&this.options.port!==443||e==="ws"&&this.options.port!==80)&&(r=":"+this.options.port),s=this.options.hostname+r}i=this.options.path}else s=this.options.socketPath,i=`:${this.options.path}`;return e+"://"+s+i+n}clearAllListeners(){this._onOpenHandler=function(){},this._onOpenAbortHandler=function(){},this._onCloseHandler=function(){},this._onEventHandler=function(){},this._onErrorHandler=function(){},this._onInboundInvokeHandler=function(){},this._onInboundTransmitHandler=function(){}}startBatch(){this.isBufferingBatch=!0,this._batchBuffer=[]}flushBatch(){if(this.isBufferingBatch=!1,!this._batchBuffer.length)return;let n=this.serializeObject(this._batchBuffer);this._batchBuffer=[],this.send(n)}cancelBatch(){this.isBufferingBatch=!1,this._batchBuffer=[]}getBytesReceived(){return this.socket.bytesReceived}close(n,e){(this.state===u.OPEN||this.state===u.CONNECTING)&&(n=n||1e3,this._destroy(n,e),this.socket.close(n,e))}transmitObject(n){let e={event:n.event,data:n.data};return n.callback&&(e.cid=n.cid=this.callIdGenerator(),this._callbackMap[n.cid]=n),this.sendObject(e),n.cid||null}transmit(n,e,t){let s={event:n,data:e};return(this.state===u.OPEN||t.force)&&this.transmitObject(s),Promise.resolve()}invokeRaw(n,e,t,s){let i={event:n,data:e,callback:s};t.noTimeout||(i.timeout=setTimeout(()=>{this._handleEventAckTimeout(i)},this.options.ackTimeout));let r=null;return(this.state===u.OPEN||t.force)&&(r=this.transmitObject(i)),r}invoke(n,e,t){return new Promise((s,i)=>{this.invokeRaw(n,e,t,(r,o)=>{if(r){i(r);return}s(o)})})}cancelPendingResponse(n){delete this._callbackMap[n]}decode(n){return this.codec.decode(n)}encode(n){return this.codec.encode(n)}send(n){this.socket.readyState!==this.socket.OPEN?this._destroy(1005):this.socket.send(n)}serializeObject(n){let e;try{e=this.encode(n)}catch(t){return this._onError(t),null}return e}sendObject(n){if(this.isBufferingBatch){this._batchBuffer.push(n);return}let e=this.serializeObject(n);e!=null&&this.send(e)}_handleEventAckTimeout(n){n.cid&&delete this._callbackMap[n.cid],delete n.timeout;let e=n.callback;if(e){delete n.callback;let t=new (0, _chunk2WJ4JSQRjs.m)(`Event response for "${n.event}" timed out`);e.call(n,t,n)}}async _onOpen(){clearTimeout(this._connectTimeoutRef),this._resetPingTimeout();let n;try{n=await this._handshake()}catch(e){e.statusCode==null&&(e.statusCode=4003),this._onError(e),this._destroy(e.statusCode,e.toString()),this.socket.close(e.statusCode);return}this.state=u.OPEN,n&&(this.pingTimeout=n.pingTimeout),this._resetPingTimeout(),this._onOpenHandler(n)}async _handshake(){let n=await this.auth.loadToken(this.authTokenName),e={force:!0},t=await this.invoke("#handshake",{authToken:n},e);return t&&(t.authToken=n,t.authError&&(t.authError=_chunk2WJ4JSQRjs.s.call(void 0, t.authError))),t}_abortAllPendingEventsDueToBadConnection(n){Object.keys(this._callbackMap||{}).forEach(e=>{let t=this._callbackMap[e];delete this._callbackMap[e],clearTimeout(t.timeout),delete t.timeout;let s=`Event "${t.event}" was aborted due to a bad connection`,i=new (0, _chunk2WJ4JSQRjs.n)(s,n),r=t.callback;r&&(delete t.callback,r.call(t,i,t))})}_destroy(n,e){!e&&_chunk2WJ4JSQRjs.p[n]&&(e=_chunk2WJ4JSQRjs.p[n]),delete this.socket.onopen,delete this.socket.onclose,delete this.socket.onmessage,delete this.socket.onerror,clearTimeout(this._connectTimeoutRef),clearTimeout(this._pingTimeoutTicker),this.state===u.OPEN?(this.state=u.CLOSED,this._abortAllPendingEventsDueToBadConnection("disconnect"),this._onCloseHandler({code:n,reason:e})):this.state===u.CONNECTING?(this.state=u.CLOSED,this._abortAllPendingEventsDueToBadConnection("connectAbort"),this._onOpenAbortHandler({code:n,reason:e})):this.state===u.CLOSED&&this._abortAllPendingEventsDueToBadConnection("connectAbort")}_processInboundPacket(n,e){if(n&&n.event!=null)if(n.cid==null)this._onInboundTransmitHandler({...n});else{let t=new (0, _chunk2WJ4JSQRjs.y)(this,n.cid,n.event,n.data);this._onInboundInvokeHandler(t)}else if(n&&n.rid!=null){let t=this._callbackMap[n.rid];if(t&&(clearTimeout(t.timeout),delete t.timeout,delete this._callbackMap[n.rid],t.callback)){let s=_chunk2WJ4JSQRjs.s.call(void 0, n.error);t.callback(s,n.data)}}else this._onEventHandler({event:"raw",data:{message:e}})}_onMessage(n){if(this._onEventHandler({event:"message",data:{message:n}}),this._handlePing(n))return;let e=this.decode(n);if(Array.isArray(e)){let t=e.length;for(let s=0;s<t;s++)this._processInboundPacket(e[s],n)}else this._processInboundPacket(e,n)}_onError(n){this._onErrorHandler({error:n})}_resetPingTimeout(){this.pingTimeoutDisabled||(clearTimeout(this._pingTimeoutTicker),this._pingTimeoutTicker=setTimeout(()=>{this._destroy(4e3),this.socket.close(4e3)},this.pingTimeout))}},b= exports.TGTransport =u;b.CONNECTING="connecting",b.OPEN="open",b.CLOSED="closed";var W=typeof window<"u",I=_chunk2WJ4JSQRjs.t.call(void 0, ),h=class extends _chunk2WJ4JSQRjs.v{constructor(e){super();this._privateDataHandlerMap={"#publish":e=>{let t=this._undecorateChannelName(e.channel);this.isSubscribed(t,!0)&&this._channelDataDemux.write(t,e.data)},"#kickOut":e=>{let t=this._undecorateChannelName(e.channel),s=this._channelMap[t];s&&(this.emit("kickOut",{channel:t,message:e.message}),this._channelEventDemux.write(`${t}/kickOut`,{message:e.message}),this._triggerChannelUnsubscribe(s))},"#setAuthToken":e=>{e&&this._setAuthToken(e)},"#removeAuthToken":e=>{this._removeAuthToken()}};this._privateRPCHandlerMap={"#setAuthToken":(e,t)=>{e?(this._setAuthToken(e),t.end()):t.error(new (0, _chunk2WJ4JSQRjs.j)("No token data provided by #setAuthToken event"))},"#removeAuthToken":(e,t)=>{this._removeAuthToken(),t.end()}};let s=Object.assign({path:"/topgunsocket/",secure:!1,protocolScheme:null,socketPath:null,autoConnect:!0,autoReconnect:!0,autoSubscribeOnConnect:!0,connectTimeout:2e4,ackTimeout:1e4,timestampRequests:!1,timestampParam:"t",authTokenName:"topgunsocket.authToken",binaryType:"arraybuffer",batchOnHandshake:!1,batchOnHandshakeDuration:100,batchInterval:50,protocolVersion:2,wsOptions:{},cloneData:!1},e);this.id=null,this.version=s.version||null,this.protocolVersion=s.protocolVersion,this.state=h.CLOSED,this.authState=h.UNAUTHENTICATED,this.signedAuthToken=null,this.authToken=null,this.pendingReconnect=!1,this.pendingReconnectTimeout=null,this.preparingPendingSubscriptions=!1,this.clientId=s.clientId,this.wsOptions=s.wsOptions,this.connectTimeout=s.connectTimeout,this.ackTimeout=s.ackTimeout,this.channelPrefix=s.channelPrefix||null,this.disconnectOnUnload=s.disconnectOnUnload==null?!0:s.disconnectOnUnload,this.authTokenName=s.authTokenName,s.pingTimeout=s.connectTimeout,this.pingTimeout=s.pingTimeout,this.pingTimeoutDisabled=!!s.pingTimeoutDisabled;let i=Math.pow(2,31)-1,r=o=>{if(this[o]>i)throw new (0, _chunk2WJ4JSQRjs.h)(`The ${o} value provided exceeded the maximum amount allowed`)};if(r("connectTimeout"),r("ackTimeout"),r("pingTimeout"),this.connectAttempts=0,this.isBatching=!1,this.batchOnHandshake=s.batchOnHandshake,this.batchOnHandshakeDuration=s.batchOnHandshakeDuration,this._batchingIntervalId=null,this._outboundBuffer=new D,this._channelMap={},this._channelEventDemux=new _chunk2WJ4JSQRjs.u,this._channelDataDemux=new _chunk2WJ4JSQRjs.u,this._receiverDemux=new _chunk2WJ4JSQRjs.u,this._procedureDemux=new _chunk2WJ4JSQRjs.u,this.options=s,this._cid=1,this.options.callIdGenerator=()=>this._cid++,this.options.autoReconnect){this.options.autoReconnectOptions==null&&(this.options.autoReconnectOptions={});let o=this.options.autoReconnectOptions;o.initialDelay==null&&(o.initialDelay=1e4),o.randomness==null&&(o.randomness=1e4),o.multiplier==null&&(o.multiplier=1.5),o.maxDelay==null&&(o.maxDelay=6e4)}if(this.options.subscriptionRetryOptions==null&&(this.options.subscriptionRetryOptions={}),this.options.authEngine?this.auth=this.options.authEngine:this.auth=new B,this.options.codecEngine?this.codec=this.options.codecEngine:this.codec=_chunk2WJ4JSQRjs.w,this.options.protocol){let o=new (0, _chunk2WJ4JSQRjs.h)('The "protocol" option does not affect socketcluster-client - If you want to utilize SSL/TLS, use "secure" option instead');this._onError(o)}if(this.options.query=s.query||{},typeof this.options.query=="string"){let o=new URLSearchParams(this.options.query),l={};o.forEach((m,v)=>{let k=l[v];k==null?l[v]=m:(Array.isArray(k)||(l[v]=[k]),l[v].push(m))}),this.options.query=l}W&&this.disconnectOnUnload&&I.addEventListener&&I.removeEventListener&&this._handleBrowserUnload(),this.options.autoConnect&&this.connect()}get isBufferingBatch(){return this.transport.isBufferingBatch}getBackpressure(){return Math.max(this.getAllListenersBackpressure(),this.getAllReceiversBackpressure(),this.getAllProceduresBackpressure(),this.getAllChannelsBackpressure())}getState(){return this.state}getBytesReceived(){return this.transport.getBytesReceived()}async deauthenticate(){(async()=>{let e;try{e=await this.auth.removeToken(this.authTokenName)}catch(t){this._onError(t);return}this.emit("removeAuthToken",{oldAuthToken:e})})(),this.state!==h.CLOSED&&this.transmit("#removeAuthToken"),this._changeToUnauthenticatedStateAndClearTokens(),await O(0)}connect(){if(this.state===h.CLOSED){this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef),this.state=h.CONNECTING,this.emit("connecting",{}),this.transport&&this.transport.clearAllListeners();let e={onOpen:t=>{this.state=h.OPEN,this._onOpen(t)},onOpenAbort:t=>{this.state!==h.CLOSED&&(this.state=h.CLOSED,this._destroy(t.code,t.reason,!0))},onClose:t=>{this.state!==h.CLOSED&&(this.state=h.CLOSED,this._destroy(t.code,t.reason))},onEvent:t=>{this.emit(t.event,t.data)},onError:t=>{this._onError(t.error)},onInboundInvoke:t=>{this._onInboundInvoke(t)},onInboundTransmit:t=>{this._onInboundTransmit(t.event,t.data)}};this.transport=new b(this.auth,this.codec,this.options,this.wsOptions,e)}}reconnect(e,t){this.disconnect(e,t),this.connect()}disconnect(e,t){if(e=e||1e3,typeof e!="number")throw new (0, _chunk2WJ4JSQRjs.h)("If specified, the code argument must be a number");let s=this.state===h.CONNECTING;s||this.state===h.OPEN?(this.state=h.CLOSED,this._destroy(e,t,s),this.transport.close(e,t)):(this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef))}decodeBase64(e){return _3.default.Buffer.from(e,"base64").toString("utf8")}encodeBase64(e){return _3.default.Buffer.from(e,"utf8").toString("base64")}getAuthToken(){return this.authToken}getSignedAuthToken(){return this.signedAuthToken}async authenticate(e){let t;try{t=await this.invoke("#authenticate",e)}catch(s){throw s.name!=="BadConnectionError"&&s.name!=="TimeoutError"&&this._changeToUnauthenticatedStateAndClearTokens(),await O(0),s}return t&&t.isAuthenticated!=null?t.authError&&(t.authError=_chunk2WJ4JSQRjs.s.call(void 0, t.authError)):t={isAuthenticated:this.authState,authError:null},t.isAuthenticated?this._changeToAuthenticatedState(e):this._changeToUnauthenticatedStateAndClearTokens(),(async()=>{try{await this.auth.saveToken(this.authTokenName,e,{})}catch(s){this._onError(s)}})(),await O(0),t}decode(e){return this.transport.decode(e)}encode(e){return this.transport.encode(e)}send(e){this.transport.send(e)}transmit(e,t,s){return this._processOutboundEvent(e,t,s)}invoke(e,t,s){return this._processOutboundEvent(e,t,s,!0)}transmitPublish(e,t){let s={channel:this._decorateChannelName(e),data:t};return this.transmit("#publish",s)}invokePublish(e,t){let s={channel:this._decorateChannelName(e),data:t};return this.invoke("#publish",s)}startBatch(){this.transport.startBatch()}flushBatch(){this.transport.flushBatch()}cancelBatch(){this.transport.cancelBatch()}startBatching(){this.isBatching=!0,this._startBatching()}stopBatching(){this.isBatching=!1,this._stopBatching()}cancelBatching(){this.isBatching=!1,this._cancelBatching()}subscribe(e,t){t=t||{};let s=this._channelMap[e],i={waitForAuth:!!t.waitForAuth};return t.priority!=null&&(i.priority=t.priority),t.data!==void 0&&(i.data=t.data),s?t&&(s.options=i):(s={name:e,state:_chunkZARTXZMYjs.a.PENDING,options:i},this._channelMap[e]=s,this._trySubscribe(s)),new (0, _chunkZARTXZMYjs.a)(e,this,this._channelEventDemux,this._channelDataDemux)}async unsubscribe(e){let t=this._channelMap[e];t&&(this._triggerChannelUnsubscribe(t),this._tryUnsubscribe(t))}receiver(e){return this._receiverDemux.stream(e)}closeReceiver(e){this._receiverDemux.close(e)}closeAllReceivers(){this._receiverDemux.closeAll()}killReceiver(e){this._receiverDemux.kill(e)}killAllReceivers(){this._receiverDemux.killAll()}killReceiverConsumer(e){this._receiverDemux.killConsumer(e)}getReceiverConsumerStats(e){return this._receiverDemux.getConsumerStats(e)}getReceiverConsumerStatsList(e){return this._receiverDemux.getConsumerStatsList(e)}getAllReceiversConsumerStatsList(){return this._receiverDemux.getConsumerStatsListAll()}getReceiverBackpressure(e){return this._receiverDemux.getBackpressure(e)}getAllReceiversBackpressure(){return this._receiverDemux.getBackpressureAll()}getReceiverConsumerBackpressure(e){return this._receiverDemux.getConsumerBackpressure(e)}hasReceiverConsumer(e,t){return this._receiverDemux.hasConsumer(e,t)}hasAnyReceiverConsumer(e){return this._receiverDemux.hasConsumerAll(e)}procedure(e){return this._procedureDemux.stream(e)}closeProcedure(e){this._procedureDemux.close(e)}closeAllProcedures(){this._procedureDemux.closeAll()}killProcedure(e){this._procedureDemux.kill(e)}killAllProcedures(){this._procedureDemux.killAll()}killProcedureConsumer(e){this._procedureDemux.killConsumer(e)}getProcedureConsumerStats(e){return this._procedureDemux.getConsumerStats(e)}getProcedureConsumerStatsList(e){return this._procedureDemux.getConsumerStatsList(e)}getAllProceduresConsumerStatsList(){return this._procedureDemux.getConsumerStatsListAll()}getProcedureBackpressure(e){return this._procedureDemux.getBackpressure(e)}getAllProceduresBackpressure(){return this._procedureDemux.getBackpressureAll()}getProcedureConsumerBackpressure(e){return this._procedureDemux.getConsumerBackpressure(e)}hasProcedureConsumer(e,t){return this._procedureDemux.hasConsumer(e,t)}hasAnyProcedureConsumer(e){return this._procedureDemux.hasConsumerAll(e)}channel(e){return new (0, _chunkZARTXZMYjs.a)(e,this,this._channelEventDemux,this._channelDataDemux)}closeChannel(e){this.channelCloseOutput(e),this.channelCloseAllListeners(e)}closeAllChannelOutputs(){this._channelDataDemux.closeAll()}closeAllChannelListeners(){this._channelEventDemux.closeAll()}closeAllChannels(){this.closeAllChannelOutputs(),this.closeAllChannelListeners()}killChannel(e){this.channelKillOutput(e),this.channelKillAllListeners(e)}killAllChannelOutputs(){this._channelDataDemux.killAll()}killAllChannelListeners(){this._channelEventDemux.killAll()}killAllChannels(){this.killAllChannelOutputs(),this.killAllChannelListeners()}killChannelOutputConsumer(e){this._channelDataDemux.killConsumer(e)}killChannelListenerConsumer(e){this._channelEventDemux.killConsumer(e)}getChannelOutputConsumerStats(e){return this._channelDataDemux.getConsumerStats(e)}getChannelListenerConsumerStats(e){return this._channelEventDemux.getConsumerStats(e)}getAllChannelOutputsConsumerStatsList(){return this._channelDataDemux.getConsumerStatsListAll()}getAllChannelListenersConsumerStatsList(){return this._channelEventDemux.getConsumerStatsListAll()}getChannelBackpressure(e){return Math.max(this.channelGetOutputBackpressure(e),this.channelGetAllListenersBackpressure(e))}getAllChannelOutputsBackpressure(){return this._channelDataDemux.getBackpressureAll()}getAllChannelListenersBackpressure(){return this._channelEventDemux.getBackpressureAll()}getAllChannelsBackpressure(){return Math.max(this.getAllChannelOutputsBackpressure(),this.getAllChannelListenersBackpressure())}getChannelListenerConsumerBackpressure(e){return this._channelEventDemux.getConsumerBackpressure(e)}getChannelOutputConsumerBackpressure(e){return this._channelDataDemux.getConsumerBackpressure(e)}hasAnyChannelOutputConsumer(e){return this._channelDataDemux.hasConsumerAll(e)}hasAnyChannelListenerConsumer(e){return this._channelEventDemux.hasConsumerAll(e)}getChannelState(e){let t=this._channelMap[e];return t?t.state:_chunkZARTXZMYjs.a.UNSUBSCRIBED}getChannelOptions(e){let t=this._channelMap[e];return t?{...t.options}:{}}channelCloseOutput(e){this._channelDataDemux.close(e)}channelCloseListener(e,t){this._channelEventDemux.close(`${e}/${t}`)}channelCloseAllListeners(e){this._getAllChannelStreamNames(e).forEach(t=>{this._channelEventDemux.close(t)})}channelKillOutput(e){this._channelDataDemux.kill(e)}channelKillListener(e,t){this._channelEventDemux.kill(`${e}/${t}`)}channelKillAllListeners(e){this._getAllChannelStreamNames(e).forEach(t=>{this._channelEventDemux.kill(t)})}channelGetOutputConsumerStatsList(e){return this._channelDataDemux.getConsumerStatsList(e)}channelGetListenerConsumerStatsList(e,t){return this._channelEventDemux.getConsumerStatsList(`${e}/${t}`)}channelGetAllListenersConsumerStatsList(e){return this._getAllChannelStreamNames(e).map(t=>this._channelEventDemux.getConsumerStatsList(t)).reduce((t,s)=>(s.forEach(i=>{t.push(i)}),t),[])}channelGetOutputBackpressure(e){return this._channelDataDemux.getBackpressure(e)}channelGetListenerBackpressure(e,t){return this._channelEventDemux.getBackpressure(`${e}/${t}`)}channelGetAllListenersBackpressure(e){let t=this._getAllChannelStreamNames(e).map(s=>this._channelEventDemux.getBackpressure(s));return Math.max(...t.concat(0))}channelHasOutputConsumer(e,t){return this._channelDataDemux.hasConsumer(e,t)}channelHasListenerConsumer(e,t,s){return this._channelEventDemux.hasConsumer(`${e}/${t}`,s)}channelHasAnyListenerConsumer(e,t){return this._getAllChannelStreamNames(e).some(s=>this._channelEventDemux.hasConsumer(s,t))}subscriptions(e){let t=[];return Object.keys(this._channelMap).forEach(s=>{(e||this._channelMap[s].state===_chunkZARTXZMYjs.a.SUBSCRIBED)&&t.push(s)}),t}isSubscribed(e,t){let s=this._channelMap[e];return t?!!s:!!s&&s.state===_chunkZARTXZMYjs.a.SUBSCRIBED}processPendingSubscriptions(){this.preparingPendingSubscriptions=!1;let e=[];Object.keys(this._channelMap).forEach(t=>{let s=this._channelMap[t];s.state===_chunkZARTXZMYjs.a.PENDING&&e.push(s)}),e.sort((t,s)=>{let i=t.options.priority||0,r=s.options.priority||0;return i>r?-1:i<r?1:0}),e.forEach(t=>{this._trySubscribe(t)})}_getAllChannelStreamNames(e){let t=this._channelEventDemux.getConsumerStatsListAll().filter(s=>s.stream.indexOf(`${e}/`)===0).reduce((s,i)=>(s[i.stream]=!0,s),{});return Object.keys(t)}_tryUnsubscribe(e){if(this.state===h.OPEN){let t={noTimeout:!0};this._cancelPendingSubscribeCallback(e);let s=this._decorateChannelName(e.name);this.transport.transmit("#unsubscribe",s,t)}}_triggerChannelUnsubscribe(e,t){let s=e.name;if(this._cancelPendingSubscribeCallback(e),e.state===_chunkZARTXZMYjs.a.SUBSCRIBED){let i={oldChannelState:e.state,newChannelState:t?_chunkZARTXZMYjs.a.PENDING:_chunkZARTXZMYjs.a.UNSUBSCRIBED};this._channelEventDemux.write(`${s}/subscribeStateChange`,i),this._channelEventDemux.write(`${s}/unsubscribe`,{}),this.emit("subscribeStateChange",{channel:s,...i}),this.emit("unsubscribe",{channel:s})}t?e.state=_chunkZARTXZMYjs.a.PENDING:delete this._channelMap[s]}_trySubscribe(e){let t=!e.options.waitForAuth||this.authState===h.AUTHENTICATED;if(this.state===h.OPEN&&!this.preparingPendingSubscriptions&&e._pendingSubscriptionCid==null&&t){let s={noTimeout:!0},i={};e.options.waitForAuth&&(s.waitForAuth=!0,i.waitForAuth=s.waitForAuth),e.options.data&&(i.data=e.options.data),e._pendingSubscriptionCid=this.transport.invokeRaw("#subscribe",{channel:this._decorateChannelName(e.name),...i},s,r=>{if(r){if(r.name==="BadConnectionError")return;delete e._pendingSubscriptionCid,this._triggerChannelSubscribeFail(r,e,i)}else delete e._pendingSubscriptionCid,this._triggerChannelSubscribe(e,i)}),this.emit("subscribeRequest",{channel:e.name,subscriptionOptions:i})}}_cancelBatching(){this._batchingIntervalId!=null&&clearInterval(this._batchingIntervalId),this._batchingIntervalId=null,this.cancelBatch()}_stopBatching(){this._batchingIntervalId!=null&&clearInterval(this._batchingIntervalId),this._batchingIntervalId=null,this.flushBatch()}_startBatching(){this._batchingIntervalId==null&&(this.startBatch(),this._batchingIntervalId=setInterval(()=>{this.flushBatch(),this.startBatch()},this.options.batchInterval))}_undecorateChannelName(e){return this.channelPrefix&&e.indexOf(this.channelPrefix)===0?e.replace(this.channelPrefix,""):e}_decorateChannelName(e){return this.channelPrefix&&(e=this.channelPrefix+e),e}_cancelPendingSubscribeCallback(e){e._pendingSubscriptionCid!=null&&(this.transport.cancelPendingResponse(e._pendingSubscriptionCid),delete e._pendingSubscriptionCid)}_triggerChannelSubscribeFail(e,t,s){let i=t.name,r=!t.options.waitForAuth||this.authState===h.AUTHENTICATED;!!this._channelMap[i]&&r&&(delete this._channelMap[i],this._channelEventDemux.write(`${i}/subscribeFail`,{error:e,subscriptionOptions:s}),this.emit("subscribeFail",{error:e,channel:i,subscriptionOptions:s}))}_triggerChannelSubscribe(e,t){let s=e.name;if(e.state!==_chunkZARTXZMYjs.a.SUBSCRIBED){let i=e.state;e.state=_chunkZARTXZMYjs.a.SUBSCRIBED;let r={oldChannelState:i,newChannelState:e.state,subscriptionOptions:t};this._channelEventDemux.write(`${s}/subscribeStateChange`,r),this._channelEventDemux.write(`${s}/subscribe`,{subscriptionOptions:t}),this.emit("subscribeStateChange",{channel:s,...r}),this.emit("subscribe",{channel:s,subscriptionOptions:t})}}_processOutboundEvent(e,t,s,i){s=s||{},this.state===h.CLOSED&&this.connect();let r={event:e,data:null},o;i?o=new Promise((v,k)=>{r.callback=(w,z)=>{if(w){k(w);return}v(z)}}):o=Promise.resolve();let l=new A;this.options.cloneData?r.data=_chunk2WJ4JSQRjs.x.call(void 0, t):r.data=t,l.data=r;let m=s.ackTimeout==null?this.ackTimeout:s.ackTimeout;return r.timeout=setTimeout(()=>{this._handleEventAckTimeout(r,l)},m),this._outboundBuffer.append(l),this.state===h.OPEN&&this._flushOutboundBuffer(),o}_handleEventAckTimeout(e,t){t&&t.detach(),delete e.timeout;let s=e.callback;if(s){delete e.callback;let i=new (0, _chunk2WJ4JSQRjs.m)(`Event response for "${e.event}" timed out`);s.call(e,i,e)}e.cid&&this.transport.cancelPendingResponse(e.cid)}_flushOutboundBuffer(){let e=this._outboundBuffer.head,t;for(;e;){t=e.next;let s=e.data;e.detach(),this.transport.transmitObject(s),e=t}}_onInboundInvoke(e){let{procedure:t,data:s}=e,i=this._privateRPCHandlerMap[t];i?i.call(this,s,e):this._procedureDemux.write(t,e)}_onInboundTransmit(e,t){let s=this._privateDataHandlerMap[e];s?s.call(this,t):this._receiverDemux.write(e,t)}_destroy(e,t,s){if(this.id=null,this._cancelBatching(),this.transport&&this.transport.clearAllListeners(),this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef),this._suspendSubscriptions(),s?this.emit("connectAbort",{code:e,reason:t}):this.emit("disconnect",{code:e,reason:t}),this.emit("close",{code:e,reason:t}),!h.ignoreStatuses[e]){let i;t?i="Socket connection closed with status code "+e+" and reason: "+t:i="Socket connection closed with status code "+e;let r=new (0, _chunk2WJ4JSQRjs.k)(h.errorStatuses[e]||i,e);this._onError(r)}this._abortAllPendingEventsDueToBadConnection(s?"connectAbort":"disconnect"),this.options.autoReconnect&&(e===4e3||e===4001||e===1005?this._tryReconnect(0):e!==1e3&&e<4500&&this._tryReconnect())}_abortAllPendingEventsDueToBadConnection(e){let t=this._outboundBuffer.head,s;for(;t;){s=t.next;let i=t.data;clearTimeout(i.timeout),delete i.timeout,t.detach(),t=s;let r=i.callback;if(r){delete i.callback;let o=`Event "${i.event}" was aborted due to a bad connection`,l=new (0, _chunk2WJ4JSQRjs.n)(o,e);r.call(i,l,i)}i.cid&&this.transport.cancelPendingResponse(i.cid)}}_suspendSubscriptions(){Object.keys(this._channelMap).forEach(e=>{let t=this._channelMap[e];this._triggerChannelUnsubscribe(t,!0)})}_onError(e){this.emit("error",{error:e})}_tryReconnect(e){let t=this.connectAttempts++,s=this.options.autoReconnectOptions,i;if(e==null||t>0){let r=Math.round(s.initialDelay+(s.randomness||0)*Math.random());i=Math.round(r*Math.pow(s.multiplier,t))}else i=e;i>s.maxDelay&&(i=s.maxDelay),clearTimeout(this._reconnectTimeoutRef),this.pendingReconnect=!0,this.pendingReconnectTimeout=i,this._reconnectTimeoutRef=setTimeout(()=>{this.connect()},i)}_onOpen(e){this.isBatching?this._startBatching():this.batchOnHandshake&&(this._startBatching(),setTimeout(()=>{this.isBatching||this._stopBatching()},this.batchOnHandshakeDuration)),this.preparingPendingSubscriptions=!0,e?(this.id=e.id,this.pingTimeout=e.pingTimeout,e.isAuthenticated?this._changeToAuthenticatedState(e.authToken):this._changeToUnauthenticatedStateAndClearTokens()):this._changeToUnauthenticatedStateAndClearTokens(),this.connectAttempts=0,this.options.autoSubscribeOnConnect&&this.processPendingSubscriptions(),this.emit("connect",{...e,processPendingSubscriptions:()=>{this.processPendingSubscriptions()}}),this.state===h.OPEN&&this._flushOutboundBuffer()}_extractAuthTokenData(e){let s=(e||"").split(".")[1];if(s!=null){let i=s;try{return i=this.decodeBase64(i),JSON.parse(i)}catch (e2){return i}}return null}_changeToAuthenticatedState(e){if(this.signedAuthToken=e,this.authToken=this._extractAuthTokenData(e),this.authState!==h.AUTHENTICATED){let t=this.authState;this.authState=h.AUTHENTICATED;let s={oldAuthState:t,newAuthState:this.authState,signedAuthToken:e,authToken:this.authToken};this.preparingPendingSubscriptions||this.processPendingSubscriptions(),this.emit("authStateChange",s)}this.emit("authenticate",{signedAuthToken:e,authToken:this.authToken})}_changeToUnauthenticatedStateAndClearTokens(){if(this.authState!==h.UNAUTHENTICATED){let e=this.authState,t=this.authToken,s=this.signedAuthToken;this.authState=h.UNAUTHENTICATED,this.signedAuthToken=null,this.authToken=null;let i={oldAuthState:e,newAuthState:this.authState};this.emit("authStateChange",i),this.emit("deauthenticate",{oldSignedAuthToken:s,oldAuthToken:t})}}async _handleBrowserUnload(){let e=()=>{this.disconnect()},t=!1,s=()=>{t||(t=!0,I.addEventListener("beforeunload",e,!1))},i=()=>{t&&(t=!1,I.removeEventListener("beforeunload",e,!1))};(async()=>{let r=this.listener("connecting").createConsumer();for(;!(await r.next()).done;)s()})(),(async()=>{let r=this.listener("close").createConsumer();for(;!(await r.next()).done;)i()})()}_setAuthToken(e){this._changeToAuthenticatedState(e.token),(async()=>{try{await this.auth.saveToken(this.authTokenName,e.token,{})}catch(t){this._onError(t)}})()}_removeAuthToken(){(async()=>{let e;try{e=await this.auth.removeToken(this.authTokenName)}catch(t){this._onError(t);return}this.emit("removeAuthToken",{oldAuthToken:e})})(),this._changeToUnauthenticatedStateAndClearTokens()}},d= exports.TGClientSocket =h;d.CONNECTING="connecting",d.OPEN="open",d.CLOSED="closed",d.AUTHENTICATED="authenticated",d.UNAUTHENTICATED="unauthenticated",d.SUBSCRIBED="subscribed",d.PENDING="pending",d.UNSUBSCRIBED="unsubscribed",d.ignoreStatuses=_chunk2WJ4JSQRjs.q,d.errorStatuses=_chunk2WJ4JSQRjs.p;var P=_chunk2WJ4JSQRjs.t.call(void 0, );function J(){return P.location&&location.protocol==="https:"}function Q(a,n){let e=a.secure==null?n:a.secure;return a.port||(P.location&&location.port?parseFloat(location.port):e?443:80)}function q(a){if(a=a||{},a.host&&!a.host.match(/[^:]+:\d{2,5}/))throw new (0, _chunk2WJ4JSQRjs.h)('The host option should include both the hostname and the port number in the format "hostname:port"');if(a.host&&a.hostname)throw new (0, _chunk2WJ4JSQRjs.h)('The host option should already include the hostname and the port number in the format "hostname:port" - Because of this, you should never use host and hostname options together');if(a.host&&a.port)throw new (0, _chunk2WJ4JSQRjs.h)('The host option should already include the hostname and the port number in the format "hostname:port" - Because of this, you should never use host and port options together');let n=J(),e={clientId:V(),port:Q(a,n),hostname:P.location&&location.hostname||"localhost",secure:n};return Object.assign(e,a),new d(e)}var X="1.0.0";function qe(a){return q({...a,version:X})}exports.AuthEngine = B; exports.TGClientSocket = d; exports.TGTransport = b; exports.create = qe; exports.version = X; |
{ | ||
"name": "topgun-socket", | ||
"version": "1.1.10", | ||
"version": "1.1.11", | ||
"description": "Scalable realtime pub/sub and RPC serverless framework", | ||
@@ -5,0 +5,0 @@ "publishConfig": { |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
456744
2927