/* esm.sh - eventhub-jsclient@2.4.0 */
var f=Object.create;var h=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var m=Object.getPrototypeOf,C=Object.prototype.hasOwnProperty;var R=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports);var w=(n,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of k(t))!C.call(n,i)&&i!==e&&h(n,i,{get:()=>t[i],enumerable:!(s=g(t,i))||s.enumerable});return n};var P=(n,t,e)=>(e=n!=null?f(m(n)):{},w(t||!n||!n.__esModule?h(e,"default",{value:n,enumerable:!0}):e,n));var _=R((S,u)=>{var c=null;typeof WebSocket<"u"?c=WebSocket:typeof MozWebSocket<"u"?c=MozWebSocket:typeof globalThis<"u"?c=globalThis.WebSocket||globalThis.MozWebSocket:typeof window<"u"?c=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(c=self.WebSocket||self.MozWebSocket);u.exports=c});var o=P(_(),1);function d(n){return{all:n=n||new Map,on:function(t,e){var s=n.get(t);s?s.push(e):n.set(t,[e])},off:function(t,e){var s=n.get(t);s&&(e?s.splice(s.indexOf(e)>>>0,1):n.set(t,[]))},emit:function(t,e){var s=n.get(t);s&&s.slice().map(function(i){i(e)}),(s=n.get("*"))&&s.slice().map(function(i){i(t,e)})}}}var a=class{constructor(){this.pingInterval=1e4,this.pingTimeout=3e3,this.maxFailedPings=3,this.reconnectInterval=1e4,this.disablePingCheck=!1}},p=class{constructor(t,e,s){this._wsUrl=void 0,this._socket=void 0,this._opts=new a,this._isConnected=!1,this._manuallyDisconnected=!1,this._rpcResponseCounter=0,this._rpcCallbackList=new Map,this._subscriptionCallbackList=[],this._sentPingsList=[],this._pingTimer=void 0,this._pingTimeOutTimer=void 0,this._emitter=void 0,this._wsUrl=`${t}/?auth=${e}`,this._opts=new a,this._emitter=d(),Object.assign(this._opts,s)}connect(){return this._manuallyDisconnected=!1,new Promise((t,e)=>{this._socket=new o.default(this._wsUrl),this._socket.onmessage=this._parseRPCResponse.bind(this),this._socket.onopen=()=>{this._emitter.emit("connect"),this._isConnected=!0,this._opts.disablePingCheck||this._startPingMonitor(),t(!0)},this._socket.onerror=s=>{this._emitter.emit("offline",s),this._isConnected?(console.warn("Eventhub WebSocket connection error:",s),this._isConnected=!1,this._reconnect()):e(s)},this._socket.onclose=s=>{this._isConnected&&(this._emitter.emit("offline",s),this._isConnected=!1,this._reconnect())}})}_reconnect(){if(this._isConnected||this._manuallyDisconnected)return;this._emitter.emit("reconnect");let{reconnectInterval:t}=this._opts;this._socket.readyState!=o.default.CLOSED&&this._socket.readyState!=o.default.CLOSING&&this._socket.close(),this._resetPingMonitor(),this.connect().then(e=>{let s=this._subscriptionCallbackList.slice();this._rpcResponseCounter=0,this._rpcCallbackList=new Map,this._subscriptionCallbackList=[];for(let i of s)this.subscribe(i.topic,i.callback,{sinceEventId:i.lastRecvMessageId})}).catch(e=>{setTimeout(this._reconnect.bind(this),t)})}_startPingMonitor(){let{pingInterval:t,maxFailedPings:e}=this._opts;this._pingTimer=setInterval(()=>{if(!this._isConnected)return;let s={timestamp:Date.now(),rpcRequestId:this._rpcResponseCounter+1};this._sentPingsList.push(s),this._sendRPCRequest("ping",[]).then(i=>{for(let r=0;r<this._sentPingsList.length;r++)if(this._sentPingsList[r].rpcRequestId==s.rpcRequestId){this._sentPingsList.splice(r,1);break}})},t),this._pingTimeOutTimer=setInterval(()=>{let s=Date.now();this._sentPingsList.filter(r=>s>r.timestamp+this._opts.pingTimeout).length>=e&&(this._isConnected=!1,this._reconnect())},t)}_resetPingMonitor(){this._opts.disablePingCheck||(clearInterval(this._pingTimer),clearInterval(this._pingTimeOutTimer),this._sentPingsList=[])}_sendRPCRequest(t,e){let s={id:++this._rpcResponseCounter,jsonrpc:"2.0",method:t,params:e};return new Promise((i,r)=>{if(this._socket.readyState!=o.default.OPEN){r(new Error("WebSocket is not connected."));return}this._rpcCallbackList.set(s.id,(l,b)=>{l!=null?r(l):i(b)});try{this._socket.send(JSON.stringify(s))}catch(l){r(l)}})}_parseRPCResponse(t){try{let e=JSON.parse(t.data.toString());if(!e.hasOwnProperty("id")||e.id=="null")return;if(e.hasOwnProperty("result")&&e.result.hasOwnProperty("message")&&e.result.hasOwnProperty("topic")){for(let i of this._subscriptionCallbackList)if(i.rpcRequestId==e.id){i.lastRecvMessageId=e.result.id,i.callback(e.result);return}}let s=this._rpcCallbackList.get(e.id);if(!s)return;e.hasOwnProperty("error")?s(e.error,null):e.hasOwnProperty("result")&&s(null,e.result),this._rpcCallbackList.delete(e.id)}catch(e){console.warn("Failed to parse websocket response:",e)}}isSubscribed(t){return this._subscriptionCallbackList.some(e=>e.topic==t)}async subscribe(t,e,s){if(!t)throw new Error("Topic cannot be empty.");let i={topic:t};if(s&&Object.assign(i,s),this.isSubscribed(t))throw new Error(`Already subscribed to ${t}`);return this._subscriptionCallbackList.push({topic:t,rpcRequestId:this._rpcResponseCounter+1,callback:e}),this._sendRPCRequest("subscribe",i)}unsubscribe(t){let e=Array.isArray(t)?t:[t];e.length>0&&(this._subscriptionCallbackList=this._subscriptionCallbackList.filter(s=>!e.includes(s.topic)),this._sendRPCRequest("unsubscribe",e))}unsubscribeAll(){this._subscriptionCallbackList=[],this._sendRPCRequest("unsubscribeAll",[])}publish(t,e,s){let i={topic:t,message:e};return s&&Object.assign(i,s),this._sendRPCRequest("publish",i)}listSubscriptions(){return this._sendRPCRequest("list",[])}async getEventlog(t,e){if(!t)throw new Error("Topic cannot be empty.");if(!("since"in e)&&!("sinceEventId"in e))throw new Error("You need to specify either since or sinceEventId.");if("since"in e&&"sinceEventId"in e)throw new Error("You need to specify either since or sinceEventId, not both at the same time.");let s={topic:t};return Object.assign(s,e),this._sendRPCRequest("eventlog",s)}get(t){return this._sendRPCRequest("get",{key:t})}set(t,e,s){let i={key:t,value:e};return s>0&&(i.ttl=s),this._sendRPCRequest("set",i)}del(t){return this._sendRPCRequest("del",{key:t})}async disconnect(){this._manuallyDisconnected=!0,(this._isConnected||this._socket.readyState===o.default.CONNECTING)&&(this._isConnected=!1,await new Promise(t=>{let e=setTimeout(()=>{this._socket.readyState!=o.default.CLOSED&&this._socket.readyState!=o.default.CLOSING&&this._socket.close()},1e3);this._socket.onclose=()=>{clearTimeout(e),t(!0)},this._socket.onerror=()=>{clearTimeout(e),t(!0)},this._sendRPCRequest("disconnect",[]).catch(()=>{})})),this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null,this._rpcResponseCounter=0,this._rpcCallbackList=new Map,this._subscriptionCallbackList=[],this._resetPingMonitor(),this._emitter.emit("disconnect")}on(t,e){return this._emitter.on(t,e),this}off(t,e){return this._emitter.off(t,e),this}};export{p as default};
//# sourceMappingURL=eventhub-jsclient.bundle.mjs.map