Files
sm-bm-plugin/public/assets/index-B53bcf0x.js
2026-10-08 18:14:15 +02:00

8 lines
80 KiB
JavaScript

function w(o,e,t,s){function i(n){return n instanceof t?n:new t(function(r){r(n)})}return new(t||(t=Promise))(function(n,r){function h(f){try{d(s.next(f))}catch(P){r(P)}}function a(f){try{d(s.throw(f))}catch(P){r(P)}}function d(f){f.done?n(f.value):i(f.value).then(h,a)}d((s=s.apply(o,[])).next())})}function Z(o){return o&&o.__esModule&&Object.prototype.hasOwnProperty.call(o,"default")?o.default:o}var A={exports:{}},K;function ee(){if(K)return A.exports;K=1;var o=typeof Reflect=="object"?Reflect:null,e=o&&typeof o.apply=="function"?o.apply:function(c,u,_){return Function.prototype.apply.call(c,u,_)},t;o&&typeof o.ownKeys=="function"?t=o.ownKeys:Object.getOwnPropertySymbols?t=function(c){return Object.getOwnPropertyNames(c).concat(Object.getOwnPropertySymbols(c))}:t=function(c){return Object.getOwnPropertyNames(c)};function s(l){console&&console.warn&&console.warn(l)}var i=Number.isNaN||function(c){return c!==c};function n(){n.init.call(this)}A.exports=n,A.exports.once=I,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var r=10;function h(l){if(typeof l!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof l)}Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return r},set:function(l){if(typeof l!="number"||l<0||i(l))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+l+".");r=l}}),n.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},n.prototype.setMaxListeners=function(c){if(typeof c!="number"||c<0||i(c))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+c+".");return this._maxListeners=c,this};function a(l){return l._maxListeners===void 0?n.defaultMaxListeners:l._maxListeners}n.prototype.getMaxListeners=function(){return a(this)},n.prototype.emit=function(c){for(var u=[],_=1;_<arguments.length;_++)u.push(arguments[_]);var p=c==="error",S=this._events;if(S!==void 0)p=p&&S.error===void 0;else if(!p)return!1;if(p){var m;if(u.length>0&&(m=u[0]),m instanceof Error)throw m;var x=new Error("Unhandled error."+(m?" ("+m.message+")":""));throw x.context=m,x}var U=S[c];if(U===void 0)return!1;if(typeof U=="function")e(U,this,u);else for(var J=U.length,Y=v(U,J),_=0;_<J;++_)e(Y[_],this,u);return!0};function d(l,c,u,_){var p,S,m;if(h(u),S=l._events,S===void 0?(S=l._events=Object.create(null),l._eventsCount=0):(S.newListener!==void 0&&(l.emit("newListener",c,u.listener?u.listener:u),S=l._events),m=S[c]),m===void 0)m=S[c]=u,++l._eventsCount;else if(typeof m=="function"?m=S[c]=_?[u,m]:[m,u]:_?m.unshift(u):m.push(u),p=a(l),p>0&&m.length>p&&!m.warned){m.warned=!0;var x=new Error("Possible EventEmitter memory leak detected. "+m.length+" "+String(c)+" listeners added. Use emitter.setMaxListeners() to increase limit");x.name="MaxListenersExceededWarning",x.emitter=l,x.type=c,x.count=m.length,s(x)}return l}n.prototype.addListener=function(c,u){return d(this,c,u,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(c,u){return d(this,c,u,!0)};function f(){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 P(l,c,u){var _={fired:!1,wrapFn:void 0,target:l,type:c,listener:u},p=f.bind(_);return p.listener=u,_.wrapFn=p,p}n.prototype.once=function(c,u){return h(u),this.on(c,P(this,c,u)),this},n.prototype.prependOnceListener=function(c,u){return h(u),this.prependListener(c,P(this,c,u)),this},n.prototype.removeListener=function(c,u){var _,p,S,m,x;if(h(u),p=this._events,p===void 0)return this;if(_=p[c],_===void 0)return this;if(_===u||_.listener===u)--this._eventsCount===0?this._events=Object.create(null):(delete p[c],p.removeListener&&this.emit("removeListener",c,_.listener||u));else if(typeof _!="function"){for(S=-1,m=_.length-1;m>=0;m--)if(_[m]===u||_[m].listener===u){x=_[m].listener,S=m;break}if(S<0)return this;S===0?_.shift():y(_,S),_.length===1&&(p[c]=_[0]),p.removeListener!==void 0&&this.emit("removeListener",c,x||u)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(c){var u,_,p;if(_=this._events,_===void 0)return this;if(_.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):_[c]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete _[c]),this;if(arguments.length===0){var S=Object.keys(_),m;for(p=0;p<S.length;++p)m=S[p],m!=="removeListener"&&this.removeAllListeners(m);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(u=_[c],typeof u=="function")this.removeListener(c,u);else if(u!==void 0)for(p=u.length-1;p>=0;p--)this.removeListener(c,u[p]);return this};function R(l,c,u){var _=l._events;if(_===void 0)return[];var p=_[c];return p===void 0?[]:typeof p=="function"?u?[p.listener||p]:[p]:u?T(p):v(p,p.length)}n.prototype.listeners=function(c){return R(this,c,!0)},n.prototype.rawListeners=function(c){return R(this,c,!1)},n.listenerCount=function(l,c){return typeof l.listenerCount=="function"?l.listenerCount(c):g.call(l,c)},n.prototype.listenerCount=g;function g(l){var c=this._events;if(c!==void 0){var u=c[l];if(typeof u=="function")return 1;if(u!==void 0)return u.length}return 0}n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function v(l,c){for(var u=new Array(c),_=0;_<c;++_)u[_]=l[_];return u}function y(l,c){for(;c+1<l.length;c++)l[c]=l[c+1];l.pop()}function T(l){for(var c=new Array(l.length),u=0;u<c.length;++u)c[u]=l[u].listener||l[u];return c}function I(l,c){return new Promise(function(u,_){function p(m){l.removeListener(c,S),_(m)}function S(){typeof l.removeListener=="function"&&l.removeListener("error",p),u([].slice.call(arguments))}V(l,c,S,{once:!0}),c!=="error"&&X(l,p,{once:!0})})}function X(l,c,u){typeof l.on=="function"&&V(l,"error",c,u)}function V(l,c,u,_){if(typeof l.on=="function")_.once?l.once(c,u):l.on(c,u);else if(typeof l.addEventListener=="function")l.addEventListener(c,function p(S){_.once&&l.removeEventListener(c,p),u(S)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof l)}return A.exports}var te=ee(),Q=Z(te),b;(function(o){o[o.timeout=1]="timeout",o[o.transportClosed=2]="transportClosed",o[o.clientDisconnected=3]="clientDisconnected",o[o.clientClosed=4]="clientClosed",o[o.clientConnectToken=5]="clientConnectToken",o[o.clientRefreshToken=6]="clientRefreshToken",o[o.subscriptionUnsubscribed=7]="subscriptionUnsubscribed",o[o.subscriptionSubscribeToken=8]="subscriptionSubscribeToken",o[o.subscriptionRefreshToken=9]="subscriptionRefreshToken",o[o.transportWriteError=10]="transportWriteError",o[o.connectionClosed=11]="connectionClosed",o[o.badConfiguration=12]="badConfiguration",o[o.subscriptionGetState=13]="subscriptionGetState",o[o.sharedPollGetSignature=14]="sharedPollGetSignature"})(b||(b={}));var D;(function(o){o[o.connectCalled=0]="connectCalled",o[o.transportClosed=1]="transportClosed",o[o.noPing=2]="noPing",o[o.subscribeTimeout=3]="subscribeTimeout",o[o.unsubscribeError=4]="unsubscribeError"})(D||(D={}));var M;(function(o){o[o.disconnectCalled=0]="disconnectCalled",o[o.unauthorized=1]="unauthorized",o[o.badProtocol=2]="badProtocol",o[o.messageSizeLimit=3]="messageSizeLimit",o[o.stateInvalidated=3014]="stateInvalidated"})(M||(M={}));var N;(function(o){o[o.subscribeCalled=0]="subscribeCalled",o[o.transportClosed=1]="transportClosed"})(N||(N={}));var z;(function(o){o[o.unsubscribeCalled=0]="unsubscribeCalled",o[o.unauthorized=1]="unauthorized",o[o.clientClosed=2]="clientClosed",o[o.stateInvalidated=2502]="stateInvalidated"})(z||(z={}));var B;(function(o){o[o.channelCompaction=1]="channelCompaction",o[o.rejectUnrecovered=2]="rejectUnrecovered"})(B||(B={}));var k;(function(o){o.Disconnected="disconnected",o.Connecting="connecting",o.Connected="connected"})(k||(k={}));var E;(function(o){o.Unsubscribed="unsubscribed",o.Subscribing="subscribing",o.Subscribed="subscribed"})(E||(E={}));function se(o,e){return o.lastIndexOf(e,0)===0}function q(o){return o==null?!1:typeof o=="function"}function ie(o,e){if(globalThis.console){const t=globalThis.console[o];q(t)&&t.apply(globalThis.console,e)}}function ne(o,e){return Math.floor(Math.random()*(e-o+1)+o)}function L(o,e,t){o>31&&(o=31);const s=ne(0,Math.min(t,e*Math.pow(2,o)));return Math.min(t,e+s)}function re(o){return"error"in o&&o.error!==null}function j(o){return Math.min(o*1e3,2147483647)}function oe(o){try{return typeof localStorage>"u"||localStorage===null||!q(localStorage.getItem)?null:localStorage.getItem(o)}catch{return null}}var C;(function(o){o[o.Live=0]="Live",o[o.Stream=1]="Stream",o[o.State=2]="State"})(C||(C={}));class W extends Q{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=E.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",i=>{this._debug("subscription state",t,i.oldState,"->",i.newState)}),this.on("error",i=>{this._debug("subscription error",t,i)})):this.on("error",function(){Function.prototype()})}ready(e){return this.state===E.Unsubscribed?Promise.reject({code:b.subscriptionUnsubscribed,message:this.state}):this.state===E.Subscribed?Promise.resolve():new Promise((t,s)=>{const i={resolve:t,reject:s};e&&(i.timeout=setTimeout(function(){s({code:b.timeout,message:"timeout"})},e)),this._promises[this._nextPromiseId()]=i})}subscribe(){this._isSubscribed()||(this._resubscribeAttempts=0,this._setSubscribing(N.subscribeCalled,"subscribe called"))}unsubscribe(){this._unsubPromise=this._setUnsubscribed(z.unsubscribeCalled,"unsubscribe called",!0)}_debouncedPublish(e,t,s){const i=this._debouncePending.get(e);if(i)return i.data=t,i.dirty=!0,Promise.resolve({});const n={data:t,dirty:!1,timer:null};return n.timer=setTimeout(()=>{const h=this._debouncePending.get(e);if(!h||!h.dirty){this._debouncePending.delete(e);return}h.dirty=!1;const a=h.data;(s?this._centrifuge.mapPublish(this.channel,e,a):this._centrifuge.publish(this.channel,a)).catch(()=>{}),h.timer=setTimeout(()=>{const f=this._debouncePending.get(e);if(!f||!f.dirty){this._debouncePending.delete(e);return}this._debouncePending.delete(e),this._debouncedPublish(e,f.data,s)},this._debounceMs)},this._debounceMs),this._debouncePending.set(e,n),s?this._centrifuge.mapPublish(this.channel,e,t):this._centrifuge.publish(this.channel,t)}_cancelDebounce(e){const t=this._debouncePending.get(e);t&&(clearTimeout(t.timer),this._debouncePending.delete(e))}_cancelAllDebounce(){for(const[,e]of this._debouncePending)clearTimeout(e.timer);this._debouncePending.clear()}presence(){return w(this,void 0,void 0,function*(){return yield this._methodCall(),this._centrifuge.presence(this.channel)})}presenceStats(){return w(this,void 0,void 0,function*(){return yield 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(){const 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:b.subscriptionUnsubscribed,message:this.state}):new Promise((e,t)=>{const s=this._centrifuge._config.timeout,i=setTimeout(()=>{t({code:b.timeout,message:"timeout"})},s);this._promises[this._nextPromiseId()]={timeout:i,resolve:e,reject:t}})}_nextPromiseId(){return++this._promiseId}_needRecover(){return this._recover===!0}_isUnsubscribed(){return this.state===E.Unsubscribed}_isSubscribing(){return this.state===E.Subscribing}_isSubscribed(){return this.state===E.Subscribed}_setState(e){if(this.state!==e){const 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._cancelAllDebounce(),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):(this._offset=0,this._epoch="_")}_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){const i=e.epoch||"";if(this._sharedPollEpoch!==""&&this._sharedPollEpoch!==i)for(const n of this._sharedPollTrackedItems.keys())this._sharedPollTrackedItems.set(n,0);this._sharedPollEpoch=i}this._setState(E.Subscribed);const t=this._centrifuge._getSubscribeContext(this.channel,e);this.emit("subscribed",t),this._resolvePromises();const s=e.publications;if(s&&s.length>0)for(const i in s)s.hasOwnProperty(i)&&this._handlePublication(s[i]);e.expires===!0&&(this._refreshTimeout=setTimeout(()=>this._refresh(),j(e.ttl)))}_setSubscribing(e,t){return w(this,void 0,void 0,function*(){this._isSubscribing()||(this._isSubscribed()&&this._clearSubscribedState(),this._id=0,this._setState(E.Subscribing)&&this.emit("subscribing",{channel:this.channel,code:e,reason:t}),this._centrifuge._transport&&this._centrifuge._transport.emulation()&&(yield 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:b.subscriptionGetState,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 O){this._inflight=!1,this._failUnauthorized();return}this.emit("error",{type:"subscribeData",channel:this.channel,error:{code:b.badConfiguration,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 O){this._inflight=!1,this._failUnauthorized();return}this.emit("error",{type:"subscribeToken",channel:this.channel,error:{code:b.subscriptionSubscribeToken,message:e?.toString()||""}}),this._inflight=!1,this._scheduleResubscribe()}_sendSubscribe(e){if(!this._isTransportOpen())return this._inflight=!1,null;const t=this._buildSubscribeCommand(e);return this._centrifuge._call(t).then(s=>{this._inflight=!1;const i=s.reply.subscribe;this._handleSubscribeResponse(i),s.next&&s.next()},s=>{this._inflight=!1,this._handleSubscribeError(s.error),s.next&&s.next()}),t}_buildSubscribeCommand(e){const 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=B.channelCompaction,this._getState&&(t.flag|=B.rejectUnrecovered),this._needRecover()){t.recover=!0;const s=this._getOffset();s&&(t.offset=s);const i=this._getEpoch();i&&(t.epoch=i)}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===b.timeout){this._centrifuge._disconnect(D.subscribeTimeout,"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 i=Promise.resolve();return this._isSubscribed()?(s&&(i=this._centrifuge._unsubscribe(this)),this._clearSubscribedState()):this._isSubscribing()&&(this._inflight&&s&&(i=this._centrifuge._unsubscribe(this)),this._clearSubscribingState()),this._inflight=!1,this._id=0,this._sharedPollEpoch="",this._sharedPollSignatures=[],this._sharedPollTrackedItems.clear(),this._sharedPollSignatureRefreshInFlight=!1,this._sharedPollSignatureRefreshTargetMs=null,this._cancelAllDebounce(),this._setState(E.Unsubscribed)&&this.emit("unsubscribed",{channel:this.channel,code:e,reason:t}),this._rejectPromises({code:b.subscriptionUnsubscribed,message:this.state}),i}_handlePublication(e){if(this._delta&&this._delta_negotiated){const s=(this._map||this._sharedPoll)&&e.key||"",{newData:i,newPrevValue:n,isDelta:r,wireBytes:h,fullBytes:a}=this._centrifuge._codec.applyDeltaIfNeeded(e,this._prevValueMap.get(s));e.data=i,this._deltaNumPubs++,this._deltaBytesReceived+=h,this._deltaBytesDecoded+=a,r?this._deltaNumDelta++:this._deltaNumFull++,e.removed?this._prevValueMap.delete(s):this._prevValueMap.set(s,n)}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"){const t=e.data,s=new TextEncoder().encode(t);e.removed?this._prevValueMap.delete(e.key):this._prevValueMap.set(e.key,s);const i=s.length;this._deltaNumPubs++,this._deltaNumFull++,this._deltaBytesReceived+=i,this._deltaBytesDecoded+=i,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);const t=e.data.length;this._deltaNumPubs++,this._deltaNumFull++,this._deltaBytesReceived+=t,this._deltaBytesDecoded+=t}}}_handleJoin(e){const t=this._centrifuge._getJoinLeaveContext(e.info);this.emit("join",{channel:this.channel,info:t})}_handleLeave(e){const t=this._centrifuge._getJoinLeaveContext(e.info);this.emit("leave",{channel:this.channel,info:t})}_resolvePromises(){for(const 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(const 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}const 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="");const t={channel:this.channel,type:"subscribe",error:e};this._centrifuge.state===k.Connected&&this.emit("error",t),this._scheduleResubscribe()}else this._setUnsubscribed(e.code,e.message,!1)}_getResubscribeDelay(){const e=L(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(){const e=this._offset;return e!==null?e:0}_getEpoch(){const 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);const e={channel:this.channel},t=this._getToken;return t===null?(this.emit("error",{type:"configuration",channel:this.channel,error:{code:b.badConfiguration,message:"provide a function to get channel subscription token"}}),Promise.reject(new O(""))):t(e)}_refresh(){this._clearRefreshTimeout();const e=this;this._getSubscriptionToken().then(function(t){if(!e._isSubscribed())return;if(!t){e._failUnauthorized();return}e._token=t;const i={sub_refresh:{channel:e.channel,token:t}};e._centrifuge._call(i).then(n=>{const r=n.reply.sub_refresh;e._refreshResponse(r),n.next&&n.next()},n=>{e._refreshError(n.error),n.next&&n.next()})}).catch(function(t){if(t instanceof O){e._failUnauthorized();return}e.emit("error",{type:"refreshToken",channel:e.channel,error:{code:b.subscriptionRefreshToken,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(),j(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 L(0,1e4,2e4)}_failUnauthorized(){this._setUnsubscribed(z.unauthorized,"unauthorized",!0)}_sendTrackRequest(e,t){if(e.length===0)return Promise.resolve();const s=6e4,i=[];let n=[],r=100;if(t&&t.length>0)for(const a of t)r+=a.length+4;for(const a of e){let d=100;for(const f of a.items)d+=f.key.length+16;n.length>0&&r+d>s&&(i.push(n),n=[],r=100),n.push(a),r+=d}n.length>0&&i.push(n);const h=(a,d)=>new Promise((f,P)=>{const R={channel:this.channel,type:1,track:a.map(v=>({signature:v.signature,items:v.items.map(y=>y.version>0?y:{key:y.key})}))};d&&d.length>0&&(R.untrack=d);const g={sub_refresh:R};this._centrifuge._call(g).then(v=>{this._handleTrackResponse(v.reply.sub_refresh),v.next&&v.next(),f()},v=>{v.next&&v.next(),P(v.error)})});return i.reduce((a,d,f)=>a.then(()=>h(d,f===0?t:void 0)),Promise.resolve())}_sendUntrackRequest(e){return new Promise((t,s)=>{const n={sub_refresh:{channel:this.channel,type:2,untrack:e}};this._centrifuge._call(n).then(r=>{r.next&&r.next(),t()},r=>{r.next&&r.next(),s(r.error)})})}_handleTrackResponse(e){if(this._clearSharedPollTrackRetry(),e&&e.items&&e.items.length>0)for(const t of e.items)this._handlePublication(t);if(e&&e.expires===!0&&e.ttl>0){const 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(),L(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;const e=Array.from(this._sharedPollTrackedItems.keys()),t=this;this._sharedPollGetSignature({keys:e}).then(s=>{if(t._sharedPollSignatureRefreshInFlight=!1,!t._isSubscribed())return;t._sharedPollSignatureRefreshAttempts=0;const i=new Set(s.keys),n=[];for(const d of e)i.has(d)||(t._sharedPollTrackedItems.delete(d),n.push(d),t.emit("update",{channel:t.channel,key:d,data:null,removed:!0}));n.length>0&&t._sendUntrackRequest(n).catch(d=>{t.emit("error",{type:"untrack",channel:t.channel,error:d})});const r=[];for(const d of s.keys){const f=t._sharedPollTrackedItems.get(d);f!==void 0&&r.push({key:d,version:f})}const h=new Set(s.keys),a=t._sharedPollSignatures.filter(d=>d.keys.some(f=>t._sharedPollTrackedItems.has(f)&&!h.has(f)));t._sharedPollSignatures=r.length>0?[{keys:s.keys,signature:s.signature},...a]:a,r.length!==0&&t._sendTrackRequest([{items:r,signature:s.signature}]).catch(d=>{t._handleTrackError(d)})}).catch(s=>{t._sharedPollSignatureRefreshInFlight=!1,t.emit("error",{type:"signatureRefresh",channel:t.channel,error:{code:b.sharedPollGetSignature,message:s!==void 0?s.toString():""}}),t._sharedPollSignatureRefreshTimeout=setTimeout(()=>t._sharedPollRefreshSignature(),L(t._sharedPollSignatureRefreshAttempts++,5e3,3e4))})}_sharedPollReplayTrack(){if(!this._isSubscribed()||this._sharedPollTrackedItems.size===0&&this._sharedPollSignatures.length===0)return;const e=new Set,t=[],s=[];for(const r of this._sharedPollSignatures){const h=r.keys.map(a=>{var d;return{key:a,version:(d=this._sharedPollTrackedItems.get(a))!==null&&d!==void 0?d:0}});t.push({items:h,signature:r.signature});for(const a of r.keys)this._sharedPollTrackedItems.has(a)?e.add(a):s.push(a)}t.length>0&&this._sendTrackRequest(t,s).catch(r=>{this._handleTrackError(r)});const i=[];for(const r of this._sharedPollTrackedItems.keys())e.has(r)||i.push(r);if(i.length===0)return;if(!this._sharedPollGetSignature){this.emit("error",{type:"track",channel:this.channel,error:{code:b.sharedPollGetSignature,message:"getSignature callback required for tracked keys without an explicit signature"}});return}const n=this;this._sharedPollGetSignature({keys:i}).then(r=>{if(!n._isSubscribed())return;n._clearSharedPollReplayRetry();const h=new Set(r.keys),a=[];for(const f of i)h.has(f)||(n._sharedPollTrackedItems.delete(f),a.push(f),n.emit("update",{channel:n.channel,key:f,data:null,removed:!0}));a.length>0&&n._sendUntrackRequest(a).catch(f=>{n.emit("error",{type:"untrack",channel:n.channel,error:f})});const d=[];for(const f of r.keys){const P=n._sharedPollTrackedItems.get(f);P!==void 0&&d.push({key:f,version:P})}d.length!==0&&(n._sharedPollSignatures.push({keys:r.keys,signature:r.signature}),n._sendTrackRequest([{items:d,signature:r.signature}]).catch(f=>{n._handleTrackError(f)}))}).catch(r=>{n.emit("error",{type:"signatureRefresh",channel:n.channel,error:{code:b.sharedPollGetSignature,message:r!==void 0?r.toString():""}}),n._sharedPollReplayRetryTimeout=setTimeout(()=>n._sharedPollReplayTrack(),L(n._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=C.State,this._recover&&this._offset!==null&&this._epoch!==null){this._debug("map subscribe: recovering from position, skipping to stream phase"),this._mapPhase=C.Stream,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}const t=this._buildMapSubscribeCommand(C.State,e);this._debug("map subscribe: fetching snapshot page",e?`cursor=${e}`:"initial"),this._centrifuge._call(t).then(s=>{const i=s.reply.subscribe;this._handleMapStateResponse(i),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(const 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=C.Stream,this._fetchStream()}_fetchStream(){if(!this._isSubscribing()||!this._isTransportOpen()){this._inflight=!1;return}const e=this._buildMapSubscribeCommand(C.Stream);this._debug("map subscribe: fetching stream from offset",this._offset),this._centrifuge._call(e).then(t=>{const 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=C.State,this._fetchSnapshot();return}if(e.publications&&e.publications.length>0)for(const 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=C.State,this._fetchSnapshot();return}if(e.state&&e.state.length>0)for(const s of e.state)this._seedDeltaTracking(s),this._mapStateBuffer.push(this._getMapUpdateContext(s));if(e.publications&&e.publications.length>0)for(const s of e.publications){if(this._delta&&e.delta){const i=s.key||"",{newData:n,newPrevValue:r,isDelta:h,wireBytes:a,fullBytes:d}=this._centrifuge._codec.applyDeltaIfNeeded(s,this._prevValueMap.get(i));s.data=n,this._deltaNumPubs++,this._deltaBytesReceived+=a,this._deltaBytesDecoded+=d,h?this._deltaNumDelta++:this._deltaNumFull++,s.removed?this._prevValueMap.delete(i):this._prevValueMap.set(i,r)}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(E.Subscribed);const 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){const s=new Map;for(const i of this._mapStateBuffer)s.set(i.key,i);for(const i of this._mapStreamBuffer)i.removed?s.delete(i.key):s.set(i.key,i);this._mapStateBuffer=Array.from(s.values()),this._mapStreamBuffer=[]}this.emit("sync",{entries:this._mapStateBuffer})}for(const 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(),j(e.ttl)))}_handleMapSubscribeError(e){if(this._inflight=!1,!!this._isSubscribing()){if(e.code===b.timeout){this._centrifuge._disconnect(D.subscribeTimeout,"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){const 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=B.channelCompaction,e===C.State&&(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===C.Stream&&(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){const 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){const 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}}class ae extends W{publish(e){return w(this,void 0,void 0,function*(){return yield this._methodCall(),this._debounceMs>0?this._debouncedPublish("",e,!1):this._centrifuge.publish(this.channel,e)})}history(e){return w(this,void 0,void 0,function*(){return yield this._methodCall(),this._centrifuge.history(this.channel,e)})}}class F extends W{publish(e,t){return w(this,void 0,void 0,function*(){return yield this._methodCall(),this._debounceMs>0?this._debouncedPublish(e,t,!0):this._centrifuge.mapPublish(this.channel,e,t)})}remove(e){return w(this,void 0,void 0,function*(){return yield this._methodCall(),this._cancelDebounce(e),this._centrifuge.mapRemove(this.channel,e)})}}class he extends W{track(e,t){if(e.length===0)return;let s;const i=t;typeof e[0]=="string"?s=e.map(h=>({key:h,version:0})):s=e;for(const r of s){const h=this._sharedPollTrackedItems.get(r.key);(h===void 0||r.version>h)&&this._sharedPollTrackedItems.set(r.key,r.version)}if(i!==void 0){this._sharedPollSignatures.push({keys:s.map(r=>r.key),signature:i}),this._isSubscribed()&&this._sendTrackRequest([{items:s,signature:i}]).catch(r=>{this._handleTrackError(r)});return}if(!this._sharedPollGetSignature){this.emit("error",{type:"track",channel:this.channel,error:{code:b.sharedPollGetSignature,message:"getSignature callback required for track(keys)"}});return}if(!this._isSubscribed())return;const n=s.map(r=>r.key);this._sharedPollGetSignature({keys:n}).then(r=>{if(!this._isSubscribed())return;const h=new Set(r.keys),a=[];for(const f of n)h.has(f)||(this._sharedPollTrackedItems.delete(f),a.push(f),this.emit("update",{channel:this.channel,key:f,data:null,removed:!0}));a.length>0&&this._sendUntrackRequest(a).catch(f=>{this.emit("error",{type:"untrack",channel:this.channel,error:f})});const d=[];for(const f of r.keys){const P=this._sharedPollTrackedItems.get(f);P!==void 0&&d.push({key:f,version:P})}d.length!==0&&(this._sharedPollSignatures.push({keys:r.keys,signature:r.signature}),this._sendTrackRequest([{items:d,signature:r.signature}]).catch(f=>{this._handleTrackError(f)}))}).catch(r=>{this.emit("error",{type:"track",channel:this.channel,error:{code:b.sharedPollGetSignature,message:r!==void 0?r.toString():"getSignature failed"}})})}untrack(e){for(const t of e)this._sharedPollTrackedItems.delete(t);this._sharedPollSignatures=this._sharedPollSignatures.filter(t=>t.keys.some(s=>this._sharedPollTrackedItems.has(s))),this._isSubscribed()&&this._sendUntrackRequest(e).catch(t=>{this.emit("error",{type:"untrack",channel:this.channel,error:t})})}trackedKeys(){return new Set(this._sharedPollTrackedItems.keys())}}class ce{constructor(e,t){this.endpoint=e,this.options=t,this._transport=null}name(){return"sockjs"}subName(){return"sockjs-"+this._transport.transport}emulation(){return!1}supported(){return this.options.sockjs!==null}initialize(e,t){this._transport=new this.options.sockjs(this.endpoint,null,this.options.sockjsOptions),this._transport.onopen=()=>{t.onOpen()},this._transport.onerror=s=>{t.onError(s)},this._transport.onclose=s=>{t.onClose(s)},this._transport.onmessage=s=>{t.onMessage(s.data)}}close(){this._transport.close()}send(e){this._transport.send(e)}}class H{constructor(e,t){this.endpoint=e,this.options=t,this._transport=null}name(){return"websocket"}subName(){return"websocket"}emulation(){return!1}supported(){return this.options.websocket!==void 0&&this.options.websocket!==null}initialize(e,t){let s="";e==="protobuf"&&(s="centrifuge-protobuf"),s!==""?this._transport=new this.options.websocket(this.endpoint,s):this._transport=new this.options.websocket(this.endpoint),e==="protobuf"&&(this._transport.binaryType="arraybuffer"),this._transport.onopen=()=>{t.onOpen()},this._transport.onerror=i=>{t.onError(i)},this._transport.onclose=i=>{t.onClose(i)},this._transport.onmessage=i=>{t.onMessage(i.data)}}close(){this._transport.close()}send(e){this._transport.send(e)}}class le{constructor(e,t){this.endpoint=e,this.options=t,this._abortController=null,this._utf8decoder=new TextDecoder,this._protocol="json"}name(){return"http_stream"}subName(){return"http_stream"}emulation(){return!0}_handleErrors(e){if(!e.ok)throw new Error(e.status);return e}_fetchEventTarget(e,t,s){const i=new EventTarget,n=e.options.fetch;return n(t,s).then(e._handleErrors).then(r=>{i.dispatchEvent(new Event("open"));let h="",a=0,d=new Uint8Array;const f=r.body.getReader();return new e.options.readableStream({start(P){function R(){return f.read().then(({done:g,value:v})=>{if(g){i.dispatchEvent(new Event("close")),P.close();return}try{if(e._protocol==="json")for(h+=e._utf8decoder.decode(v);a<h.length;)if(h[a]===`
`){const y=h.substring(0,a);i.dispatchEvent(new MessageEvent("message",{data:y})),h=h.substring(a+1),a=0}else++a;else{const y=new Uint8Array(d.length+v.length);for(y.set(d),y.set(v,d.length),d=y;;){const T=e.options.decoder.decodeReply(d);if(T.ok){const I=d.slice(0,T.pos);i.dispatchEvent(new MessageEvent("message",{data:I})),d=d.slice(T.pos);continue}break}}}catch(y){i.dispatchEvent(new Event("error",{detail:y})),i.dispatchEvent(new Event("close")),P.close();return}R()}).catch(function(g){i.dispatchEvent(new Event("error",{detail:g})),i.dispatchEvent(new Event("close")),P.close()})}return R()}})}).catch(r=>{i.dispatchEvent(new Event("error",{detail:r})),i.dispatchEvent(new Event("close"))}),i}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(e,t,s){this._protocol=e,this._abortController=new AbortController;let i,n;e==="json"?(i={Accept:"application/json","Content-Type":"application/json"},n=s):(i={Accept:"application/octet-stream","Content-Type":"application/octet-stream"},n=s);const r={method:"POST",headers:i,body:n,mode:"cors",credentials:"same-origin",signal:this._abortController.signal},h=this._fetchEventTarget(this,this.endpoint,r);h.addEventListener("open",()=>{t.onOpen()}),h.addEventListener("error",a=>{this._abortController.abort(),t.onError(a)}),h.addEventListener("close",()=>{this._abortController.abort(),t.onClose({code:4,reason:"connection closed"})}),h.addEventListener("message",a=>{t.onMessage(a.data)})}close(){this._abortController.abort()}send(e,t,s){let i,n;const r={session:t,node:s,data:e};this._protocol==="json"?(i={"Content-Type":"application/json"},n=JSON.stringify(r)):(i={"Content-Type":"application/octet-stream"},n=this.options.encoder.encodeEmulationRequest(r));const h=this.options.fetch,a={method:"POST",headers:i,body:n,mode:"cors",credentials:"same-origin"};h(this.options.emulationEndpoint,a)}}class ue{constructor(e,t){this.endpoint=e,this.options=t,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(e,t,s){let i;globalThis&&globalThis.document&&globalThis.document.baseURI?i=new URL(this.endpoint,globalThis.document.baseURI):i=new URL(this.endpoint),i.searchParams.append("cf_connect",s);const n={},r=new this.options.eventsource(i.toString(),n);this._transport=r;const h=this;r.onopen=function(){t.onOpen()},r.onerror=function(a){r.close(),t.onError(a),t.onClose({code:4,reason:"connection closed"})},r.onmessage=function(a){t.onMessage(a.data)},h._onClose=function(){t.onClose({code:4,reason:"connection closed"})}}close(){this._transport.close(),this._onClose!==null&&this._onClose()}send(e,t,s){const i={session:t,node:s,data:e},n={"Content-Type":"application/json"},r=JSON.stringify(i),h=this.options.fetch,a={method:"POST",headers:n,body:r,mode:"cors",credentials:"same-origin"};h(this.options.emulationEndpoint,a)}}class de{constructor(e,t){this.endpoint=e,this.options=t,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}initialize(e,t){return w(this,void 0,void 0,function*(){let s;globalThis&&globalThis.document&&globalThis.document.baseURI?s=new URL(this.endpoint,globalThis.document.baseURI):s=new URL(this.endpoint),e==="protobuf"&&s.searchParams.append("cf_protocol","protobuf"),this._protocol=e;const i=new EventTarget;this._transport=new this.options.webtransport(s.toString()),this._transport.closed.then(()=>{t.onClose({code:4,reason:"connection closed"})}).catch(()=>{t.onClose({code:4,reason:"connection closed"})});try{yield this._transport.ready}catch{this.close();return}let n;try{n=yield this._transport.createBidirectionalStream()}catch{this.close();return}this._stream=n,this._writer=this._stream.writable.getWriter(),i.addEventListener("close",()=>{t.onClose({code:4,reason:"connection closed"})}),i.addEventListener("message",r=>{t.onMessage(r.data)}),this._startReading(i),t.onOpen()})}_startReading(e){return w(this,void 0,void 0,function*(){const t=this._stream.readable.getReader();let s="",i=0,n=new Uint8Array;try{for(;;){const{done:r,value:h}=yield t.read();if(h&&h.length>0)if(this._protocol==="json")for(s+=this._utf8decoder.decode(h);i<s.length;)if(s[i]===`
`){const a=s.substring(0,i);e.dispatchEvent(new MessageEvent("message",{data:a})),s=s.substring(i+1),i=0}else++i;else{const a=new Uint8Array(n.length+h.length);for(a.set(n),a.set(h,n.length),n=a;;){const d=this.options.decoder.decodeReply(n);if(d.ok){const f=n.slice(0,d.pos);e.dispatchEvent(new MessageEvent("message",{data:f})),n=n.slice(d.pos);continue}break}}if(r)break}}catch{e.dispatchEvent(new Event("close"))}})}close(){return w(this,void 0,void 0,function*(){try{this._writer&&(yield this._writer.close()),this._transport.close()}catch{}})}send(e){return w(this,void 0,void 0,function*(){let t;this._protocol==="json"?t=new TextEncoder().encode(e+`
`):t=e;try{yield this._writer.write(t)}catch{this.close()}})}}const fe=[-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];class _e{constructor(e){this.a=e,this.pos=0}haveBytes(){return this.pos<this.a.length}getByte(){const e=this.a[this.pos];if(this.pos++,this.pos>this.a.length)throw new RangeError("out of bounds");return e}getChar(){return String.fromCharCode(this.getByte())}getInt(){let e=0,t;for(;this.haveBytes()&&(t=fe[127&this.getByte()])>=0;)e=(e<<6)+t;return this.pos--,e>>>0}}class pe{constructor(){this.a=[]}toByteArray(e){return Array.isArray(e)?this.a:new Uint8Array(this.a)}putArray(e,t,s){for(let i=t;i<s;i++)this.a.push(e[i])}}function me(o){let e=0,t=0,s=0,i=0,n=0,r=o.length;for(;r>=16;)e=e+o[n+0]|0,t=t+o[n+1]|0,s=s+o[n+2]|0,i=i+o[n+3]|0,e=e+o[n+4]|0,t=t+o[n+5]|0,s=s+o[n+6]|0,i=i+o[n+7]|0,e=e+o[n+8]|0,t=t+o[n+9]|0,s=s+o[n+10]|0,i=i+o[n+11]|0,e=e+o[n+12]|0,t=t+o[n+13]|0,s=s+o[n+14]|0,i=i+o[n+15]|0,n+=16,r-=16;for(;r>=4;)e=e+o[n+0]|0,t=t+o[n+1]|0,s=s+o[n+2]|0,i=i+o[n+3]|0,n+=4,r-=4;switch(i=((i+(s<<8)|0)+(t<<16)|0)+(e<<24)|0,r){case 3:i=i+(o[n+2]<<8)|0;case 2:i=i+(o[n+1]<<16)|0;case 1:i=i+(o[n+0]<<24)|0}return i>>>0}function be(o,e){let t=0;const s=new _e(e),i=o.length,n=e.length,r=s.getInt();if(s.getChar()!==`
`)throw new Error("size integer not terminated by '\\n'");const h=new pe;for(;s.haveBytes();){const a=s.getInt();let d;switch(s.getChar()){case"@":if(d=s.getInt(),s.haveBytes()&&s.getChar()!==",")throw new Error("copy command not terminated by ','");if(t+=a,t>r)throw new Error("copy exceeds output file size");if(d+a>i)throw new Error("copy extends past end of input");h.putArray(o,d,d+a);break;case":":if(t+=a,t>r)throw new Error("insert command gives an output larger than predicted");if(a>n)throw new Error("insert count exceeds size of delta");h.putArray(s.a,s.pos,s.pos+a),s.pos+=a;break;case";":{const f=h.toByteArray(o);if(a!==me(f))throw new Error("bad checksum");if(t!==r)throw new Error("generated size does not match predicted size");return f}default:throw new Error("unknown delta operator")}}throw new Error("unterminated delta")}class ${name(){return"json"}encodeCommands(e){return e.map(t=>JSON.stringify(t)).join(`
`)}decodeReplies(e){return e.trim().split(`
`).map(t=>JSON.parse(t))}applyDeltaIfNeeded(e,t){let s,i,n,r;if(e.delta){r=!0;const h=new TextEncoder().encode(e.data),a=be(t,h);s=JSON.parse(new TextDecoder().decode(a)),i=a,n=h.length}else r=!1,s=JSON.parse(e.data),i=new TextEncoder().encode(e.data),n=i.length;return{newData:s,newPrevValue:i,isDelta:r,wireBytes:n,fullBytes:i.length}}}const ge={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};class O extends Error{constructor(e){super(e),this.name=this.constructor.name}}class G extends Q{constructor(e,t){super(),this._reconnectTimeout=null,this._refreshTimeout=null,this._serverPingTimeout=null,this.state=k.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 $,this._reconnecting=!1,this._reconnectTimeout=null,this._reconnectAttempts=0,this._client=null,this._session="",this._node="",this._subs={},this._serverSubs={},this._commandId=0,this._commands=[],this._batching=!1,this._refreshRequired=!1,this._refreshTimeout=null,this._callbacks={},this._token="",this._data=null,this._dispatchPromise=Promise.resolve(),this._serverPing=0,this._serverPingTimeout=null,this._sendPong=!1,this._promises={},this._promiseId=0,this._debugEnabled=!1,this._networkEventsSet=!1,this._config=Object.assign(Object.assign({},ge),t),this._configure(),this._debugEnabled?(this.on("state",s=>{this._debug("client state",s.oldState,"->",s.newState)}),this.on("error",s=>{this._debug("client error",s)})):this.on("error",function(){Function.prototype()})}newSubscription(e,t){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const s=new ae(this,e,t);return this._subs[e]=s,s}newMapSubscription(e,t){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const s=new F(this,e,{token:t?.token,getToken:t?.getToken,data:t?.data,minResubscribeDelay:t?.minResubscribeDelay,maxResubscribeDelay:t?.maxResubscribeDelay,delta:t?.delta,tagsFilter:t?.tagsFilter,map:!0,mapPageSize:t?.pageSize,mapUnrecoverableStrategy:t?.unrecoverableStrategy});return this._subs[e]=s,s}newMapClientsSubscription(e,t){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const s=new F(this,e,{token:t?.token,getToken:t?.getToken,data:t?.data,minResubscribeDelay:t?.minResubscribeDelay,maxResubscribeDelay:t?.maxResubscribeDelay,delta:t?.delta,tagsFilter:t?.tagsFilter,map:!0,mapPresenceType:2,mapPageSize:t?.pageSize,mapUnrecoverableStrategy:t?.unrecoverableStrategy});return this._subs[e]=s,s}newMapUsersSubscription(e,t){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const s=new F(this,e,{token:t?.token,getToken:t?.getToken,data:t?.data,minResubscribeDelay:t?.minResubscribeDelay,maxResubscribeDelay:t?.maxResubscribeDelay,delta:t?.delta,tagsFilter:t?.tagsFilter,map:!0,mapPresenceType:3,mapPageSize:t?.pageSize,mapUnrecoverableStrategy:t?.unrecoverableStrategy});return this._subs[e]=s,s}newSharedPollSubscription(e,t){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const s=new he(this,e,{token:t?.token,getToken:t?.getToken,data:t?.data,minResubscribeDelay:t?.minResubscribeDelay,maxResubscribeDelay:t?.maxResubscribeDelay,delta:t?.delta,sharedPoll:!0,sharedPollGetSignature:t?.getSignature});return this._subs[e]=s,s}getSubscription(e){return this._getSub(e)}getMapSubscription(e){return this._getSub(e)}getSharedPollSubscription(e){return this._getSub(e)}removeSubscription(e){e&&(e.state!==E.Unsubscribed&&e.unsubscribe(),this._removeSubscription(e))}removeMapSubscription(e){this.removeSubscription(e)}removeSharedPollSubscription(e){this.removeSubscription(e)}subscriptions(){return this._subs}mapSubscriptions(){const e={};for(const[t,s]of Object.entries(this._subs))s.type==="map"&&(e[t]=s);return e}sharedPollSubscriptions(){const e={};for(const[t,s]of Object.entries(this._subs))s.type==="shared_poll"&&(e[t]=s);return e}ready(e){return w(this,void 0,void 0,function*(){switch(this.state){case k.Disconnected:throw{code:b.clientDisconnected,message:"client disconnected"};case k.Connected:return;default:return new Promise((t,s)=>{const i={resolve:t,reject:s};e&&(i.timeout=setTimeout(()=>{s({code:b.timeout,message:"timeout"})},e)),this._promises[this._nextPromiseId()]=i})}})}connect(){if(this._isConnected()){this._debug("connect called when already connected");return}if(this._isConnecting()){this._debug("connect called when already connecting");return}this._debug("connect called"),this._reconnectAttempts=0,this._startConnecting()}disconnect(){this._disconnect(M.disconnectCalled,"disconnect called",!1)}setToken(e){this._token=e}setData(e){this._data=e}setHeaders(e){this._config.headers=e}send(e){return w(this,void 0,void 0,function*(){const t={send:{data:e}};if(yield this._methodCall(),!this._transportSendCommands([t]))throw this._createErrorObject(b.transportWriteError,"transport write error")})}rpc(e,t){return w(this,void 0,void 0,function*(){const s={rpc:{method:e,data:t}};return yield this._methodCall(),{data:(yield this._callPromise(s,n=>n.rpc)).data}})}publish(e,t){return w(this,void 0,void 0,function*(){const s={publish:{channel:e,data:t}};return yield this._methodCall(),yield this._callPromise(s,()=>({})),{}})}mapPublish(e,t,s){return w(this,void 0,void 0,function*(){const i={publish:{channel:e,type:1,key:t,data:s}};return yield this._methodCall(),yield this._callPromise(i,()=>({})),{}})}mapRemove(e,t){return w(this,void 0,void 0,function*(){const s={publish:{channel:e,type:1,key:t,removed:!0}};return yield this._methodCall(),yield this._callPromise(s,()=>({})),{}})}history(e,t){return w(this,void 0,void 0,function*(){const s={history:this._getHistoryRequest(e,t)};yield this._methodCall();const i=yield this._callPromise(s,r=>r.history),n=[];if(i.publications)for(let r=0;r<i.publications.length;r++)n.push(this._getPublicationContext(e,i.publications[r]));return{publications:n,epoch:i.epoch||"",offset:i.offset||0}})}presence(e){return w(this,void 0,void 0,function*(){const t={presence:{channel:e}};yield this._methodCall();const i=(yield this._callPromise(t,n=>n.presence)).presence;for(const n in i)if(Object.prototype.hasOwnProperty.call(i,n)){const r=i[n],h=r.conn_info,a=r.chan_info;h&&(r.connInfo=h),a&&(r.chanInfo=a)}return{clients:i}})}presenceStats(e){return w(this,void 0,void 0,function*(){const t={presence_stats:{channel:e}};yield this._methodCall();const s=yield this._callPromise(t,i=>i.presence_stats);return{numUsers:s.num_users,numClients:s.num_clients}})}startBatching(){this._batching=!0}stopBatching(){const e=this;Promise.resolve().then(function(){Promise.resolve().then(function(){e._batching=!1,e._flush()})})}_debug(...e){this._debugEnabled&&ie("debug",e)}_codecName(){return this._codec.name()}_formatOverride(){}_configure(){if(!("Promise"in globalThis))throw new Error("Promise polyfill required");if(!this._endpoint)throw new Error("endpoint configuration required");if(this._config.token!==null&&(this._token=this._config.token),this._config.data!==null&&(this._data=this._config.data),this._codec=new $,this._formatOverride(),(this._config.debug===!0||oe("centrifuge.debug"))&&(this._debugEnabled=!0),this._debug("config",this._config),typeof this._endpoint!="string")if(Array.isArray(this._endpoint)){this._transports=this._endpoint,this._emulation=!0;for(const e in this._transports)if(this._transports.hasOwnProperty(e)){const t=this._transports[e];if(!t.endpoint||!t.transport)throw new Error("malformed transport configuration");const s=t.transport;if(["websocket","http_stream","sse","sockjs","webtransport"].indexOf(s)<0)throw new Error("unsupported transport name: "+s)}}else throw new Error("unsupported url configuration type: only string or array of objects are supported")}_setState(e){if(this.state!==e){this._reconnecting=!1;const t=this.state;return this.state=e,this.emit("state",{newState:e,oldState:t}),!0}return!1}_isDisconnected(){return this.state===k.Disconnected}_isConnecting(){return this.state===k.Connecting}_isConnected(){return this.state===k.Connected}_nextCommandId(){return++this._commandId}_setNetworkEvents(){if(this._networkEventsSet)return;let e=null;this._config.networkEventTarget!==null?e=this._config.networkEventTarget:typeof globalThis.addEventListener<"u"&&(e=globalThis),e&&(e.addEventListener("offline",()=>{this._debug("offline event triggered"),(this.state===k.Connected||this.state===k.Connecting)&&(this._disconnect(D.transportClosed,"transport closed",!0),this._deviceWentOffline=!0)}),e.addEventListener("online",()=>{this._debug("online event triggered"),this.state===k.Connecting&&(this._deviceWentOffline&&!this._transportClosed&&(this._deviceWentOffline=!1,this._transportClosed=!0),this._clearReconnectTimeout(),this._startReconnecting())}),this._networkEventsSet=!0)}_getReconnectDelay(){const e=L(this._reconnectAttempts,this._config.minReconnectDelay,this._config.maxReconnectDelay);return this._reconnectAttempts+=1,e}_clearOutgoingRequests(){for(const e in this._callbacks)if(this._callbacks.hasOwnProperty(e)){const t=this._callbacks[e];clearTimeout(t.timeout);const s=t.errback;if(!s)continue;s({error:this._createErrorObject(b.connectionClosed,"connection closed")})}this._callbacks={}}_clearConnectedState(){this._client=null,this._clearServerPingTimeout(),this._clearRefreshTimeout();for(const e in this._subs){if(!this._subs.hasOwnProperty(e))continue;const t=this._subs[e];t.state===E.Subscribed&&t._setSubscribing(N.transportClosed,"transport closed")}for(const e in this._serverSubs)this._serverSubs.hasOwnProperty(e)&&this.emit("subscribing",{channel:e})}_handleWriteError(e){for(const t of e){const s=t.id;if(!(s in this._callbacks))continue;const i=this._callbacks[s];clearTimeout(this._callbacks[s].timeout),delete this._callbacks[s];const n=i.errback;n({error:this._createErrorObject(b.transportWriteError,"transport write error")})}}_transportSendCommands(e){if(!e.length)return!0;if(!this._transport)return!1;try{this._transport.send(this._codec.encodeCommands(e),this._session,this._node)}catch(t){return this._debug("error writing commands",t),this._handleWriteError(e),!1}return!0}_advanceTransportIndex(){this._currentTransportIndex++,this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=!0,this._currentTransportIndex=0)}_initializeTransport(){let e;this._config.websocket!==null?e=this._config.websocket:typeof globalThis.WebSocket!="function"&&typeof globalThis.WebSocket!="object"||(e=globalThis.WebSocket);let t=null;this._config.sockjs!==null?t=this._config.sockjs:typeof globalThis.SockJS<"u"&&(t=globalThis.SockJS);let s=null;this._config.eventsource!==null?s=this._config.eventsource:typeof globalThis.EventSource<"u"&&(s=globalThis.EventSource);let i=null;this._config.fetch!==null?i=this._config.fetch:typeof globalThis.fetch<"u"&&(i=globalThis.fetch);let n=null;if(this._config.readableStream!==null?n=this._config.readableStream:typeof globalThis.ReadableStream<"u"&&(n=globalThis.ReadableStream),this._emulation){this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=!0,this._currentTransportIndex=0);let g=0;for(;;){if(g>=this._transports.length)throw new Error("no supported transport found");const v=this._transports[this._currentTransportIndex],y=v.transport,T=v.endpoint;if(y==="websocket"){if(this._debug("trying websocket transport"),this._transport=new H(T,{websocket:e}),!this._transport.supported()){this._debug("websocket transport not available"),this._advanceTransportIndex(),g++;continue}}else if(y==="webtransport"){if(this._debug("trying webtransport transport"),this._transport=new de(T,{webtransport:globalThis.WebTransport,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("webtransport transport not available"),this._advanceTransportIndex(),g++;continue}}else if(y==="http_stream"){if(this._debug("trying http_stream transport"),this._transport=new le(T,{fetch:i,readableStream:n,emulationEndpoint:this._config.emulationEndpoint,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("http_stream transport not available"),this._advanceTransportIndex(),g++;continue}}else if(y==="sse"){if(this._debug("trying sse transport"),this._transport=new ue(T,{eventsource:s,fetch:i,emulationEndpoint:this._config.emulationEndpoint}),!this._transport.supported()){this._debug("sse transport not available"),this._advanceTransportIndex(),g++;continue}}else if(y==="sockjs"){if(this._debug("trying sockjs"),this._transport=new ce(T,{sockjs:t,sockjsOptions:this._config.sockjsOptions}),!this._transport.supported()){this._debug("sockjs transport not available"),this._advanceTransportIndex(),g++;continue}}else throw new Error("unknown transport "+y);break}}else{if(se(this._endpoint,"http"))throw new Error("Provide explicit transport endpoints configuration in case of using HTTP (i.e. using array of TransportEndpoint instead of a single string), or use ws(s):// scheme in an endpoint if you aimed using WebSocket transport");if(this._debug("client will use websocket"),this._transport=new H(this._endpoint,{websocket:e}),!this._transport.supported())throw new Error("WebSocket constructor not found, make sure it is available globally or passed as a dependency in Centrifuge options")}const r=this,h=this._transport,a=this._nextTransportId();r._debug("id of transport",a);let d=!1;const f=[];if(this._transport.emulation()){const g=r._sendConnect(!0);f.push(g)}this._setNetworkEvents();const P=this._codec.encodeCommands(f);this._transportClosed=!1;let R;R=setTimeout(function(){h.close()},this._config.timeout),this._transport.initialize(this._codecName(),{onOpen:function(){if(R&&(clearTimeout(R),R=null),r._transportId!=a){r._debug("open callback from non-actual transport"),h.close();return}d=!0,r._debug(h.subName(),"transport open"),!h.emulation()&&(r._transportIsOpen=!0,r._transportWasOpen=!0,r.startBatching(),r._sendConnect(!1),r._sendSubscribeCommands(),r.stopBatching(),r.emit("__centrifuge_debug:connect_frame_sent",{}))},onError:function(g){if(r._transportId!=a){r._debug("error callback from non-actual transport");return}r._debug("transport level error",g)},onClose:function(g){if(R&&(clearTimeout(R),R=null),r._transportId!=a){r._debug("close callback from non-actual transport");return}r._debug(h.subName(),"transport closed"),r._transportClosed=!0,r._transportIsOpen=!1;let v="connection closed",y=!0,T=0;if(g&&"code"in g&&g.code&&(T=g.code),g&&g.reason)try{const I=JSON.parse(g.reason);v=I.reason,y=I.reconnect}catch{v=g.reason,(T>=3500&&T<4e3||T>=4500&&T<5e3)&&(y=!1)}T<3e3?(T===1009?(T=M.messageSizeLimit,v="message size limit exceeded",y=!1):(T=D.transportClosed,v="transport closed"),r._emulation&&!r._transportWasOpen&&r._advanceTransportIndex()):r._transportWasOpen=!0,r._isConnecting()&&!d&&r.emit("error",{type:"transport",error:{code:b.transportClosed,message:"transport closed"},transport:h.name()}),r._reconnecting=!1,r._disconnect(T,v,y)},onMessage:function(g){r._dataReceived(g)}},P),r.emit("__centrifuge_debug:transport_initialized",{})}_sendConnect(e){const t=this._constructConnectCommand(),s=this;return this._call(t,e).then(i=>{const n=i.reply.connect;s._connectResponse(n),i.next&&i.next()},i=>{s._connectError(i.error),i.next&&i.next()}),t}_startReconnecting(){if(this._debug("start reconnecting"),!this._isConnecting()){this._debug("stop reconnecting: client not in connecting state");return}if(this._reconnecting){this._debug("reconnect already in progress, return from reconnect routine");return}if(this._transportClosed===!1){this._debug("waiting for transport close");return}this._reconnecting=!0;const e=this._token==="";if(!(this._refreshRequired||e&&this._config.getToken!==null)){this._config.getData?this._config.getData().then(i=>{this._isConnecting()&&(this._data=i,this._initializeTransport())}).catch(i=>this._handleGetDataError(i)):this._initializeTransport();return}const s=this;this._getToken().then(function(i){if(s._isConnecting()){if(i==null||i==null){s._failUnauthorized();return}s._token=i,s._debug("connection token refreshed"),s._config.getData?s._config.getData().then(function(n){s._isConnecting()&&(s._data=n,s._initializeTransport())}).catch(n=>s._handleGetDataError(n)):s._initializeTransport()}}).catch(function(i){if(!s._isConnecting())return;if(i instanceof O){s._failUnauthorized();return}s.emit("error",{type:"connectToken",error:{code:b.clientConnectToken,message:i!==void 0?i.toString():""}});const n=s._getReconnectDelay();s._debug("error on getting connection token, reconnect after "+n+" milliseconds",i),s._reconnecting=!1,s._reconnectTimeout=setTimeout(()=>{s._startReconnecting()},n)})}_handleGetDataError(e){if(e instanceof O){this._failUnauthorized();return}this.emit("error",{type:"connectData",error:{code:b.badConfiguration,message:e?.toString()||""}});const t=this._getReconnectDelay();this._debug("error on getting connect data, reconnect after "+t+" milliseconds",e),this._reconnecting=!1,this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},t)}_connectError(e){this.state===k.Connecting&&(e.code===109&&(this._refreshRequired=!0),e.code<100||e.temporary===!0||e.code===109?(this.emit("error",{type:"connect",error:e}),this._debug("closing transport due to connect error"),this._disconnect(e.code,e.message,!0)):this._disconnect(e.code,e.message,!1))}_scheduleReconnect(){if(!this._isConnecting())return;let e=!1;this._emulation&&!this._transportWasOpen&&!this._triedAllTransports&&(e=!0);let t=this._getReconnectDelay();e&&(t=0),this._debug("reconnect after "+t+" milliseconds"),this._clearReconnectTimeout(),this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},t)}_constructConnectCommand(){const e={};this._token&&(e.token=this._token),this._data&&(e.data=this._data),this._config.name&&(e.name=this._config.name),this._config.version&&(e.version=this._config.version),Object.keys(this._config.headers).length>0&&(e.headers=this._config.headers);const t={};let s=!1;for(const i in this._serverSubs)if(this._serverSubs.hasOwnProperty(i)&&this._serverSubs[i].recoverable){s=!0;const n={recover:!0};this._serverSubs[i].offset&&(n.offset=this._serverSubs[i].offset),this._serverSubs[i].epoch&&(n.epoch=this._serverSubs[i].epoch),t[i]=n}return s&&(e.subs=t),{connect:e}}_getHistoryRequest(e,t){const s={channel:e};return t!==void 0&&(t.since&&(s.since={offset:t.since.offset},t.since.epoch&&(s.since.epoch=t.since.epoch)),t.limit!==void 0&&(s.limit=t.limit),t.reverse===!0&&(s.reverse=!0)),s}_methodCall(){return this._isConnected()?Promise.resolve():new Promise((e,t)=>{const s=setTimeout(function(){t({code:b.timeout,message:"timeout"})},this._config.timeout);this._promises[this._nextPromiseId()]={timeout:s,resolve:e,reject:t}})}_callPromise(e,t){return new Promise((s,i)=>{this._call(e,!1).then(n=>{var r;const h=t(n.reply);s(h),(r=n.next)===null||r===void 0||r.call(n)},n=>{var r;i(n.error),(r=n.next)===null||r===void 0||r.call(n)})})}_dataReceived(e){this._serverPing>0&&this._waitServerPing();const t=this._codec.decodeReplies(e);this._dispatchPromise=this._dispatchPromise.then(()=>{let s;this._dispatchPromise=new Promise(i=>{s=i}),this._dispatchSynchronized(t,s)})}_dispatchSynchronized(e,t){let s=Promise.resolve();for(const i in e)e.hasOwnProperty(i)&&(s=s.then(()=>this._dispatchReply(e[i])));s.then(()=>{t()})}_dispatchReply(e){let t;const s=new Promise(n=>{t=n});if(e==null)return this._debug("dispatch: got undefined or null reply"),t(),s;const i=e.id;return i&&i>0?this._handleReply(e,t):e.push?this._handlePush(e.push,t):this._handleServerPing(t),s}_call(e,t){return new Promise((s,i)=>{e.id=this._nextCommandId(),this._registerCall(e.id,s,i),t||this._addCommand(e)})}_startConnecting(){this._debug("start connecting"),this._setState(k.Connecting)&&this.emit("connecting",{code:D.connectCalled,reason:"connect called"}),this._client=null,this._startReconnecting()}_disconnect(e,t,s){if(e===M.stateInvalidated){this._token="",this._refreshRequired=!0;for(const h in this._subs)this._subs.hasOwnProperty(h)&&this._subs[h]._invalidateState();for(const h in this._serverSubs)this._serverSubs.hasOwnProperty(h)&&(this._serverSubs[h].offset=0,this._serverSubs[h].epoch="_")}if(this._isDisconnected())return;this._transportIsOpen=!1;const i=this.state;this._reconnecting=!1;const n={code:e,reason:t};let r;if(s?r=this._setState(k.Connecting):(r=this._setState(k.Disconnected),this._rejectPromises({code:b.clientDisconnected,message:"disconnected"})),this._clearOutgoingRequests(),i===k.Connecting&&this._clearReconnectTimeout(),i===k.Connected&&this._clearConnectedState(),r&&(this._isConnecting()?this.emit("connecting",n):this.emit("disconnected",n)),this._transport){this._debug("closing existing transport");const h=this._transport;this._transport=null,h.close(),this._transportClosed=!0,this._nextTransportId()}else this._debug("no transport to close");this._scheduleReconnect()}_failUnauthorized(){this._disconnect(M.unauthorized,"unauthorized",!1)}_getToken(){return this._debug("get connection token"),this._config.getToken?this._config.getToken({}):(this.emit("error",{type:"configuration",error:{code:b.badConfiguration,message:"token expired but no getToken function set in the configuration"}}),Promise.reject(new O("")))}_refresh(){const e=this._client,t=this;this._getToken().then(function(s){if(e!==t._client)return;if(!s){t._failUnauthorized();return}if(t._token=s,t._debug("connection token refreshed"),!t._isConnected())return;const i={refresh:{token:t._token}};t._call(i,!1).then(n=>{const r=n.reply.refresh;t._refreshResponse(r),n.next&&n.next()},n=>{t._refreshError(n.error),n.next&&n.next()})}).catch(function(s){if(t._isConnected()){if(s instanceof O){t._failUnauthorized();return}t.emit("error",{type:"refreshToken",error:{code:b.clientRefreshToken,message:s!==void 0?s.toString():""}}),t._refreshTimeout=setTimeout(()=>t._refresh(),t._getRefreshRetryDelay())}})}_refreshError(e){e.code<100||e.temporary===!0?(this.emit("error",{type:"refresh",error:e}),this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay())):this._disconnect(e.code,e.message,!1)}_getRefreshRetryDelay(){return L(0,5e3,1e4)}_refreshResponse(e){this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),e.expires&&(this._client=e.client,this._refreshTimeout=setTimeout(()=>this._refresh(),j(e.ttl)))}_removeSubscription(e){e!==null&&delete this._subs[e.channel]}_unsubscribe(e){if(!this._transportIsOpen)return Promise.resolve();const s={unsubscribe:{channel:e.channel}},i=this;return new Promise((r,h)=>{this._call(s,!1).then(a=>{r(),a.next&&a.next()},a=>{r(),a.next&&a.next(),i._disconnect(D.unsubscribeError,"unsubscribe error",!0)})})}_getSub(e,t){if(t&&t>0){for(const i in this._subs)if(this._subs.hasOwnProperty(i)){const n=this._subs[i];if(n._id===t)return n}return null}const s=this._subs[e];return s||null}_isServerSub(e){return this._serverSubs[e]!==void 0}_sendSubscribeCommands(){const e=[];for(const t in this._subs){if(!this._subs.hasOwnProperty(t))continue;const s=this._subs[t];if(s._inflight!==!0&&s.state===E.Subscribing){const i=s._subscribe();i&&e.push(i)}}return e}_connectResponse(e){if(this._transportIsOpen=!0,this._transportWasOpen=!0,this._reconnectAttempts=0,this._refreshRequired=!1,this._isConnected())return;this._client=e.client,this._setState(k.Connected),this._refreshTimeout&&clearTimeout(this._refreshTimeout),e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),j(e.ttl))),this._session=e.session,this._node=e.node,this.startBatching(),this._sendSubscribeCommands(),this.stopBatching();const t={client:e.client,transport:this._transport.subName()};e.data&&(t.data=e.data),this.emit("connected",t),this._resolvePromises(),this._processServerSubs(e.subs||{}),e.ping&&e.ping>0?(this._serverPing=e.ping*1e3,this._sendPong=e.pong===!0,this._waitServerPing()):this._serverPing=0}_processServerSubs(e){for(const t in e){if(!e.hasOwnProperty(t))continue;const s=e[t];this._serverSubs[t]={offset:s.offset,epoch:s.epoch,recoverable:s.recoverable||!1};const i=this._getSubscribeContext(t,s);this.emit("subscribed",i)}for(const t in e){if(!e.hasOwnProperty(t))continue;const s=e[t];if(s.recovered){const i=s.publications;if(i&&i.length>0)for(const n in i)i.hasOwnProperty(n)&&this._handlePublication(t,i[n])}}for(const t in this._serverSubs)this._serverSubs.hasOwnProperty(t)&&(e[t]||(this.emit("unsubscribed",{channel:t}),delete this._serverSubs[t]))}_clearRefreshTimeout(){this._refreshTimeout!==null&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearReconnectTimeout(){this._reconnectTimeout!==null&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null)}_clearServerPingTimeout(){this._serverPingTimeout!==null&&(clearTimeout(this._serverPingTimeout),this._serverPingTimeout=null)}_waitServerPing(){this._config.maxServerPingDelay!==0&&this._isConnected()&&(this._clearServerPingTimeout(),this._serverPingTimeout=setTimeout(()=>{this._isConnected()&&this._disconnect(D.noPing,"no ping",!0)},this._serverPing+this._config.maxServerPingDelay))}_getSubscribeContext(e,t){const s={channel:e,positioned:!1,recoverable:!1,wasRecovering:!1,recovered:!1,hasRecoveredPublications:!1};t.recovered&&(s.recovered=!0),t.positioned&&(s.positioned=!0),t.recoverable&&(s.recoverable=!0),t.was_recovering&&(s.wasRecovering=!0);let i="";"epoch"in t&&(i=t.epoch);let n=0;return"offset"in t&&(n=t.offset),(s.positioned||s.recoverable)&&(s.streamPosition={offset:n,epoch:i}),Array.isArray(t.publications)&&t.publications.length>0&&(s.hasRecoveredPublications=!0),t.data&&(s.data=t.data),s}_handleReply(e,t){const s=e.id;if(!(s in this._callbacks)){t();return}const i=this._callbacks[s];if(clearTimeout(this._callbacks[s].timeout),delete this._callbacks[s],re(e)){const n=i.errback;if(!n){t();return}const r={code:e.error.code,message:e.error.message||"",temporary:e.error.temporary||!1};n({error:r,next:t})}else{const n=i.callback;if(!n)return;n({reply:e,next:t})}}_handleJoin(e,t,s){const i=this._getSub(e,s);if(!i){if(e&&this._isServerSub(e)){const n={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit("join",n)}return}i._handleJoin(t)}_handleLeave(e,t,s){const i=this._getSub(e,s);if(!i){if(e&&this._isServerSub(e)){const n={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit("leave",n)}return}i._handleLeave(t)}_handleUnsubscribe(e,t){const s=this._getSub(e,0);if(!s&&e){this._isServerSub(e)&&(delete this._serverSubs[e],this.emit("unsubscribed",{channel:e}));return}t.code<2500?s._setUnsubscribed(t.code,t.reason,!1):(t.code===z.stateInvalidated&&s._invalidateState(),s._setSubscribing(t.code,t.reason))}_handleSubscribe(e,t){this._serverSubs[e]={offset:t.offset,epoch:t.epoch,recoverable:t.recoverable||!1},this.emit("subscribed",this._getSubscribeContext(e,t))}_handleDisconnect(e){const t=e.code;let s=!0;(t>=3500&&t<4e3||t>=4500&&t<5e3)&&(s=!1),this._disconnect(t,e.reason,s)}_getPublicationContext(e,t){const s={channel:e,data:t.data};return t.offset&&(s.offset=t.offset),t.info&&(s.info=this._getJoinLeaveContext(t.info)),t.tags&&(s.tags=t.tags),s}_getJoinLeaveContext(e){const t={client:e.client,user:e.user},s=e.conn_info;s&&(t.connInfo=s);const i=e.chan_info;return i&&(t.chanInfo=i),t}_handlePublication(e,t,s){const i=this._getSub(e,s);if(!i){if(e&&this._isServerSub(e)){const n=this._getPublicationContext(e,t);this.emit("publication",n),t.offset!==void 0&&(this._serverSubs[e].offset=t.offset)}return}i._handlePublication(t)}_handleMessage(e){this.emit("message",{data:e.data})}_handleServerPing(e){if(this._sendPong){const t={};this._transportSendCommands([t])}e()}_handlePush(e,t){const s=e.channel,i=e.id;e.pub?this._handlePublication(s,e.pub,i):e.message?this._handleMessage(e.message):e.join?this._handleJoin(s,e.join,i):e.leave?this._handleLeave(s,e.leave,i):e.unsubscribe?this._handleUnsubscribe(s,e.unsubscribe):e.subscribe?this._handleSubscribe(s,e.subscribe):e.disconnect&&this._handleDisconnect(e.disconnect),t()}_flush(){const e=this._commands.slice(0);this._commands=[],this._transportSendCommands(e)}_createErrorObject(e,t,s){const i={code:e,message:t};return s&&(i.temporary=!0),i}_registerCall(e,t,s){this._callbacks[e]={callback:t,errback:s,timeout:null},this._callbacks[e].timeout=setTimeout(()=>{delete this._callbacks[e],q(s)&&s({error:this._createErrorObject(b.timeout,"timeout")})},this._config.timeout)}_addCommand(e){this._batching?this._commands.push(e):this._transportSendCommands([e])}_nextPromiseId(){return++this._promiseId}_nextTransportId(){return++this._transportId}_resolvePromises(){for(const 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(const 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])}}G.SubscriptionState=E;G.State=k;G.UnauthorizedError=O;export{G as Centrifuge,k as State,ae as Subscription,E as SubscriptionState,O as UnauthorizedError,D as connectingCodes,M as disconnectedCodes,b as errorCodes,N as subscribingCodes,B as subscriptionFlags,z as unsubscribedCodes};