New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

topgun-socket

Package Overview
Dependencies
Maintainers
1
Versions
44
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

topgun-socket - npm Package Compare versions

Comparing version 1.2.3 to 1.2.4

dist/channel-549bdfaa.d.ts

3

dist/channel.d.ts

@@ -1,1 +0,2 @@

export { f as ChannelState, d as TGChannel, T as TGChannelClient } from './channel-2c868064.js';
export { f as ChannelState, d as TGChannel, T as TGChannelClient } from './channel-549bdfaa.js';
import 'topgun-jsonwebtoken';

@@ -1,2 +0,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-2c868064.js';
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-549bdfaa.js';
import 'topgun-jsonwebtoken';

@@ -68,3 +69,3 @@ interface TGAuthEngine {

query?: string | {
[key: string]: string | number;
[key: string]: string | number | boolean;
} | undefined;

@@ -143,5 +144,7 @@ ackTimeout?: number | undefined;

isBufferingBatch: boolean;
socket: WebSocket;
socket: any;
_callbackMap: {
[key: string]: any;
};
private _pingTimeoutTicker;
private _callbackMap;
private _batchBuffer;

@@ -178,2 +181,3 @@ private _onOpenHandler;

sendObject(object: any): void;
_resetPingTimeout(): void;
private _handleEventAckTimeout;

@@ -187,3 +191,2 @@ private _onOpen;

private _onError;
private _resetPingTimeout;
}

@@ -202,2 +205,10 @@

static readonly errorStatuses: SocketProtocolErrorStatuses;
readonly CONNECTING: States;
readonly OPEN: States;
readonly CLOSED: States;
readonly AUTHENTICATED: AuthStates;
readonly UNAUTHENTICATED: AuthStates;
readonly SUBSCRIBED = "subscribed";
readonly PENDING = "pending";
readonly UNSUBSCRIBED = "unsubscribed";
options: ClientOptions;

@@ -204,0 +215,0 @@ id: string | null;

@@ -1,1 +0,1 @@

