centrifuge
Version:
JavaScript client SDK for bidirectional communication with Centrifugo and Centrifuge-based server from browser, NodeJS and React Native
9 lines • 95.9 kB
JavaScript
"use strict";(()=>{var ye=Object.create;var te=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var Te=Object.getPrototypeOf,ke=Object.prototype.hasOwnProperty;var we=(a,r)=>()=>{try{return r||a((r={exports:{}}).exports,r),r.exports}catch(e){throw r=0,e}};var Re=(a,r,e,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of Pe(r))!ke.call(a,s)&&s!==e&&te(a,s,{get:()=>r[s],enumerable:!(t=Se(r,s))||t.enumerable});return a};var se=(a,r,e)=>(e=a!=null?ye(Te(a)):{},Re(r||!a||!a.__esModule?te(e,"default",{value:a,enumerable:!0}):e,a));var H=we((Ge,V)=>{"use strict";var x=typeof Reflect=="object"?Reflect:null,ie=x&&typeof x.apply=="function"?x.apply:function(r,e,t){return Function.prototype.apply.call(r,e,t)},M;x&&typeof x.ownKeys=="function"?M=x.ownKeys:Object.getOwnPropertySymbols?M=function(r){return Object.getOwnPropertyNames(r).concat(Object.getOwnPropertySymbols(r))}:M=function(r){return Object.getOwnPropertyNames(r)};function Ee(a){console&&console.warn&&console.warn(a)}var re=Number.isNaN||function(r){return r!==r};function p(){p.init.call(this)}V.exports=p;V.exports.once=De;p.EventEmitter=p;p.prototype._events=void 0;p.prototype._eventsCount=0;p.prototype._maxListeners=void 0;var ne=10;function U(a){if(typeof a!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof a)}Object.defineProperty(p,"defaultMaxListeners",{enumerable:!0,get:function(){return ne},set:function(a){if(typeof a!="number"||a<0||re(a))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+a+".");ne=a}});p.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};p.prototype.setMaxListeners=function(r){if(typeof r!="number"||r<0||re(r))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+r+".");return this._maxListeners=r,this};function oe(a){return a._maxListeners===void 0?p.defaultMaxListeners:a._maxListeners}p.prototype.getMaxListeners=function(){return oe(this)};p.prototype.emit=function(r){for(var e=[],t=1;t<arguments.length;t++)e.push(arguments[t]);var s=r==="error",i=this._events;if(i!==void 0)s=s&&i.error===void 0;else if(!s)return!1;if(s){var n;if(e.length>0&&(n=e[0]),n instanceof Error)throw n;var o=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw o.context=n,o}var c=i[r];if(c===void 0)return!1;if(typeof c=="function")ie(c,this,e);else for(var l=c.length,h=ue(c,l),t=0;t<l;++t)ie(h[t],this,e);return!0};function ae(a,r,e,t){var s,i,n;if(U(e),i=a._events,i===void 0?(i=a._events=Object.create(null),a._eventsCount=0):(i.newListener!==void 0&&(a.emit("newListener",r,e.listener?e.listener:e),i=a._events),n=i[r]),n===void 0)n=i[r]=e,++a._eventsCount;else if(typeof n=="function"?n=i[r]=t?[e,n]:[n,e]:t?n.unshift(e):n.push(e),s=oe(a),s>0&&n.length>s&&!n.warned){n.warned=!0;var o=new Error("Possible EventEmitter memory leak detected. "+n.length+" "+String(r)+" listeners added. Use emitter.setMaxListeners() to increase limit");o.name="MaxListenersExceededWarning",o.emitter=a,o.type=r,o.count=n.length,Ee(o)}return a}p.prototype.addListener=function(r,e){return ae(this,r,e,!1)};p.prototype.on=p.prototype.addListener;p.prototype.prependListener=function(r,e){return ae(this,r,e,!0)};function xe(){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 ce(a,r,e){var t={fired:!1,wrapFn:void 0,target:a,type:r,listener:e},s=xe.bind(t);return s.listener=e,t.wrapFn=s,s}p.prototype.once=function(r,e){return U(e),this.on(r,ce(this,r,e)),this};p.prototype.prependOnceListener=function(r,e){return U(e),this.prependListener(r,ce(this,r,e)),this};p.prototype.removeListener=function(r,e){var t,s,i,n,o;if(U(e),s=this._events,s===void 0)return this;if(t=s[r],t===void 0)return this;if(t===e||t.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete s[r],s.removeListener&&this.emit("removeListener",r,t.listener||e));else if(typeof t!="function"){for(i=-1,n=t.length-1;n>=0;n--)if(t[n]===e||t[n].listener===e){o=t[n].listener,i=n;break}if(i<0)return this;i===0?t.shift():Ce(t,i),t.length===1&&(s[r]=t[0]),s.removeListener!==void 0&&this.emit("removeListener",r,o||e)}return this};p.prototype.off=p.prototype.removeListener;p.prototype.removeAllListeners=function(r){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[r]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete t[r]),this;if(arguments.length===0){var i=Object.keys(t),n;for(s=0;s<i.length;++s)n=i[s],n!=="removeListener"&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=t[r],typeof e=="function")this.removeListener(r,e);else if(e!==void 0)for(s=e.length-1;s>=0;s--)this.removeListener(r,e[s]);return this};function le(a,r,e){var t=a._events;if(t===void 0)return[];var s=t[r];return s===void 0?[]:typeof s=="function"?e?[s.listener||s]:[s]:e?Oe(s):ue(s,s.length)}p.prototype.listeners=function(r){return le(this,r,!0)};p.prototype.rawListeners=function(r){return le(this,r,!1)};p.listenerCount=function(a,r){return typeof a.listenerCount=="function"?a.listenerCount(r):he.call(a,r)};p.prototype.listenerCount=he;function he(a){var r=this._events;if(r!==void 0){var e=r[a];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}p.prototype.eventNames=function(){return this._eventsCount>0?M(this._events):[]};function ue(a,r){for(var e=new Array(r),t=0;t<r;++t)e[t]=a[t];return e}function Ce(a,r){for(;r+1<a.length;r++)a[r]=a[r+1];a.pop()}function Oe(a){for(var r=new Array(a.length),e=0;e<r.length;++e)r[e]=a[e].listener||a[e];return r}function De(a,r){return new Promise(function(e,t){function s(n){a.removeListener(r,i),t(n)}function i(){typeof a.removeListener=="function"&&a.removeListener("error",s),e([].slice.call(arguments))}de(a,r,i,{once:!0}),r!=="error"&&Ie(a,s,{once:!0})})}function Ie(a,r,e){typeof a.on=="function"&&de(a,"error",r,e)}function de(a,r,e,t){if(typeof a.on=="function")t.once?a.once(r,e):a.on(r,e);else if(typeof a.addEventListener=="function")a.addEventListener(r,function s(i){t.once&&a.removeEventListener(r,s),e(i)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof a)}});var K=se(H());var L=(t=>(t.Disconnected="disconnected",t.Connecting="connecting",t.Connected="connected",t))(L||{}),A=(t=>(t.Unsubscribed="unsubscribed",t.Subscribing="subscribing",t.Subscribed="subscribed",t))(A||{});function fe(a,r){return a.lastIndexOf(r,0)===0}function w(a){return a==null?!1:typeof a=="function"}function _e(a,r){if(globalThis.console){let e=globalThis.console[a];w(e)&&e.apply(globalThis.console,r)}}function Fe(a,r){return Math.floor(Math.random()*(r-a+1)+a)}function P(a,r,e){a>31&&(a=31);let t=Fe(0,Math.min(e,r*Math.pow(2,a)));return Math.min(e,r+t)}function pe(a){return"error"in a&&a.error!==null}function R(a){return Math.min(a*1e3,2147483647)}function be(a){try{return typeof localStorage>"u"||localStorage===null||!w(localStorage.getItem)?null:localStorage.getItem(a)}catch{return null}}function k(a){return a!=null&&Number(a)>0}function b(a){if(a==null)return 0;if(typeof a=="object"){let e=a.low,t=a.high;if(typeof e=="number"&&typeof t=="number")return(t>>>0)*4294967296+(e>>>0)}let r=Number(a);return isNaN(r)?0:r}var I=class extends K.default{constructor(e,t,s){super();this._resubscribeTimeout=null;this._refreshTimeout=null;this._pendingOffset=null;this._removed=!1;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._mapPositionResets=0;this._subscribeFlow=0;this._refreshGeneration=0;this._sharedPollReplayPending=!1;this._stateTransitions=0;this._sharedPollQueue=Promise.resolve();this._subscribeCallFlow=null;this._deferredUnsubscribe=null;this._mapFlowRecovering=!1;this._mapFlowOffset=0;this._mapFlowEpoch=null;this._mapFlowPositionResets=0;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._sharedPollSignatureRefreshAgain=!1;this._sharedPollSignatureRefreshKeys=new Set;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",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==="unsubscribed"?Promise.reject({code:7,message:this.state}):this.state==="subscribed"?Promise.resolve():new Promise((t,s)=>{let i=this._nextPromiseId(),n={resolve:t,reject:s};e&&(n.timeout=setTimeout(()=>{delete this._promises[i],s({code:1,message:"timeout"})},e)),this._promises[i]=n})}subscribe(){if(this._removed)throw new Error("Subscription to the channel "+this.channel+" was removed from the client");this._isSubscribed()||(this._isUnsubscribed()&&(this._resubscribeAttempts=0),this._setSubscribing(0,"subscribe called"))}unsubscribe(){this._setUnsubscribed(0,"unsubscribe called",!0)}_debouncedPublish(e,t,s){let i=this._debouncePending.get(e);if(i)return i.data=t,i.dirty=!0,Promise.resolve({});let n={data:t,dirty:!1,timer:null};return n.timer=setTimeout(()=>{let c=this._debouncePending.get(e);if(!c||!c.dirty){this._debouncePending.delete(e);return}c.dirty=!1;let l=c.data;(s?this._centrifuge.mapPublish(this.channel,e,l):this._centrifuge.publish(this.channel,l)).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).catch(()=>{})},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){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,this._mapPositionResets++)}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,i=this._nextPromiseId(),n=setTimeout(()=>{delete this._promises[i],t({code:1,message:"timeout"})},s);this._promises[i]={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._stateTransitions++,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._refreshGeneration++,this._cancelAllDebounce(),this._clearSharedPollSignatureRefresh(),this._clearSharedPollTrackRetry(),this._clearSharedPollReplayRetry(),this._sharedPollSignatureRefreshTargetMs=null,this._sharedPollSignatureRefreshInFlight=!1,this._sharedPollSignatureRefreshAgain=!1}_invalidateState(){this._getToken!==null&&(this._token=""),this._prevValueMap=new Map,this._map?(this._offset=null,this._epoch=null,this._recover=!1,this._mapPositionResets++,this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapCursor="",this._mapPhase=null):this._offset!==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=b(e.offset),this._epoch=e.epoch||""):this._recover=!1,e.delta?this._delta_negotiated=!0:this._delta_negotiated=!1,e.publish_debounce&&(this._debounceMs=e.publish_debounce),this._sharedPoll){let i=e.epoch||"";if(this._sharedPollEpoch!==""&&this._sharedPollEpoch!==i)for(let n of this._sharedPollTrackedItems.keys())this._sharedPollTrackedItems.set(n,0);this._sharedPollEpoch=i}if(this._setState("subscribed"),!this._isSubscribed())return;let t=this._centrifuge._getSubscribeContext(this.channel,e);if(this.emit("subscribed",t),!this._isSubscribed())return;this._resolvePromises();let s=e.publications||[];for(let i=0;i<s.length&&this._isSubscribed();i++)this._handlePublication(s[i]);e.expires===!0&&this._isSubscribed()&&(this._refreshTimeout=setTimeout(()=>this._refresh(),R(e.ttl)))}async _setSubscribing(e,t){if(this._isSubscribing())return;this._isSubscribed()&&this._clearSubscribedState(),this._id=0;let s=this._stateTransitions+1;this._setState("subscribing")&&this._stateTransitions===s&&this.emit("subscribing",{channel:this.channel,code:e,reason:t}),this._centrifuge._transport&&this._centrifuge._transport.emulation()&&(await this._unsubPromise,await this._centrifuge._removedSubscriptionUnsubscribed(this.channel),await this._sharedPollQueue),this._isSubscribing()&&this._subscribe()}_subscribe(){if(this._debug("subscribing on",this.channel),!this._isTransportOpen())return this._debug("delay subscribe on",this.channel,"till connected"),null;if(this._inflight)return null;if(this._inflight=!0,this._map)return this._mapSubscribe(),null;let e=this._subscribeFlow;return this._getState&&this._offset===null?(this._loadStreamState(e),null):this._canSubscribeWithoutGettingToken()?this._subscribeWithoutToken(e):(this._getSubscriptionToken().then(t=>this._handleTokenResponse(t,e)).catch(t=>this._handleTokenError(t,e)),null)}_flowOutdated(e){return e!==this._subscribeFlow}_mustDeferUnsubscribe(){let e=this._centrifuge._transport;return this._subscribeCallFlow===this._subscribeFlow&&!!e&&e.emulation()}_settleSubscribeCall(e,t,s){this._subscribeCallFlow===e&&(this._subscribeCallFlow=null);let i=this._deferredUnsubscribe;return i===null||i.flow!==e?!1:(this._deferredUnsubscribe=null,t?(this._centrifuge._unsubscribe(this).then(i.resolve),!0):(i.resolve(),s&&s.code===1&&this._centrifuge._disconnect(3,"subscribe timeout",!0),!0))}_isTransportOpen(){return this._centrifuge._transportIsOpen}_canSubscribeWithoutGettingToken(){return!this._usesToken()||!!this._token}_subscribeWithoutToken(e){return this._getData?(this._getDataAndSubscribe(this._token,e),null):this._sendSubscribe(this._token)}_loadStreamState(e){if(!this._isSubscribing()){this._inflight=!1;return}this._callAsync(()=>this._getState()).then(t=>{if(!this._flowOutdated(e)){if(!this._isSubscribing()){this._inflight=!1;return}this._offset=b(t.offset),this._epoch=t.epoch,this._recover=!0,this._canSubscribeWithoutGettingToken()?this._subscribeWithoutToken(e):this._getSubscriptionToken().then(s=>this._handleTokenResponse(s,e)).catch(s=>this._handleTokenError(s,e))}}).catch(t=>{if(!this._flowOutdated(e)){if(!this._isSubscribing()){this._inflight=!1;return}this._inflight=!1,this._subscribeError({code:13,message:t?.toString()||"getState failed",temporary:!0})}})}_getDataAndSubscribe(e,t){if(!this._getData){this._inflight=!1;return}this._callAsync(()=>this._getData({channel:this.channel})).then(s=>{if(!this._flowOutdated(t)){if(!this._isSubscribing()){this._inflight=!1;return}this._data=s,this._sendSubscribe(e)}}).catch(s=>this._handleGetDataError(s,t))}_handleGetDataError(e,t){if(!this._flowOutdated(t)){if(!this._isSubscribing()){this._inflight=!1;return}if(e instanceof S){this._inflight=!1,this._failUnauthorized();return}this._emitError({type:"subscribeData",channel:this.channel,error:{code:12,message:e?.toString()||""}},()=>{this._inflight=!1,this._scheduleResubscribe()})}}_handleTokenResponse(e,t){if(!this._flowOutdated(t)){if(!this._isSubscribing()){this._inflight=!1;return}if(!e){this._inflight=!1,this._failUnauthorized();return}this._token=e,this._getData?this._getDataAndSubscribe(e,t):this._sendSubscribe(e)}}_handleTokenError(e,t){if(!this._flowOutdated(t)){if(!this._isSubscribing()){this._inflight=!1;return}if(e instanceof S){this._inflight=!1,this._failUnauthorized();return}this._emitError({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),s=this._subscribeFlow;return this._subscribeCallFlow=s,this._centrifuge._call(t).then(i=>{try{if(this._settleSubscribeCall(s,!0)||s!==this._subscribeFlow)return;this._inflight=!1,this._handleSubscribeResponse(i.reply.subscribe)}catch(n){this._centrifuge._dispatchFailed(n)}finally{i.next&&i.next()}},i=>{try{if(this._settleSubscribeCall(s,!1,i.error)||s!==this._subscribeFlow)return;this._inflight=!1,this._handleSubscribeError(i.error)}catch(n){this._centrifuge._rejectionFailed(n,i)}finally{i.next&&i.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 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)}emit(e,...t){try{return K.default.prototype.emit.call(this,e,...t)}catch(s){return this._centrifuge._handlerFailed(s),!0}}_handleSubscribeError(e){if(this._isSubscribing()&&e.code!==11){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){if(this._isSubscribing()){this._sharedPollReplayPending=this._sharedPoll;try{this._setSubscribed(e)}finally{this._sharedPollReplayPending=!1}this._sharedPoll&&this._sharedPollReplayTrack()}}_setUnsubscribed(e,t,s){if(this._isUnsubscribed())return Promise.resolve();let i=Promise.resolve();if(this._isSubscribed())s&&(i=this._unsubPromise=this._centrifuge._unsubscribe(this)),this._clearSubscribedState();else if(this._isSubscribing()){if(this._inflight&&s)if(this._mustDeferUnsubscribe()){let o=this._subscribeFlow;i=this._unsubPromise=new Promise(c=>{this._deferredUnsubscribe={flow:o,resolve:c}})}else i=this._unsubPromise=this._centrifuge._unsubscribe(this);this._clearSubscribingState()}this._inflight=!1,this._subscribeFlow++,this._id=0,this._sharedPollEpoch="",this._sharedPollSignatures=[],this._sharedPollTrackedItems.clear(),this._sharedPollSignatureRefreshInFlight=!1,this._sharedPollSignatureRefreshAgain=!1,this._sharedPollSignatureRefreshTargetMs=null,this._cancelAllDebounce(),this._rejectPromises({code:7,message:"unsubscribed"});let n=this._stateTransitions+1;return this._setState("unsubscribed")&&this._stateTransitions===n&&this.emit("unsubscribed",{channel:this.channel,code:e,reason:t}),i}_handlePublication(e){if(this._sharedPoll&&e.key&&!e.removed&&k(e.version)){let s=this._sharedPollTrackedItems.get(e.key);if(s!==void 0&&s>0&&b(e.version)<=s)return}if(this._delta&&this._delta_negotiated){let s=(this._map||this._sharedPoll)&&e.key||"";if(e.removed)this._prevValueMap.delete(s);else{let{newData:i,newPrevValue:n,isDelta:o,wireBytes:c,fullBytes:l}=this._centrifuge._codec.applyDeltaIfNeeded(e,this._prevValueMap.get(s));e.data=i,this._deltaNumPubs++,this._deltaBytesReceived+=c,this._deltaBytesDecoded+=l,o?this._deltaNumDelta++:this._deltaNumFull++,this._prevValueMap.set(s,n)}}let t;if(this._sharedPoll){if(e.key&&!this._sharedPollTrackedItems.has(e.key))return;t=this._getSharedPollUpdateContext(e)}else this._map?t=this._getMapUpdateContext(e):t=this._centrifuge._getPublicationContext(this.channel,e);if(this._map||this._sharedPoll){if(this.emit("publication",t),!this._isSubscribed())return;this._setPublicationPosition(e),this.emit("update",t)}else{this._pendingOffset=k(e.offset)?b(e.offset):null;let s=this._centrifuge._handlerFailures;try{this.emit("publication",t)}finally{this._pendingOffset=null}if(this._centrifuge._handlerFailures!==s)return;this._setPublicationPosition(e)}}_setPublicationPosition(e){this._sharedPoll&&e.key&&this._sharedPollTrackedItems.has(e.key)&&(e.removed?this._sharedPollTrackedItems.delete(e.key):e.version&&this._sharedPollTrackedItems.set(e.key,b(e.version))),k(e.offset)&&(this._offset=b(e.offset)),e.epoch&&(this._epoch=e.epoch)}_seedDeltaTracking(e,t){if(!(!this._delta||!e.key)){if(e.removed){this._prevValueMap.delete(e.key);return}if(!t){this._prevValueMap.set(e.key,e.data);return}if(typeof e.data=="string"){let s=e.data,i=new TextEncoder().encode(s);this._prevValueMap.set(e.key,i);let n=i.length;this._deltaNumPubs++,this._deltaNumFull++,this._deltaBytesReceived+=n,this._deltaBytesDecoded+=n,e.data=JSON.parse(s)}else if(e.data instanceof Uint8Array){this._prevValueMap.set(e.key,e.data);let s=e.data.length;this._deltaNumPubs++,this._deltaNumFull++,this._deltaBytesReceived+=s,this._deltaBytesDecoded+=s}}}_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._clearResubscribeTimeout(),this._resubscribeTimeout=setTimeout(function(){e._resubscribeTimeout=null,e._isSubscribing()&&e._subscribe()},t),this._debug("resubscribe scheduled after "+t,this.channel)}_emitError(e,t){let s=this._subscribeFlow;try{this.emit("error",e)}finally{s===this._subscribeFlow&&t()}}_subscribeError(e){if(this._isSubscribing()){if(e.code===109&&this._getToken===null){try{this.emit("error",{type:"configuration",channel:this.channel,error:{code:12,message:"subscription token expired but no getToken function set"}})}catch(t){this._centrifuge._reportDispatchError(t)}this._setUnsubscribed(1,"unauthorized",!1);return}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._emitError(t,()=>this._scheduleResubscribe()):this._scheduleResubscribe()}else this._setUnsubscribed(e.code,e.message,!1)}}_getResubscribeDelay(){let e=P(this._resubscribeAttempts,this._minResubscribeDelay,this._maxResubscribeDelay);return this._resubscribeAttempts++,e}_setOptions(e){if(e){if(e.since&&(this._offset=b(e.since.offset),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(){if(this._pendingOffset!==null)return this._pendingOffset;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;if(t===null){try{this.emit("error",{type:"configuration",channel:this.channel,error:{code:12,message:"provide a function to get channel subscription token"}})}catch(s){this._centrifuge._reportDispatchError(s)}return Promise.reject(new S(""))}return this._callAsync(()=>t(e))}_refresh(){this._clearRefreshTimeout();let e=this,t=this._refreshGeneration;this._getSubscriptionToken().then(function(s){if(t!==e._refreshGeneration||!e._isSubscribed())return;if(!s){e._failUnauthorized();return}e._token=s;let n={sub_refresh:{channel:e.channel,token:s}};e._centrifuge._call(n).then(o=>{try{e._refreshResponse(o.reply.sub_refresh)}catch(c){e._centrifuge._dispatchFailed(c)}finally{o.next&&o.next()}},o=>{try{e._refreshError(o.error)}catch(c){e._centrifuge._rejectionFailed(c,o)}finally{o.next&&o.next()}})}).catch(function(s){if(!(t!==e._refreshGeneration||!e._isSubscribed())){if(s instanceof S){e._failUnauthorized();return}e._emitError({type:"refreshToken",channel:e.channel,error:{code:9,message:s!==void 0?s.toString():""}},()=>{t!==e._refreshGeneration||!e._isSubscribed()||(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(),R(e.ttl))))}_refreshError(e){this._isSubscribed()&&(e.code<100||e.temporary===!0?this._emitError({type:"refresh",channel:this.channel,error:e},()=>{this._isSubscribed()&&(this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay()))}):this._setUnsubscribed(e.code,e.message,!0))}_getRefreshRetryDelay(){return P(0,1e4,2e4)}_callAsync(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}_failUnauthorized(){this._setUnsubscribed(1,"unauthorized",!0)}_sendTrackRequest(e,t){if(e.length===0)return Promise.resolve();let s=6e4,i=[],n=[],o=100;if(t&&t.length>0)for(let h of t)o+=h.length+4;for(let h of e){let u=100;for(let f of h.items)u+=f.key.length+16;n.length>0&&o+u>s&&(i.push(n),n=[],o=100),n.push(h),o+=u}n.length>0&&i.push(n);let c=h=>i.slice(h).flatMap(u=>u.flatMap(f=>f.items.map(_=>_.key))),l=(h,u,f)=>new Promise((_,d)=>{let m={channel:this.channel,type:1,track:h.map(g=>({signature:g.signature,items:g.items.map(v=>v.version>0?v:{key:v.key})}))};f&&f.length>0&&(m.untrack=f);let T={sub_refresh:m};this._centrifuge._call(T).then(g=>{try{this._handleTrackResponse(g.reply.sub_refresh,h.flatMap(v=>v.items.map(y=>y.key)),f)}catch(v){this._centrifuge._dispatchFailed(v)}finally{g.next&&g.next()}_()},g=>{g.next&&g.next(),this._sharedPollRequestFailed(g.error),d({error:g.error,keys:c(u)})})});return this._sharedPollSerial(()=>i.reduce((h,u,f)=>h.then(()=>l(u,f,f===0?t:void 0)),Promise.resolve()))}_isEmulation(){let e=this._centrifuge._transport;return!!e&&e.emulation()}_sharedPollSerial(e){if(!this._isEmulation())return e();let t=this._refreshGeneration,s=this._sharedPollQueue.then(()=>{if(!(t!==this._refreshGeneration||!this._isSubscribed()))return e()});return this._sharedPollQueue=s.then(()=>{},()=>{}),s}_sharedPollRequestFailed(e){e&&e.code===1&&this._isEmulation()&&this._centrifuge._disconnect(3,"shared poll request timeout",!0)}_sendUntrackRequest(e){return this._sharedPollSerial(()=>new Promise((t,s)=>{let n={sub_refresh:{channel:this.channel,type:2,untrack:e}};this._centrifuge._call(n).then(o=>{o.next&&o.next(),t()},o=>{o.next&&o.next(),this._sharedPollRequestFailed(o.error),s(o.error)})}))}_handleTrackResponse(e,t,s){if(!this._isSubscribed())return;if(this._clearSharedPollTrackRetry(),e&&e.items&&e.items.length>0)for(let o of e.items){if(!this._isSubscribed())return;this._handlePublication(o)}if(!this._isSubscribed())return;let i=new Set(s||[]),n=t.filter(o=>!i.has(o)&&!this._sharedPollTrackedItems.has(o));if(n.length>0&&this._sendUntrackRequest(n).catch(o=>{this.emit("error",{type:"untrack",channel:this.channel,error:o})}),e&&e.expires===!0){let o=Date.now()+(e.ttl>0?e.ttl*1e3:1e3);this._maybeScheduleSharedPollSignatureRefresh(o)}}_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}_scheduleSharedPollReplayRetry(){this._sharedPollReplayRetryTimeout!==null&&clearTimeout(this._sharedPollReplayRetryTimeout),this._sharedPollReplayRetryTimeout=setTimeout(()=>this._sharedPollReplayTrack(),P(this._sharedPollReplayRetryAttempts++,5e3,3e4))}_clearSharedPollReplayRetry(){this._sharedPollReplayRetryTimeout!==null&&(clearTimeout(this._sharedPollReplayRetryTimeout),this._sharedPollReplayRetryTimeout=null),this._sharedPollReplayRetryAttempts=0}_addSharedPollSignature(e,t){let s=new Set(e);this._sharedPollSignatures=this._sharedPollSignatures.filter(i=>!i.keys.every(n=>s.has(n))),this._sharedPollSignatures.push({keys:e,signature:t})}_handleTrackError(e,t){this._isSubscribed()&&this._emitError({type:"track",channel:this.channel,error:e},()=>{if(this._isSubscribed()){if(e.code===109){this._sharedPollRefreshSignature();return}if(e.code<100||e.temporary===!0){this._sharedPollTrackRetryTimeout=setTimeout(()=>this._sharedPollReplayTrack(),P(this._sharedPollTrackRetryAttempts++,1e3,15e3));return}this._untrackFailedKeys(t)}})}_untrackFailedKeys(e){let t=e.filter(s=>this._sharedPollTrackedItems.has(s));if(t.length!==0){for(let s of t)this._sharedPollTrackedItems.delete(s);this._sharedPollSignatures=this._sharedPollSignatures.filter(s=>s.keys.some(i=>this._sharedPollTrackedItems.has(i))),this._sendUntrackRequest(t).catch(s=>{this.emit("error",{type:"untrack",channel:this.channel,error:s})});for(let s of t){if(!this._isSubscribed())return;this.emit("update",{channel:this.channel,key:s,data:null,removed:!0})}}}_sharedPollRefreshSignature(){if(this._clearSharedPollSignatureRefresh(),!this._isSubscribed()||!this._sharedPollGetSignature||this._sharedPollTrackedItems.size===0)return;if(this._sharedPollSignatureRefreshInFlight){for(let i of this._sharedPollTrackedItems.keys())if(!this._sharedPollSignatureRefreshKeys.has(i)){this._sharedPollSignatureRefreshAgain=!0;break}return}this._sharedPollSignatureRefreshTargetMs=null,this._sharedPollSignatureRefreshInFlight=!0;let e=Array.from(this._sharedPollTrackedItems.keys());this._sharedPollSignatureRefreshKeys=new Set(e);let t=this,s=this._refreshGeneration;this._callAsync(()=>this._sharedPollGetSignature({keys:e})).then(i=>{if(s!==t._refreshGeneration||(t._sharedPollSignatureRefreshInFlight=!1,!t._isSubscribed()))return;t._sharedPollSignatureRefreshAttempts=0,t._sharedPollSignatureRefreshAgain&&(t._sharedPollSignatureRefreshAgain=!1,Promise.resolve().then(()=>t._sharedPollRefreshSignature()));let n=new Set(i.keys),o=[];for(let u of e)if(!n.has(u)&&this._sharedPollTrackedItems.has(u)){if(t._sharedPollTrackedItems.delete(u),o.push(u),!t._isSubscribed())continue;t.emit("update",{channel:t.channel,key:u,data:null,removed:!0})}o.length>0&&t._sendUntrackRequest(o).catch(u=>{t.emit("error",{type:"untrack",channel:t.channel,error:u})});let c=[];for(let u of i.keys){let f=t._sharedPollTrackedItems.get(u);f!==void 0&&c.push({key:u,version:f})}let l=new Set(i.keys),h=t._sharedPollSignatures.filter(u=>u.keys.some(f=>t._sharedPollTrackedItems.has(f)&&!l.has(f)));t._sharedPollSignatures=c.length>0?[{keys:i.keys,signature:i.signature},...h]:h,c.length!==0&&t._sendTrackRequest([{items:c,signature:i.signature}]).catch(u=>{t._handleTrackError(u.error,u.keys)})}).catch(i=>{s===t._refreshGeneration&&(t._sharedPollSignatureRefreshInFlight=!1,t._sharedPollSignatureRefreshAgain=!1,t._emitError({type:"signatureRefresh",channel:t.channel,error:{code:14,message:i!==void 0?i.toString():""}},()=>{s!==t._refreshGeneration||!t._isSubscribed()||(t._sharedPollSignatureRefreshTimeout=setTimeout(()=>t._sharedPollRefreshSignature(),P(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 c of this._sharedPollSignatures){let l=c.keys.map(h=>({key:h,version:this._sharedPollTrackedItems.get(h)??0}));t.push({items:l,signature:c.signature});for(let h of c.keys)this._sharedPollTrackedItems.has(h)?e.add(h):s.push(h)}t.length>0&&this._sendTrackRequest(t,s).catch(c=>{this._handleTrackError(c.error,c.keys)});let i=[];for(let c of this._sharedPollTrackedItems.keys())e.has(c)||i.push(c);if(i.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 n=this,o=this._refreshGeneration;this._callAsync(()=>this._sharedPollGetSignature({keys:i})).then(c=>{if(o!==n._refreshGeneration||!n._isSubscribed())return;n._clearSharedPollReplayRetry();let l=new Set(c.keys),h=[];for(let f of i)if(!l.has(f)&&this._sharedPollTrackedItems.has(f)){if(n._sharedPollTrackedItems.delete(f),h.push(f),!n._isSubscribed())continue;n.emit("update",{channel:n.channel,key:f,data:null,removed:!0})}h.length>0&&n._sendUntrackRequest(h).catch(f=>{n.emit("error",{type:"untrack",channel:n.channel,error:f})});let u=[];for(let f of c.keys){let _=n._sharedPollTrackedItems.get(f);_!==void 0&&u.push({key:f,version:_})}u.length!==0&&(n._addSharedPollSignature(c.keys,c.signature),n._sendTrackRequest([{items:u,signature:c.signature}]).catch(f=>{n._handleTrackError(f.error,f.keys)}))}).catch(c=>{o!==n._refreshGeneration||!n._isSubscribed()||n._emitError({type:"signatureRefresh",channel:n.channel,error:{code:14,message:c!==void 0?c.toString():""}},()=>{o!==n._refreshGeneration||!n._isSubscribed()||(n._sharedPollReplayRetryTimeout=setTimeout(()=>n._sharedPollReplayTrack(),P(n._sharedPollReplayRetryAttempts++,5e3,3e4)))})})}_mapSubscribe(){this._debug("starting map subscribe on",this.channel);let e=++this._subscribeFlow,t=()=>{this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapCursor="";let s=this._recover&&this._offset!==null&&this._epoch!==null;s||(this._prevValueMap=new Map),this._mapFlowRecovering=s,this._mapFlowOffset=s?this._offset:0,this._mapFlowEpoch=s?this._epoch:null,this._mapFlowPositionResets=this._mapPositionResets,this._mapPhase=2,s?(this._debug("map subscribe: recovering from position, skipping to stream phase"),this._mapPhase=1,this._fetchStream(e)):this._fetchSnapshot(e)};this._canSubscribeWithoutGettingToken()?t():this._getSubscriptionToken().then(s=>{if(e===this._subscribeFlow){if(!this._isSubscribing()){this._inflight=!1;return}if(!s){this._inflight=!1,this._failUnauthorized();return}this._token=s,t()}}).catch(s=>{this._handleTokenError(s,e)})}_fetchSnapshot(e,t){if(!this._isSubscribing()||!this._isTransportOpen()){this._inflight=!1;return}let s=this._buildMapSubscribeCommand(2,t);this._debug("map subscribe: fetching snapshot page",t?`cursor=${t}`:"initial"),this._subscribeCallFlow=e,this._centrifuge._call(s).then(i=>{try{if(this._settleSubscribeCall(e,!0))return;e===this._subscribeFlow&&this._handleMapStateResponse(e,i.reply.subscribe)}catch(n){this._centrifuge._dispatchFailed(n)}finally{i.next&&i.next()}},i=>{try{if(this._settleSubscribeCall(e,!1,i.error))return;e===this._subscribeFlow&&this._handleMapSubscribeError(i.error)}catch(n){this._centrifuge._rejectionFailed(n,i)}finally{i.next&&i.next()}})}_handleMapStateResponse(e,t){if(!this._isSubscribing()){this._inflight=!1;return}if(!t.phase){this._debug("map subscribe: server forced LIVE transition during state pagination"),this._handleMapLiveResponse(e,t);return}if(!this._mapFlowEpoch&&t.epoch&&(this._mapFlowEpoch=t.epoch,this._mapFlowOffset=b(t.offset)),this._mapFlowEpoch&&t.epoch&&this._mapFlowEpoch!==t.epoch){this._debug("map subscribe: epoch changed during snapshot pagination, restarting"),this._restartMapFlow(),this._fetchSnapshot(e);return}if(t.state&&t.state.length>0&&this._mapStateBuffer.push(...t.state),t.cursor){this._mapCursor=t.cursor,this._fetchSnapshot(e,this._mapCursor);return}this._transitionFromSnapshot(e)}_restartMapFlow(){this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapCursor="",this._mapFlowRecovering=!1,this._mapFlowOffset=0,this._mapFlowEpoch=null,this._epoch=null,this._offset=null,this._recover=!1,this._prevValueMap=new Map,this._mapPhase=2}_transitionFromSnapshot(e){this._debug("map subscribe: snapshot complete, transitioning to stream phase"),this._mapPhase=1,this._fetchStream(e)}_fetchStream(e){if(!this._isSubscribing()||!this._isTransportOpen()){this._inflight=!1;return}let t=this._buildMapSubscribeCommand(1);this._debug("map subscribe: fetching stream from offset",this._mapFlowOffset),this._subscribeCallFlow=e,this._centrifuge._call(t).then(s=>{try{if(this._settleSubscribeCall(e,!0))return;e===this._subscribeFlow&&this._handleMapStreamResponse(e,s.reply.subscribe)}catch(i){this._centrifuge._dispatchFailed(i)}finally{s.next&&s.next()}},s=>{try{if(this._settleSubscribeCall(e,!1,s.error))return;e===this._subscribeFlow&&this._handleMapSubscribeError(s.error)}catch(i){this._centrifuge._rejectionFailed(i,s)}finally{s.next&&s.next()}})}_handleMapStreamResponse(e,t){if(!this._isSubscribing()){this._inflight=!1;return}if(!t.phase){this._debug("map subscribe: server forced LIVE transition during stream"),this._handleMapLiveResponse(e,t);return}if(this._mapFlowEpoch&&t.epoch&&this._mapFlowEpoch!==t.epoch){this._debug("map subscribe: epoch changed during stream, restarting"),this._restartMapFlow(),this._fetchSnapshot(e);return}t.publications&&t.publications.length>0&&this._mapStreamBuffer.push(...t.publications),t.offset!==void 0&&(this._mapFlowOffset=b(t.offset)),this._fetchStream(e)}_handleMapLiveResponse(e,t){if(!this._isSubscribing()){this._inflight=!1;return}if(this._inflight=!1,this._mapFlowEpoch&&t.epoch&&this._mapFlowEpoch!==t.epoch){this._debug("map subscribe: epoch changed during live transition, restarting"),this._restartMapFlow(),this._inflight=!0,this._fetchSnapshot(e);return}let s=!!(this._delta&&t.delta),i=t.state&&t.state.length>0?this._mapStateBuffer.concat(t.state):this._mapStateBuffer;if(this._mapStateBuffer=i.map(_=>(this._seedDeltaTracking(_,s),this._getMapUpdateContext(_))),this._mapStreamBuffer=this._mapStreamBuffer.map(_=>(this._seedDeltaTracking(_,s),this._getMapUpdateContext(_))),t.publications&&t.publications.length>0)for(let _ of t.publications){if(s){let d=_.key||"";if(_.removed)this._prevValueMap.delete(d);else{let{newData:m,newPrevValue:T,isDelta:g,wireBytes:v,fullBytes:y}=this._centrifuge._codec.applyDeltaIfNeeded(_,this._prevValueMap.get(d));_.data=m,this._deltaNumPubs++,this._deltaBytesReceived+=v,this._deltaBytesDecoded+=y,g?this._deltaNumDelta++:this._deltaNumFull++,this._prevValueMap.set(d,T)}}else this._delta&&_.key&&(_.removed?this._prevValueMap.delete(_.key):this._prevValueMap.set(_.key,_.data));this._mapStreamBuffer.push(this._getMapUpdateContext(_))}let n=b(t.offset),o=t.epoch||"";this._clearSubscribingState(),t.id&&(this._id=t.id);let c=t.recoverable===!0;t.delta?this._delta_negotiated=!0:this._delta_negotiated=!1,t.publish_debounce&&(this._debounceMs=t.publish_debounce);let l=this._mapStateBuffer,h=this._mapStreamBuffer;this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapPhase=null;let u=this._centrifuge._getSubscribeContext(this.channel,t);u.state=l;let f=this._mapFlowPositionResets;if(this._mapPositionResets===f&&(this._recover=c,this._epoch=o,u.recovered?h.length>0&&h[0].offset!==void 0?this._offset=h[0].offset-1:this._offset=n:(this._recover=!1,this._offset=null,this._epoch=null)),this._setState("subscribed"),!!this._isSubscribed()&&(this.emit("subscribed",u),!!this._isSubscribed())){if(this._resolvePromises(),!u.recovered){if(h.length>0){let _=new Map;for(let d of l)_.set(d.key,d);for(let d of h)d.removed?_.delete(d.key):_.set(d.key,d);l=Array.from(_.values()),h=[]}this._mapPositionResets===f&&(this._recover=c,this._offset=n,this._epoch=o),this.emit("sync",{entries:l})}for(let _ of h){if(!this._isSubscribed()||(this.emit("publication",_),!this._isSubscribed()))return;_.offset!==void 0&&this._mapPositionResets===f&&(this._offset=_.offset),this.emit("update",_)}this._isSubscribed()&&(this._mapPositionResets===f&&(this._offset=n),t.expires===!0&&(this._refreshTimeout=setTimeout(()=>this._refresh(),R(t.ttl))))}}_handleMapSubscribeError(e){if(this._inflight=!1,!!this._isSubscribing()&&e.code!==11){if(e.code===1){this._centrifuge._disconnect(3,"subscribe timeout",!0);return}if(this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapPhase=null,e.code===112&&this._mapUnrecoverableStrategy==="from_scratch"){this._debug("map subscribe: unrecoverable position, restarting from scratch"),this._prevValueMap=new Map,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._mapFlowEpoch?(s.offset=this._mapFlowOffset,s.epoch=this._mapFlowEpoch):this._data&&(s.data=this._data)),e===1&&(this._mapPageSize>0&&(s.limit=this._mapPageSize),s.offset=this._mapFlowOffset,s.epoch=this._mapFlowEpoch,this._mapFlowRecovering&&(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=b(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=b(e.version)),t}},B=class extends I{async publish(r){return await this._methodCall(),this._debounceMs>0?this._debouncedPublish("",r,!1):this._centrifuge.publish(this.channel,r)}async history(r){return await this._methodCall(),this._centrifuge.history(this.channel,r)}},C=class extends I{async publish(r,e){return await this._methodCall(),this._debounceMs>0?this._debouncedPublish(r,e,!0):this._centrifuge.mapPublish(this.channel,r,e)}async remove(r){return await this._methodCall(),this._cancelDebounce(r),this._centrifuge.mapRemove(this.channel,r)}},j=class extends I{track(r,e){if(r.length===0)return;let t,s=e;typeof r[0]=="string"?t=r.map(c=>({key:c,version:0})):t=r;for(let o of t){let c=b(o.version),l=this._sharedPollTrackedItems.get(o.key);(l===void 0||c>l)&&this._sharedPollTrackedItems.set(o.key,c)}if(s!==void 0){this._addSharedPollSignature(t.map(o=>o.key),s),this._isSubscribed()&&!this._sharedPollReplayPending&&this._sendTrackRequest([{items:t,signature:s}]).catch(o=>{this._handleTrackError(o.error,o.keys)});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()||this._sharedPollReplayPending)return;let i=t.map(o=>o.key),n=this._refreshGeneration;this._callAsync(()=>this._sharedPollGetSignature({keys:i})).then(o=>{if(n!==this._refreshGeneration||!this._isSubscribed())return;let c=new Set(o.keys),l=[];for(let u of i)if(!c.has(u)&&this._sharedPollTrackedItems.has(u)){if(this._sharedPollTrackedItems.delete(u),l.push(u),!this._isSubscribed())continue;this.emit("update",{channel:this.channel,key:u,data:null,removed:!0})}l.length>0&&this._sendUntrackRequest(l).catch(u=>{this.emit("error",{type:"untrack",channel:this.channel,error:u})}),this._sharedPollReplayRetryAttempts=0;let h=[];for(let u of o.keys){let f=this._sharedPollTrackedItems.get(u);f!==void 0&&h.push({key:u,version:f})}h.length!==0&&(this._addSharedPollSignature(o.keys,o.signature),this._sendTrackRequest([{items:h,signature:o.signature}]).catch(u=>{this._handleTrackError(u.error,u.keys)}))}).catch(o=>{n!==this._refreshGeneration||!this._isSubscribed()||this._emitError({type:"track",channel:this.channel,error:{code:14,message:o!==void 0?o.toString():"getSignature failed"}},()=>{n!==this._refreshGeneration||!this._isSubscribed()||this._scheduleSharedPollReplayRetry()})})}untrack(r){for(let e of r)this._sharedPollTrackedItems.delete(e);this._sharedPollSignatures=this._sharedPollSignatures.filter(e=>e.keys.some(t=>this._sharedPollTrackedItems.has(t))),this._isSubscribed()&&this._sendUntrackRequest(r).catch(e=>{this.emit("error",{type:"untrack",channel:this.channel,error:e})})}trackedKeys(){return new Set(this._sharedPollTrackedItems.keys())}};var z=class{constructor(r,e){this.endpoint=r,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(r,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!==null&&this._transport.close()}send(r){this._transport.send(r)}};var N=class{constructor(r,e){this.endpoint=r,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(r,e){let t="";r==="protobuf"&&(t="centrifuge-protobuf"),t!==""?this._transport=new this.options.websocket(this.endpoint,t):this._transport=new this.options.websocket(this.endpoint),r==="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!==null&&this._transport.close()}send(r){this._transport.send(r)}};var O=class{constructor(){this._buf=new Uint8Array(0);this._start=0;this._end=0}push(r){let e=this._end-this._start;if(this._end+r.length>this._buf.length){if(e+r.length<=this._buf.length/2)this._buf.copyWithin(0,this._start,this._end);else{let t=new Uint8Array(Math.max(this._buf.length*2,e+r.length));t.set(this._buf.subarray(this._start,this._end)),this._buf=t}this._start=0,this._end=e}this._buf.set(r,this._end),this._end+=r.length}drain(r,e){for(;this._start<this._end;){let s=r(this._buf.subarray(this._start,this._end));if(!s.ok)break;let i=this._start+s.pos,n=this._buf.slice(this._start,i);this._start=i,e(n)}let t=this._end-this._start;this._buf.length>65536&&t<=this._buf.length/4?(this._buf=this._buf.slice(this._start,this._end),this._start=0,this._end=t):t===0&&(this._start=0,this._end=0)}},D=class{constructor(){this._decoder=new TextDecoder;this._parts=[]}push(r,e){let t=this._decoder.decode(r,{stream:!0}),s=0,i=t.indexOf(`
`);for(;i!==-1;){this._parts.push(t.substring(s,i));let n=this._parts.join("");this._parts=[],s=i+1,e(n),i=t.indexOf(`
`,s)}s<t.length&&this._parts.push(t.substring(s))}};var G=class{constructor(r,e){this.endpoint=r,this.options=e,this._abortController=null,this._protocol="json"}name(){return"http_stream"}subName(){return"http_stream"}emulation(){return!0}_handleErrors(r){if(!r.ok)throw new Error(r.status);return r}_fetchEventTarget(r,e,t){let s=new EventTarget,i=r.options.fetch;return i(e,t).then(r._handleErrors).then(n=>{s.dispatchEvent(new Event("open"));let o=new D,c=new O,l=n.body.getReader();return new r.options.readableStream({start(h){function u(){return l.read().then(({done:f,value:_})=>{if(f){s.dispatchEvent(new Event("close")),h.close();return}try{r._protocol==="json"?o.push(_,d=>s.dispatchEvent(new MessageEvent("message",{data:d}))):(c.push(_),c.drain(d=>r.options.decoder.decodeReply(d),d=>s.dispatchEvent(new MessageEvent("message",{data:d}))))}catch(d){s.dispatchEvent(new Event("error",{detail:d})),s.dispatchEvent(new Event("close")),h.close();return}u()}).catch(function(f){s.dispatchEvent(new Event("error",{detail:f})),s.dispatchEvent(new Event("close")),h.close()})}return u()}})}).catch(n=>{s.dispatchEvent(new Event("error",{detail:n})),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(r,e,t){this._protocol=r,this._abortController=new AbortController;let s,i;r==="json"?(s={Accept:"application/json","Content-Type":"application/json"},i=t):(s={Accept:"application/octet-stream","Content-Type":"application/octet-stream"},i=t);let n={method:"POST",headers:s,body:i,mode:"cors",credentials:"same-origin",signal:this._abortController.signal},o=this._fetchEventTarget(this,this.endpoint,n);o.addEventListener("open",()=>{e.onOpen()}),o.addEventListener("error",c=>{this._abortController.abort(),e.onError(c)}),o.addEventListener("close",()=>{this._abortController.abort(),e.onClose({code:4,reason:"connection closed"})}),o.addEventListener("message",c=>{e.onMessage(c.data)})}close(){this._abortController!==null&&this._abortController.abort()}send(r,e,t){let s,i,n={session:e,node:t,data:r};this._protocol==="json"?(s={"Content-Type":"application/json"},i=JSON.stringify(n)):(s={"Content-Type":"application/octet-stream"},i=this.options.encoder.encodeEmulationRequest(n));let o=this.options.fetch,c={method:"POST",headers:s,body:i,mode:"cors",credentials:"same-origin",signal:this._abortController.signal};o(this.options.emulationEndpoint,c).then(l=>{l&&(l.status===404||l.status>=500)&&this.close()},()=>{this.close()})}};var q=class{constructor(r,e){this.endpoint=r,this.options=e,this._protocol="json",this._transport=null,this._onClose=null,this._abortController=null}name(){return"sse"}subName(){return"sse"}emulation(){return!0}supported(){return this.options.eventsource!==null&&this.options.fetch!==null}initialize(r,e,t){typeof AbortController<"u"&&(this._abortController=new AbortController);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 i={},n=new this.options.eventsource(s.toString(),i);this._transport=n;let o=this;n.onopen=function(){e.onOpen()},n.onerror=function(c){n.close(),e.onError(c),e.onClose({code:4,reason:"connection closed"})},n.onmessage=function(c){e.onMessage(c.data)},o._onClose=function(){e.onClose({code:4,reason:"connection closed"})}}close(){this._abortController!==null&&this._abortController.abort(),this._transport!==null&&this._transport.close(),this._onClose!==null&&this._onClose()}send(r,e,t){let s={session:e,node:t,data:r},i={"Content-Type":"application/json"},n=JSON.stringify(s),o=this.options.fetch,c=this._abortController!==null?this._abortController.signal:void 0,l={method:"POST",headers:i,body:n,mode:"cors",credentials:"same-origin",signal:c};o(this.options.emulationEndpoint,l).then(h=>{h&&(h.status===404||h.status>=500)&&this.close()},()=>{c&&c.aborted||this.close()})}};var W=class{constructor(r,e){this.endpoint=r,this.options=e,this._transport=null,this._stream=null,this._writer=null,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(r,e){let t;globalThis&&globalThis.document&&globalThis.document.baseURI?t=new URL(this.endpoint,globalThis.document.baseURI):t=new URL(this.endpoint),r==="protobuf"&&t.searchParams.append("cf_protocol","protobuf"),this._protocol=r;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 i;try{i=await this._transport.createBidirectionalStream()}catch{this.close();return}this._stream=i,this._writer=this._stream.writable.getWriter(),s.addEventListener("close",()=>{e.onClose({code:4,reason:"connection closed"})}),s.addEventListener("message",n=>{e.onMessage(n.data)}),this._startReading(s),e.onOpen()}async _startReading(r){let e=this._stream.readable.getReader(),t=new D,s=new O;try{for(;;){let{done:i,value:n}=await e.read();if(n&&n.length>0&&(this._protocol==="json"?t.push(n,o=>r.dispatchEvent(new MessageEvent("message",{data:o}))):(s.push(n),s.drain(o=>this.options.decoder.decodeReply(o),o=>r.dispatchEvent(new MessageEvent("message",{data:o}))))),i)break}}catch{r.dispatchEvent(new Event("close"))}}async close(){try{this._writer&&await this._writer.close(),this._transport.close()}catch{}}async send(r){let e;this._protocol==="json"?e=new TextEncoder().encode(r+`
`):e=r;try{await this._writer.write(e)}catch{this.close()}}};var Be=[-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(r){this.a=r,this.pos=0}haveBytes(){return this.pos<this.a.length}getByte(){let r=this.a[this.pos];if(this.pos++,this.pos>this.a.length)throw new RangeError("out of bounds");return r}getChar(){return String.fromCharCode(this.getByte())}getInt(){let r=0,e;for(;this.haveBytes()&&(e=Be[127&this.getByte()])>=0;)r=(r<<6)+e;return this.pos--,r>>>0}},$=class{constructor(){this.a=[]}toByteArray(r){return Array.isArray(r)?this.a:new Uint8Array(this.a)}putArray(r,e,t){for(let s=e;s<t;s++)this.a.push(r[s])}};function je(a){let r=0,e=0,t=0,s=0,i=0,n=a.length;for(;n>=16;)r=r+a[i+0]|0,e=e+a[i+1]|0,t=t+a[i+2]|0,s=s+a[i+3]|0,r=r+a[i+4]|0,e=e+a[i+5]|0,t=t+a[i+6]|0,s=s+a[i+7]|0,r=r+a[i+8]|0,e=e+a[i+9]|0,t=t+a[i+10]|0,s=s+a[i+11]|0,r=r+a[i+12]|0,e=e+a[i+13]|0,t=t+a[i+14]|0,s=s+a[i+15]|0,i+=16,n-=16;for(;n>=4;)r=r+a[i+0]|0,e=e+a[i+1]|0,t=t+a[i+2]|0,s=s+a[i+3]|0,i+=4,n-=4;switch(s=((s+(t<<8)|0)+(e<<16)|0)+(r<<24)|0,n){case 3:s=s+(a[i+2]<<8)|0;case 2:s=s+(a[i+1]<<16)|0;case 1:s=s+(a[i+0]<<24)|0}return s>>>0}function me(a,r){let e=0,t=new Q(r),s=a.length,i=r.length,n=t.getInt();if(t.getChar()!==`
`)throw new Error("size integer not terminated by '\\n'");let o=new $;for(;t.haveBytes();){let c=t.getInt(),l;switch(t.getChar()){case"@":if(l=t.getInt(),t.haveBytes()&&t.getChar()!==",")throw new Error("copy command not terminated by ','");if(e+=c,e>n)throw new Error("copy exceeds output file size");if(l+c>s)throw new Error("copy extends past end of input");o.putArray(a,l,l+c);break;case":":if(e+=c,e>n)throw new Error("insert command gives an output larger than predicted");if(c>i)throw new Error("insert count exceeds size of delta");o.putArray(t.a,t.pos,t.pos+c),t.pos+=c;break;case";":{let h=o.toByteArray(a);if(c!==je(h))throw new Error("bad checksum");if(e!==n)throw new Error("generated size does not match predicted size");return h}default:throw new Error("unknown delta operator")}}throw new Error("unterminated delta")}var F=class{name(){return"json"}encodeCommands(r){return r.map(e=>JSON.stringify(e)).join(`
`)}decodeReplies(r){return r.split(`
`).filter(e=>e.trim()!=="").map(e=>JSON.parse(e))}applyDeltaIfNeeded(r,e){let t,s,i,n;if(r.delta){n=!0;let o=new TextEncoder().encode(r.data),c=me(e,o);t=JSON.parse(new TextDecoder().decode(c)),s=c,i=o.length}else n=!1,t=JSON.parse(r.data),s=new TextEncoder().encode(r.data),i=s.length;return{newData:t,newPrevValue:s,isDelta:n,wireBytes:i,fullBytes:s.length}}};var Z=se(H()),ze={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,pageEventTarget:null},ge="WebSocket constructor not found, make sure it is available globally or passed as a dependency in Centrifuge options",X=1e3,Y=1e3;function ve(a){try{return a instanceof Error?a.message:String(a)}catch{return"value without a string form"}}var S=class extends Error{constructor(r){super(r),this.name=this.constructor.name}},E=class extends Z.default{constructor(e,t){super();this._reconnectTimeout=null;this._connectTimeout=null;this._removedUnsubscribes={};this._pendingServerSubOffsets={};this._refreshTimeout=null;this._serverPingTimeout=null;this._handlerFailures=0;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 F,this._reconnecting=!1,this._reconnectTimeout=null,this._connectTimeout=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._networkEvents=null,this._pageEvents=null,this._pageCached=!1,this._stateTransitions=0,this._disconnects=0,this._abortedTransportId=0,this._reconnectAttemptsResetPending=!1,this._config={...ze,...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");let s=new B(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");let s=new C(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");let s=new C(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");let s=new C(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");let s=new j(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&&this._subs[e.channel]===e&&(delete this._subs[e.channel],e._removed=!0,e.state!=="unsubscribed"&&e.unsubscribe(),this._recordRemovedUnsubscribe(e))}removeMapSubscription(e){this.removeSubscription(e)}removeSharedPollSubscription(e){this.removeSubscription(e)}subscriptions(){return this._subs}mapSubscriptions(){let e={};for(let[t,s]of Object.entries(this._subs))s.type==="map"&&(e[t]=s);return e}sharedPollSubscriptions(){let e={};for(let[t,s]of Object.entries(this._subs))s.type==="shared_poll"&&(e[t]=s);return e}async ready(e){switch(this.state){case"disconnected":throw{code:3,message:"client disconnected"};case"connected":return;default:return new Promise((t,s)=>{let i=this._nextPromiseId(),n={resolve:t,reject:s};e&&(n.timeout=setTimeout(()=>{delete this._promises[i],s({code:1,message:"timeout"})},e)),this._promises[i]=n})}}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._validateTransportConfig(),this._reconnectAttempts=0,this._startConnecting()}disconnect(){this._disconnect(0,"disconnect called",!1)}setToken(e){this._token=e,this._config.getToken===null&&(this._refreshRequired=!1)}setData(e){this._data=e}setHeaders(e){this._config.headers=e}async send(e){let t={send:{data:e}};if(await this._methodCall(),!this._transportSendCommands([t]))throw this._createErrorObject(10,"transport write error")}async rpc(e,t){let s={rpc:{method:e,data:t}};return await this._methodCall(),{data:(await this._callPromise(s,n=>n.rpc)).data}}async publish(e,t){let s={publish:{channel:e,data:t}};return await this._methodCall(),await this._callPromise(s,()=>({})),{}}async mapPublish(e,t,s){let i={publish:{channel:e,type:1,key:t,data:s}};return await this._methodCall(),await this._callPromise(i,()=>({})),{}}async mapRemove(e,t){let s={publish:{channel:e,type:1,key:t,removed:!0}};return await this._methodCall(),await this._callPromise(s,()=>({})),{}}async history(e,t){let s={history:this._getHistoryRequest(e,t)};await this._methodCall();let i=await this._callPromise(s,o=>o.history),n=[];if(i.publications)for(let o=0;o<i.publications.length;o++)n.push(this._getPublicationContext(e,i.publications[o]));return{publications:n,epoch:i.epoch||"",offset:b(i.offset)}}async presence(e){let t={presence:{channel:e}};await this._methodCall();let i=(await this._callPromise(t,n=>n.presence)).presence;for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let o=i[n],c=o.conn_info,l=o.chan_info;c&&(o.connInfo=c),l&&(o.chanInfo=l)}return{clients:i}}async presenceStats(e){let t={presence_stats:{channel:e}};await this._methodCall();let s=await this._callPromise(t,i=>i.presence_stats);return{numUsers:s.num_users,numClients:s.num_clients}}startBatching(){this._batching=!0}stopBatching(){let e=this;Promise.resolve().then(function(){Promise.resolve().then(function(){e._batching=!1,e._flush()})})}_debug(...e){this._debugEnabled&&_e("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 F,this._formatOverride(),(this._config.debug===!0||be("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(let e in this._transports)if(this._transports.hasOwnProperty(e)){let t=this._transports[e];if(!t.endpoint||!t.transport)throw new Error("malformed transport configuration");let 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;let t=this.state;this.state=e;let s=++this._stateTransitions;return e==="connecting"?(this._setNetworkEvents(),this._setPageEvents()):e==="disconnected"&&(this._clearNetworkEvents(),this._clearPageEvents()),this.emit("state",{newState:e,oldState:t}),s}return 0}_transitionSuperseded(e){return e!==0&&this._stateTransitions!==e}_isDisconnected(){return this.state==="disconnected"}_isConnecting(){return this.state==="connecting"}_isConnected(){return this.state==="connected"}_nextCommandId(){return++this._commandId}_setNetworkEvents(){if(this._networkEvents!==null)return;let e=null;if(this._config.networkEventTarget!==null?e=this._config.networkEventTarget:typeof globalThis.addEventListener<"u"&&(e=globalThis),e){let t=()=>{this._debug("offline event triggered"),(this.state==="connected"||this.state==="connecting")&&(this._deviceWentOffline=!0,this._disconnect(1,"transport closed",!0))},s=()=>{this._debug("online event triggered");let i=this._deviceWentOffline;this._deviceWentOffline=!1,this.state==="connecting"&&(i&&!this._transportClosed&&(this._abortedTransportId=this._transportId,this._disconnect(1,"transport closed",!0)),this._clearReconnectTimeout(),this._startReconnecting())};e.addEventListener("offline",t),e.addEventListener("online",s),this._networkEvents={target:e,onOffline:t,onOnline:s}}}_clearNetworkEvents(){if(this._networkEvents===null)return;let{target:e,onOffline:t,onOnline:s}=this._networkEvents;if(!w(e.removeEventListener)){this._debug("network event target has no removeEventListener, listeners kept");return}e.removeEventListener("offline",t),e.removeEventListener("online",s),this._networkEvents=null}_setPageEvents(){if(this._pageEvents!==null)return;let e=null;if(this._config.pageEventTarget!==null?e=this._config.pageEventTarget:typeof globalThis.addEventListener<"u"&&(e=globalThis),!e)return;let t=i=>{i.persisted&&(this._debug("page entered back/forward cache"),(this.state==="connected"||this.state==="connecting")&&(this._pageCached=!0,this._disconnect(1,"page entered back/forward cache",!0)))},s=i=>{if(!i.persisted)return;this._debug("page restored from back/forward cache");let n=this._pageCached;this._pageCached=!1,!(!n||this.state!=="connecting")&&(this._clearReconnectTimeout(),this._startReconnecting())};e.addEventListener("pagehide",t),e.addEventListener("pageshow",s),this._pageEvents={target:e,onPageHide:t,onPageShow:s}}_clearPageEvents(){if(this._pageEvents===null)return;let{target:e,onPageHide:t,onPageShow:s}=this._pageEvents;if(!w(e.removeEventListener)){this._debug("page event target has no removeEventListener, listeners kept");return}e.removeEventListener("pagehide",t),e.removeEventListener("pageshow",s),this._pageEvents=null}_getReconnectDelay(){let e=P(this._reconnectAttempts,this._config.minReconnectDelay,this._config.maxReconnectDelay);return this._reconnectAttempts+=1,e}_resetReconnectAttemptsIfPending(){this._reconnectAttemptsResetPending&&(this._reconnectAttemptsResetPending=!1,this._reconnectAttempts=0)}_clearOutgoingRequests(){for(let e in this._callbacks)if(this._callbacks.hasOwnProperty(e)){let t=this._callbacks[e];clearTimeout(t.timeout);let s=t.errback;if(!s)continue;s({error:this._createErrorObject(11,"connection closed")})}this._callbacks={}}_clearConnectedState(){this._client=null,this._clearServerPingTimeout(),this._clearRefreshTimeout();for(let e in this._subs){if(!this._subs.hasOwnProperty(e))continue;let t=this._subs[e];t.state==="subscribed"&&t._setSubscribing(1,"transport closed")}for(let e in this._serverSubs)this._serverSubs.hasOwnProperty(e)&&this._serverSubs[e].subscribed&&(this._serverSubs[e].subscribed=!1,this.emit("subscribing",{channel:e}))}_handleWriteError(e){for(let t of e){let s=t.id;if(!(s in this._callbacks))continue;let i=this._callbacks[s];clearTimeout(this._callbacks[s].timeout),delete this._callbacks[s];let n=i.errback;n({error:this._createErrorObject(10,"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)}_resolveTransportDeps(){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;return this._config.readableStream!==null?n=this._config.readableStream:typeof globalThis.ReadableStream<"u"&&(n=globalThis.ReadableStream),{websocket:e,sockjs:t,eventsource:s,fetchFunc:i,readableStream:n}}_createTransport(e,t,s){switch(e){case"websocket":return new N(t,{websocket:s.websocket});case"webtransport":return new W(t,{webtransport:globalThis.WebTransport,decoder:this._codec,encoder:this._codec});case"http_stream":return new G(t,{fetch:s.fetchFunc,readableStream:s.readableStream,emulationEndpoint:this._config.emulationEndpoint,decoder:this._codec,encoder:this._codec});case"sse":return new q(t,{eventsource:s.eventsource,fetch:s.fetchFunc,emulationEndpoint:this._config.emulationEndpoint});case"sockjs":return new z(t,{sockjs:s.sockjs,sockjsOptions:this._config.sockjsOptions});default:throw new Error("unknown transport "+e)}}_validateTransportConfig(){let e=this._resolveTransportDeps();if(!this._emulation){if(fe(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._createTransport("websocket",this._endpoint,e).supported())throw new Error(ge);return}for(let t of this._transports)if(this._createTransport(t.transport,t.endpoint,e).supported())return;throw new Error("no supported transport found")}_initializeTransport(){let e=this._resolveTransportDeps(),t=null;if(this._emulation){this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=!0,this._currentTransportIndex=0);for(let d=0;d<this._transports.length;d++){let m=this._transports[this._currentTransportIndex];this._debug("trying "+m.transport+" transport");let T=this._createTransport(m.transport,m.endpoint,e);if(T.supported()){t=T;break}this._debug(m.transport+" transport not available"),this._advanceTransportIndex()}}else{this._debug("client will use websocket");let d=this._createTransport("websocket",this._endpoint,e);d.supported()&&(t=d)}if(t===null){let d=this._emulation?"no supported transport found":ge;this._debug(d),this._disconnect(1,"transport closed",!0),this.emit("error",{type:"transport",error:{code:2,message:d}});return}this._transport=t;let s=this,i=this._transport,n=this._nextTransportId();s._debug("id of transport",n);let o=!1,c=[];if(this._transport.emulation()){let d=s._sendConnect(!0);c.push(d)}this._transportClosed=!1;let l=function(d){if(s._transportId!=n){s._debug("failure of non-actual transport",d);return}s._debug(i.name(),"transport failed:",d),s._emulation&&!s._transportWasOpen&&s._advanceTransportIndex(),s._abortedTransportId=n,s._disconnect(1,"transport closed",!0),s.emit("error",{type:"transport",error:{code:2,message:d},transport:i.name()})};this._clearConnectTimeout();let h=Date.now()+this._config.timeout;this._connectTimeout=setTimeout(function(){let d=Date.now()-h>=X;s._connectTimeout=setTimeout(function(){s._connectTimeout=null,l("connect timeout")},d?Y:0)},this._config.timeout);let u={onOpen:function(){if(s._transportId!=n){s._debug("open callback from non-actual transport");try{i.close()}catch(d){s._debug("error closing transport",d)}return}if(s._clearConnectTimeout(),o=!0,s._debug(i.subName(),"transport open"),!i.emulation()){s._transportIsOpen=!0,s._transportWasOpen=!0,s.startBatching();try{s._sendConnect(!1),s._sendSubscribeCommands()}catch(d){s._reportDispatchError(d)}finally{s.stopBatching()}s.emit("__centrifuge_debug:connect_frame_sent",{})}},onError:function(d){if(s._transportId!=n){s._debug("error callback from non-actual transport");return}s._debug("transport level error",d)},onClose:function d(m,T){if(s._transportId!=n){s._debug("close callback from non-actual transport");return}if(!T&&(i.emulation()||i.name()==="webtransport")){s._dispatchPromise.then(()=>d(m,!0));return}s._clearConnectTimeout(),s._debug(i.subName(),"transport closed"),s._transportClosed=!0,s._transportIsOpen=!1;let g="connection closed",v=!0,y=0;if(m&&"code"in m&&m.code&&(y=m.code),m&&m.reason)try{let J=JSON.parse(m.reason);g=J.reason,v=J.reconnect}catch{g=m.reason,(y>=3500&&y<4e3||y>=4500&&y<5e3)&&(v=!1)}y<3e3?(y===1009?(y=3,g="message size limit exceeded",v=!1):(y=1,g="transport closed"),s._emulation&&!s._transportWasOpen&&s._advanceTransportIndex()):s._transportWasOpen=!0;let ee=function(){s._reconnecting=!1,s._disconnect(y,g,v)};s._isConnecting()&&!o?(s._abortedTransportId=n,s._emitError({type:"transport",error:{code:2,message:"transport closed"},transport:i.name()},ee)):ee()},onMessage:function(d){if(s._transportId!=n){s._debug("message from non-actual transport");return}s._dataReceived(d,n)}},f=function(d){s._debug("error initializing transport",d),l(d instanceof Error?d.message:String(d))},_;try{_=i.initialize(this._codecName(),u,this._codec.encodeCommands(c))}catch(d){f(d);return}_&&w(_.then)&&_.then(null,f),s.emit("__centrifuge_debug:transport_initialized",{})}_sendConnect(e){let t=this._constructConnectCommand(),s=this,i=this._transportId,n=this._token;return this._call(t,e).then(o=>{try{s._connectResponse(o.reply.connect)}catch(c){s._dispatchFailed(c)}finally{o.next&&o.next()}},o=>{try{i===s._abortedTransportId?s._debug("connect command of a transport aborted by the client rejected"):s._connectError(o.error,s._transportId!==i,o.next!==void 0,n)}catch(c){s._rejectionFailed(c,o)}finally{o.next&&o.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;let e=this._disconnects,t=this._token==="",s=this._refreshRequired||t&&this._config.getToken!==null,i=!1,n=!1;if(!s){this._config.getData?this._getData().then(c=>{n=!0,!this._attemptAborted(e)&&(this._data=c,this._initializeTransport())}).catch(c=>this._handleGetDataError(c,e,n)):this._initializeTransport();return}let o=this;this._getToken().then(function(c){if(i=!0,!o._attemptAborted(e)){if(c==null||c==null){o._failUnauthorized();return}o._token=c,o._debug("connection token refreshed"),o._config.getData?o._getData().then(function(l){n=!0,!o._attemptAborted(e)&&(o._data=l,o._initializeTransport())}).catch(l=>o._handleGetDataError(l,e,n)):o._initializeTransport()}}).catch(function(c){if(o._attemptAborted(e)){i&&o._reportDispatchError(c);return}if(c instanceof S){o._failUnauthorized();return}o._emitError({type:"connectToken",error:{code:5,message:c!==void 0?c.toString():""}},()=>{let l=o._getReconnectDelay();o._debug("error on getting connection token, reconnect after "+l+" milliseconds",c),o._reconnecting=!1,o._reconnectTimeout=setTimeout(()=>{o._startReconnecting()},l)})})}_emitError(e,t){let s=this._disconnects;try{this.emit("error",e)}finally{this._disconnects===s&&t()}}_attemptAborted(e){return!this._isConnecting()||this._disconnects!==e}_handleGetDataError(e,t,s){if(this._attemptAborted(t)){s&&this._reportDispatchError(e);return}if(e instanceof S){this._failUnauthorized();return}this._emitError({type:"connectData",error:{code:12,message:e?.toString()||""}},()=>{let i=this._getReconnectDelay();this._debug("error on getting connect data, reconnect after "+i+" milliseconds",e),this._reconnecting=!1,this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},i)})}_connectError(e,t,s,i){this.state==="connecting"&&(e.code===109&&i===this._token&&(this._refreshRequired=!0),e.code<100||e.temporary===!0||e.code===109?this._emitError({type:"connect",error:e},()=>{t||(s&&(this._transportWasOpen=!0),!s&&this._emulation&&!this._transportWasOpen&&this._advanceTransportIndex(),this._debug("closing transport due to connect error"),this._disconnect(e.code,e.message,!0))}):t||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=e?0:this._getReconnectDelay();this._debug("reconnect after "+t+" milliseconds"),this._clearReconnectTimeout(),this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},t)}_constructConnectCommand(){let 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);let t={},s=!1;for(let i in this._serverSubs)if(this._serverSubs.hasOwnProperty(i)&&this._serverSubs[i].recoverable){s=!0;let n={recover:!0},o=this._pendingServerSubOffsets[i],c=o??this._serverSubs[i].offset;c&&(n.offset=c),this._serverSubs[i].epoch&&(n.epoch=this._serverSubs[i].epoch),t[i]=n}return s&&(e.subs=t),{connect:e}}_getHistoryRequest(e,t){let 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)=>{let s=this._nextPromiseId(),i=setTimeout(()=>{delete this._promises[s],t({code:1,message:"timeout"})},this._config.timeout);this._promises[s]={timeout:i,resolve:e,reject:t}})}_callPromise(e,t){return new Promise((s,i)=>{this._call(e,!1).then(n=>{try{s(t(n.reply))}catch(o){i(o)}finally{n.next?.()}},n=>{i(n.error),n.next?.()})})}_dataReceived(e,t=this._transportId){let s;try{s=this._codec.decodeReplies(e)}catch(i){this._debug("error decoding received data",i),this._emulation&&!this._transportWasOpen&&this._advanceTransportIndex(),this._disconnect(1,"transport closed",!0);return}this._serverPing>0&&s.length>0&&this._waitServerPing(),this._dispatchPromise=this._dispatchPromise.then(()=>new Promise(i=>{this._dispatchSynchronized(s,i,t)}))}_dispatchSynchronized(e,t,s){let i=Promise.resolve();for(let n in e)e.hasOwnProperty(n)&&(i=i.then(()=>{if(this._transportId===s)return this._dispatchReply(e[n])}).catch(o=>{this._dispatchFailed(o)}));i.then(()=>{t()})}emit(e,...t){try{return Z.default.prototype.emit.call(this,e,...t)}catch(s){return this._handlerFailed(s),!0}}_handlerFailed(e){this._handlerFailures++,this._reportDispatchError(e),this._disconnect(2,`exception in event handler: ${ve(e)}`,!1)}_dispatchFailed(e){this._reportDispatchError(e),this._disconnect(2,`exception during message handling: ${ve(e)}`,!1)}_reportDispatchError(e){this._debug("error dispatching reply",e),Promise.reject(e)}_rejectionFailed(e,t){t.next!==void 0?this._dispatchFailed(e):this._reportDispatchError(e)}_dispatchReply(e){let t,s=new Promise(n=>{t=n});if(e==null)return this._debug("dispatch: got undefined or null reply"),t(),s;let 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");let e=this.state!=="connecting"?this._stateTransitions+1:0;try{this._setState("connecting"),e&&!this._transitionSuperseded(e)&&this.emit("connecting",{code:0,reason:"connect called"})}finally{this._transitionSuperseded(e)||(this._client=null,this._startReconnecting())}}_disconnect(e,t,s){if(e===3014){this._config.getToken!==null&&(this._token="",this._refreshRequired=!0);for(let l in this._subs)this._subs.hasOwnProperty(l)&&this._subs[l]._invalidateState();for(let l in this._serverSubs)this._serverSubs.hasOwnProperty(l)&&(this._serverSubs[l].offset=0,this._serverSubs[l].epoch="_")}if(this._isDisconnected()){s||this._rejectPromises({code:3,message:"disconnected"});return}let i=this.state,n=s?"connecting":"disconnected";if(this._transportIsOpen=!1,this._reconnecting=!1,i==="connecting"&&this._clearReconnectTimeout(),this._clearConnectTimeout(),this._nextTransportId(),this._disconnects++,this._transport){this._debug("closing existing transport");let l=this._transport;this._transport=null;try{l.close()}catch(h){this._debug("error closing transport",h)}this._transportClosed=!0}else this._debug("no transport to close");this._reconnectAttemptsResetPending=!1,this._commands=[],this._clearOutgoingRequests(),s||(this._rejectPromises({code:3,message:"disconnected"}),this._deviceWentOffline=!1,this._pageCached=!1);let o={code:e,reason:t},c=this.state!==n?this._stateTransitions+1:0;try{try{this._setState(n)}finally{!s&&!this._transitionSuperseded(c)&&this._rejectPromises({code:3,message:"disconnected"}),i==="connected"&&this._clearConnectedState()}c&&!this._transitionSuperseded(c)&&(s?this.emit("connecting",o):this.emit("disconnected",o))}finally{s&&!this._transitionSuperseded(c)&&this._scheduleReconnect()}}_failUnauthorized(){this._disconnect(1,"unauthorized",!1)}_getToken(){if(this._debug("get connection token"),!this._config.getToken){try{this.emit("error",{type:"configuration",error:{code:12,message:"token expired but no getToken function set in the configuration"}})}catch(e){this._reportDispatchError(e)}return Promise.reject(new S(""))}try{return Promise.resolve(this._config.getToken({}))}catch(e){return Promise.reject(e)}}_getData(){try{return Promise.resolve(this._config.getData())}catch(e){return Promise.reject(e)}}_refresh(){let e=this._client,t=this,s=!1;this._getToken().then(function(i){if(s=!0,e!==t._client)return;if(!i){t._failUnauthorized();return}if(t._token=i,t._debug("connection token refreshed"),!t._isConnected())return;let n={refresh:{token:t._token}};t._call(n,!1).then(o=>{try{t._refreshResponse(o.reply.refresh)}catch(c){t._dispatchFailed(c)}finally{o.next&&o.next()}},o=>{try{e===t._client&&t._refreshError(o.error)}catch(c){t._rejectionFailed(c,o)}finally{o.next&&o.next()}})}).catch(function(i){if(e!==t._client||!t._isConnected()){s&&t._reportDispatchError(i);return}if(i instanceof S){t._failUnauthorized();return}t._emitError({type:"refreshToken",error:{code:6,message:i!==void 0?i.toString():""}},()=>{t._refreshTimeout=setTimeout(()=>t._refresh(),t._getRefreshRetryDelay())})})}_refreshError(e){e.code<100||e.temporary===!0?this._emitError({type:"refresh",error:e},()=>{this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay())}):this._disconnect(e.code,e.message,!1)}_getRefreshRetryDelay(){return P(0,5e3,1e4)}_refreshResponse(e){this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),e.expires&&(e.client&&(this._client=e.client),this._refreshTimeout=setTimeout(()=>this._refresh(),R(e.ttl)))}_recordRemovedUnsubscribe(e){let t=e.channel,s=this._removedUnsubscribes[t],i=e._unsubPromise,n=s?Promise.all([s,i]).then(()=>{}):i;this._removedUnsubscribes[t]=n,n.then(()=>{this._removedUnsubscribes[t]===n&&delete this._removedUnsubscribes[t]})}_removedSubscriptionUnsubscribed(e){return this._removedUnsubscribes[e]||Promise.resolve()}_unsubscribe(e){if(!this._transportIsOpen)return Promise.resolve();let s={unsubscribe:{channel:e.channel}},i=this,n=this._transportId;return new Promise((c,l)=>{this._call(s,!1).then(h=>{c(),h.next&&h.next()},h=>{if(c(),h.next&&h.next(),i._transportId!==n){i._debug("unsubscribe command of a closed transport rejected");return}try{i._disconnect(4,"unsubscribe error",!0)}catch(u){i._rejectionFailed(u,h)}})})}_getSub(e,t){if(t&&t>0){for(let i in this._subs)if(this._subs.hasOwnProperty(i)){let n=this._subs[i];if(n._id===t)return n}return null}let s=this._subs[e];return s||null}_isServerSub(e){return this._serverSubs[e]!==void 0}_getSubForPush(e,t){let s=this._getSub(e,t);return s&&e&&this._isServerSub(e)&&!s._isSubscribed()?null:s}_sendSubscribeCommands(){let e=[];for(let t in this._subs){if(!this._subs.hasOwnProperty(t))continue;let s=this._subs[t];if(s._inflight!==!0&&s._resubscribeTimeout===null&&s.state==="subscribing"){let i=s._subscribe();i&&e.push(i)}}return e}_connectResponse(e){if(this._transportIsOpen=!0,this._transportWasOpen=!0,this._transport!==null&&this._transport.emulation()?this._reconnectAttemptsResetPending=!0:this._reconnectAttempts=0,this._refreshRequired=!1,this._deviceWentOffline=!1,this._pageCached=!1,this._isConnected())return;this._client=e.client;let t=this._setState("connected");if(this._transitionSuperseded(t))return;this._refreshTimeout&&clearTimeout(this._refreshTimeout),e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),R(e.ttl))),this._session=e.session,this._node=e.node,this.startBatching(),this._sendSubscribeCommands(),this.stopBatching();let s={client:e.client,transport:this._transport.subName()};e.data&&(s.data=e.data),this.emit("connected",s),!this._transitionSuperseded(t)&&(this._resolvePromises(),this._processServerSubs(e.subs||{},t),e.ping&&e.ping>0?(this._serverPing=e.ping*1e3,this._sendPong=e.pong===!0,this._waitServerPing()):this._serverPing=0)}_processServerSubs(e,t){for(let s in e){if(!e.hasOwnProperty(s)||this._transitionSuperseded(t))continue;let i=e[s];this._serverSubs[s]={offset:b(i.offset),epoch:i.epoch,recoverable:i.recoverable||!1,subscribed:!0};let n=this._getSubscribeContext(s,i);this.emit("subscribed",n)}for(let s in e){if(!e.hasOwnProperty(s))continue;let i=e[s];if(i.recovered){let n=i.publications||[];for(let o=0;o<n.length&&!this._transitionSuperseded(t);o++)this._handlePublication(s,n[o])}}for(let s in this._serverSubs)this._serverSubs.hasOwnProperty(s)&&(e[s]||(this.emit("unsubscribed",{channel:s}),delete this._serverSubs[s]))}_clearRefreshTimeout(){this._refreshTimeout!==null&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearReconnectTimeout(){this._reconnectTimeout!==null&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null)}_clearConnectTimeout(){this._connectTimeout!==null&&(clearTimeout(this._connectTimeout),this._connectTimeout=null)}_clearServerPingTimeout(){this._serverPingTimeout!==null&&(clearTimeout(this._serverPingTimeout),this._serverPingTimeout=null)}_waitServerPing(){if(this._config.maxServerPingDelay===0||!this._isConnected())return;this._clearServerPingTimeout();let e=this._serverPing+this._config.maxServerPingDelay,t=Date.now()+e;this._serverPingTimeout=setTimeout(()=>{if(!this._isConnected())return;let s=Date.now()-t>=X;this._serverPingTimeout=setTimeout(()=>{this._isConnected()&&this._disconnect(2,"no ping",!0)},s?Y:0)},e)}_getSubscribeContext(e,t){let 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=b(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){this._resetReconnectAttemptsIfPending();let s=e.id;if(!(s in this._callbacks)){t();return}let i=this._callbacks[s];if(clearTimeout(this._callbacks[s].timeout),delete this._callbacks[s],pe(e)){let n=i.errback;if(!n){t();return}let o={code:e.error.code,message:e.error.message||"",temporary:e.error.temporary||!1};n({error:o,next:t})}else{let n=i.callback;if(!n)return;n({reply:e,next:t})}}_handleJoin(e,t,s){let i=this._getSubForPush(e,s);if(!i){if(e&&this._isServerSub(e)){let n={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit("join",n)}return}if(!i._isSubscribed()){this._debug("join for a subscription that is not subscribed",e);return}i._handleJoin(t)}_handleLeave(e,t,s){let i=this._getSubForPush(e,s);if(!i){if(e&&this._isServerSub(e)){let n={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit("leave",n)}return}if(!i._isSubscribed()){this._debug("leave for a subscription that is not subscribed",e);return}i._handleLeave(t)}_handleUnsubscribe(e,t){let s=this._getSubForPush(e,0);if(!s){e&&this._isServerSub(e)&&(delete this._serverSubs[e],this.emit("unsubscribed",{channel:e}));return}if(!s._isSubscribed()){this._debug("unsubscribe push for a previous subscription",e);return}t.code<2500?s._setUnsubscribed(t.code,t.reason,!1):(t.code===2502&&s._invalidateState(),s._setSubscribing(t.code,t.reason))}_handleSubscribe(e,t){this._serverSubs[e]={offset:b(t.offset),epoch:t.epoch,recoverable:t.recoverable||!1,subscribed:!0},this.emit("subscribed",this._getSubscribeContext(e,t))}_handleDisconnect(e){this._transportWasOpen=!0;let t=e.code,s=!0;(t>=3500&&t<4e3||t>=4500&&t<5e3)&&(s=!1),this._disconnect(t,e.reason,s)}_getPublicationContext(e,t){let s={channel:e,data:t.data};return k(t.offset)&&(s.offset=b(t.offset)),t.info&&(s.info=this._getJoinLeaveContext(t.info)),t.tags&&(s.tags=t.tags),s}_getJoinLeaveContext(e){let t={client:e.client,user:e.user},s=e.conn_info;s&&(t.connInfo=s);let i=e.chan_info;return i&&(t.chanInfo=i),t}_handlePublication(e,t,s){let i=this._getSubForPush(e,s);if(!i){if(e&&this._isServerSub(e)){let n=this._getPublicationContext(e,t);this._pendingServerSubOffsets[e]=k(t.offset)?b(t.offset):null;let o=this._handlerFailures;try{this.emit("publication",n)}finally{delete this._pendingServerSubOffsets[e]}if(this._handlerFailures!==o)return;k(t.offset)&&(this._serverSubs[e].offset=b(t.offset)),t.epoch&&(this._serverSubs[e].epoch=t.epoch)}return}if(!i._isSubscribed()){this._debug("publication for a subscription that is not subscribed",e);return}i._handlePublication(t)}_handleMessage(e){this.emit("message",{data:e.data})}_handleServerPing(e){if(this._resetReconnectAttemptsIfPending(),this._sendPong){let t={};this._transportSendCommands([t])}e()}_handlePush(e,t){let 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(){let e=this._commands.slice(0);this._commands=[],this._transportSendCommands(e)}_createErrorObject(e,t,s){let i={code:e,message:t};return s&&(i.temporary=!0),i}_registerCall(e,t,s){this._callbacks[e]={callback:t,errback:s,timeout:null};let i=Date.now()+this._config.timeout;this._callbacks[e].timeout=setTimeout(()=>{let n=Date.now()-i>=X;this._callbacks[e].timeout=setTimeout(()=>{delete this._callbacks[e],w(s)&&s({error:this._createErrorObject(1,"timeout")})},n?Y:0)},this._config.timeout)}_addCommand(e){this._batching?this._commands.push(e):this._transportSendCommands([e])}_nextPromiseId(){return++this._promiseId}_nextTransportId(){return++this._transportId}_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])}};E.SubscriptionState=A;E.State=L;E.UnauthorizedError=S;globalThis.Centrifuge=E;})();
//# sourceMappingURL=centrifuge.js.map