centrifuge
Version:
JavaScript client SDK for bidirectional communication with Centrifugo and Centrifuge-based server from browser, NodeJS and React Native
7 lines • 77.1 kB
JavaScript
"use strict";(()=>{var ce=Object.create;var G=Object.defineProperty;var he=Object.getOwnPropertyDescriptor;var le=Object.getOwnPropertyNames;var ue=Object.getPrototypeOf,de=Object.prototype.hasOwnProperty;var pe=(o,i)=>()=>(i||o((i={exports:{}}).exports,i),i.exports);var fe=(o,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let s of le(i))!de.call(o,s)&&s!==e&&G(o,s,{get:()=>i[s],enumerable:!(t=he(i,s))||t.enumerable});return o};var V=(o,i,e)=>(e=o!=null?ce(ue(o)):{},fe(i||!o||!o.__esModule?G(e,"default",{value:o,enumerable:!0}):e,o));var N=pe((Ce,z)=>{"use strict";var T=typeof Reflect=="object"?Reflect:null,J=T&&typeof T.apply=="function"?T.apply:function(i,e,t){return Function.prototype.apply.call(i,e,t)},E;T&&typeof T.ownKeys=="function"?E=T.ownKeys:Object.getOwnPropertySymbols?E=function(i){return Object.getOwnPropertyNames(i).concat(Object.getOwnPropertySymbols(i))}:E=function(i){return Object.getOwnPropertyNames(i)};function _e(o){console&&console.warn&&console.warn(o)}var K=Number.isNaN||function(i){return i!==i};function d(){d.init.call(this)}z.exports=d;z.exports.once=ve;d.EventEmitter=d;d.prototype._events=void 0;d.prototype._eventsCount=0;d.prototype._maxListeners=void 0;var H=10;function C(o){if(typeof o!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof o)}Object.defineProperty(d,"defaultMaxListeners",{enumerable:!0,get:function(){return H},set:function(o){if(typeof o!="number"||o<0||K(o))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+o+".");H=o}});d.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};d.prototype.setMaxListeners=function(i){if(typeof i!="number"||i<0||K(i))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+i+".");return this._maxListeners=i,this};function $(o){return o._maxListeners===void 0?d.defaultMaxListeners:o._maxListeners}d.prototype.getMaxListeners=function(){return $(this)};d.prototype.emit=function(i){for(var e=[],t=1;t<arguments.length;t++)e.push(arguments[t]);var s=i==="error",n=this._events;if(n!==void 0)s=s&&n.error===void 0;else if(!s)return!1;if(s){var r;if(e.length>0&&(r=e[0]),r instanceof Error)throw r;var a=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw a.context=r,a}var c=n[i];if(c===void 0)return!1;if(typeof c=="function")J(c,this,e);else for(var h=c.length,l=ee(c,h),t=0;t<h;++t)J(l[t],this,e);return!0};function Q(o,i,e,t){var s,n,r;if(C(e),n=o._events,n===void 0?(n=o._events=Object.create(null),o._eventsCount=0):(n.newListener!==void 0&&(o.emit("newListener",i,e.listener?e.listener:e),n=o._events),r=n[i]),r===void 0)r=n[i]=e,++o._eventsCount;else if(typeof r=="function"?r=n[i]=t?[e,r]:[r,e]:t?r.unshift(e):r.push(e),s=$(o),s>0&&r.length>s&&!r.warned){r.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+r.length+" "+String(i)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=o,a.type=i,a.count=r.length,_e(a)}return o}d.prototype.addListener=function(i,e){return Q(this,i,e,!1)};d.prototype.on=d.prototype.addListener;d.prototype.prependListener=function(i,e){return Q(this,i,e,!0)};function be(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function X(o,i,e){var t={fired:!1,wrapFn:void 0,target:o,type:i,listener:e},s=be.bind(t);return s.listener=e,t.wrapFn=s,s}d.prototype.once=function(i,e){return C(e),this.on(i,X(this,i,e)),this};d.prototype.prependOnceListener=function(i,e){return C(e),this.prependListener(i,X(this,i,e)),this};d.prototype.removeListener=function(i,e){var t,s,n,r,a;if(C(e),s=this._events,s===void 0)return this;if(t=s[i],t===void 0)return this;if(t===e||t.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete s[i],s.removeListener&&this.emit("removeListener",i,t.listener||e));else if(typeof t!="function"){for(n=-1,r=t.length-1;r>=0;r--)if(t[r]===e||t[r].listener===e){a=t[r].listener,n=r;break}if(n<0)return this;n===0?t.shift():me(t,n),t.length===1&&(s[i]=t[0]),s.removeListener!==void 0&&this.emit("removeListener",i,a||e)}return this};d.prototype.off=d.prototype.removeListener;d.prototype.removeAllListeners=function(i){var e,t,s;if(t=this._events,t===void 0)return this;if(t.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):t[i]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete t[i]),this;if(arguments.length===0){var n=Object.keys(t),r;for(s=0;s<n.length;++s)r=n[s],r!=="removeListener"&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=t[i],typeof e=="function")this.removeListener(i,e);else if(e!==void 0)for(s=e.length-1;s>=0;s--)this.removeListener(i,e[s]);return this};function Y(o,i,e){var t=o._events;if(t===void 0)return[];var s=t[i];return s===void 0?[]:typeof s=="function"?e?[s.listener||s]:[s]:e?ge(s):ee(s,s.length)}d.prototype.listeners=function(i){return Y(this,i,!0)};d.prototype.rawListeners=function(i){return Y(this,i,!1)};d.listenerCount=function(o,i){return typeof o.listenerCount=="function"?o.listenerCount(i):Z.call(o,i)};d.prototype.listenerCount=Z;function Z(o){var i=this._events;if(i!==void 0){var e=i[o];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}d.prototype.eventNames=function(){return this._eventsCount>0?E(this._events):[]};function ee(o,i){for(var e=new Array(i),t=0;t<i;++t)e[t]=o[t];return e}function me(o,i){for(;i+1<o.length;i++)o[i]=o[i+1];o.pop()}function ge(o){for(var i=new Array(o.length),e=0;e<i.length;++e)i[e]=o[e].listener||o[e];return i}function ve(o,i){return new Promise(function(e,t){function s(r){o.removeListener(i,n),t(r)}function n(){typeof o.removeListener=="function"&&o.removeListener("error",s),e([].slice.call(arguments))}te(o,i,n,{once:!0}),i!=="error"&&ye(o,s,{once:!0})})}function ye(o,i,e){typeof o.on=="function"&&te(o,"error",i,e)}function te(o,i,e,t){if(typeof o.on=="function")t.once?o.once(i,e):o.on(i,e);else if(typeof o.addEventListener=="function")o.addEventListener(i,function s(n){t.once&&o.removeEventListener(i,s),e(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof o)}});var re=V(N());var M=(t=>(t.Disconnected="disconnected",t.Connecting="connecting",t.Connected="connected",t))(M||{}),D=(t=>(t.Unsubscribed="unsubscribed",t.Subscribing="subscribing",t.Subscribed="subscribed",t))(D||{});function se(o,i){return o.lastIndexOf(i,0)===0}function F(o){return o==null?!1:typeof o=="function"}function ne(o,i){if(globalThis.console){let e=globalThis.console[o];F(e)&&e.apply(globalThis.console,i)}}function Se(o,i){return Math.floor(Math.random()*(i-o+1)+o)}function y(o,i,e){o>31&&(o=31);let t=Se(0,Math.min(e,i*Math.pow(2,o)));return Math.min(e,i+t)}function ie(o){return"error"in o&&o.error!==null}function S(o){return Math.min(o*1e3,2147483647)}var x=class extends re.default{constructor(e,t,s){super();this._resubscribeTimeout=null;this._refreshTimeout=null;this._getState=null;this._map=!1;this._mapPresenceType=1;this._mapPhase=null;this._mapStateBuffer=[];this._mapStreamBuffer=[];this._mapCursor="";this._mapPageSize=0;this._mapUnrecoverableStrategy="from_scratch";this._debounceMs=0;this._debouncePending=new Map;this._sharedPoll=!1;this._sharedPollEpoch="";this._sharedPollTrackedItems=new Map;this._sharedPollGetSignature=null;this._sharedPollSignatureRefreshTimeout=null;this._sharedPollSignatureRefreshAttempts=0;this._sharedPollTrackRetryTimeout=null;this._sharedPollTrackRetryAttempts=0;this._sharedPollReplayRetryTimeout=null;this._sharedPollReplayRetryAttempts=0;this._sharedPollSignatures=[];this._sharedPollSignatureRefreshTargetMs=null;this._sharedPollSignatureRefreshInFlight=!1;this.channel=t,this.state="unsubscribed",this._centrifuge=e,this._token="",this._getToken=null,this._data=null,this._getData=null,this._recover=!1,this._offset=null,this._epoch=null,this._id=0,this._recoverable=!1,this._positioned=!1,this._joinLeave=!1,this._minResubscribeDelay=500,this._maxResubscribeDelay=2e4,this._resubscribeTimeout=null,this._resubscribeAttempts=0,this._promises={},this._promiseId=0,this._inflight=!1,this._refreshTimeout=null,this._delta="",this._delta_negotiated=!1,this._tagsFilter=null,this._prevValueMap=new Map,this._unsubPromise=Promise.resolve(),this._deltaNumPubs=0,this._deltaNumFull=0,this._deltaNumDelta=0,this._deltaBytesReceived=0,this._deltaBytesDecoded=0,this._setOptions(s),this.type=this._sharedPoll?"shared_poll":this._map?"map":"stream",this._centrifuge._debugEnabled?(this.on("state",n=>{this._debug("subscription state",t,n.oldState,"->",n.newState)}),this.on("error",n=>{this._debug("subscription error",t,n)})):this.on("error",function(){Function.prototype()})}ready(e){return this.state==="unsubscribed"?Promise.reject({code:7,message:this.state}):this.state==="subscribed"?Promise.resolve():new Promise((t,s)=>{let n={resolve:t,reject:s};e&&(n.timeout=setTimeout(function(){s({code:1,message:"timeout"})},e)),this._promises[this._nextPromiseId()]=n})}subscribe(){this._isSubscribed()||(this._resubscribeAttempts=0,this._setSubscribing(0,"subscribe called"))}unsubscribe(){this._unsubPromise=this._setUnsubscribed(0,"unsubscribe called",!0)}_debouncedPublish(e,t,s){let n=this._debouncePending.get(e);if(n)return n.data=t,n.dirty=!0,Promise.resolve({});let r={data:t,dirty:!1,timer:null};return r.timer=setTimeout(()=>{let c=this._debouncePending.get(e);if(!c||!c.dirty){this._debouncePending.delete(e);return}c.dirty=!1;let h=c.data;(s?this._centrifuge.mapPublish(this.channel,e,h):this._centrifuge.publish(this.channel,h)).catch(()=>{}),c.timer=setTimeout(()=>{let u=this._debouncePending.get(e);if(!u||!u.dirty){this._debouncePending.delete(e);return}this._debouncePending.delete(e),this._debouncedPublish(e,u.data,s)},this._debounceMs)},this._debounceMs),this._debouncePending.set(e,r),s?this._centrifuge.mapPublish(this.channel,e,t):this._centrifuge.publish(this.channel,t)}_cancelDebounce(e){let t=this._debouncePending.get(e);t&&(clearTimeout(t.timer),this._debouncePending.delete(e))}_cancelAllDebounce(){for(let[,e]of this._debouncePending)clearTimeout(e.timer);this._debouncePending.clear()}async presence(){return await this._methodCall(),this._centrifuge.presence(this.channel)}async presenceStats(){return await this._methodCall(),this._centrifuge.presenceStats(this.channel)}setTagsFilter(e){if(e&&this._delta)throw new Error("cannot use delta and tagsFilter together");this._tagsFilter=e,this._map&&(this._recover=!1,this._offset=null,this._epoch=null)}setData(e){this._data=e}deltaStats(){let e=this._deltaBytesDecoded;return{numPublications:this._deltaNumPubs,numFullPayloads:this._deltaNumFull,numDeltaPayloads:this._deltaNumDelta,bytesReceived:this._deltaBytesReceived,bytesDecoded:e,compressionRatio:e>0?1-this._deltaBytesReceived/e:0}}_methodCall(){return this._isSubscribed()?Promise.resolve():this._isUnsubscribed()?Promise.reject({code:7,message:this.state}):new Promise((e,t)=>{let s=this._centrifuge._config.timeout,n=setTimeout(()=>{t({code:1,message:"timeout"})},s);this._promises[this._nextPromiseId()]={timeout:n,resolve:e,reject:t}})}_nextPromiseId(){return++this._promiseId}_needRecover(){return this._recover===!0}_isUnsubscribed(){return this.state==="unsubscribed"}_isSubscribing(){return this.state==="subscribing"}_isSubscribed(){return this.state==="subscribed"}_setState(e){if(this.state!==e){let t=this.state;return this.state=e,this.emit("state",{newState:e,oldState:t,channel:this.channel}),!0}return!1}_usesToken(){return this._token!==""||this._getToken!==null}_clearSubscribingState(){this._resubscribeAttempts=0,this._clearResubscribeTimeout()}_clearSubscribedState(){this._clearRefreshTimeout(),this._clearSharedPollSignatureRefresh(),this._clearSharedPollTrackRetry(),this._clearSharedPollReplayRetry(),this._sharedPollSignatureRefreshTargetMs=null,this._sharedPollSignatureRefreshInFlight=!1}_invalidateState(){this._token="",this._prevValueMap=new Map,this._map&&(this._offset=null,this._epoch=null,this._recover=!1,this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapCursor="",this._mapPhase=null)}_setSubscribed(e){if(!this._isSubscribing())return;if(this._clearSubscribingState(),e.id&&(this._id=e.id),e.recoverable&&(this._recover=!0,this._offset=e.offset||0,this._epoch=e.epoch||""),e.delta?this._delta_negotiated=!0:this._delta_negotiated=!1,e.publish_debounce&&(this._debounceMs=e.publish_debounce),this._sharedPoll){let n=e.epoch||"";if(this._sharedPollEpoch!==""&&this._sharedPollEpoch!==n)for(let r of this._sharedPollTrackedItems.keys())this._sharedPollTrackedItems.set(r,0);this._sharedPollEpoch=n}this._setState("subscribed");let t=this._centrifuge._getSubscribeContext(this.channel,e);this.emit("subscribed",t),this._resolvePromises();let s=e.publications;if(s&&s.length>0)for(let n in s)s.hasOwnProperty(n)&&this._handlePublication(s[n]);e.expires===!0&&(this._refreshTimeout=setTimeout(()=>this._refresh(),S(e.ttl)))}async _setSubscribing(e,t){this._isSubscribing()||(this._isSubscribed()&&this._clearSubscribedState(),this._setState("subscribing")&&this.emit("subscribing",{channel:this.channel,code:e,reason:t}),this._centrifuge._transport&&this._centrifuge._transport.emulation()&&await this._unsubPromise,this._isSubscribing()&&this._subscribe())}_subscribe(){return this._debug("subscribing on",this.channel),this._isTransportOpen()?this._inflight?null:(this._inflight=!0,this._map?(this._mapSubscribe(),null):this._getState&&this._offset===null?(this._loadStreamState(),null):this._canSubscribeWithoutGettingToken()?this._subscribeWithoutToken():(this._getSubscriptionToken().then(e=>this._handleTokenResponse(e)).catch(e=>this._handleTokenError(e)),null)):(this._debug("delay subscribe on",this.channel,"till connected"),null)}_isTransportOpen(){return this._centrifuge._transportIsOpen}_canSubscribeWithoutGettingToken(){return!this._usesToken()||!!this._token}_subscribeWithoutToken(){return this._getData?(this._getDataAndSubscribe(this._token),null):this._sendSubscribe(this._token)}_loadStreamState(){if(!this._isSubscribing()){this._inflight=!1;return}this._getState().then(e=>{if(!this._isSubscribing()){this._inflight=!1;return}this._offset=e.offset,this._epoch=e.epoch,this._recover=!0,this._canSubscribeWithoutGettingToken()?this._subscribeWithoutToken():this._getSubscriptionToken().then(t=>this._handleTokenResponse(t)).catch(t=>this._handleTokenError(t))}).catch(e=>{if(!this._isSubscribing()){this._inflight=!1;return}this._inflight=!1,this._subscribeError({code:13,message:e?.toString()||"getState failed",temporary:!0})})}_getDataAndSubscribe(e){if(!this._getData){this._inflight=!1;return}this._getData({channel:this.channel}).then(t=>{if(!this._isSubscribing()){this._inflight=!1;return}this._data=t,this._sendSubscribe(e)}).catch(t=>this._handleGetDataError(t))}_handleGetDataError(e){if(!this._isSubscribing()){this._inflight=!1;return}if(e instanceof g){this._inflight=!1,this._failUnauthorized();return}this.emit("error",{type:"subscribeData",channel:this.channel,error:{code:12,message:e?.toString()||""}}),this._inflight=!1,this._scheduleResubscribe()}_handleTokenResponse(e){if(!this._isSubscribing()){this._inflight=!1;return}if(!e){this._inflight=!1,this._failUnauthorized();return}this._token=e,this._getData?this._getDataAndSubscribe(e):this._sendSubscribe(e)}_handleTokenError(e){if(!this._isSubscribing()){this._inflight=!1;return}if(e instanceof g){this._inflight=!1,this._failUnauthorized();return}this.emit("error",{type:"subscribeToken",channel:this.channel,error:{code:8,message:e?.toString()||""}}),this._inflight=!1,this._scheduleResubscribe()}_sendSubscribe(e){if(!this._isTransportOpen())return this._inflight=!1,null;let t=this._buildSubscribeCommand(e);return this._centrifuge._call(t).then(s=>{this._inflight=!1;let n=s.reply.subscribe;this._handleSubscribeResponse(n),s.next&&s.next()},s=>{this._inflight=!1,this._handleSubscribeError(s.error),s.next&&s.next()}),t}_buildSubscribeCommand(e){let t={channel:this.channel};if(e&&(t.token=e),this._data&&(t.data=this._data),this._sharedPoll)return t.type=4,this._delta&&(t.delta=this._delta),{subscribe:t};if(this._positioned&&(t.positioned=!0),this._recoverable&&(t.recoverable=!0),this._joinLeave&&(t.join_leave=!0),t.flag=1,this._getState&&(t.flag|=2),this._needRecover()){t.recover=!0;let s=this._getOffset();s&&(t.offset=s);let n=this._getEpoch();n&&(t.epoch=n)}return this._delta&&(t.delta=this._delta),this._tagsFilter&&(t.tf=this._tagsFilter),{subscribe:t}}_debug(...e){this._centrifuge._debug(...e)}_handleSubscribeError(e){if(this._isSubscribing()){if(e.code===1){this._centrifuge._disconnect(3,"subscribe timeout",!0);return}if(e.code===112&&this._getState){this._offset=null,this._epoch=null,this._recover=!1,this._prevValueMap=new Map,this._scheduleResubscribe();return}this._subscribeError(e)}}_handleSubscribeResponse(e){this._isSubscribing()&&(this._setSubscribed(e),this._sharedPoll&&this._sharedPollReplayTrack())}_setUnsubscribed(e,t,s){if(this._isUnsubscribed())return Promise.resolve();let n=Promise.resolve();return this._isSubscribed()?(s&&(n=this._centrifuge._unsubscribe(this)),this._clearSubscribedState()):this._isSubscribing()&&(this._inflight&&s&&(n=this._centrifuge._unsubscribe(this)),this._clearSubscribingState()),this._inflight=!1,this._sharedPollEpoch="",this._sharedPollSignatures=[],this._sharedPollTrackedItems.clear(),this._sharedPollSignatureRefreshInFlight=!1,this._sharedPollSignatureRefreshTargetMs=null,this._cancelAllDebounce(),this._setState("unsubscribed")&&this.emit("unsubscribed",{channel:this.channel,code:e,reason:t}),this._rejectPromises({code:7,message:this.state}),n}_handlePublication(e){if(this._delta&&this._delta_negotiated){let s=(this._map||this._sharedPoll)&&e.key||"",{newData:n,newPrevValue:r,isDelta:a,wireBytes:c,fullBytes:h}=this._centrifuge._codec.applyDeltaIfNeeded(e,this._prevValueMap.get(s));e.data=n,this._deltaNumPubs++,this._deltaBytesReceived+=c,this._deltaBytesDecoded+=h,a?this._deltaNumDelta++:this._deltaNumFull++,e.removed?this._prevValueMap.delete(s):this._prevValueMap.set(s,r)}let t;if(this._sharedPoll){if(e.key&&!this._sharedPollTrackedItems.has(e.key))return;e.key&&(e.removed?this._sharedPollTrackedItems.delete(e.key):e.version&&this._sharedPollTrackedItems.set(e.key,e.version)),t=this._getSharedPollUpdateContext(e)}else this._map?t=this._getMapUpdateContext(e):t=this._centrifuge._getPublicationContext(this.channel,e);this.emit("publication",t),(this._map||this._sharedPoll)&&this.emit("update",t),e.offset&&(this._offset=e.offset),e.epoch&&(this._epoch=e.epoch)}_seedDeltaTracking(e){if(!(!this._delta||!e.key)){if(typeof e.data=="string"){let t=e.data;e.removed?this._prevValueMap.delete(e.key):this._prevValueMap.set(e.key,new TextEncoder().encode(t));let s=t.length;this._deltaNumPubs++,this._deltaNumFull++,this._deltaBytesReceived+=s,this._deltaBytesDecoded+=s,e.data=JSON.parse(t)}else if(e.data instanceof Uint8Array){e.removed?this._prevValueMap.delete(e.key):this._prevValueMap.set(e.key,e.data);let t=e.data.length;this._deltaNumPubs++,this._deltaNumFull++,this._deltaBytesReceived+=t,this._deltaBytesDecoded+=t}}}_handleJoin(e){let t=this._centrifuge._getJoinLeaveContext(e.info);this.emit("join",{channel:this.channel,info:t})}_handleLeave(e){let t=this._centrifuge._getJoinLeaveContext(e.info);this.emit("leave",{channel:this.channel,info:t})}_resolvePromises(){for(let e in this._promises)this._promises.hasOwnProperty(e)&&(this._promises[e].timeout&&clearTimeout(this._promises[e].timeout),this._promises[e].resolve(),delete this._promises[e])}_rejectPromises(e){for(let t in this._promises)this._promises.hasOwnProperty(t)&&(this._promises[t].timeout&&clearTimeout(this._promises[t].timeout),this._promises[t].reject(e),delete this._promises[t])}_scheduleResubscribe(){if(!this._isSubscribing()){this._debug("not in subscribing state, skip resubscribe scheduling",this.channel);return}let e=this,t=this._getResubscribeDelay();this._resubscribeTimeout=setTimeout(function(){e._isSubscribing()&&e._subscribe()},t),this._debug("resubscribe scheduled after "+t,this.channel)}_subscribeError(e){if(this._isSubscribing())if(e.code<100||e.code===109||e.temporary===!0){e.code===109&&(this._token="");let t={channel:this.channel,type:"subscribe",error:e};this._centrifuge.state==="connected"&&this.emit("error",t),this._scheduleResubscribe()}else this._setUnsubscribed(e.code,e.message,!1)}_getResubscribeDelay(){let e=y(this._resubscribeAttempts,this._minResubscribeDelay,this._maxResubscribeDelay);return this._resubscribeAttempts++,e}_setOptions(e){if(e){if(e.since&&(this._offset=e.since.offset||0,this._epoch=e.since.epoch||"",this._recover=!0),e.data&&(this._data=e.data),e.getData&&(this._getData=e.getData),e.minResubscribeDelay!==void 0&&(this._minResubscribeDelay=e.minResubscribeDelay),e.maxResubscribeDelay!==void 0&&(this._maxResubscribeDelay=e.maxResubscribeDelay),e.token&&(this._token=e.token),e.getToken&&(this._getToken=e.getToken),e.positioned===!0&&(this._positioned=!0),e.recoverable===!0&&(this._recoverable=!0),e.joinLeave===!0&&(this._joinLeave=!0),e.delta){if(e.delta!=="fossil")throw new Error("unsupported delta format");this._delta=e.delta}if(e.tagsFilter&&(this._tagsFilter=e.tagsFilter),this._tagsFilter&&this._delta)throw new Error("cannot use delta and tagsFilter together");e.getState&&(this._getState=e.getState,this._recover=!0),e.map===!0&&(this._map=!0),e.mapPageSize!==void 0&&(this._mapPageSize=e.mapPageSize),e.mapPresenceType!==void 0&&(this._mapPresenceType=e.mapPresenceType,this._map=!0),e.mapUnrecoverableStrategy&&(this._mapUnrecoverableStrategy=e.mapUnrecoverableStrategy),e.sharedPoll===!0&&(this._sharedPoll=!0),e.sharedPollGetSignature&&(this._sharedPollGetSignature=e.sharedPollGetSignature)}}_getOffset(){let e=this._offset;return e!==null?e:0}_getEpoch(){let e=this._epoch;return e!==null?e:""}_clearRefreshTimeout(){this._refreshTimeout!==null&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearResubscribeTimeout(){this._resubscribeTimeout!==null&&(clearTimeout(this._resubscribeTimeout),this._resubscribeTimeout=null)}_getSubscriptionToken(){this._debug("get subscription token for channel",this.channel);let e={channel:this.channel},t=this._getToken;return t===null?(this.emit("error",{type:"configuration",channel:this.channel,error:{code:12,message:"provide a function to get channel subscription token"}}),Promise.reject(new g(""))):t(e)}_refresh(){this._clearRefreshTimeout();let e=this;this._getSubscriptionToken().then(function(t){if(!e._isSubscribed())return;if(!t){e._failUnauthorized();return}e._token=t;let n={sub_refresh:{channel:e.channel,token:t}};e._centrifuge._call(n).then(r=>{let a=r.reply.sub_refresh;e._refreshResponse(a),r.next&&r.next()},r=>{e._refreshError(r.error),r.next&&r.next()})}).catch(function(t){if(t instanceof g){e._failUnauthorized();return}e.emit("error",{type:"refreshToken",channel:e.channel,error:{code:9,message:t!==void 0?t.toString():""}}),e._refreshTimeout=setTimeout(()=>e._refresh(),e._getRefreshRetryDelay())})}_refreshResponse(e){this._isSubscribed()&&(this._debug("subscription token refreshed, channel",this.channel),this._clearRefreshTimeout(),e.expires===!0&&(this._refreshTimeout=setTimeout(()=>this._refresh(),S(e.ttl))))}_refreshError(e){this._isSubscribed()&&(e.code<100||e.temporary===!0?(this.emit("error",{type:"refresh",channel:this.channel,error:e}),this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay())):this._setUnsubscribed(e.code,e.message,!0))}_getRefreshRetryDelay(){return y(0,1e4,2e4)}_failUnauthorized(){this._setUnsubscribed(1,"unauthorized",!0)}_sendTrackRequest(e,t){if(e.length===0)return Promise.resolve();let s=6e4,n=[],r=[],a=100;if(t&&t.length>0)for(let h of t)a+=h.length+4;for(let h of e){let l=100;for(let u of h.items)l+=u.key.length+16;r.length>0&&a+l>s&&(n.push(r),r=[],a=100),r.push(h),a+=l}r.length>0&&n.push(r);let c=(h,l)=>new Promise((u,v)=>{let m={channel:this.channel,type:1,track:h.map(f=>({signature:f.signature,items:f.items.map(_=>_.version>0?_:{key:_.key})}))};l&&l.length>0&&(m.untrack=l);let p={sub_refresh:m};this._centrifuge._call(p).then(f=>{this._handleTrackResponse(f.reply.sub_refresh),f.next&&f.next(),u()},f=>{f.next&&f.next(),v(f.error)})});return n.reduce((h,l,u)=>h.then(()=>c(l,u===0?t:void 0)),Promise.resolve())}_sendUntrackRequest(e){return new Promise((t,s)=>{let r={sub_refresh:{channel:this.channel,type:2,untrack:e}};this._centrifuge._call(r).then(a=>{a.next&&a.next(),t()},a=>{a.next&&a.next(),s(a.error)})})}_handleTrackResponse(e){if(this._clearSharedPollTrackRetry(),e&&e.items&&e.items.length>0)for(let t of e.items)this._handlePublication(t);if(e&&e.expires===!0&&e.ttl>0){let t=Date.now()+e.ttl*1e3;this._maybeScheduleSharedPollSignatureRefresh(t)}}_maybeScheduleSharedPollSignatureRefresh(e){if(e===null){this._sharedPollSignatureRefreshTargetMs=null,this._clearSharedPollSignatureRefresh();return}this._isSubscribed()&&(this._sharedPollSignatureRefreshTargetMs!==null&&e>=this._sharedPollSignatureRefreshTargetMs||(this._sharedPollSignatureRefreshTargetMs=e,this._clearSharedPollSignatureRefresh(),this._sharedPollSignatureRefreshTimeout=setTimeout(()=>this._sharedPollRefreshSignature(),Math.max(0,e-Date.now()))))}_clearSharedPollSignatureRefresh(){this._sharedPollSignatureRefreshTimeout!==null&&(clearTimeout(this._sharedPollSignatureRefreshTimeout),this._sharedPollSignatureRefreshTimeout=null),this._sharedPollSignatureRefreshAttempts=0}_clearSharedPollTrackRetry(){this._sharedPollTrackRetryTimeout!==null&&(clearTimeout(this._sharedPollTrackRetryTimeout),this._sharedPollTrackRetryTimeout=null),this._sharedPollTrackRetryAttempts=0}_clearSharedPollReplayRetry(){this._sharedPollReplayRetryTimeout!==null&&(clearTimeout(this._sharedPollReplayRetryTimeout),this._sharedPollReplayRetryTimeout=null),this._sharedPollReplayRetryAttempts=0}_handleTrackError(e){if(this._isSubscribed()){if(this.emit("error",{type:"track",channel:this.channel,error:e}),e.code===109){this._sharedPollRefreshSignature();return}(e.code<100||e.temporary===!0)&&(this._sharedPollTrackRetryTimeout=setTimeout(()=>this._sharedPollReplayTrack(),y(this._sharedPollTrackRetryAttempts++,1e3,15e3)))}}_sharedPollRefreshSignature(){if(this._clearSharedPollSignatureRefresh(),!this._isSubscribed()||!this._sharedPollGetSignature||this._sharedPollTrackedItems.size===0||this._sharedPollSignatureRefreshInFlight)return;this._sharedPollSignatureRefreshTargetMs=null,this._sharedPollSignatureRefreshInFlight=!0;let e=Array.from(this._sharedPollTrackedItems.keys()),t=this;this._sharedPollGetSignature({keys:e}).then(s=>{if(t._sharedPollSignatureRefreshInFlight=!1,!t._isSubscribed())return;t._sharedPollSignatureRefreshAttempts=0;let n=new Set(s.keys),r=[];for(let l of e)n.has(l)||(t._sharedPollTrackedItems.delete(l),r.push(l),t.emit("update",{channel:t.channel,key:l,data:null,removed:!0}));r.length>0&&t._sendUntrackRequest(r).catch(l=>{t.emit("error",{type:"untrack",channel:t.channel,error:l})});let a=[];for(let l of s.keys){let u=t._sharedPollTrackedItems.get(l);u!==void 0&&a.push({key:l,version:u})}let c=new Set(s.keys),h=t._sharedPollSignatures.filter(l=>l.keys.some(u=>t._sharedPollTrackedItems.has(u)&&!c.has(u)));t._sharedPollSignatures=a.length>0?[{keys:s.keys,signature:s.signature},...h]:h,a.length!==0&&t._sendTrackRequest([{items:a,signature:s.signature}]).catch(l=>{t._handleTrackError(l)})}).catch(s=>{t._sharedPollSignatureRefreshInFlight=!1,t.emit("error",{type:"signatureRefresh",channel:t.channel,error:{code:14,message:s!==void 0?s.toString():""}}),t._sharedPollSignatureRefreshTimeout=setTimeout(()=>t._sharedPollRefreshSignature(),y(t._sharedPollSignatureRefreshAttempts++,5e3,3e4))})}_sharedPollReplayTrack(){if(!this._isSubscribed()||this._sharedPollTrackedItems.size===0&&this._sharedPollSignatures.length===0)return;let e=new Set,t=[],s=[];for(let a of this._sharedPollSignatures){let c=a.keys.map(h=>({key:h,version:this._sharedPollTrackedItems.get(h)??0}));t.push({items:c,signature:a.signature});for(let h of a.keys)this._sharedPollTrackedItems.has(h)?e.add(h):s.push(h)}t.length>0&&this._sendTrackRequest(t,s).catch(a=>{this._handleTrackError(a)});let n=[];for(let a of this._sharedPollTrackedItems.keys())e.has(a)||n.push(a);if(n.length===0)return;if(!this._sharedPollGetSignature){this.emit("error",{type:"track",channel:this.channel,error:{code:14,message:"getSignature callback required for tracked keys without an explicit signature"}});return}let r=this;this._sharedPollGetSignature({keys:n}).then(a=>{if(!r._isSubscribed())return;r._clearSharedPollReplayRetry();let c=new Set(a.keys),h=[];for(let u of n)c.has(u)||(r._sharedPollTrackedItems.delete(u),h.push(u),r.emit("update",{channel:r.channel,key:u,data:null,removed:!0}));h.length>0&&r._sendUntrackRequest(h).catch(u=>{r.emit("error",{type:"untrack",channel:r.channel,error:u})});let l=[];for(let u of a.keys){let v=r._sharedPollTrackedItems.get(u);v!==void 0&&l.push({key:u,version:v})}l.length!==0&&(r._sharedPollSignatures.push({keys:a.keys,signature:a.signature}),r._sendTrackRequest([{items:l,signature:a.signature}]).catch(u=>{r._handleTrackError(u)}))}).catch(a=>{r.emit("error",{type:"signatureRefresh",channel:r.channel,error:{code:14,message:a!==void 0?a.toString():""}}),r._sharedPollReplayRetryTimeout=setTimeout(()=>r._sharedPollReplayTrack(),y(r._sharedPollReplayRetryAttempts++,5e3,3e4))})}_mapSubscribe(){if(this._debug("starting map subscribe on",this.channel),this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapCursor="",this._recover&&this._offset!==null&&this._epoch!==null||(this._prevValueMap=new Map),this._mapPhase=2,this._recover&&this._offset!==null&&this._epoch!==null){this._debug("map subscribe: recovering from position, skipping to stream phase"),this._mapPhase=1,this._fetchStream();return}this._canSubscribeWithoutGettingToken()?this._fetchSnapshot():this._getSubscriptionToken().then(e=>{if(!this._isSubscribing()){this._inflight=!1;return}if(!e){this._inflight=!1,this._failUnauthorized();return}this._token=e,this._fetchSnapshot()}).catch(e=>this._handleTokenError(e))}_fetchSnapshot(e){if(!this._isSubscribing()||!this._isTransportOpen()){this._inflight=!1;return}let t=this._buildMapSubscribeCommand(2,e);this._debug("map subscribe: fetching snapshot page",e?`cursor=${e}`:"initial"),this._centrifuge._call(t).then(s=>{let n=s.reply.subscribe;this._handleMapStateResponse(n),s.next&&s.next()},s=>{this._handleMapSubscribeError(s.error),s.next&&s.next()})}_handleMapStateResponse(e){if(!this._isSubscribing()){this._inflight=!1;return}if(!e.phase){this._debug("map subscribe: server forced LIVE transition during state pagination"),this._handleMapLiveResponse(e);return}if(!this._epoch&&e.epoch&&(this._epoch=e.epoch,this._offset=e.offset||0),this._epoch&&e.epoch&&this._epoch!==e.epoch){this._debug("map subscribe: epoch changed during snapshot pagination, restarting"),this._mapStateBuffer=[],this._mapCursor="",this._epoch=null,this._offset=null,this._prevValueMap=new Map,this._fetchSnapshot();return}if(e.state&&e.state.length>0)for(let t of e.state)this._seedDeltaTracking(t),this._mapStateBuffer.push(this._getMapUpdateContext(t));if(e.cursor){this._mapCursor=e.cursor,this._fetchSnapshot(this._mapCursor);return}this._transitionFromSnapshot()}_transitionFromSnapshot(){this._debug("map subscribe: snapshot complete, transitioning to stream phase"),this._mapPhase=1,this._fetchStream()}_fetchStream(){if(!this._isSubscribing()||!this._isTransportOpen()){this._inflight=!1;return}let e=this._buildMapSubscribeCommand(1);this._debug("map subscribe: fetching stream from offset",this._offset),this._centrifuge._call(e).then(t=>{let s=t.reply.subscribe;this._handleMapStreamResponse(s),t.next&&t.next()},t=>{this._handleMapSubscribeError(t.error),t.next&&t.next()})}_handleMapStreamResponse(e){if(!this._isSubscribing()){this._inflight=!1;return}if(!e.phase){this._debug("map subscribe: server forced LIVE transition during stream"),this._handleMapLiveResponse(e);return}if(this._epoch&&e.epoch&&this._epoch!==e.epoch){this._debug("map subscribe: epoch changed during stream, restarting"),this._mapStateBuffer=[],this._mapStreamBuffer=[],this._epoch=null,this._offset=null,this._prevValueMap=new Map,this._mapPhase=2,this._fetchSnapshot();return}if(e.publications&&e.publications.length>0)for(let t of e.publications)this._seedDeltaTracking(t),this._mapStreamBuffer.push(this._getMapUpdateContext(t));e.offset!==void 0&&(this._offset=e.offset),this._fetchStream()}_handleMapLiveResponse(e){if(!this._isSubscribing()){this._inflight=!1;return}if(this._inflight=!1,this._epoch&&e.epoch&&this._epoch!==e.epoch){this._debug("map subscribe: epoch changed during live transition, restarting"),this._mapStateBuffer=[],this._mapStreamBuffer=[],this._epoch=null,this._offset=null,this._prevValueMap=new Map,this._inflight=!0,this._mapPhase=2,this._fetchSnapshot();return}if(e.state&&e.state.length>0)for(let s of e.state)this._seedDeltaTracking(s),this._mapStateBuffer.push(this._getMapUpdateContext(s));if(e.publications&&e.publications.length>0)for(let s of e.publications){if(this._delta&&e.delta){let n=s.key||"",{newData:r,newPrevValue:a,isDelta:c,wireBytes:h,fullBytes:l}=this._centrifuge._codec.applyDeltaIfNeeded(s,this._prevValueMap.get(n));s.data=r,this._deltaNumPubs++,this._deltaBytesReceived+=h,this._deltaBytesDecoded+=l,c?this._deltaNumDelta++:this._deltaNumFull++,s.removed?this._prevValueMap.delete(n):this._prevValueMap.set(n,a)}else this._delta&&s.key&&(s.removed?this._prevValueMap.delete(s.key):this._prevValueMap.set(s.key,s.data));this._mapStreamBuffer.push(this._getMapUpdateContext(s))}this._offset=e.offset||0,this._epoch=e.epoch||"",this._clearSubscribingState(),e.id&&(this._id=e.id),this._recover=e.recoverable===!0,e.delta?this._delta_negotiated=!0:this._delta_negotiated=!1,e.publish_debounce&&(this._debounceMs=e.publish_debounce),this._setState("subscribed");let t=this._centrifuge._getSubscribeContext(this.channel,e);if(t.state=this._mapStateBuffer,this.emit("subscribed",t),this._resolvePromises(),!t.recovered){if(this._mapStreamBuffer.length>0){let s=new Map;for(let n of this._mapStateBuffer)s.set(n.key,n);for(let n of this._mapStreamBuffer)n.removed?s.delete(n.key):s.set(n.key,n);this._mapStateBuffer=Array.from(s.values()),this._mapStreamBuffer=[]}this.emit("sync",{entries:this._mapStateBuffer})}for(let s of this._mapStreamBuffer)this.emit("publication",s),this.emit("update",s);this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapPhase=null,e.expires===!0&&(this._refreshTimeout=setTimeout(()=>this._refresh(),S(e.ttl)))}_handleMapSubscribeError(e){if(this._inflight=!1,!!this._isSubscribing()){if(e.code===1){this._centrifuge._disconnect(3,"subscribe timeout",!0);return}if(this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapPhase=null,this._prevValueMap=new Map,e.code===112&&this._mapUnrecoverableStrategy==="from_scratch"){this._debug("map subscribe: unrecoverable position, restarting from scratch"),this._offset=null,this._epoch=null,this._recover=!1,this._scheduleResubscribe();return}this._subscribeError(e)}}_buildMapSubscribeCommand(e,t){let s={channel:this.channel,type:this._mapPresenceType||1,phase:e};return this._token&&(s.token=this._token),this._tagsFilter&&(s.tf=this._tagsFilter),this._delta&&(s.delta=this._delta),s.flag=1,e===2&&(this._mapPageSize>0&&(s.limit=this._mapPageSize),t&&(s.cursor=t),this._epoch?(s.offset=this._offset,s.epoch=this._epoch):this._data&&(s.data=this._data)),e===1&&(this._mapPageSize>0&&(s.limit=this._mapPageSize),s.offset=this._offset,s.epoch=this._epoch,this._recover&&(s.recover=!0,this._mapStreamBuffer.length===0&&this._data&&(s.data=this._data))),{subscribe:s}}_getMapUpdateContext(e){let t={channel:this.channel,data:e.data,key:e.key||""};return e.removed===!0&&(t.removed=!0),e.offset!==void 0&&(t.offset=e.offset),e.info&&(t.info=this._centrifuge._getJoinLeaveContext(e.info)),e.tags&&(t.tags=e.tags),t}_getSharedPollUpdateContext(e){let t={channel:this.channel,key:e.key||"",data:e.data};return e.removed===!0&&(t.removed=!0),e.version!==void 0&&(t.version=e.version),t}},O=class extends x{async publish(i){return await this._methodCall(),this._debounceMs>0?this._debouncedPublish("",i,!1):this._centrifuge.publish(this.channel,i)}async history(i){return await this._methodCall(),this._centrifuge.history(this.channel,i)}},k=class extends x{async publish(i,e){return await this._methodCall(),this._debounceMs>0?this._debouncedPublish(i,e,!0):this._centrifuge.mapPublish(this.channel,i,e)}async remove(i){return await this._methodCall(),this._cancelDebounce(i),this._centrifuge.mapRemove(this.channel,i)}},I=class extends x{track(i,e){if(i.length===0)return;let t,s=e;typeof i[0]=="string"?t=i.map(a=>({key:a,version:0})):t=i;for(let r of t){let a=this._sharedPollTrackedItems.get(r.key);(a===void 0||r.version>a)&&this._sharedPollTrackedItems.set(r.key,r.version)}if(s!==void 0){this._sharedPollSignatures.push({keys:t.map(r=>r.key),signature:s}),this._isSubscribed()&&this._sendTrackRequest([{items:t,signature:s}]).catch(r=>{this._handleTrackError(r)});return}if(!this._sharedPollGetSignature){this.emit("error",{type:"track",channel:this.channel,error:{code:14,message:"getSignature callback required for track(keys)"}});return}if(!this._isSubscribed())return;let n=t.map(r=>r.key);this._sharedPollGetSignature({keys:n}).then(r=>{if(!this._isSubscribed())return;let a=new Set(r.keys),c=[];for(let l of n)a.has(l)||(this._sharedPollTrackedItems.delete(l),c.push(l),this.emit("update",{channel:this.channel,key:l,data:null,removed:!0}));c.length>0&&this._sendUntrackRequest(c).catch(l=>{this.emit("error",{type:"untrack",channel:this.channel,error:l})});let h=[];for(let l of r.keys){let u=this._sharedPollTrackedItems.get(l);u!==void 0&&h.push({key:l,version:u})}h.length!==0&&(this._sharedPollSignatures.push({keys:r.keys,signature:r.signature}),this._sendTrackRequest([{items:h,signature:r.signature}]).catch(l=>{this._handleTrackError(l)}))}).catch(r=>{this.emit("error",{type:"track",channel:this.channel,error:{code:14,message:r!==void 0?r.toString():"getSignature failed"}})})}untrack(i){for(let e of i)this._sharedPollTrackedItems.delete(e);this._sharedPollSignatures=this._sharedPollSignatures.filter(e=>e.keys.some(t=>this._sharedPollTrackedItems.has(t))),this._isSubscribed()&&this._sendUntrackRequest(i).catch(e=>{this.emit("error",{type:"untrack",channel:this.channel,error:e})})}trackedKeys(){return new Set(this._sharedPollTrackedItems.keys())}};var L=class{constructor(i,e){this.endpoint=i,this.options=e,this._transport=null}name(){return"sockjs"}subName(){return"sockjs-"+this._transport.transport}emulation(){return!1}supported(){return this.options.sockjs!==null}initialize(i,e){this._transport=new this.options.sockjs(this.endpoint,null,this.options.sockjsOptions),this._transport.onopen=()=>{e.onOpen()},this._transport.onerror=t=>{e.onError(t)},this._transport.onclose=t=>{e.onClose(t)},this._transport.onmessage=t=>{e.onMessage(t.data)}}close(){this._transport.close()}send(i){this._transport.send(i)}};var w=class{constructor(i,e){this.endpoint=i,this.options=e,this._transport=null}name(){return"websocket"}subName(){return"websocket"}emulation(){return!1}supported(){return this.options.websocket!==void 0&&this.options.websocket!==null}initialize(i,e){let t="";i==="protobuf"&&(t="centrifuge-protobuf"),t!==""?this._transport=new this.options.websocket(this.endpoint,t):this._transport=new this.options.websocket(this.endpoint),i==="protobuf"&&(this._transport.binaryType="arraybuffer"),this._transport.onopen=()=>{e.onOpen()},this._transport.onerror=s=>{e.onError(s)},this._transport.onclose=s=>{e.onClose(s)},this._transport.onmessage=s=>{e.onMessage(s.data)}}close(){this._transport.close()}send(i){this._transport.send(i)}};var U=class{constructor(i,e){this.endpoint=i,this.options=e,this._abortController=null,this._utf8decoder=new TextDecoder,this._protocol="json"}name(){return"http_stream"}subName(){return"http_stream"}emulation(){return!0}_handleErrors(i){if(!i.ok)throw new Error(i.status);return i}_fetchEventTarget(i,e,t){let s=new EventTarget,n=i.options.fetch;return n(e,t).then(i._handleErrors).then(r=>{s.dispatchEvent(new Event("open"));let a="",c=0,h=new Uint8Array,l=r.body.getReader();return new i.options.readableStream({start(u){function v(){return l.read().then(({done:m,value:p})=>{if(m){s.dispatchEvent(new Event("close")),u.close();return}try{if(i._protocol==="json")for(a+=i._utf8decoder.decode(p);c<a.length;)if(a[c]===`
`){let f=a.substring(0,c);s.dispatchEvent(new MessageEvent("message",{data:f})),a=a.substring(c+1),c=0}else++c;else{let f=new Uint8Array(h.length+p.length);for(f.set(h),f.set(p,h.length),h=f;;){let _=i.options.decoder.decodeReply(h);if(_.ok){let b=h.slice(0,_.pos);s.dispatchEvent(new MessageEvent("message",{data:b})),h=h.slice(_.pos);continue}break}}}catch(f){s.dispatchEvent(new Event("error",{detail:f})),s.dispatchEvent(new Event("close")),u.close();return}v()}).catch(function(m){s.dispatchEvent(new Event("error",{detail:m})),s.dispatchEvent(new Event("close")),u.close()})}return v()}})}).catch(r=>{s.dispatchEvent(new Event("error",{detail:r})),s.dispatchEvent(new Event("close"))}),s}supported(){return this.options.fetch!==null&&this.options.readableStream!==null&&typeof TextDecoder<"u"&&typeof AbortController<"u"&&typeof EventTarget<"u"&&typeof Event<"u"&&typeof MessageEvent<"u"&&typeof Error<"u"}initialize(i,e,t){this._protocol=i,this._abortController=new AbortController;let s,n;i==="json"?(s={Accept:"application/json","Content-Type":"application/json"},n=t):(s={Accept:"application/octet-stream","Content-Type":"application/octet-stream"},n=t);let r={method:"POST",headers:s,body:n,mode:"cors",credentials:"same-origin",signal:this._abortController.signal},a=this._fetchEventTarget(this,this.endpoint,r);a.addEventListener("open",()=>{e.onOpen()}),a.addEventListener("error",c=>{this._abortController.abort(),e.onError(c)}),a.addEventListener("close",()=>{this._abortController.abort(),e.onClose({code:4,reason:"connection closed"})}),a.addEventListener("message",c=>{e.onMessage(c.data)})}close(){this._abortController.abort()}send(i,e,t){let s,n,r={session:e,node:t,data:i};this._protocol==="json"?(s={"Content-Type":"application/json"},n=JSON.stringify(r)):(s={"Content-Type":"application/octet-stream"},n=this.options.encoder.encodeEmulationRequest(r));let a=this.options.fetch,c={method:"POST",headers:s,body:n,mode:"cors",credentials:"same-origin"};a(this.options.emulationEndpoint,c)}};var B=class{constructor(i,e){this.endpoint=i,this.options=e,this._protocol="json",this._transport=null,this._onClose=null}name(){return"sse"}subName(){return"sse"}emulation(){return!0}supported(){return this.options.eventsource!==null&&this.options.fetch!==null}initialize(i,e,t){let s;globalThis&&globalThis.document&&globalThis.document.baseURI?s=new URL(this.endpoint,globalThis.document.baseURI):s=new URL(this.endpoint),s.searchParams.append("cf_connect",t);let n={},r=new this.options.eventsource(s.toString(),n);this._transport=r;let a=this;r.onopen=function(){e.onOpen()},r.onerror=function(c){r.close(),e.onError(c),e.onClose({code:4,reason:"connection closed"})},r.onmessage=function(c){e.onMessage(c.data)},a._onClose=function(){e.onClose({code:4,reason:"connection closed"})}}close(){this._transport.close(),this._onClose!==null&&this._onClose()}send(i,e,t){let s={session:e,node:t,data:i},n={"Content-Type":"application/json"},r=JSON.stringify(s),a=this.options.fetch,c={method:"POST",headers:n,body:r,mode:"cors",credentials:"same-origin"};a(this.options.emulationEndpoint,c)}};var A=class{constructor(i,e){this.endpoint=i,this.options=e,this._transport=null,this._stream=null,this._writer=null,this._utf8decoder=new TextDecoder,this._protocol="json"}name(){return"webtransport"}subName(){return"webtransport"}emulation(){return!1}supported(){return this.options.webtransport!==void 0&&this.options.webtransport!==null}async initialize(i,e){let t;globalThis&&globalThis.document&&globalThis.document.baseURI?t=new URL(this.endpoint,globalThis.document.baseURI):t=new URL(this.endpoint),i==="protobuf"&&t.searchParams.append("cf_protocol","protobuf"),this._protocol=i;let s=new EventTarget;this._transport=new this.options.webtransport(t.toString()),this._transport.closed.then(()=>{e.onClose({code:4,reason:"connection closed"})}).catch(()=>{e.onClose({code:4,reason:"connection closed"})});try{await this._transport.ready}catch{this.close();return}let n;try{n=await this._transport.createBidirectionalStream()}catch{this.close();return}this._stream=n,this._writer=this._stream.writable.getWriter(),s.addEventListener("close",()=>{e.onClose({code:4,reason:"connection closed"})}),s.addEventListener("message",r=>{e.onMessage(r.data)}),this._startReading(s),e.onOpen()}async _startReading(i){let e=this._stream.readable.getReader(),t="",s=0,n=new Uint8Array;try{for(;;){let{done:r,value:a}=await e.read();if(a.length>0)if(this._protocol==="json")for(t+=this._utf8decoder.decode(a);s<t.length;)if(t[s]===`
`){let c=t.substring(0,s);i.dispatchEvent(new MessageEvent("message",{data:c})),t=t.substring(s+1),s=0}else++s;else{let c=new Uint8Array(n.length+a.length);for(c.set(n),c.set(a,n.length),n=c;;){let h=this.options.decoder.decodeReply(n);if(h.ok){let l=n.slice(0,h.pos);i.dispatchEvent(new MessageEvent("message",{data:l})),n=n.slice(h.pos);continue}break}}if(r)break}}catch{i.dispatchEvent(new Event("close"))}}async close(){try{this._writer&&await this._writer.close(),this._transport.close()}catch{}}async send(i){let e;this._protocol==="json"?e=new TextEncoder().encode(i+`
`):e=i;try{await this._writer.write(e)}catch{this.close()}}};var xe=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,36,-1,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,-1,-1,-1,63,-1],q=class{constructor(i){this.a=i,this.pos=0}haveBytes(){return this.pos<this.a.length}getByte(){let i=this.a[this.pos];if(this.pos++,this.pos>this.a.length)throw new RangeError("out of bounds");return i}getChar(){return String.fromCharCode(this.getByte())}getInt(){let i=0,e;for(;this.haveBytes()&&(e=xe[127&this.getByte()])>=0;)i=(i<<6)+e;return this.pos--,i>>>0}},W=class{constructor(){this.a=[]}toByteArray(i){return Array.isArray(i)?this.a:new Uint8Array(this.a)}putArray(i,e,t){for(let s=e;s<t;s++)this.a.push(i[s])}};function we(o){let i=0,e=0,t=0,s=0,n=0,r=o.length;for(;r>=16;)i=i+o[n+0]|0,e=e+o[n+1]|0,t=t+o[n+2]|0,s=s+o[n+3]|0,i=i+o[n+4]|0,e=e+o[n+5]|0,t=t+o[n+6]|0,s=s+o[n+7]|0,i=i+o[n+8]|0,e=e+o[n+9]|0,t=t+o[n+10]|0,s=s+o[n+11]|0,i=i+o[n+12]|0,e=e+o[n+13]|0,t=t+o[n+14]|0,s=s+o[n+15]|0,n+=16,r-=16;for(;r>=4;)i=i+o[n+0]|0,e=e+o[n+1]|0,t=t+o[n+2]|0,s=s+o[n+3]|0,n+=4,r-=4;switch(s=((s+(t<<8)|0)+(e<<16)|0)+(i<<24)|0,r){case 3:s=s+(o[n+2]<<8)|0;case 2:s=s+(o[n+1]<<16)|0;case 1:s=s+(o[n+0]<<24)|0}return s>>>0}function oe(o,i){let e=0,t=new q(i),s=o.length,n=i.length,r=t.getInt();if(t.getChar()!==`
`)throw new Error("size integer not terminated by '\\n'");let a=new W;for(;t.haveBytes();){let c=t.getInt(),h;switch(t.getChar()){case"@":if(h=t.getInt(),t.haveBytes()&&t.getChar()!==",")throw new Error("copy command not terminated by ','");if(e+=c,e>r)throw new Error("copy exceeds output file size");if(h+c>s)throw new Error("copy extends past end of input");a.putArray(o,h,h+c);break;case":":if(e+=c,e>r)throw new Error("insert command gives an output larger than predicted");if(c>n)throw new Error("insert count exceeds size of delta");a.putArray(t.a,t.pos,t.pos+c),t.pos+=c;break;case";":{let l=a.toByteArray(o);if(c!==we(l))throw new Error("bad checksum");if(e!==r)throw new Error("generated size does not match predicted size");return l}default:throw new Error("unknown delta operator")}}throw new Error("unterminated delta")}var R=class{name(){return"json"}encodeCommands(i){return i.map(e=>JSON.stringify(e)).join(`
`)}decodeReplies(i){return i.trim().split(`
`).map(e=>JSON.parse(e))}applyDeltaIfNeeded(i,e){let t,s,n;if(i.delta){n=!0;let r=new TextEncoder().encode(i.data),a=oe(e,r);t=JSON.parse(new TextDecoder().decode(a)),s=a}else n=!1,t=JSON.parse(i.data),s=new TextEncoder().encode(i.data);return{newData:t,newPrevValue:s,isDelta:n,wireBytes:i.data.length,fullBytes:s.length}}};var ae=V(N()),Re={headers:{},token:"",getToken:null,data:null,getData:null,debug:!1,name:"js",version:"",fetch:null,readableStream:null,websocket:null,eventsource:null,sockjs:null,sockjsOptions:{},emulationEndpoint:"/emulation",minReconnectDelay:500,maxReconnectDelay:2e4,timeout:5e3,maxServerPingDelay:1e4,networkEventTarget:null},g=class extends Error{constructor(i){super(i),this.name=this.constructor.name}},P=class extends ae.default{constructor(e,t){super();this._reconnectTimeout=null;this._refreshTimeout=null;this._serverPingTimeout=null;this.state="disconnected",this._transportIsOpen=!1,this._endpoint=e,this._emulation=!1,this._transports=[],this._currentTransportIndex=0,this._triedAllTransports=!1,this._transportWasOpen=!1,this._transport=null,this._transportId=0,this._deviceWentOffline=!1,this._transportClosed=!0,this._codec=new R,this._reconnecting=!1,this._reconnectTimeout=null,this._reconnectAttempts=0,this._client=null,this._session="",this._node="",this._subs={},this._serverSubs={},this._commandId=0,this._co