var ce=Object.create;var D=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var he=Object.getOwnPropertyNames;var me=Object.getPrototypeOf,de=Object.prototype.hasOwnProperty;var pe=(s,e,t)=>e in s?D(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var fe=(s,e)=>{for(var t in e)D(s,t,{get:e[t],enumerable:!0})},Q=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of he(e))!de.call(s,r)&&r!==t&&D(s,r,{get:()=>e[r],enumerable:!(n=le(e,r))||n.enumerable});return s};var ge=(s,e,t)=>(t=s!=null?ce(me(s)):{},Q(e||!s||!s.__esModule?D(t,"default",{value:s,enumerable:!0}):t,s)),be=s=>Q(D({},"__esModule",{value:!0}),s);var h=(s,e,t)=>(pe(s,typeof e!="symbol"?e+"":e,t),t);var De={};fe(De,{AuthEngine:()=>I,TGClientSocket:()=>p,TGTransport:()=>v,create:()=>Oe,version:()=>ae});module.exports=be(De);function X(s){let e=[],t=[];return function n(r,i){let o,u,a;if(typeof r=="object"&&r!==null&&!(r instanceof Boolean)&&!(r instanceof Date)&&!(r instanceof Number)&&!(r instanceof RegExp)&&!(r instanceof String)){for(o=0;o<e.length;o+=1)if(e[o]===r)return{$ref:t[o]};if(e.push(r),t.push(i),Object.prototype.toString.apply(r)==="[object Array]")for(a=[],o=0;o<r.length;o+=1)a[o]=n(r[o],i+"["+o+"]");else{a={};for(u in r)Object.prototype.hasOwnProperty.call(r,u)&&(a[u]=n(r[u],i+"["+JSON.stringify(u)+"]"))}return a}return r}(s,"$")}function A(){"use strict";return typeof function(){return this}()>"u"}var _=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,_.prototype),this.name="InvalidActionError",this.message=e,Error.captureStackTrace&&!A()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}},f=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,f.prototype),this.name="InvalidArgumentsError",this.message=e,Error.captureStackTrace&&!A()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}};var x=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,x.prototype),this.name="InvalidMessageError",this.message=e,Error.captureStackTrace&&!A()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}},E=class extends Error{code;constructor(e,t){super(e),Object.setPrototypeOf(this,E.prototype),this.name="SocketProtocolError",this.message=e,this.code=t,Error.captureStackTrace&&!A()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}};var C=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,C.prototype),this.name="TimeoutError",this.message=e,Error.captureStackTrace&&!A()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}},S=class extends Error{type;constructor(e,t){super(e),Object.setPrototypeOf(this,S.prototype),this.name="BadConnectionError",this.message=e,this.type=t,Error.captureStackTrace&&!A()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}};var B={1001:"Socket was disconnected",1002:"A WebSocket protocol error was encountered",1003:"Server terminated socket because it received invalid data",1005:"Socket closed without status code",1006:"Socket hung up",1007:"Message format was incorrect",1008:"Encountered a policy violation",1009:"Message was too big to process",1010:"Client ended the connection because the server did not comply with extension requirements",1011:"Server encountered an unexpected fatal condition",4e3:"Server ping timed out",4001:"Client pong timed out",4002:"Server failed to sign auth token",4003:"Failed to complete handshake",4004:"Client failed to save auth token",4005:"Did not receive #handshake from client before timeout",4006:"Failed to bind socket to message broker",4007:"Client connection establishment timed out",4008:"Server rejected handshake from client",4009:"Server received a message before the client handshake"},Y={1e3:"Socket closed normally",1001:"Socket hung up"},ke={domain:1,domainEmitter:1,domainThrown:1};function Z(s,e){let t;if(s&&typeof s=="object"){t={message:s.message},e&&(t.stack=s.stack);for(let n in s)ke[n]||(t[n]=s[n])}else typeof s=="function"?t="[function "+(s.name||"anonymous")+"]":t=s;return X(t)}function w(s){let e=null;if(s!=null)if(typeof s=="object"){e=new Error(s.message);for(let t in s)s.hasOwnProperty(t)&&(e[t]=s[t])}else e=s;return e}function g(){return typeof WorkerGlobalScope<"u"?self:typeof window<"u"&&window||function(){return this}()}function ee(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{let e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}var W=ge(require("topgun-buffer"));var y=class{async next(e){let t=this.createConsumer(e),n=await t.next();return t.return(),n}async once(e){let t=await this.next(e);return t.done&&await new Promise(()=>{}),t.value}createConsumer(e){throw new TypeError("Method must be overriden by subclass")}[Symbol.asyncIterator](){return this.createConsumer()}};var L=class{id;timeout;stream;currentNode;isAlive;_backpressure;_timeoutId;_resolve;_killPacket;constructor(e,t,n,r=0){this.id=t,this._backpressure=0,this.stream=e,this.currentNode=n,this.timeout=r,this.isAlive=!0,this.stream.setConsumer(this.id,this)}getStats(){let e={id:this.id,backpressure:this._backpressure};return this.timeout!=null&&(e.timeout=this.timeout),e}applyBackpressure(e){this._backpressure++}releaseBackpressure(e){this._backpressure--}getBackpressure(){return this._backpressure}write(e){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this.applyBackpressure(e),this._resolve&&(this._resolve(),delete this._resolve)}kill(e){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this._killPacket={value:e,done:!0},this._destroy(),this._resolve&&(this._resolve(),delete this._resolve)}async next(){for(this.stream.setConsumer(this.id,this);;){if(this.currentNode&&!this.currentNode.next)try{await this._waitForNextItem(this.timeout)}catch(e){throw this._destroy(),e}if(this._killPacket){this._destroy();let e=this._killPacket;return delete this._killPacket,e}if(this.currentNode){if(this.currentNode=this.currentNode.next,this.releaseBackpressure(this.currentNode.data),this.currentNode.consumerId&&this.currentNode.consumerId!==this.id)continue;return this.currentNode.data.done&&this._destroy(),this.currentNode.data}}}return(){return delete this.currentNode,this._destroy(),{}}_resetBackpressure(){this._backpressure=0}_destroy(){this.isAlive=!1,this._resetBackpressure(),this.stream.removeConsumer(this.id)}async _waitForNextItem(e){return new Promise((t,n)=>{this._resolve=t;let r;if(e!==void 0){let i=new Error("Stream consumer iteration timed out");(async()=>{let o=Ce(e);r=o.timeoutId,await o.promise,i.name="TimeoutError",delete this._resolve,n(i)})()}this._timeoutId=r})}[Symbol.asyncIterator](){return this}};function Ce(s){let e,t=new Promise(n=>{e=setTimeout(n,s)});return{timeoutId:e,promise:t}}var N=class extends y{type;nextConsumerId;_consumers;_tailNode;constructor(){super(),this.nextConsumerId=1,this._consumers=new Map,this._tailNode={next:null,data:{value:void 0,done:!1}}}write(e){this._write(e,!1)}close(e){this._write(e,!0)}writeToConsumer(e,t){this._write(t,!1,e)}closeConsumer(e,t){this._write(t,!0,e)}kill(e){for(let t of this._consumers.keys())this.killConsumer(t,e)}killConsumer(e,t){let n=this._consumers.get(e);!n||n.kill(t)}getBackpressure(){let e=0;for(let t of this._consumers.values()){let n=t.getBackpressure();n>e&&(e=n)}return e}getConsumerBackpressure(e){let t=this._consumers.get(e);return t?t.getBackpressure():0}hasConsumer(e){return this._consumers.has(e)}setConsumer(e,t){this._consumers.set(e,t),t.currentNode||(t.currentNode=this._tailNode)}removeConsumer(e){return this._consumers.delete(e)}getConsumerStats(e){let t=this._consumers.get(e);if(t)return t.getStats()}getConsumerStatsList(){let e=[];for(let t of this._consumers.values())e.push(t.getStats());return e}createConsumer(e){return new L(this,this.nextConsumerId++,this._tailNode,e)}getConsumerList(){return[...this._consumers.values()]}getConsumerCount(){return this._consumers.size}_write(e,t,n){let r={data:{value:e,done:t},next:null};n&&(r.consumerId=n),this._tailNode.next=r,this._tailNode=r;for(let i of this._consumers.values())i.write(r.data)}};var R=class extends y{name;_streamDemux;constructor(e,t){super(),this.name=t,this._streamDemux=e}createConsumer(e){return this._streamDemux.createConsumer(this.name,e)}};var b=class{_mainStream;constructor(){this._mainStream=new N}write(e,t){this._mainStream.write({stream:e,data:{value:t,done:!1}})}close(e,t){this._mainStream.write({stream:e,data:{value:t,done:!0}})}closeAll(e){this._mainStream.close(e)}writeToConsumer(e,t){this._mainStream.writeToConsumer(e,{consumerId:e,data:{value:t,done:!1}})}closeConsumer(e,t){this._mainStream.closeConsumer(e,{consumerId:e,data:{value:t,done:!0}})}getConsumerStats(e){return this._mainStream.getConsumerStats(e)}getConsumerStatsList(e){return this._mainStream.getConsumerStatsList().filter(n=>n.stream===e)}getConsumerStatsListAll(){return this._mainStream.getConsumerStatsList()}kill(e,t){let n=this.getConsumerStatsList(e),r=n.length;for(let i=0;i<r;i++)this.killConsumer(n[i].id,t)}killAll(e){this._mainStream.kill(e)}killConsumer(e,t){this._mainStream.killConsumer(e,t)}getBackpressure(e){let t=this.getConsumerStatsList(e),n=t.length,r=0;for(let i=0;i<n;i++){let o=t[i];o.backpressure>r&&(r=o.backpressure)}return r}getBackpressureAll(){return this._mainStream.getBackpressure()}getConsumerBackpressure(e){return this._mainStream.getConsumerBackpressure(e)}hasConsumer(e,t){let n=this._mainStream.getConsumerStats(t);return!!n&&n.stream===e}hasConsumerAll(e){return this._mainStream.hasConsumer(e)}getConsumerCount(e){return this.getConsumerStatsList(e).length}getConsumerCountAll(){return this.getConsumerStatsListAll().length}createConsumer(e,t){let n=this._mainStream.createConsumer(t),r=n.next;n.next=async function(){for(;;){let a=arguments,c=await r.apply(this,a);if(c.value&&(c.value.stream===e||c.value.consumerId===this.id))return c.value.data.done&&this.return(),c.value.data;if(c.done)return c}};let i=n.getStats;n.getStats=function(){let a=arguments,c=i.apply(this,a);return c.stream=e,c};let o=n.applyBackpressure;n.applyBackpressure=function(a){let c=arguments;if(a.value&&(a.value.stream===e||a.value.consumerId===this.id)){o.apply(this,c);return}a.done&&o.apply(this,c)};let u=n.releaseBackpressure;return n.releaseBackpressure=function(a){let c=arguments;if(a.value&&(a.value.stream===e||a.value.consumerId===this.id)){u.apply(this,c);return}a.done&&u.apply(this,c)},n}stream(e){return new R(this,e)}};var U=class{_listenerDemux;constructor(){this._listenerDemux=new b}emit(e,t){this._listenerDemux.write(e,t)}listener(e){return this._listenerDemux.stream(e)}closeListener(e){this._listenerDemux.close(e)}closeAllListeners(){this._listenerDemux.closeAll()}getListenerConsumerStats(e){return this._listenerDemux.getConsumerStats(e)}getListenerConsumerStatsList(e){return this._listenerDemux.getConsumerStatsList(e)}getAllListenersConsumerStatsList(){return this._listenerDemux.getConsumerStatsListAll()}getListenerConsumerCount(e){return this._listenerDemux.getConsumerCount(e)}getAllListenersConsumerCount(){return this._listenerDemux.getConsumerCountAll()}killListener(e){this._listenerDemux.kill(e)}killAllListeners(){this._listenerDemux.killAll()}killListenerConsumer(e){this._listenerDemux.killConsumer(e)}getListenerBackpressure(e){return this._listenerDemux.getBackpressure(e)}getAllListenersBackpressure(){return this._listenerDemux.getBackpressureAll()}getListenerConsumerBackpressure(e){return this._listenerDemux.getConsumerBackpressure(e)}hasListenerConsumer(e,t){return this._listenerDemux.hasConsumer(e,t)}hasAnyListenerConsumer(e){return this._listenerDemux.hasConsumerAll(e)}};var P=class extends y{name;PENDING;SUBSCRIBED;UNSUBSCRIBED;client;_eventDemux;_dataStream;_pendingSubscriptionCid;constructor(e,t,n,r){super(),this.PENDING=P.PENDING,this.SUBSCRIBED=P.SUBSCRIBED,this.UNSUBSCRIBED=P.UNSUBSCRIBED,this.name=e,this.client=t,this._eventDemux=n,this._dataStream=r.stream(this.name)}get state(){return this.client.getChannelState(this.name)}set state(e){throw new Error("Cannot directly set channel state")}get options(){return this.client.getChannelOptions(this.name)}set options(e){throw new Error("Cannot directly set channel options")}createConsumer(e){return this._dataStream.createConsumer(e)}listener(e){return this._eventDemux.stream(`${this.name}/${e}`)}close(){this.client.closeChannel(this.name)}kill(){this.client.killChannel(this.name)}killOutputConsumer(e){this.hasOutputConsumer(e)&&this.client.killChannelOutputConsumer(e)}killListenerConsumer(e){this.hasAnyListenerConsumer(e)&&this.client.killChannelListenerConsumer(e)}getOutputConsumerStats(e){if(this.hasOutputConsumer(e))return this.client.getChannelOutputConsumerStats(e)}getListenerConsumerStats(e){if(this.hasAnyListenerConsumer(e))return this.client.getChannelListenerConsumerStats(e)}getBackpressure(){return this.client.getChannelBackpressure(this.name)}getListenerConsumerBackpressure(e){return this.hasAnyListenerConsumer(e)?this.client.getChannelListenerConsumerBackpressure(e):0}getOutputConsumerBackpressure(e){return this.hasOutputConsumer(e)?this.client.getChannelOutputConsumerBackpressure(e):0}closeOutput(){this.client.channelCloseOutput(this.name)}closeListener(e){this.client.channelCloseListener(this.name,e)}closeAllListeners(){this.client.channelCloseAllListeners(this.name)}killOutput(){this.client.channelKillOutput(this.name)}killListener(e){this.client.channelKillListener(this.name,e)}killAllListeners(){this.client.channelKillAllListeners(this.name)}getOutputConsumerStatsList(){return this.client.channelGetOutputConsumerStatsList(this.name)}getListenerConsumerStatsList(e){return this.client.channelGetListenerConsumerStatsList(this.name,e)}getAllListenersConsumerStatsList(){return this.client.channelGetAllListenersConsumerStatsList(this.name)}getOutputBackpressure(){return this.client.channelGetOutputBackpressure(this.name)}getListenerBackpressure(e){return this.client.channelGetListenerBackpressure(this.name,e)}getAllListenersBackpressure(){return this.client.channelGetAllListenersBackpressure(this.name)}hasOutputConsumer(e){return this.client.channelHasOutputConsumer(this.name,e)}hasListenerConsumer(e,t){return this.client.channelHasListenerConsumer(this.name,e,t)}hasAnyListenerConsumer(e){return this.client.channelHasAnyListenerConsumer(this.name,e)}subscribe(e){this.client.subscribe(this.name,e)}unsubscribe(){this.client.unsubscribe(this.name)}isSubscribed(e){return this.client.isSubscribed(this.name,e)}transmitPublish(e){return this.client.transmitPublish(this.name,e)}invokePublish(e){return this.client.invokePublish(this.name,e)}},m=P;h(m,"PENDING","pending"),h(m,"SUBSCRIBED","subscribed"),h(m,"UNSUBSCRIBED","unsubscribed");var H="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Se=/^[ \n\r\t]*[{\[]/,T=g(),ye=function(s){let e=new Uint8Array(s),t=e.length,n="";for(let r=0;r<t;r+=3)n+=H[e[r]>>2],n+=H[(e[r]&3)<<4|e[r+1]>>4],n+=H[(e[r+1]&15)<<2|e[r+2]>>6],n+=H[e[r+2]&63];return t%3===2?n=n.substring(0,n.length-1)+"=":t%3===1&&(n=n.substring(0,n.length-2)+"=="),n},ve=function(s,e){if(T.ArrayBuffer&&e instanceof T.ArrayBuffer)return{base64:!0,data:ye(e)};if(T.Buffer){if(e instanceof T.Buffer)return{base64:!0,data:e.toString("base64")};if(e&&e.type==="Buffer"&&Array.isArray(e.data)){let t;return T.Buffer.from?t=T.Buffer.from(e.data):t=new T.Buffer(e.data),{base64:!0,data:t.toString("base64")}}}return e};function Te(s){if(s==null)return null;if(s==="#1"||s==="#2")return s;let e=s.toString();if(!Se.test(e))return e;try{return JSON.parse(e)}catch{}return e}function _e(s){return s==="#1"||s==="#2"?s:JSON.stringify(s,ve)}var te={encode:_e,decode:Te};function G(s,e){if(!e)return s;if(e[Symbol.iterator]){let t=e[Symbol.iterator](),n;for(;(n=t.next())&&!n.done;)s.append(n.value)}else{let t=-1;for(;++t<e.length;){let n=e[t];s.append(n)}}return s}var j=class{next;prev;list;constructor(){this.next=null,this.prev=null,this.list=null}append(e){let t=this.list;if(!e||!e.append||!e.prepend||!e.detach)throw new Error("An argument without append, prepend, or detach methods was given to `Item#append`.");return!t||this===e?!1:(e.detach(),this.next&&(e.next=this.next,this.next.prev=e),e.prev=this,e.list=t,this.next=e,(this===t.tail||!t.tail)&&(t.tail=e),t.size++,e)}prepend(e){let t=this.list;if(!e||!e.append||!e.prepend||!e.detach)throw new Error("An argument without append, prepend, or detach methods was given to `Item#prepend`.");return!t||this===e?!1:(e.detach(),this.prev&&(e.prev=this.prev,this.prev.next=e),e.next=this,e.list=t,this.prev=e,this===t.head&&(t.head=e),t.tail||(t.tail=this),t.size++,e)}detach(){let e=this.list;return e?(e.tail===this&&(e.tail=this.prev),e.head===this&&(e.head=this.next),e.tail===e.head&&(e.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,e.size--,this):this}};var M=class{item=null;constructor(e){this.item=e}next(){let e=this.item;return e?(this.item=e.next,{value:e,done:!1}):{value:null,done:!0}}};var V=class{size;head;tail;static from(e){let t=new this;return G(t,e)}static of(...e){let t=new this;return G(t,e)}constructor(...e){this.size=0,this.tail=null,this.head=null,G(this,e)}append(e){if(!e)return!1;if(!e.append||!e.prepend||!e.detach)throw new Error("An argument without append, prepend, or detach methods was given to `List#append`.");return this.tail?this.tail.append(e):this.head?this.head.append(e):(e.detach(),e.list=this,this.head=e,this.size++,e)}prepend(e){if(!e)return!1;if(!e.append||!e.prepend||!e.detach)throw new Error("An argument without append, prepend, or detach methods was given to `List#prepend`.");return this.head?this.head.prepend(e):(e.detach(),e.list=this,this.head=e,this.size++,e)}toArray(){let e=this.head,t=[];for(;e;)t.push(e),e=e.next;return t}[Symbol.iterator](){return new M(this.head)}};function ne(s){return Object.prototype.toString.call(s)==="[object Date]"}function re(s){return!!s&&typeof s=="object"&&Object.prototype.toString.call(s)!=="[object Array]"}function $(s){if(ne(s))return new Date(s.getTime());if(Array.isArray(s))return[...s].map(e=>$(e));if(s instanceof Map||s instanceof Set)return s;if(re(s)){let e={};for(let t of Object.keys(s))e[t]=$(s[t]);return e}return s}function F(s=0){return new Promise(e=>{setTimeout(()=>e(),s)})}var k=g(),I=class{_internalStorage;isLocalStorageEnabled;constructor(){this._internalStorage={},this.isLocalStorageEnabled=this._checkLocalStorageEnabled()}saveToken(e,t,n){return this.isLocalStorageEnabled&&k.localStorage?k.localStorage.setItem(e,t):this._internalStorage[e]=t,Promise.resolve(t)}removeToken(e){let t=this.loadToken(e);return this.isLocalStorageEnabled&&k.localStorage?k.localStorage.removeItem(e):delete this._internalStorage[e],t}loadToken(e){let t;return this.isLocalStorageEnabled&&k.localStorage?t=k.localStorage.getItem(e):t=this._internalStorage[e]||null,Promise.resolve(t)}_checkLocalStorageEnabled(){let e;try{k.localStorage,k.localStorage.setItem("__scLocalStorageTest",1),k.localStorage.removeItem("__scLocalStorageTest")}catch(t){e=t}return!e}};var z=class{id;socket;procedure;data;sent;constructor(e,t,n,r){this.socket=e,this.id=t,this.procedure=n,this.data=r,this.sent=!1}end(e,t){let n={rid:this.id};e!==void 0&&(n.data=e),this._respond(n,t)}error(e,t){let n={rid:this.id,error:Z(e)};this._respond(n,t)}_respond(e,t){if(this.sent)throw new _(`Response to request ${this.id} has already been sent`);this.sent=!0,this.socket.sendObject(e,t)}};function se(s){return typeof s=="function"}function ie(s,e){let t=g();if(t&&se(t.WebSocket))return new t.WebSocket(s);throw Error("WebSocket instance not found")}var d=class{state;auth;codec;options;wsOptions;protocolVersion;connectTimeout;pingTimeout;pingTimeoutDisabled;callIdGenerator;authTokenName;isBufferingBatch;socket;_pingTimeoutTicker;_callbackMap;_batchBuffer;_onOpenHandler;_onOpenAbortHandler;_onCloseHandler;_onEventHandler;_onErrorHandler;_onInboundInvokeHandler;_onInboundTransmitHandler;_connectTimeoutRef;_handlePing;constructor(e,t,n,r,i){this.state=d.CLOSED,this.auth=e,this.codec=t,this.options=n,this.wsOptions=r,this.protocolVersion=n.protocolVersion,this.connectTimeout=n.connectTimeout,this.pingTimeout=n.pingTimeout,this.pingTimeoutDisabled=!!n.pingTimeoutDisabled,this.callIdGenerator=n.callIdGenerator,this.authTokenName=n.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=d.CONNECTING;let o=this.uri(),u=ie(o,r);u.binaryType=this.options.binaryType,this.socket=u,u.onopen=()=>{this._onOpen()},u.onclose=async a=>{let c;a.code==null?c=1005:c=a.code,this._destroy(c,a.reason)},u.onmessage=(a,c)=>{this._onMessage(a.data)},u.onerror=()=>{this.state===d.CONNECTING&&this._destroy(1006)},this._connectTimeoutRef=setTimeout(()=>{this._destroy(4007),this.socket.close(4007)},this.connectTimeout),this.protocolVersion===1?this._handlePing=a=>a==="#1"?(this._resetPingTimeout(),this.socket.readyState===this.socket.OPEN&&this.send("#2"),!0):!1:this._handlePing=a=>a===""?(this._resetPingTimeout(),this.socket.readyState===this.socket.OPEN&&this.send(""),!0):!1}uri(){let e=this.options.query||{},t;this.options.protocolScheme==null?t=this.options.secure?"wss":"ws":t=this.options.protocolScheme,this.options.timestampRequests&&(e[this.options.timestampParam]=new Date().getTime());let n=new URLSearchParams;for(let[o,u]of Object.entries(e))if(Array.isArray(u))for(let a of u)n.append(o,a);else n.set(o,`${u}`);e=n.toString(),e.length&&(e="?"+e);let r,i;if(this.options.socketPath==null){if(this.options.host)r=this.options.host;else{let o="";this.options.port&&(t==="wss"&&this.options.port!==443||t==="ws"&&this.options.port!==80)&&(o=":"+this.options.port),r=this.options.hostname+o}i=this.options.path}else r=this.options.socketPath,i=`:${this.options.path}`;return t+"://"+r+i+e}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 e=this.serializeObject(this._batchBuffer);this._batchBuffer=[],this.send(e)}cancelBatch(){this.isBufferingBatch=!1,this._batchBuffer=[]}getBytesReceived(){return this.socket.bytesReceived}close(e,t){(this.state===d.OPEN||this.state===d.CONNECTING)&&(e=e||1e3,this._destroy(e,t),this.socket.close(e,t))}transmitObject(e){let t={event:e.event,data:e.data};return e.callback&&(t.cid=e.cid=this.callIdGenerator(),this._callbackMap[e.cid]=e),this.sendObject(t),e.cid||null}transmit(e,t,n){let r={event:e,data:t};return(this.state===d.OPEN||n.force)&&this.transmitObject(r),Promise.resolve()}invokeRaw(e,t,n,r){let i={event:e,data:t,callback:r};n.noTimeout||(i.timeout=setTimeout(()=>{this._handleEventAckTimeout(i)},this.options.ackTimeout));let o=null;return(this.state===d.OPEN||n.force)&&(o=this.transmitObject(i)),o}invoke(e,t,n){return new Promise((r,i)=>{this.invokeRaw(e,t,n,(o,u)=>{if(o){i(o);return}r(u)})})}cancelPendingResponse(e){delete this._callbackMap[e]}decode(e){return this.codec.decode(e)}encode(e){return this.codec.encode(e)}send(e){this.socket.readyState!==this.socket.OPEN?this._destroy(1005):this.socket.send(e)}serializeObject(e){let t;try{t=this.encode(e)}catch(n){return this._onError(n),null}return t}sendObject(e){if(this.isBufferingBatch){this._batchBuffer.push(e);return}let t=this.serializeObject(e);t!=null&&this.send(t)}_handleEventAckTimeout(e){e.cid&&delete this._callbackMap[e.cid],delete e.timeout;let t=e.callback;if(t){delete e.callback;let n=new C(`Event response for "${e.event}" timed out`);t.call(e,n,e)}}async _onOpen(){clearTimeout(this._connectTimeoutRef),this._resetPingTimeout();let e;try{e=await this._handshake()}catch(t){t.statusCode==null&&(t.statusCode=4003),this._onError(t),this._destroy(t.statusCode,t.toString()),this.socket.close(t.statusCode);return}this.state=d.OPEN,e&&(this.pingTimeout=e.pingTimeout),this._resetPingTimeout(),this._onOpenHandler(e)}async _handshake(){let e=await this.auth.loadToken(this.authTokenName),t={force:!0},n=await this.invoke("#handshake",{authToken:e},t);return n&&(n.authToken=e,n.authError&&(n.authError=w(n.authError))),n}_abortAllPendingEventsDueToBadConnection(e){Object.keys(this._callbackMap||{}).forEach(t=>{let n=this._callbackMap[t];delete this._callbackMap[t],clearTimeout(n.timeout),delete n.timeout;let r=`Event "${n.event}" was aborted due to a bad connection`,i=new S(r,e),o=n.callback;o&&(delete n.callback,o.call(n,i,n))})}_destroy(e,t){!t&&B[e]&&(t=B[e]),delete this.socket.onopen,delete this.socket.onclose,delete this.socket.onmessage,delete this.socket.onerror,clearTimeout(this._connectTimeoutRef),clearTimeout(this._pingTimeoutTicker),this.state===d.OPEN?(this.state=d.CLOSED,this._abortAllPendingEventsDueToBadConnection("disconnect"),this._onCloseHandler({code:e,reason:t})):this.state===d.CONNECTING?(this.state=d.CLOSED,this._abortAllPendingEventsDueToBadConnection("connectAbort"),this._onOpenAbortHandler({code:e,reason:t})):this.state===d.CLOSED&&this._abortAllPendingEventsDueToBadConnection("connectAbort")}_processInboundPacket(e,t){if(e&&e.event!=null)if(e.cid==null)this._onInboundTransmitHandler({...e});else{let n=new z(this,e.cid,e.event,e.data);this._onInboundInvokeHandler(n)}else if(e&&e.rid!=null){let n=this._callbackMap[e.rid];if(n&&(clearTimeout(n.timeout),delete n.timeout,delete this._callbackMap[e.rid],n.callback)){let r=w(e.error);n.callback(r,e.data)}}else this._onEventHandler({event:"raw",data:{message:t}})}_onMessage(e){if(this._onEventHandler({event:"message",data:{message:e}}),this._handlePing(e))return;let t=this.decode(e);if(Array.isArray(t)){let n=t.length;for(let r=0;r<n;r++)this._processInboundPacket(t[r],e)}else this._processInboundPacket(t,e)}_onError(e){this._onErrorHandler({error:e})}_resetPingTimeout(){this.pingTimeoutDisabled||(clearTimeout(this._pingTimeoutTicker),this._pingTimeoutTicker=setTimeout(()=>{this._destroy(4e3),this.socket.close(4e3)},this.pingTimeout))}},v=d;h(v,"CONNECTING","connecting"),h(v,"OPEN","open"),h(v,"CLOSED","closed");var xe=typeof window<"u",q=g(),l=class extends U{options;id;clientId;version;protocolVersion;state;authState;signedAuthToken;authToken;authTokenName;wsOptions;pendingReconnect;pendingReconnectTimeout;preparingPendingSubscriptions;ackTimeout;connectTimeout;pingTimeout;pingTimeoutDisabled;channelPrefix;disconnectOnUnload;connectAttempts;isBatching;batchOnHandshake;batchOnHandshakeDuration;auth;codec;transport;poolIndex;_batchingIntervalId;_outboundBuffer;_channelMap;_channelEventDemux;_channelDataDemux;_receiverDemux;_procedureDemux;_cid;_reconnectTimeoutRef;_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),n=this._channelMap[t];n&&(this.emit("kickOut",{channel:t,message:e.message}),this._channelEventDemux.write(`${t}/kickOut`,{message:e.message}),this._triggerChannelUnsubscribe(n))},"#setAuthToken":e=>{e&&this._setAuthToken(e)},"#removeAuthToken":e=>{this._removeAuthToken()}};_privateRPCHandlerMap={"#setAuthToken":(e,t)=>{e?(this._setAuthToken(e),t.end()):t.error(new x("No token data provided by #setAuthToken event"))},"#removeAuthToken":(e,t)=>{this._removeAuthToken(),t.end()}};constructor(e){super();let n=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=n.version||null,this.protocolVersion=n.protocolVersion,this.state=l.CLOSED,this.authState=l.UNAUTHENTICATED,this.signedAuthToken=null,this.authToken=null,this.pendingReconnect=!1,this.pendingReconnectTimeout=null,this.preparingPendingSubscriptions=!1,this.clientId=n.clientId,this.wsOptions=n.wsOptions,this.connectTimeout=n.connectTimeout,this.ackTimeout=n.ackTimeout,this.channelPrefix=n.channelPrefix||null,this.disconnectOnUnload=n.disconnectOnUnload==null?!0:n.disconnectOnUnload,this.authTokenName=n.authTokenName,n.pingTimeout=n.connectTimeout,this.pingTimeout=n.pingTimeout,this.pingTimeoutDisabled=!!n.pingTimeoutDisabled;let r=Math.pow(2,31)-1,i=o=>{if(this[o]>r)throw new f(`The ${o} value provided exceeded the maximum amount allowed`)};if(i("connectTimeout"),i("ackTimeout"),i("pingTimeout"),this.connectAttempts=0,this.isBatching=!1,this.batchOnHandshake=n.batchOnHandshake,this.batchOnHandshakeDuration=n.batchOnHandshakeDuration,this._batchingIntervalId=null,this._outboundBuffer=new V,this._channelMap={},this._channelEventDemux=new b,this._channelDataDemux=new b,this._receiverDemux=new b,this._procedureDemux=new b,this.options=n,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 I,this.options.codecEngine?this.codec=this.options.codecEngine:this.codec=te,this.options.protocol){let o=new f('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=n.query||{},typeof this.options.query=="string"){let o=new URLSearchParams(this.options.query),u={};o.forEach((a,c)=>{let O=u[c];O==null?u[c]=a:(Array.isArray(O)||(u[c]=[O]),u[c].push(a))}),this.options.query=u}xe&&this.disconnectOnUnload&&q.addEventListener&&q.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!==l.CLOSED&&this.transmit("#removeAuthToken"),this._changeToUnauthenticatedStateAndClearTokens(),await F(0)}connect(){if(this.state===l.CLOSED){this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef),this.state=l.CONNECTING,this.emit("connecting",{}),this.transport&&this.transport.clearAllListeners();let e={onOpen:t=>{this.state=l.OPEN,this._onOpen(t)},onOpenAbort:t=>{this.state!==l.CLOSED&&(this.state=l.CLOSED,this._destroy(t.code,t.reason,!0))},onClose:t=>{this.state!==l.CLOSED&&(this.state=l.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 v(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 f("If specified, the code argument must be a number");let n=this.state===l.CONNECTING;n||this.state===l.OPEN?(this.state=l.CLOSED,this._destroy(e,t,n),this.transport.close(e,t)):(this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef))}decodeBase64(e){return W.default.from(e,"base64").toString("utf8")}encodeBase64(e){return W.default.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(n){throw n.name!=="BadConnectionError"&&n.name!=="TimeoutError"&&this._changeToUnauthenticatedStateAndClearTokens(),await F(0),n}return t&&t.isAuthenticated!=null?t.authError&&(t.authError=w(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(n){this._onError(n)}})(),await F(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,n){return this._processOutboundEvent(e,t,n)}invoke(e,t,n){return this._processOutboundEvent(e,t,n,!0)}transmitPublish(e,t){let n={channel:this._decorateChannelName(e),data:t};return this.transmit("#publish",n)}invokePublish(e,t){let n={channel:this._decorateChannelName(e),data:t};return this.invoke("#publish",n)}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 n=this._channelMap[e],r={waitForAuth:!!t.waitForAuth};return t.priority!=null&&(r.priority=t.priority),t.data!==void 0&&(r.data=t.data),n?t&&(n.options=r):(n={name:e,state:m.PENDING,options:r},this._channelMap[e]=n,this._trySubscribe(n)),new m(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 m(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:m.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,n)=>(n.forEach(r=>{t.push(r)}),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(n=>this._channelEventDemux.getBackpressure(n));return Math.max(...t.concat(0))}channelHasOutputConsumer(e,t){return this._channelDataDemux.hasConsumer(e,t)}channelHasListenerConsumer(e,t,n){return this._channelEventDemux.hasConsumer(`${e}/${t}`,n)}channelHasAnyListenerConsumer(e,t){return this._getAllChannelStreamNames(e).some(n=>this._channelEventDemux.hasConsumer(n,t))}subscriptions(e){let t=[];return Object.keys(this._channelMap).forEach(n=>{(e||this._channelMap[n].state===m.SUBSCRIBED)&&t.push(n)}),t}isSubscribed(e,t){let n=this._channelMap[e];return t?!!n:!!n&&n.state===m.SUBSCRIBED}processPendingSubscriptions(){this.preparingPendingSubscriptions=!1;let e=[];Object.keys(this._channelMap).forEach(t=>{let n=this._channelMap[t];n.state===m.PENDING&&e.push(n)}),e.sort((t,n)=>{let r=t.options.priority||0,i=n.options.priority||0;return r>i?-1:r<i?1:0}),e.forEach(t=>{this._trySubscribe(t)})}_getAllChannelStreamNames(e){let t=this._channelEventDemux.getConsumerStatsListAll().filter(n=>n.stream.indexOf(`${e}/`)===0).reduce((n,r)=>(n[r.stream]=!0,n),{});return Object.keys(t)}_tryUnsubscribe(e){if(this.state===l.OPEN){let t={noTimeout:!0};this._cancelPendingSubscribeCallback(e);let n=this._decorateChannelName(e.name);this.transport.transmit("#unsubscribe",n,t)}}_triggerChannelUnsubscribe(e,t){let n=e.name;if(this._cancelPendingSubscribeCallback(e),e.state===m.SUBSCRIBED){let r={oldChannelState:e.state,newChannelState:t?m.PENDING:m.UNSUBSCRIBED};this._channelEventDemux.write(`${n}/subscribeStateChange`,r),this._channelEventDemux.write(`${n}/unsubscribe`,{}),this.emit("subscribeStateChange",{channel:n,...r}),this.emit("unsubscribe",{channel:n})}t?e.state=m.PENDING:delete this._channelMap[n]}_trySubscribe(e){let t=!e.options.waitForAuth||this.authState===l.AUTHENTICATED;if(this.state===l.OPEN&&!this.preparingPendingSubscriptions&&e._pendingSubscriptionCid==null&&t){let n={noTimeout:!0},r={};e.options.waitForAuth&&(n.waitForAuth=!0,r.waitForAuth=n.waitForAuth),e.options.data&&(r.data=e.options.data),e._pendingSubscriptionCid=this.transport.invokeRaw("#subscribe",{channel:this._decorateChannelName(e.name),...r},n,i=>{if(i){if(i.name==="BadConnectionError")return;delete e._pendingSubscriptionCid,this._triggerChannelSubscribeFail(i,e,r)}else delete e._pendingSubscriptionCid,this._triggerChannelSubscribe(e,r)}),this.emit("subscribeRequest",{channel:e.name,subscriptionOptions:r})}}_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,n){let r=t.name,i=!t.options.waitForAuth||this.authState===l.AUTHENTICATED;!!this._channelMap[r]&&i&&(delete this._channelMap[r],this._channelEventDemux.write(`${r}/subscribeFail`,{error:e,subscriptionOptions:n}),this.emit("subscribeFail",{error:e,channel:r,subscriptionOptions:n}))}_triggerChannelSubscribe(e,t){let n=e.name;if(e.state!==m.SUBSCRIBED){let r=e.state;e.state=m.SUBSCRIBED;let i={oldChannelState:r,newChannelState:e.state,subscriptionOptions:t};this._channelEventDemux.write(`${n}/subscribeStateChange`,i),this._channelEventDemux.write(`${n}/subscribe`,{subscriptionOptions:t}),this.emit("subscribeStateChange",{channel:n,...i}),this.emit("subscribe",{channel:n,subscriptionOptions:t})}}_processOutboundEvent(e,t,n,r){n=n||{},this.state===l.CLOSED&&this.connect();let i={event:e,data:null},o;r?o=new Promise((c,O)=>{i.callback=(J,ue)=>{if(J){O(J);return}c(ue)}}):o=Promise.resolve();let u=new j;this.options.cloneData?i.data=$(t):i.data=t,u.data=i;let a=n.ackTimeout==null?this.ackTimeout:n.ackTimeout;return i.timeout=setTimeout(()=>{this._handleEventAckTimeout(i,u)},a),this._outboundBuffer.append(u),this.state===l.OPEN&&this._flushOutboundBuffer(),o}_handleEventAckTimeout(e,t){t&&t.detach(),delete e.timeout;let n=e.callback;if(n){delete e.callback;let r=new C(`Event response for "${e.event}" timed out`);n.call(e,r,e)}e.cid&&this.transport.cancelPendingResponse(e.cid)}_flushOutboundBuffer(){let e=this._outboundBuffer.head,t;for(;e;){t=e.next;let n=e.data;e.detach(),this.transport.transmitObject(n),e=t}}_onInboundInvoke(e){let{procedure:t,data:n}=e,r=this._privateRPCHandlerMap[t];r?r.call(this,n,e):this._procedureDemux.write(t,e)}_onInboundTransmit(e,t){let n=this._privateDataHandlerMap[e];n?n.call(this,t):this._receiverDemux.write(e,t)}_destroy(e,t,n){if(this.id=null,this._cancelBatching(),this.transport&&this.transport.clearAllListeners(),this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef),this._suspendSubscriptions(),n?this.emit("connectAbort",{code:e,reason:t}):this.emit("disconnect",{code:e,reason:t}),this.emit("close",{code:e,reason:t}),!l.ignoreStatuses[e]){let r;t?r="Socket connection closed with status code "+e+" and reason: "+t:r="Socket connection closed with status code "+e;let i=new E(l.errorStatuses[e]||r,e);this._onError(i)}this._abortAllPendingEventsDueToBadConnection(n?"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,n;for(;t;){n=t.next;let r=t.data;clearTimeout(r.timeout),delete r.timeout,t.detach(),t=n;let i=r.callback;if(i){delete r.callback;let o=`Event "${r.event}" was aborted due to a bad connection`,u=new S(o,e);i.call(r,u,r)}r.cid&&this.transport.cancelPendingResponse(r.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++,n=this.options.autoReconnectOptions,r;if(e==null||t>0){let i=Math.round(n.initialDelay+(n.randomness||0)*Math.random());r=Math.round(i*Math.pow(n.multiplier,t))}else r=e;r>n.maxDelay&&(r=n.maxDelay),clearTimeout(this._reconnectTimeoutRef),this.pendingReconnect=!0,this.pendingReconnectTimeout=r,this._reconnectTimeoutRef=setTimeout(()=>{this.connect()},r)}_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===l.OPEN&&this._flushOutboundBuffer()}_extractAuthTokenData(e){let n=(e||"").split(".")[1];if(n!=null){let r=n;try{return r=this.decodeBase64(r),JSON.parse(r)}catch{return r}}return null}_changeToAuthenticatedState(e){if(this.signedAuthToken=e,this.authToken=this._extractAuthTokenData(e),this.authState!==l.AUTHENTICATED){let t=this.authState;this.authState=l.AUTHENTICATED;let n={oldAuthState:t,newAuthState:this.authState,signedAuthToken:e,authToken:this.authToken};this.preparingPendingSubscriptions||this.processPendingSubscriptions(),this.emit("authStateChange",n)}this.emit("authenticate",{signedAuthToken:e,authToken:this.authToken})}_changeToUnauthenticatedStateAndClearTokens(){if(this.authState!==l.UNAUTHENTICATED){let e=this.authState,t=this.authToken,n=this.signedAuthToken;this.authState=l.UNAUTHENTICATED,this.signedAuthToken=null,this.authToken=null;let r={oldAuthState:e,newAuthState:this.authState};this.emit("authStateChange",r),this.emit("deauthenticate",{oldSignedAuthToken:n,oldAuthToken:t})}}async _handleBrowserUnload(){let e=()=>{this.disconnect()},t=!1,n=()=>{t||(t=!0,q.addEventListener("beforeunload",e,!1))},r=()=>{t&&(t=!1,q.removeEventListener("beforeunload",e,!1))};(async()=>{let i=this.listener("connecting").createConsumer();for(;!(await i.next()).done;)n()})(),(async()=>{let i=this.listener("close").createConsumer();for(;!(await i.next()).done;)r()})()}_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()}},p=l;h(p,"CONNECTING","connecting"),h(p,"OPEN","open"),h(p,"CLOSED","closed"),h(p,"AUTHENTICATED","authenticated"),h(p,"UNAUTHENTICATED","unauthenticated"),h(p,"SUBSCRIBED","subscribed"),h(p,"PENDING","pending"),h(p,"UNSUBSCRIBED","unsubscribed"),h(p,"ignoreStatuses",Y),h(p,"errorStatuses",B);var K=g();function Ee(){return K.location&&location.protocol==="https:"}function Ae(s,e){let t=s.secure==null?e:s.secure;return s.port||(K.location&&location.port?parseFloat(location.port):t?443:80)}function oe(s){if(s=s||{},s.host&&!s.host.match(/[^:]+:\d{2,5}/))throw new f('The host option should include both the hostname and the port number in the format "hostname:port"');if(s.host&&s.hostname)throw new f('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(s.host&&s.port)throw new f('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 e=Ee(),t={clientId:ee(),port:Ae(s,e),hostname:K.location&&location.hostname||"localhost",secure:e};return Object.assign(t,s),new p(t)}var ae="1.0.0";function Oe(s){return oe({...s,version:ae})}0&&(module.exports={AuthEngine,TGClientSocket,TGTransport,create,version});
var ie=Object.create;var D=Object.defineProperty;var oe=Object.getOwnPropertyDescriptor;var ae=Object.getOwnPropertyNames;var ue=Object.getPrototypeOf,ce=Object.prototype.hasOwnProperty;var le=(s,e,t)=>e in s?D(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var he=(s,e)=>{for(var t in e)D(s,t,{get:e[t],enumerable:!0})},z=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ae(e))!ce.call(s,r)&&r!==t&&D(s,r,{get:()=>e[r],enumerable:!(n=oe(e,r))||n.enumerable});return s};var me=(s,e,t)=>(t=s!=null?ie(ue(s)):{},z(e||!s||!s.__esModule?D(t,"default",{value:s,enumerable:!0}):t,s)),de=s=>z(D({},"__esModule",{value:!0}),s);var m=(s,e,t)=>(le(s,typeof e!="symbol"?e+"":e,t),t);var Ee={};he(Ee,{AuthEngine:()=>w,TGClientSocket:()=>f,TGTransport:()=>y,create:()=>_e,version:()=>re});module.exports=de(Ee);function W(s){let e=[],t=[];return function n(r,i){let o,c,a;if(typeof r=="object"&&r!==null&&!(r instanceof Boolean)&&!(r instanceof Date)&&!(r instanceof Number)&&!(r instanceof RegExp)&&!(r instanceof String)){for(o=0;o<e.length;o+=1)if(e[o]===r)return{$ref:t[o]};if(e.push(r),t.push(i),Object.prototype.toString.apply(r)==="[object Array]")for(a=[],o=0;o<r.length;o+=1)a[o]=n(r[o],i+"["+o+"]");else{a={};for(c in r)Object.prototype.hasOwnProperty.call(r,c)&&(a[c]=n(r[c],i+"["+JSON.stringify(c)+"]"))}return a}return r}(s,"$")}function E(){"use strict";return typeof function(){return this}()>"u"}var T=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,T.prototype),this.name="InvalidActionError",this.message=e,Error.captureStackTrace&&!E()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}},g=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,g.prototype),this.name="InvalidArgumentsError",this.message=e,Error.captureStackTrace&&!E()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}};var v=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,v.prototype),this.name="InvalidMessageError",this.message=e,Error.captureStackTrace&&!E()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}},_=class extends Error{code;constructor(e,t){super(e),Object.setPrototypeOf(this,_.prototype),this.name="SocketProtocolError",this.message=e,this.code=t,Error.captureStackTrace&&!E()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}};var k=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,k.prototype),this.name="TimeoutError",this.message=e,Error.captureStackTrace&&!E()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}},C=class extends Error{type;constructor(e,t){super(e),Object.setPrototypeOf(this,C.prototype),this.name="BadConnectionError",this.message=e,this.type=t,Error.captureStackTrace&&!E()?Error.captureStackTrace(this,arguments.callee):this.stack=new Error().stack}};var A={1001:"Socket was disconnected",1002:"A WebSocket protocol error was encountered",1003:"Server terminated socket because it received invalid data",1005:"Socket closed without status code",1006:"Socket hung up",1007:"Message format was incorrect",1008:"Encountered a policy violation",1009:"Message was too big to process",1010:"Client ended the connection because the server did not comply with extension requirements",1011:"Server encountered an unexpected fatal condition",4e3:"Server ping timed out",4001:"Client pong timed out",4002:"Server failed to sign auth token",4003:"Failed to complete handshake",4004:"Client failed to save auth token",4005:"Did not receive #handshake from client before timeout",4006:"Failed to bind socket to message broker",4007:"Client connection establishment timed out",4008:"Server rejected handshake from client",4009:"Server received a message before the client handshake"},K={1e3:"Socket closed normally",1001:"Socket hung up"},pe={domain:1,domainEmitter:1,domainThrown:1};function J(s,e){let t;if(s&&typeof s=="object"){t={message:s.message},e&&(t.stack=s.stack);for(let n in s)pe[n]||(t[n]=s[n])}else typeof s=="function"?t="[function "+(s.name||"anonymous")+"]":t=s;return W(t)}function O(s){let e=null;if(s!=null)if(typeof s=="object"){e=new Error(s.message);for(let t in s)s.hasOwnProperty(t)&&(e[t]=s[t])}else e=s;return e}var l=typeof self=="object"&&self.self===self&&self||typeof global=="object"&&global.global===global&&global||void 0;function Q(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{let e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}var F=me(require("topgun-buffer"));var S=class{async next(e){let t=this.createConsumer(e),n=await t.next();return t.return(),n}async once(e){let t=await this.next(e);return t.done&&await new Promise(()=>{}),t.value}createConsumer(e){throw new TypeError("Method must be overriden by subclass")}[Symbol.asyncIterator](){return this.createConsumer()}};var I=class{id;timeout;stream;currentNode;isAlive;_backpressure;_timeoutId;_resolve;_killPacket;constructor(e,t,n,r){this.id=t,this._backpressure=0,this.stream=e,this.currentNode=n,this.timeout=r,this.isAlive=!0,this.stream.setConsumer(this.id,this)}getStats(){let e={id:this.id,backpressure:this._backpressure};return this.timeout!=null&&(e.timeout=this.timeout),e}applyBackpressure(e){this._backpressure++}releaseBackpressure(e){this._backpressure--}getBackpressure(){return this._backpressure}write(e){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this.applyBackpressure(e),this._resolve&&(this._resolve(),delete this._resolve)}kill(e){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this._killPacket={value:e,done:!0},this._destroy(),this._resolve&&(this._resolve(),delete this._resolve)}async next(){for(this.stream.setConsumer(this.id,this);;){if(this.currentNode&&!this.currentNode.next)try{await this._waitForNextItem(this.timeout)}catch(e){throw this._destroy(),e}if(this._killPacket){this._destroy();let e=this._killPacket;return delete this._killPacket,e}if(this.currentNode){if(this.currentNode=this.currentNode.next,this.releaseBackpressure(this.currentNode.data),this.currentNode.consumerId&&this.currentNode.consumerId!==this.id)continue;return this.currentNode.data.done&&this._destroy(),this.currentNode.data}}}return(){return delete this.currentNode,this._destroy(),{}}_resetBackpressure(){this._backpressure=0}_destroy(){this.isAlive=!1,this._resetBackpressure(),this.stream.removeConsumer(this.id)}async _waitForNextItem(e){return new Promise((t,n)=>{this._resolve=t;let r;if(e!==void 0){let i=new Error("Stream consumer iteration timed out");(async()=>{let o=fe(e);r=o.timeoutId,await o.promise,i.name="TimeoutError",delete this._resolve,n(i)})()}this._timeoutId=r})}[Symbol.asyncIterator](){return this}};function fe(s){let e,t=new Promise(n=>{e=setTimeout(n,s)});return{timeoutId:e,promise:t}}var P=class extends S{type;nextConsumerId;_consumers;_tailNode;constructor(){super(),this.nextConsumerId=1,this._consumers=new Map,this._tailNode={next:null,data:{value:void 0,done:!1}}}write(e){this._write(e,!1)}close(e){this._write(e,!0)}writeToConsumer(e,t){this._write(t,!1,e)}closeConsumer(e,t){this._write(t,!0,e)}kill(e){for(let t of this._consumers.keys())this.killConsumer(t,e)}killConsumer(e,t){let n=this._consumers.get(e);!n||n.kill(t)}getBackpressure(){let e=0;for(let t of this._consumers.values()){let n=t.getBackpressure();n>e&&(e=n)}return e}getConsumerBackpressure(e){let t=this._consumers.get(e);return t?t.getBackpressure():0}hasConsumer(e){return this._consumers.has(e)}setConsumer(e,t){this._consumers.set(e,t),t.currentNode||(t.currentNode=this._tailNode)}removeConsumer(e){return this._consumers.delete(e)}getConsumerStats(e){let t=this._consumers.get(e);if(t)return t.getStats()}getConsumerStatsList(){let e=[];for(let t of this._consumers.values())e.push(t.getStats());return e}createConsumer(e){return new I(this,this.nextConsumerId++,this._tailNode,e)}getConsumerList(){return[...this._consumers.values()]}getConsumerCount(){return this._consumers.size}_write(e,t,n){let r={data:{value:e,done:t},next:null};n&&(r.consumerId=n),this._tailNode.next=r,this._tailNode=r;for(let i of this._consumers.values())i.write(r.data)}};var L=class extends S{name;_streamDemux;constructor(e,t){super(),this.name=t,this._streamDemux=e}createConsumer(e){return this._streamDemux.createConsumer(this.name,e)}};var b=class{_mainStream;constructor(){this._mainStream=new P}write(e,t){this._mainStream.write({stream:e,data:{value:t,done:!1}})}close(e,t){this._mainStream.write({stream:e,data:{value:t,done:!0}})}closeAll(e){this._mainStream.close(e)}writeToConsumer(e,t){this._mainStream.writeToConsumer(e,{consumerId:e,data:{value:t,done:!1}})}closeConsumer(e,t){this._mainStream.closeConsumer(e,{consumerId:e,data:{value:t,done:!0}})}getConsumerStats(e){return this._mainStream.getConsumerStats(e)}getConsumerStatsList(e){return this._mainStream.getConsumerStatsList().filter(n=>n.stream===e)}getConsumerStatsListAll(){return this._mainStream.getConsumerStatsList()}kill(e,t){let n=this.getConsumerStatsList(e),r=n.length;for(let i=0;i<r;i++)this.killConsumer(n[i].id,t)}killAll(e){this._mainStream.kill(e)}killConsumer(e,t){this._mainStream.killConsumer(e,t)}getBackpressure(e){let t=this.getConsumerStatsList(e),n=t.length,r=0;for(let i=0;i<n;i++){let o=t[i];o.backpressure>r&&(r=o.backpressure)}return r}getBackpressureAll(){return this._mainStream.getBackpressure()}getConsumerBackpressure(e){return this._mainStream.getConsumerBackpressure(e)}hasConsumer(e,t){let n=this._mainStream.getConsumerStats(t);return!!n&&n.stream===e}hasConsumerAll(e){return this._mainStream.hasConsumer(e)}getConsumerCount(e){return this.getConsumerStatsList(e).length}getConsumerCountAll(){return this.getConsumerStatsListAll().length}createConsumer(e,t){let n=this._mainStream.createConsumer(t),r=n.next;n.next=async function(){for(;;){let a=arguments,h=await r.apply(this,a);if(h.value&&(h.value.stream===e||h.value.consumerId===this.id))return h.value.data.done&&this.return(),h.value.data;if(h.done)return h}};let i=n.getStats;n.getStats=function(){let a=arguments,h=i.apply(this,a);return h.stream=e,h};let o=n.applyBackpressure;n.applyBackpressure=function(a){let h=arguments;if(a.value&&(a.value.stream===e||a.value.consumerId===this.id)){o.apply(this,h);return}a.done&&o.apply(this,h)};let c=n.releaseBackpressure;return n.releaseBackpressure=function(a){let h=arguments;if(a.value&&(a.value.stream===e||a.value.consumerId===this.id)){c.apply(this,h);return}a.done&&c.apply(this,h)},n}stream(e){return new L(this,e)}};var N=class{_listenerDemux;constructor(){this._listenerDemux=new b}emit(e,t){this._listenerDemux.write(e,t)}listener(e){return this._listenerDemux.stream(e)}closeListener(e){this._listenerDemux.close(e)}closeAllListeners(){this._listenerDemux.closeAll()}getListenerConsumerStats(e){return this._listenerDemux.getConsumerStats(e)}getListenerConsumerStatsList(e){return this._listenerDemux.getConsumerStatsList(e)}getAllListenersConsumerStatsList(){return this._listenerDemux.getConsumerStatsListAll()}getListenerConsumerCount(e){return this._listenerDemux.getConsumerCount(e)}getAllListenersConsumerCount(){return this._listenerDemux.getConsumerCountAll()}killListener(e){this._listenerDemux.kill(e)}killAllListeners(){this._listenerDemux.killAll()}killListenerConsumer(e){this._listenerDemux.killConsumer(e)}getListenerBackpressure(e){return this._listenerDemux.getBackpressure(e)}getAllListenersBackpressure(){return this._listenerDemux.getBackpressureAll()}getListenerConsumerBackpressure(e){return this._listenerDemux.getConsumerBackpressure(e)}hasListenerConsumer(e,t){return this._listenerDemux.hasConsumer(e,t)}hasAnyListenerConsumer(e){return this._listenerDemux.hasConsumerAll(e)}};var B=class extends S{name;PENDING;SUBSCRIBED;UNSUBSCRIBED;client;_eventDemux;_dataStream;_pendingSubscriptionCid;constructor(e,t,n,r){super(),this.PENDING=B.PENDING,this.SUBSCRIBED=B.SUBSCRIBED,this.UNSUBSCRIBED=B.UNSUBSCRIBED,this.name=e,this.client=t,this._eventDemux=n,this._dataStream=r.stream(this.name)}get state(){return this.client.getChannelState(this.name)}set state(e){throw new Error("Cannot directly set channel state")}get options(){return this.client.getChannelOptions(this.name)}set options(e){throw new Error("Cannot directly set channel options")}createConsumer(e){return this._dataStream.createConsumer(e)}listener(e){return this._eventDemux.stream(`${this.name}/${e}`)}close(){this.client.closeChannel(this.name)}kill(){this.client.killChannel(this.name)}killOutputConsumer(e){this.hasOutputConsumer(e)&&this.client.killChannelOutputConsumer(e)}killListenerConsumer(e){this.hasAnyListenerConsumer(e)&&this.client.killChannelListenerConsumer(e)}getOutputConsumerStats(e){if(this.hasOutputConsumer(e))return this.client.getChannelOutputConsumerStats(e)}getListenerConsumerStats(e){if(this.hasAnyListenerConsumer(e))return this.client.getChannelListenerConsumerStats(e)}getBackpressure(){return this.client.getChannelBackpressure(this.name)}getListenerConsumerBackpressure(e){return this.hasAnyListenerConsumer(e)?this.client.getChannelListenerConsumerBackpressure(e):0}getOutputConsumerBackpressure(e){return this.hasOutputConsumer(e)?this.client.getChannelOutputConsumerBackpressure(e):0}closeOutput(){this.client.channelCloseOutput(this.name)}closeListener(e){this.client.channelCloseListener(this.name,e)}closeAllListeners(){this.client.channelCloseAllListeners(this.name)}killOutput(){this.client.channelKillOutput(this.name)}killListener(e){this.client.channelKillListener(this.name,e)}killAllListeners(){this.client.channelKillAllListeners(this.name)}getOutputConsumerStatsList(){return this.client.channelGetOutputConsumerStatsList(this.name)}getListenerConsumerStatsList(e){return this.client.channelGetListenerConsumerStatsList(this.name,e)}getAllListenersConsumerStatsList(){return this.client.channelGetAllListenersConsumerStatsList(this.name)}getOutputBackpressure(){return this.client.channelGetOutputBackpressure(this.name)}getListenerBackpressure(e){return this.client.channelGetListenerBackpressure(this.name,e)}getAllListenersBackpressure(){return this.client.channelGetAllListenersBackpressure(this.name)}hasOutputConsumer(e){return this.client.channelHasOutputConsumer(this.name,e)}hasListenerConsumer(e,t){return this.client.channelHasListenerConsumer(this.name,e,t)}hasAnyListenerConsumer(e){return this.client.channelHasAnyListenerConsumer(this.name,e)}subscribe(e){this.client.subscribe(this.name,e)}unsubscribe(){this.client.unsubscribe(this.name)}isSubscribed(e){return this.client.isSubscribed(this.name,e)}transmitPublish(e){return this.client.transmitPublish(this.name,e)}invokePublish(e){return this.client.invokePublish(this.name,e)}},d=B;m(d,"PENDING","pending"),m(d,"SUBSCRIBED","subscribed"),m(d,"UNSUBSCRIBED","unsubscribed");var R="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ge=/^[ \n\r\t]*[{\[]/,be=function(s){let e=new Uint8Array(s),t=e.length,n="";for(let r=0;r<t;r+=3)n+=R[e[r]>>2],n+=R[(e[r]&3)<<4|e[r+1]>>4],n+=R[(e[r+1]&15)<<2|e[r+2]>>6],n+=R[e[r+2]&63];return t%3===2?n=n.substring(0,n.length-1)+"=":t%3===1&&(n=n.substring(0,n.length-2)+"=="),n},ke=function(s,e){if(l.ArrayBuffer&&e instanceof l.ArrayBuffer)return{base64:!0,data:be(e)};if(l.Buffer){if(e instanceof l.Buffer)return{base64:!0,data:e.toString("base64")};if(e&&e.type==="Buffer"&&Array.isArray(e.data)){let t;return l.Buffer.from?t=l.Buffer.from(e.data):t=new l.Buffer(e.data),{base64:!0,data:t.toString("base64")}}}return e};function Ce(s){if(s==null)return null;if(s==="#1"||s==="#2")return s;let e=s.toString();if(!ge.test(e))return e;try{return JSON.parse(e)}catch{}return e}function Se(s){return s==="#1"||s==="#2"?s:JSON.stringify(s,ke)}var X={encode:Se,decode:Ce};function U(s,e){if(!e)return s;if(e[Symbol.iterator]){let t=e[Symbol.iterator](),n;for(;(n=t.next())&&!n.done;)s.append(n.value)}else{let t=-1;for(;++t<e.length;){let n=e[t];s.append(n)}}return s}var H=class{next;prev;list;constructor(){this.next=null,this.prev=null,this.list=null}append(e){let t=this.list;if(!e||!e.append||!e.prepend||!e.detach)throw new Error("An argument without append, prepend, or detach methods was given to `Item#append`.");return!t||this===e?!1:(e.detach(),this.next&&(e.next=this.next,this.next.prev=e),e.prev=this,e.list=t,this.next=e,(this===t.tail||!t.tail)&&(t.tail=e),t.size++,e)}prepend(e){let t=this.list;if(!e||!e.append||!e.prepend||!e.detach)throw new Error("An argument without append, prepend, or detach methods was given to `Item#prepend`.");return!t||this===e?!1:(e.detach(),this.prev&&(e.prev=this.prev,this.prev.next=e),e.next=this,e.list=t,this.prev=e,this===t.head&&(t.head=e),t.tail||(t.tail=this),t.size++,e)}detach(){let e=this.list;return e?(e.tail===this&&(e.tail=this.prev),e.head===this&&(e.head=this.next),e.tail===e.head&&(e.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,e.size--,this):this}};var j=class{item=null;constructor(e){this.item=e}next(){let e=this.item;return e?(this.item=e.next,{value:e,done:!1}):{value:null,done:!0}}};var G=class{size;head;tail;static from(e){let t=new this;return U(t,e)}static of(...e){let t=new this;return U(t,e)}constructor(...e){this.size=0,this.tail=null,this.head=null,U(this,e)}append(e){if(!e)return!1;if(!e.append||!e.prepend||!e.detach)throw new Error("An argument without append, prepend, or detach methods was given to `List#append`.");return this.tail?this.tail.append(e):this.head?this.head.append(e):(e.detach(),e.list=this,this.head=e,this.size++,e)}prepend(e){if(!e)return!1;if(!e.append||!e.prepend||!e.detach)throw new Error("An argument without append, prepend, or detach methods was given to `List#prepend`.");return this.head?this.head.prepend(e):(e.detach(),e.list=this,this.head=e,this.size++,e)}toArray(){let e=this.head,t=[];for(;e;)t.push(e),e=e.next;return t}[Symbol.iterator](){return new j(this.head)}};function Y(s){return Object.prototype.toString.call(s)==="[object Date]"}function Z(s){return!!s&&typeof s=="object"&&Object.prototype.toString.call(s)!=="[object Array]"}function M(s){if(Y(s))return new Date(s.getTime());if(Array.isArray(s))return[...s].map(e=>M(e));if(s instanceof Map||s instanceof Set)return s;if(Z(s)){let e={};for(let t of Object.keys(s))e[t]=M(s[t]);return e}return s}function V(s=0){return new Promise(e=>{setTimeout(()=>e(),s)})}var w=class{_internalStorage;isLocalStorageEnabled;constructor(){this._internalStorage={},this.isLocalStorageEnabled=this._checkLocalStorageEnabled()}saveToken(e,t,n){return this.isLocalStorageEnabled&&l.localStorage?l.localStorage.setItem(e,t):this._internalStorage[e]=t,Promise.resolve(t)}removeToken(e){let t=this.loadToken(e);return this.isLocalStorageEnabled&&l.localStorage?l.localStorage.removeItem(e):delete this._internalStorage[e],t}loadToken(e){let t;return this.isLocalStorageEnabled&&l.localStorage?t=l.localStorage.getItem(e):t=this._internalStorage[e]||null,Promise.resolve(t)}_checkLocalStorageEnabled(){let e;try{l.localStorage,l.localStorage.setItem("__scLocalStorageTest","1"),l.localStorage.removeItem("__scLocalStorageTest")}catch(t){e=t}return!e}};var $=class{id;socket;procedure;data;sent;constructor(e,t,n,r){this.socket=e,this.id=t,this.procedure=n,this.data=r,this.sent=!1}end(e,t){let n={rid:this.id};e!==void 0&&(n.data=e),this._respond(n,t)}error(e,t){let n={rid:this.id,error:J(e)};this._respond(n,t)}_respond(e,t){if(this.sent)throw new T(`Response to request ${this.id} has already been sent`);this.sent=!0,this.socket.sendObject(e,t)}};function ee(s){return typeof s=="function"}function te(s,e){if(l&&ee(l.WebSocket))return new l.WebSocket(s);{let t=require("ws");return new t(s,[],e)}}var p=class{state;auth;codec;options;wsOptions;protocolVersion;connectTimeout;pingTimeout;pingTimeoutDisabled;callIdGenerator;authTokenName;isBufferingBatch;socket;_callbackMap;_pingTimeoutTicker;_batchBuffer;_onOpenHandler;_onOpenAbortHandler;_onCloseHandler;_onEventHandler;_onErrorHandler;_onInboundInvokeHandler;_onInboundTransmitHandler;_connectTimeoutRef;_handlePing;constructor(e,t,n,r,i){this.state=p.CLOSED,this.auth=e,this.codec=t,this.options=n,this.wsOptions=r,this.protocolVersion=n.protocolVersion,this.connectTimeout=n.connectTimeout,this.pingTimeout=n.pingTimeout,this.pingTimeoutDisabled=!!n.pingTimeoutDisabled,this.callIdGenerator=n.callIdGenerator,this.authTokenName=n.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=p.CONNECTING;let o=this.uri(),c=te(o,r);c.binaryType=this.options.binaryType,this.socket=c,c.onopen=()=>{this._onOpen()},c.onclose=async a=>{let h;a.code==null?h=1005:h=a.code,this._destroy(h,a.reason)},c.onmessage=(a,h)=>{this._onMessage(a.data)},c.onerror=()=>{this.state===p.CONNECTING&&this._destroy(1006)},this._connectTimeoutRef=setTimeout(()=>{this._destroy(4007),this.socket.close(4007)},this.connectTimeout),this.protocolVersion===1?this._handlePing=a=>a==="#1"?(this._resetPingTimeout(),this.socket.readyState===this.socket.OPEN&&this.send("#2"),!0):!1:this._handlePing=a=>a===""?(this._resetPingTimeout(),this.socket.readyState===this.socket.OPEN&&this.send(""),!0):!1}uri(){let e=this.options.query||{},t;this.options.protocolScheme==null?t=this.options.secure?"wss":"ws":t=this.options.protocolScheme,this.options.timestampRequests&&(e[this.options.timestampParam]=new Date().getTime());let n=new URLSearchParams;for(let[o,c]of Object.entries(e))if(Array.isArray(c))for(let a of c)n.append(o,a);else n.set(o,`${c}`);e=n.toString(),e.length&&(e="?"+e);let r,i;if(this.options.socketPath==null){if(this.options.host)r=this.options.host;else{let o="";this.options.port&&(t==="wss"&&this.options.port!==443||t==="ws"&&this.options.port!==80)&&(o=":"+this.options.port),r=this.options.hostname+o}i=this.options.path}else r=this.options.socketPath,i=`:${this.options.path}`;return t+"://"+r+i+e}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 e=this.serializeObject(this._batchBuffer);this._batchBuffer=[],this.send(e)}cancelBatch(){this.isBufferingBatch=!1,this._batchBuffer=[]}getBytesReceived(){return this.socket.bytesReceived}close(e,t){(this.state===p.OPEN||this.state===p.CONNECTING)&&(e=e||1e3,this._destroy(e,t),this.socket.close(e,t))}transmitObject(e){let t={event:e.event,data:e.data};return e.callback&&(t.cid=e.cid=this.callIdGenerator(),this._callbackMap[e.cid]=e),this.sendObject(t),e.cid||null}transmit(e,t,n){let r={event:e,data:t};return(this.state===p.OPEN||n.force)&&this.transmitObject(r),Promise.resolve()}invokeRaw(e,t,n,r){let i={event:e,data:t,callback:r};n.noTimeout||(i.timeout=setTimeout(()=>{this._handleEventAckTimeout(i)},this.options.ackTimeout));let o=null;return(this.state===p.OPEN||n.force)&&(o=this.transmitObject(i)),o}invoke(e,t,n){return new Promise((r,i)=>{this.invokeRaw(e,t,n,(o,c)=>{if(o){i(o);return}r(c)})})}cancelPendingResponse(e){delete this._callbackMap[e]}decode(e){return this.codec.decode(e)}encode(e){return this.codec.encode(e)}send(e){this.socket.readyState!==this.socket.OPEN?this._destroy(1005):this.socket.send(e)}serializeObject(e){let t;try{t=this.encode(e)}catch(n){return this._onError(n),null}return t}sendObject(e){if(this.isBufferingBatch){this._batchBuffer.push(e);return}let t=this.serializeObject(e);t!=null&&this.send(t)}_resetPingTimeout(){this.pingTimeoutDisabled||(clearTimeout(this._pingTimeoutTicker),this._pingTimeoutTicker=setTimeout(()=>{this._destroy(4e3),this.socket.close(4e3)},this.pingTimeout))}_handleEventAckTimeout(e){e.cid&&delete this._callbackMap[e.cid],delete e.timeout;let t=e.callback;if(t){delete e.callback;let n=new k(`Event response for "${e.event}" timed out`);t.call(e,n,e)}}async _onOpen(){clearTimeout(this._connectTimeoutRef),this._resetPingTimeout();let e;try{e=await this._handshake()}catch(t){t.statusCode==null&&(t.statusCode=4003),this._onError(t),this._destroy(t.statusCode,t.toString()),this.socket.close(t.statusCode);return}this.state=p.OPEN,e&&(this.pingTimeout=e.pingTimeout),this._resetPingTimeout(),this._onOpenHandler(e)}async _handshake(){let e=await this.auth.loadToken(this.authTokenName),t={force:!0},n=await this.invoke("#handshake",{authToken:e},t);return n&&(n.authToken=e,n.authError&&(n.authError=O(n.authError))),n}_abortAllPendingEventsDueToBadConnection(e){Object.keys(this._callbackMap||{}).forEach(t=>{let n=this._callbackMap[t];delete this._callbackMap[t],clearTimeout(n.timeout),delete n.timeout;let r=`Event "${n.event}" was aborted due to a bad connection`,i=new C(r,e),o=n.callback;o&&(delete n.callback,o.call(n,i,n))})}_destroy(e,t){!t&&A[e]&&(t=A[e]),delete this.socket.onopen,delete this.socket.onclose,delete this.socket.onmessage,delete this.socket.onerror,clearTimeout(this._connectTimeoutRef),clearTimeout(this._pingTimeoutTicker),this.state===p.OPEN?(this.state=p.CLOSED,this._abortAllPendingEventsDueToBadConnection("disconnect"),this._onCloseHandler({code:e,reason:t})):this.state===p.CONNECTING?(this.state=p.CLOSED,this._abortAllPendingEventsDueToBadConnection("connectAbort"),this._onOpenAbortHandler({code:e,reason:t})):this.state===p.CLOSED&&this._abortAllPendingEventsDueToBadConnection("connectAbort")}_processInboundPacket(e,t){if(e&&e.event!=null)if(e.cid==null)this._onInboundTransmitHandler({...e});else{let n=new $(this,e.cid,e.event,e.data);this._onInboundInvokeHandler(n)}else if(e&&e.rid!=null){let n=this._callbackMap[e.rid];if(n&&(clearTimeout(n.timeout),delete n.timeout,delete this._callbackMap[e.rid],n.callback)){let r=O(e.error);n.callback(r,e.data)}}else this._onEventHandler({event:"raw",data:{message:t}})}_onMessage(e){if(this._onEventHandler({event:"message",data:{message:e}}),this._handlePing(e))return;let t=this.decode(e);if(Array.isArray(t)){let n=t.length;for(let r=0;r<n;r++)this._processInboundPacket(t[r],e)}else this._processInboundPacket(t,e)}_onError(e){this._onErrorHandler({error:e})}},y=p;m(y,"CONNECTING","connecting"),m(y,"OPEN","open"),m(y,"CLOSED","closed");var ye=typeof window<"u",u=class extends N{CONNECTING=u.CONNECTING;OPEN=u.OPEN;CLOSED=u.CLOSED;AUTHENTICATED=u.AUTHENTICATED;UNAUTHENTICATED=u.UNAUTHENTICATED;SUBSCRIBED=u.SUBSCRIBED;PENDING=u.PENDING;UNSUBSCRIBED=u.UNSUBSCRIBED;options;id;clientId;version;protocolVersion;state;authState;signedAuthToken;authToken;authTokenName;wsOptions;pendingReconnect;pendingReconnectTimeout;preparingPendingSubscriptions;ackTimeout;connectTimeout;pingTimeout;pingTimeoutDisabled;channelPrefix;disconnectOnUnload;connectAttempts;isBatching;batchOnHandshake;batchOnHandshakeDuration;auth;codec;transport;poolIndex;_batchingIntervalId;_outboundBuffer;_channelMap;_channelEventDemux;_channelDataDemux;_receiverDemux;_procedureDemux;_cid;_reconnectTimeoutRef;_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),n=this._channelMap[t];n&&(this.emit("kickOut",{channel:t,message:e.message}),this._channelEventDemux.write(`${t}/kickOut`,{message:e.message}),this._triggerChannelUnsubscribe(n))},"#setAuthToken":e=>{e&&this._setAuthToken(e)},"#removeAuthToken":e=>{this._removeAuthToken()}};_privateRPCHandlerMap={"#setAuthToken":(e,t)=>{e?(this._setAuthToken(e),t.end()):t.error(new v("No token data provided by #setAuthToken event"))},"#removeAuthToken":(e,t)=>{this._removeAuthToken(),t.end()}};constructor(e){super();let n=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=n.version||null,this.protocolVersion=n.protocolVersion,this.state=u.CLOSED,this.authState=u.UNAUTHENTICATED,this.signedAuthToken=null,this.authToken=null,this.pendingReconnect=!1,this.pendingReconnectTimeout=null,this.preparingPendingSubscriptions=!1,this.clientId=n.clientId,this.wsOptions=n.wsOptions,this.connectTimeout=n.connectTimeout,this.ackTimeout=n.ackTimeout,this.channelPrefix=n.channelPrefix||null,this.disconnectOnUnload=n.disconnectOnUnload==null?!0:n.disconnectOnUnload,this.authTokenName=n.authTokenName,n.pingTimeout=n.connectTimeout,this.pingTimeout=n.pingTimeout,this.pingTimeoutDisabled=!!n.pingTimeoutDisabled;let r=Math.pow(2,31)-1,i=o=>{if(this[o]>r)throw new g(`The ${o} value provided exceeded the maximum amount allowed`)};if(i("connectTimeout"),i("ackTimeout"),i("pingTimeout"),this.connectAttempts=0,this.isBatching=!1,this.batchOnHandshake=n.batchOnHandshake,this.batchOnHandshakeDuration=n.batchOnHandshakeDuration,this._batchingIntervalId=null,this._outboundBuffer=new G,this._channelMap={},this._channelEventDemux=new b,this._channelDataDemux=new b,this._receiverDemux=new b,this._procedureDemux=new b,this.options=n,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 w,this.options.codecEngine?this.codec=this.options.codecEngine:this.codec=X,this.options.protocol){let o=new g('The "protocol" option does not affect topgunsocket-client - If you want to utilize SSL/TLS, use "secure" option instead');this._onError(o)}if(this.options.query=n.query||{},typeof this.options.query=="string"){let o=new URLSearchParams(this.options.query),c={};o.forEach((a,h)=>{let x=c[h];x==null?c[h]=a:(Array.isArray(x)||(c[h]=[x]),c[h].push(a))}),this.options.query=c}ye&&this.disconnectOnUnload&&l.addEventListener&&l.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!==u.CLOSED&&this.transmit("#removeAuthToken"),this._changeToUnauthenticatedStateAndClearTokens(),await V(0)}connect(){if(this.state===u.CLOSED){this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef),this.state=u.CONNECTING,this.emit("connecting",{}),this.transport&&this.transport.clearAllListeners();let e={onOpen:t=>{this.state=u.OPEN,this._onOpen(t)},onOpenAbort:t=>{this.state!==u.CLOSED&&(this.state=u.CLOSED,this._destroy(t.code,t.reason,!0))},onClose:t=>{this.state!==u.CLOSED&&(this.state=u.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 y(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 g("If specified, the code argument must be a number");let n=this.state===u.CONNECTING;n||this.state===u.OPEN?(this.state=u.CLOSED,this._destroy(e,t,n),this.transport.close(e,t)):(this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef))}decodeBase64(e){return F.default.from(e,"base64").toString("utf8")}encodeBase64(e){return F.default.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(n){throw n.name!=="BadConnectionError"&&n.name!=="TimeoutError"&&this._changeToUnauthenticatedStateAndClearTokens(),await V(0),n}return t&&t.isAuthenticated!=null?t.authError&&(t.authError=O(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(n){this._onError(n)}})(),await V(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,n){return this._processOutboundEvent(e,t,n)}invoke(e,t,n){return this._processOutboundEvent(e,t,n,!0)}transmitPublish(e,t){let n={channel:this._decorateChannelName(e),data:t};return this.transmit("#publish",n)}invokePublish(e,t){let n={channel:this._decorateChannelName(e),data:t};return this.invoke("#publish",n)}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 n=this._channelMap[e],r={waitForAuth:!!t.waitForAuth};return t.priority!=null&&(r.priority=t.priority),t.data!==void 0&&(r.data=t.data),n?t&&(n.options=r):(n={name:e,state:d.PENDING,options:r},this._channelMap[e]=n,this._trySubscribe(n)),new d(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 d(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:d.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,n)=>(n.forEach(r=>{t.push(r)}),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(n=>this._channelEventDemux.getBackpressure(n));return Math.max(...t.concat(0))}channelHasOutputConsumer(e,t){return this._channelDataDemux.hasConsumer(e,t)}channelHasListenerConsumer(e,t,n){return this._channelEventDemux.hasConsumer(`${e}/${t}`,n)}channelHasAnyListenerConsumer(e,t){return this._getAllChannelStreamNames(e).some(n=>this._channelEventDemux.hasConsumer(n,t))}subscriptions(e){let t=[];return Object.keys(this._channelMap).forEach(n=>{(e||this._channelMap[n].state===d.SUBSCRIBED)&&t.push(n)}),t}isSubscribed(e,t){let n=this._channelMap[e];return t?!!n:!!n&&n.state===d.SUBSCRIBED}processPendingSubscriptions(){this.preparingPendingSubscriptions=!1;let e=[];Object.keys(this._channelMap).forEach(t=>{let n=this._channelMap[t];n.state===d.PENDING&&e.push(n)}),e.sort((t,n)=>{let r=t.options.priority||0,i=n.options.priority||0;return r>i?-1:r<i?1:0}),e.forEach(t=>{this._trySubscribe(t)})}_getAllChannelStreamNames(e){let t=this._channelEventDemux.getConsumerStatsListAll().filter(n=>n.stream.indexOf(`${e}/`)===0).reduce((n,r)=>(n[r.stream]=!0,n),{});return Object.keys(t)}_tryUnsubscribe(e){if(this.state===u.OPEN){let t={noTimeout:!0};this._cancelPendingSubscribeCallback(e);let n=this._decorateChannelName(e.name);this.transport.transmit("#unsubscribe",n,t)}}_triggerChannelUnsubscribe(e,t){let n=e.name;if(this._cancelPendingSubscribeCallback(e),e.state===d.SUBSCRIBED){let r={oldChannelState:e.state,newChannelState:t?d.PENDING:d.UNSUBSCRIBED};this._channelEventDemux.write(`${n}/subscribeStateChange`,r),this._channelEventDemux.write(`${n}/unsubscribe`,{}),this.emit("subscribeStateChange",{channel:n,...r}),this.emit("unsubscribe",{channel:n})}t?e.state=d.PENDING:delete this._channelMap[n]}_trySubscribe(e){let t=!e.options.waitForAuth||this.authState===u.AUTHENTICATED;if(this.state===u.OPEN&&!this.preparingPendingSubscriptions&&e._pendingSubscriptionCid==null&&t){let n={noTimeout:!0},r={};e.options.waitForAuth&&(n.waitForAuth=!0,r.waitForAuth=n.waitForAuth),e.options.data&&(r.data=e.options.data),e._pendingSubscriptionCid=this.transport.invokeRaw("#subscribe",{channel:this._decorateChannelName(e.name),...r},n,i=>{if(i){if(i.name==="BadConnectionError")return;delete e._pendingSubscriptionCid,this._triggerChannelSubscribeFail(i,e,r)}else delete e._pendingSubscriptionCid,this._triggerChannelSubscribe(e,r)}),this.emit("subscribeRequest",{channel:e.name,subscriptionOptions:r})}}_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,n){let r=t.name,i=!t.options.waitForAuth||this.authState===u.AUTHENTICATED;!!this._channelMap[r]&&i&&(delete this._channelMap[r],this._channelEventDemux.write(`${r}/subscribeFail`,{error:e,subscriptionOptions:n}),this.emit("subscribeFail",{error:e,channel:r,subscriptionOptions:n}))}_triggerChannelSubscribe(e,t){let n=e.name;if(e.state!==d.SUBSCRIBED){let r=e.state;e.state=d.SUBSCRIBED;let i={oldChannelState:r,newChannelState:e.state,subscriptionOptions:t};this._channelEventDemux.write(`${n}/subscribeStateChange`,i),this._channelEventDemux.write(`${n}/subscribe`,{subscriptionOptions:t}),this.emit("subscribeStateChange",{channel:n,...i}),this.emit("subscribe",{channel:n,subscriptionOptions:t})}}_processOutboundEvent(e,t,n,r){n=n||{},this.state===u.CLOSED&&this.connect();let i={event:e,data:null},o;r?o=new Promise((h,x)=>{i.callback=(q,se)=>{if(q){x(q);return}h(se)}}):o=Promise.resolve();let c=new H;this.options.cloneData?i.data=M(t):i.data=t,c.data=i;let a=n.ackTimeout==null?this.ackTimeout:n.ackTimeout;return i.timeout=setTimeout(()=>{this._handleEventAckTimeout(i,c)},a),this._outboundBuffer.append(c),this.state===u.OPEN&&this._flushOutboundBuffer(),o}_handleEventAckTimeout(e,t){t&&t.detach(),delete e.timeout;let n=e.callback;if(n){delete e.callback;let r=new k(`Event response for "${e.event}" timed out`);n.call(e,r,e)}e.cid&&this.transport.cancelPendingResponse(e.cid)}_flushOutboundBuffer(){let e=this._outboundBuffer.head,t;for(;e;){t=e.next;let n=e.data;e.detach(),this.transport.transmitObject(n),e=t}}_onInboundInvoke(e){let{procedure:t,data:n}=e,r=this._privateRPCHandlerMap[t];r?r.call(this,n,e):this._procedureDemux.write(t,e)}_onInboundTransmit(e,t){let n=this._privateDataHandlerMap[e];n?n.call(this,t):this._receiverDemux.write(e,t)}_destroy(e,t,n){if(this.id=null,this._cancelBatching(),this.transport&&this.transport.clearAllListeners(),this.pendingReconnect=!1,this.pendingReconnectTimeout=null,clearTimeout(this._reconnectTimeoutRef),this._suspendSubscriptions(),n?this.emit("connectAbort",{code:e,reason:t}):this.emit("disconnect",{code:e,reason:t}),this.emit("close",{code:e,reason:t}),!u.ignoreStatuses[e]){let r;t?r="Socket connection closed with status code "+e+" and reason: "+t:r="Socket connection closed with status code "+e;let i=new _(u.errorStatuses[e]||r,e);this._onError(i)}this._abortAllPendingEventsDueToBadConnection(n?"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,n;for(;t;){n=t.next;let r=t.data;clearTimeout(r.timeout),delete r.timeout,t.detach(),t=n;let i=r.callback;if(i){delete r.callback;let o=`Event "${r.event}" was aborted due to a bad connection`,c=new C(o,e);i.call(r,c,r)}r.cid&&this.transport.cancelPendingResponse(r.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++,n=this.options.autoReconnectOptions,r;if(e==null||t>0){let i=Math.round(n.initialDelay+(n.randomness||0)*Math.random());r=Math.round(i*Math.pow(n.multiplier,t))}else r=e;r>n.maxDelay&&(r=n.maxDelay),clearTimeout(this._reconnectTimeoutRef),this.pendingReconnect=!0,this.pendingReconnectTimeout=r,this._reconnectTimeoutRef=setTimeout(()=>{this.connect()},r)}_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===u.OPEN&&this._flushOutboundBuffer()}_extractAuthTokenData(e){let n=(e||"").split(".")[1];if(n!=null){let r=n;try{return r=this.decodeBase64(r),JSON.parse(r)}catch{return r}}return null}_changeToAuthenticatedState(e){if(this.signedAuthToken=e,this.authToken=this._extractAuthTokenData(e),this.authState!==u.AUTHENTICATED){let t=this.authState;this.authState=u.AUTHENTICATED;let n={oldAuthState:t,newAuthState:this.authState,signedAuthToken:e,authToken:this.authToken};this.preparingPendingSubscriptions||this.processPendingSubscriptions(),this.emit("authStateChange",n)}this.emit("authenticate",{signedAuthToken:e,authToken:this.authToken})}_changeToUnauthenticatedStateAndClearTokens(){if(this.authState!==u.UNAUTHENTICATED){let e=this.authState,t=this.authToken,n=this.signedAuthToken;this.authState=u.UNAUTHENTICATED,this.signedAuthToken=null,this.authToken=null;let r={oldAuthState:e,newAuthState:this.authState};this.emit("authStateChange",r),this.emit("deauthenticate",{oldSignedAuthToken:n,oldAuthToken:t})}}async _handleBrowserUnload(){let e=()=>{this.disconnect()},t=!1,n=()=>{t||(t=!0,l.addEventListener("beforeunload",e,!1))},r=()=>{t&&(t=!1,l.removeEventListener("beforeunload",e,!1))};(async()=>{let i=this.listener("connecting").createConsumer();for(;!(await i.next()).done;)n()})(),(async()=>{let i=this.listener("close").createConsumer();for(;!(await i.next()).done;)r()})()}_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()}},f=u;m(f,"CONNECTING","connecting"),m(f,"OPEN","open"),m(f,"CLOSED","closed"),m(f,"AUTHENTICATED","authenticated"),m(f,"UNAUTHENTICATED","unauthenticated"),m(f,"SUBSCRIBED","subscribed"),m(f,"PENDING","pending"),m(f,"UNSUBSCRIBED","unsubscribed"),m(f,"ignoreStatuses",K),m(f,"errorStatuses",A);function Te(){return l.location&&location.protocol==="https:"}function ve(s,e){let t=s.secure==null?e:s.secure;return s.port||(l.location&&location.port?parseFloat(location.port):t?443:80)}function ne(s){if(s=s||{},s.host&&!s.host.match(/[^:]+:\d{2,5}/))throw new g('The host option should include both the hostname and the port number in the format "hostname:port"');if(s.host&&s.hostname)throw new g('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(s.host&&s.port)throw new g('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 e=Te(),t={clientId:Q(),port:ve(s,e),hostname:l.location&&location.hostname||"localhost",secure:e};return Object.assign(t,s),new f(t)}var re="1.0.0";function _e(s){return ne({...s,version:re})}0&&(module.exports={AuthEngine,TGClientSocket,TGTransport,create,version});

@@ -1,3 +0,4 @@

import { g as TGServerSocketGatewayOptions, h as TGServerSocketGateway } from './channel-2c868064.js';
export { j as ActionType, Z as AuthEngineType, w as AuthState, _ as AuthStateChangeData, x as AuthTokenOptions, z as AuthenticateData, $ as AuthenticationData, F as BadAuthTokenData, a1 as BadSocketAuthTokenData, L as CloseData, a7 as ClosureData, J as ConnectAbortData, G as ConnectData, a5 as ConnectionAbortData, a2 as ConnectionData, B as DeauthenticateData, a0 as DeauthenticationData, K as DisconnectData, a6 as DisconnectionData, M as IncomingMessage, N as IncomingMessageKey, U as MIDDLEWARE_HANDSHAKE, W as MIDDLEWARE_INBOUND, V as MIDDLEWARE_INBOUND_RAW, X as MIDDLEWARE_OUTBOUND, Y as Middlewares, v as SocketState, y as StateChangeData, H as SubscribeData, a3 as SubscriptionData, I as SubscriptionOptions, i as TGAction, t as TGActionAuthenticate, k as TGActionBase, m as TGActionHandshakeSC, l as TGActionHandshakeWS, p as TGActionInvoke, n as TGActionMessage, r as TGActionPublishIn, s as TGActionPublishOut, q as TGActionSubscribe, o as TGActionTransmit, u as TGServerSocket, a4 as UnsubscriptionData, O as handshakeMiddlewareFunction, Q as inboundMiddlewareFunction, P as inboundRawMiddlewareFunction, R as outboundMiddlewareFunction } from './channel-2c868064.js';
import { g as TGServerSocketGatewayOptions, h as TGServerSocketGateway } from './channel-549bdfaa.js';
export { j as ActionType, _ as AuthEngineType, w as AuthState, $ as AuthStateChangeData, x as AuthTokenOptions, z as AuthenticateData, a0 as AuthenticationData, F as BadAuthTokenData, a2 as BadSocketAuthTokenData, M as CloseData, a8 as ClosureData, K as ConnectAbortData, G as ConnectData, a6 as ConnectionAbortData, a3 as ConnectionData, B as DeauthenticateData, a1 as DeauthenticationData, L as DisconnectData, a7 as DisconnectionData, I as ITGAction, N as IncomingMessage, O as IncomingMessageKey, V as MIDDLEWARE_HANDSHAKE, X as MIDDLEWARE_INBOUND, W as MIDDLEWARE_INBOUND_RAW, Y as MIDDLEWARE_OUTBOUND, Z as Middlewares, v as SocketState, y as StateChangeData, H as SubscribeData, a4 as SubscriptionData, J as SubscriptionOptions, i as TGAction, t as TGActionAuthenticate, k as TGActionBase, m as TGActionHandshakeSC, l as TGActionHandshakeWS, p as TGActionInvoke, n as TGActionMessage, r as TGActionPublishIn, s as TGActionPublishOut, q as TGActionSubscribe, o as TGActionTransmit, u as TGServerSocket, a5 as UnsubscriptionData, P as handshakeMiddlewareFunction, R as inboundMiddlewareFunction, Q as inboundRawMiddlewareFunction, U as outboundMiddlewareFunction } from './channel-549bdfaa.js';
import 'topgun-jsonwebtoken';

@@ -8,3 +9,5 @@ /**

declare function attach(server: any, options?: TGServerSocketGatewayOptions): TGServerSocketGateway;
type ListenFn = (...rest: any[]) => void;
declare function listen(http: any, port: number, options?: TGServerSocketGatewayOptions | ListenFn, fn?: ListenFn): TGServerSocketGateway;
export { TGServerSocketGateway, TGServerSocketGatewayOptions, attach };
export { TGServerSocketGateway, TGServerSocketGatewayOptions, attach, listen };

@@ -1,1 +0,2 @@

export { a8 as WritableConsumableStream } from './channel-2c868064.js';
export { a9 as WritableConsumableStream } from './channel-549bdfaa.js';
import 'topgun-jsonwebtoken';

@@ -1,1 +0,1 @@

var TopGunSocket=(()=>{var a=Object.defineProperty;var d=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var h=Object.prototype.hasOwnProperty;var _=(o,e)=>{for(var t in e)a(o,t,{get:e[t],enumerable:!0})},p=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of l(e))!h.call(o,s)&&s!==t&&a(o,s,{get:()=>e[s],enumerable:!(r=d(e,s))||r.enumerable});return o};var b=o=>p(a({},"__esModule",{value:!0}),o);var v={};_(v,{WritableConsumableStream:()=>m});var n=class{async next(e){let t=this.createConsumer(e),r=await t.next();return t.return(),r}async once(e){let t=await this.next(e);return t.done&&await new Promise(()=>{}),t.value}createConsumer(e){throw new TypeError("Method must be overriden by subclass")}[Symbol.asyncIterator](){return this.createConsumer()}};var u=class{id;timeout;stream;currentNode;isAlive;_backpressure;_timeoutId;_resolve;_killPacket;constructor(e,t,r,s=0){this.id=t,this._backpressure=0,this.stream=e,this.currentNode=r,this.timeout=s,this.isAlive=!0,this.stream.setConsumer(this.id,this)}getStats(){let e={id:this.id,backpressure:this._backpressure};return this.timeout!=null&&(e.timeout=this.timeout),e}applyBackpressure(e){this._backpressure++}releaseBackpressure(e){this._backpressure--}getBackpressure(){return this._backpressure}write(e){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this.applyBackpressure(e),this._resolve&&(this._resolve(),delete this._resolve)}kill(e){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this._killPacket={value:e,done:!0},this._destroy(),this._resolve&&(this._resolve(),delete this._resolve)}async next(){for(this.stream.setConsumer(this.id,this);;){if(this.currentNode&&!this.currentNode.next)try{await this._waitForNextItem(this.timeout)}catch(e){throw this._destroy(),e}if(this._killPacket){this._destroy();let e=this._killPacket;return delete this._killPacket,e}if(this.currentNode){if(this.currentNode=this.currentNode.next,this.releaseBackpressure(this.currentNode.data),this.currentNode.consumerId&&this.currentNode.consumerId!==this.id)continue;return this.currentNode.data.done&&this._destroy(),this.currentNode.data}}}return(){return delete this.currentNode,this._destroy(),{}}_resetBackpressure(){this._backpressure=0}_destroy(){this.isAlive=!1,this._resetBackpressure(),this.stream.removeConsumer(this.id)}async _waitForNextItem(e){return new Promise((t,r)=>{this._resolve=t;let s;if(e!==void 0){let i=new Error("Stream consumer iteration timed out");(async()=>{let c=f(e);s=c.timeoutId,await c.promise,i.name="TimeoutError",delete this._resolve,r(i)})()}this._timeoutId=s})}[Symbol.asyncIterator](){return this}};function f(o){let e,t=new Promise(r=>{e=setTimeout(r,o)});return{timeoutId:e,promise:t}}var m=class extends n{type;nextConsumerId;_consumers;_tailNode;constructor(){super(),this.nextConsumerId=1,this._consumers=new Map,this._tailNode={next:null,data:{value:void 0,done:!1}}}write(e){this._write(e,!1)}close(e){this._write(e,!0)}writeToConsumer(e,t){this._write(t,!1,e)}closeConsumer(e,t){this._write(t,!0,e)}kill(e){for(let t of this._consumers.keys())this.killConsumer(t,e)}killConsumer(e,t){let r=this._consumers.get(e);!r||r.kill(t)}getBackpressure(){let e=0;for(let t of this._consumers.values()){let r=t.getBackpressure();r>e&&(e=r)}return e}getConsumerBackpressure(e){let t=this._consumers.get(e);return t?t.getBackpressure():0}hasConsumer(e){return this._consumers.has(e)}setConsumer(e,t){this._consumers.set(e,t),t.currentNode||(t.currentNode=this._tailNode)}removeConsumer(e){return this._consumers.delete(e)}getConsumerStats(e){let t=this._consumers.get(e);if(t)return t.getStats()}getConsumerStatsList(){let e=[];for(let t of this._consumers.values())e.push(t.getStats());return e}createConsumer(e){return new u(this,this.nextConsumerId++,this._tailNode,e)}getConsumerList(){return[...this._consumers.values()]}getConsumerCount(){return this._consumers.size}_write(e,t,r){let s={data:{value:e,done:t},next:null};r&&(s.consumerId=r),this._tailNode.next=s,this._tailNode=s;for(let i of this._consumers.values())i.write(s.data)}};return b(v);})();
var TopGunSocket=(()=>{var a=Object.defineProperty;var d=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var h=Object.prototype.hasOwnProperty;var _=(o,e)=>{for(var t in e)a(o,t,{get:e[t],enumerable:!0})},p=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of l(e))!h.call(o,s)&&s!==t&&a(o,s,{get:()=>e[s],enumerable:!(r=d(e,s))||r.enumerable});return o};var b=o=>p(a({},"__esModule",{value:!0}),o);var v={};_(v,{WritableConsumableStream:()=>m});var n=class{async next(e){let t=this.createConsumer(e),r=await t.next();return t.return(),r}async once(e){let t=await this.next(e);return t.done&&await new Promise(()=>{}),t.value}createConsumer(e){throw new TypeError("Method must be overriden by subclass")}[Symbol.asyncIterator](){return this.createConsumer()}};var u=class{id;timeout;stream;currentNode;isAlive;_backpressure;_timeoutId;_resolve;_killPacket;constructor(e,t,r,s){this.id=t,this._backpressure=0,this.stream=e,this.currentNode=r,this.timeout=s,this.isAlive=!0,this.stream.setConsumer(this.id,this)}getStats(){let e={id:this.id,backpressure:this._backpressure};return this.timeout!=null&&(e.timeout=this.timeout),e}applyBackpressure(e){this._backpressure++}releaseBackpressure(e){this._backpressure--}getBackpressure(){return this._backpressure}write(e){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this.applyBackpressure(e),this._resolve&&(this._resolve(),delete this._resolve)}kill(e){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this._killPacket={value:e,done:!0},this._destroy(),this._resolve&&(this._resolve(),delete this._resolve)}async next(){for(this.stream.setConsumer(this.id,this);;){if(this.currentNode&&!this.currentNode.next)try{await this._waitForNextItem(this.timeout)}catch(e){throw this._destroy(),e}if(this._killPacket){this._destroy();let e=this._killPacket;return delete this._killPacket,e}if(this.currentNode){if(this.currentNode=this.currentNode.next,this.releaseBackpressure(this.currentNode.data),this.currentNode.consumerId&&this.currentNode.consumerId!==this.id)continue;return this.currentNode.data.done&&this._destroy(),this.currentNode.data}}}return(){return delete this.currentNode,this._destroy(),{}}_resetBackpressure(){this._backpressure=0}_destroy(){this.isAlive=!1,this._resetBackpressure(),this.stream.removeConsumer(this.id)}async _waitForNextItem(e){return new Promise((t,r)=>{this._resolve=t;let s;if(e!==void 0){let i=new Error("Stream consumer iteration timed out");(async()=>{let c=f(e);s=c.timeoutId,await c.promise,i.name="TimeoutError",delete this._resolve,r(i)})()}this._timeoutId=s})}[Symbol.asyncIterator](){return this}};function f(o){let e,t=new Promise(r=>{e=setTimeout(r,o)});return{timeoutId:e,promise:t}}var m=class extends n{type;nextConsumerId;_consumers;_tailNode;constructor(){super(),this.nextConsumerId=1,this._consumers=new Map,this._tailNode={next:null,data:{value:void 0,done:!1}}}write(e){this._write(e,!1)}close(e){this._write(e,!0)}writeToConsumer(e,t){this._write(t,!1,e)}closeConsumer(e,t){this._write(t,!0,e)}kill(e){for(let t of this._consumers.keys())this.killConsumer(t,e)}killConsumer(e,t){let r=this._consumers.get(e);!r||r.kill(t)}getBackpressure(){let e=0;for(let t of this._consumers.values()){let r=t.getBackpressure();r>e&&(e=r)}return e}getConsumerBackpressure(e){let t=this._consumers.get(e);return t?t.getBackpressure():0}hasConsumer(e){return this._consumers.has(e)}setConsumer(e,t){this._consumers.set(e,t),t.currentNode||(t.currentNode=this._tailNode)}removeConsumer(e){return this._consumers.delete(e)}getConsumerStats(e){let t=this._consumers.get(e);if(t)return t.getStats()}getConsumerStatsList(){let e=[];for(let t of this._consumers.values())e.push(t.getStats());return e}createConsumer(e){return new u(this,this.nextConsumerId++,this._tailNode,e)}getConsumerList(){return[...this._consumers.values()]}getConsumerCount(){return this._consumers.size}_write(e,t,r){let s={data:{value:e,done:t},next:null};r&&(s.consumerId=r),this._tailNode.next=s,this._tailNode=s;for(let i of this._consumers.values())i.write(s.data)}};return b(v);})();

@@ -1,1 +0,1 @@

var a=Object.defineProperty;var d=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var h=Object.prototype.hasOwnProperty;var _=(o,e)=>{for(var t in e)a(o,t,{get:e[t],enumerable:!0})},p=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of l(e))!h.call(o,s)&&s!==t&&a(o,s,{get:()=>e[s],enumerable:!(r=d(e,s))||r.enumerable});return o};var b=o=>p(a({},"__esModule",{value:!0}),o);var v={};_(v,{WritableConsumableStream:()=>m});module.exports=b(v);var n=class{async next(e){let t=this.createConsumer(e),r=await t.next();return t.return(),r}async once(e){let t=await this.next(e);return t.done&&await new Promise(()=>{}),t.value}createConsumer(e){throw new TypeError("Method must be overriden by subclass")}[Symbol.asyncIterator](){return this.createConsumer()}};var u=class{id;timeout;stream;currentNode;isAlive;_backpressure;_timeoutId;_resolve;_killPacket;constructor(e,t,r,s=0){this.id=t,this._backpressure=0,this.stream=e,this.currentNode=r,this.timeout=s,this.isAlive=!0,this.stream.setConsumer(this.id,this)}getStats(){let e={id:this.id,backpressure:this._backpressure};return this.timeout!=null&&(e.timeout=this.timeout),e}applyBackpressure(e){this._backpressure++}releaseBackpressure(e){this._backpressure--}getBackpressure(){return this._backpressure}write(e){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this.applyBackpressure(e),this._resolve&&(this._resolve(),delete this._resolve)}kill(e){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this._killPacket={value:e,done:!0},this._destroy(),this._resolve&&(this._resolve(),delete this._resolve)}async next(){for(this.stream.setConsumer(this.id,this);;){if(this.currentNode&&!this.currentNode.next)try{await this._waitForNextItem(this.timeout)}catch(e){throw this._destroy(),e}if(this._killPacket){this._destroy();let e=this._killPacket;return delete this._killPacket,e}if(this.currentNode){if(this.currentNode=this.currentNode.next,this.releaseBackpressure(this.currentNode.data),this.currentNode.consumerId&&this.currentNode.consumerId!==this.id)continue;return this.currentNode.data.done&&this._destroy(),this.currentNode.data}}}return(){return delete this.currentNode,this._destroy(),{}}_resetBackpressure(){this._backpressure=0}_destroy(){this.isAlive=!1,this._resetBackpressure(),this.stream.removeConsumer(this.id)}async _waitForNextItem(e){return new Promise((t,r)=>{this._resolve=t;let s;if(e!==void 0){let i=new Error("Stream consumer iteration timed out");(async()=>{let c=f(e);s=c.timeoutId,await c.promise,i.name="TimeoutError",delete this._resolve,r(i)})()}this._timeoutId=s})}[Symbol.asyncIterator](){return this}};function f(o){let e,t=new Promise(r=>{e=setTimeout(r,o)});return{timeoutId:e,promise:t}}var m=class extends n{type;nextConsumerId;_consumers;_tailNode;constructor(){super(),this.nextConsumerId=1,this._consumers=new Map,this._tailNode={next:null,data:{value:void 0,done:!1}}}write(e){this._write(e,!1)}close(e){this._write(e,!0)}writeToConsumer(e,t){this._write(t,!1,e)}closeConsumer(e,t){this._write(t,!0,e)}kill(e){for(let t of this._consumers.keys())this.killConsumer(t,e)}killConsumer(e,t){let r=this._consumers.get(e);!r||r.kill(t)}getBackpressure(){let e=0;for(let t of this._consumers.values()){let r=t.getBackpressure();r>e&&(e=r)}return e}getConsumerBackpressure(e){let t=this._consumers.get(e);return t?t.getBackpressure():0}hasConsumer(e){return this._consumers.has(e)}setConsumer(e,t){this._consumers.set(e,t),t.currentNode||(t.currentNode=this._tailNode)}removeConsumer(e){return this._consumers.delete(e)}getConsumerStats(e){let t=this._consumers.get(e);if(t)return t.getStats()}getConsumerStatsList(){let e=[];for(let t of this._consumers.values())e.push(t.getStats());return e}createConsumer(e){return new u(this,this.nextConsumerId++,this._tailNode,e)}getConsumerList(){return[...this._consumers.values()]}getConsumerCount(){return this._consumers.size}_write(e,t,r){let s={data:{value:e,done:t},next:null};r&&(s.consumerId=r),this._tailNode.next=s,this._tailNode=s;for(let i of this._consumers.values())i.write(s.data)}};0&&(module.exports={WritableConsumableStream});
var a=Object.defineProperty;var d=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var h=Object.prototype.hasOwnProperty;var _=(o,e)=>{for(var t in e)a(o,t,{get:e[t],enumerable:!0})},p=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of l(e))!h.call(o,s)&&s!==t&&a(o,s,{get:()=>e[s],enumerable:!(r=d(e,s))||r.enumerable});return o};var b=o=>p(a({},"__esModule",{value:!0}),o);var v={};_(v,{WritableConsumableStream:()=>m});module.exports=b(v);var n=class{async next(e){let t=this.createConsumer(e),r=await t.next();return t.return(),r}async once(e){let t=await this.next(e);return t.done&&await new Promise(()=>{}),t.value}createConsumer(e){throw new TypeError("Method must be overriden by subclass")}[Symbol.asyncIterator](){return this.createConsumer()}};var u=class{id;timeout;stream;currentNode;isAlive;_backpressure;_timeoutId;_resolve;_killPacket;constructor(e,t,r,s){this.id=t,this._backpressure=0,this.stream=e,this.currentNode=r,this.timeout=s,this.isAlive=!0,this.stream.setConsumer(this.id,this)}getStats(){let e={id:this.id,backpressure:this._backpressure};return this.timeout!=null&&(e.timeout=this.timeout),e}applyBackpressure(e){this._backpressure++}releaseBackpressure(e){this._backpressure--}getBackpressure(){return this._backpressure}write(e){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this.applyBackpressure(e),this._resolve&&(this._resolve(),delete this._resolve)}kill(e){this._timeoutId!==void 0&&(clearTimeout(this._timeoutId),delete this._timeoutId),this._killPacket={value:e,done:!0},this._destroy(),this._resolve&&(this._resolve(),delete this._resolve)}async next(){for(this.stream.setConsumer(this.id,this);;){if(this.currentNode&&!this.currentNode.next)try{await this._waitForNextItem(this.timeout)}catch(e){throw this._destroy(),e}if(this._killPacket){this._destroy();let e=this._killPacket;return delete this._killPacket,e}if(this.currentNode){if(this.currentNode=this.currentNode.next,this.releaseBackpressure(this.currentNode.data),this.currentNode.consumerId&&this.currentNode.consumerId!==this.id)continue;return this.currentNode.data.done&&this._destroy(),this.currentNode.data}}}return(){return delete this.currentNode,this._destroy(),{}}_resetBackpressure(){this._backpressure=0}_destroy(){this.isAlive=!1,this._resetBackpressure(),this.stream.removeConsumer(this.id)}async _waitForNextItem(e){return new Promise((t,r)=>{this._resolve=t;let s;if(e!==void 0){let i=new Error("Stream consumer iteration timed out");(async()=>{let c=f(e);s=c.timeoutId,await c.promise,i.name="TimeoutError",delete this._resolve,r(i)})()}this._timeoutId=s})}[Symbol.asyncIterator](){return this}};function f(o){let e,t=new Promise(r=>{e=setTimeout(r,o)});return{timeoutId:e,promise:t}}var m=class extends n{type;nextConsumerId;_consumers;_tailNode;constructor(){super(),this.nextConsumerId=1,this._consumers=new Map,this._tailNode={next:null,data:{value:void 0,done:!1}}}write(e){this._write(e,!1)}close(e){this._write(e,!0)}writeToConsumer(e,t){this._write(t,!1,e)}closeConsumer(e,t){this._write(t,!0,e)}kill(e){for(let t of this._consumers.keys())this.killConsumer(t,e)}killConsumer(e,t){let r=this._consumers.get(e);!r||r.kill(t)}getBackpressure(){let e=0;for(let t of this._consumers.values()){let r=t.getBackpressure();r>e&&(e=r)}return e}getConsumerBackpressure(e){let t=this._consumers.get(e);return t?t.getBackpressure():0}hasConsumer(e){return this._consumers.has(e)}setConsumer(e,t){this._consumers.set(e,t),t.currentNode||(t.currentNode=this._tailNode)}removeConsumer(e){return this._consumers.delete(e)}getConsumerStats(e){let t=this._consumers.get(e);if(t)return t.getStats()}getConsumerStatsList(){let e=[];for(let t of this._consumers.values())e.push(t.getStats());return e}createConsumer(e){return new u(this,this.nextConsumerId++,this._tailNode,e)}getConsumerList(){return[...this._consumers.values()]}getConsumerCount(){return this._consumers.size}_write(e,t,r){let s={data:{value:e,done:t},next:null};r&&(s.consumerId=r),this._tailNode.next=s,this._tailNode=s;for(let i of this._consumers.values())i.write(s.data)}};0&&(module.exports={WritableConsumableStream});
{
"name": "topgun-socket",
"version": "1.2.3",
"version": "1.2.4",
"description": "Scalable realtime pub/sub and RPC serverless framework",

@@ -86,8 +86,7 @@ "publishConfig": {

"topgun-buffer": "1.0.3",
"topgun-webcrypto": "1.0.5"
"topgun-jsonwebtoken": "^1.0.2",
"topgun-webcrypto": "1.0.5",
"ws": "^8.9.0"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^24.1.0",
"@rollup/plugin-node-resolve": "^15.0.2",
"@rollup/plugin-terser": "^0.4.1",
"@semantic-release/changelog": "^6.0.3",

@@ -108,7 +107,5 @@ "@semantic-release/commit-analyzer": "^9.0.2",

"jest": "^29.5.0",
"kleur": "^4.1.5",
"lint-staged": "^13.2.1",
"localStorage": "^1.0.4",
"prettier": "^2.8.7",
"rewrite-imports": "^3.0.0",
"rollup": "^3.20.3",
"semantic-release": "^21.0.1",

@@ -115,0 +112,0 @@ "simple-git-hooks": "^2.8.1",

@@ -17,2 +17,5 @@ <h1 align="center" style="border-bottom: none;">🚀 topgun-socket</h1>

</a>
<a href="https://snyk.io/test/github/TopGunBuild/topgun">
<img alt="Snyk" src="https://snyk.io/test/github/TopGunBuild/topgun/badge.svg">
</a>
</p>

@@ -30,7 +33,7 @@

The socket-client script is called `socket-client.js` (located in the dist directory).
The socket-client script is called `client.js` (located in the dist directory).
Embed it in your HTML page like this:
```html
<script type="text/javascript" src="https://unpkg.com/topgun-socket@0.0.2/dist/socket-client.js"></script>
<script type="text/javascript" src="https://unpkg.com/topgun-socket@latest/dist/client.js"></script>
```

@@ -40,3 +43,3 @@

Once you have embedded the client `socket-client.js` into your page, you will gain access to a global `topGunSocketClient` object.
Once you have embedded the client `client.js` into your page, you will gain access to a global `TopGunSocket` object.
You may also use CommonJS `require` or ES6 module imports.

@@ -47,3 +50,3 @@

```js
let socket = topGunSocketClient.create({
let socket = TopGunSocket.create({
hostname: "localhost",

@@ -151,3 +154,3 @@ port: 8000,

// Initiate the connection to the server
let socket = topGunSocketClient.create(options);
let socket = TopGunSocket.create(options);
```

@@ -189,3 +192,3 @@

```js
let socket = topGunSocketClient.create({
let socket = TopGunSocket.create({
protocolVersion: 1,

@@ -203,3 +206,2 @@ path: "/topgunsocket/",

const topGunSocketServer = require("topgun-socket/server");
const ws = require("ws");

@@ -209,3 +211,2 @@ let httpServer = http.createServer();

path: "/topgunsocket/",
wsEngine: ws.Server,
});

@@ -331,3 +332,3 @@

```js
let tgServer = topGunSocketClient.attach(httpServer, {
let tgServer = TopGunSocket.attach(httpServer, {
protocolVersion: 1,

@@ -334,0 +335,0 @@ path: "/topgunsocket/",

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc