1(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,430769,(e,t,n)=>{e.e,t.exports=(()=>{let t;"use strict";var n,s,i,r,o,a,c,l,h,u={},d={exports:u},g=Object.defineProperty,p=Object.defineProperties,f=Object.getOwnPropertyDescriptor,m=Object.getOwnPropertyDescriptors,y=Object.getOwnPropertyNames,b=Object.getOwnPropertySymbols,v=Object.prototype.hasOwnProperty,O=Object.prototype.propertyIsEnumerable,C=(e,t,n)=>t in e?g(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,w=(e,t)=>{for(var n in t||(t={}))v.call(t,n)&&C(e,n,t[n]);if(b)for(var n of b(t))O.call(t,n)&&C(e,n,t[n]);return e},R=(e,t)=>{for(var n in t)g(e,n,{get:t[n],enumerable:!0})},A={};R(A,{ErrorInfo:()=>P,Realtime:()=>nq,Rest:()=>nl,default:()=>sm,makeProtocolMessageFromDeserialized:()=>t7,msgpack:()=>sg}),d.exports=((e,t,n,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of y(t))v.call(e,i)||i===n||g(e,i,{get:()=>t[i],enumerable:!(s=f(t,i))||s.enumerable});return e})(g({},"__esModule",{value:!0}),A);var S=class{},k=e.g;function T(e,t){return`${e}`.padStart(t?3:2,"0")}function M(e){return S.Config.logTimestamps?function(t){let n=new Date;e(T(n.getHours())+":"+T(n.getMinutes())+":"+T(n.getSeconds())+"."+T(n.getMilliseconds(),1)+" "+t)}:function(t){e(t)}}var I=class e{constructor(){this.deprecated=(e,t)=>{this.deprecationWarning(`${e} is deprecated and will be removed in a future version. ${t}`)},this.shouldLog=e=>e<=this.logLevel,this.setLog=(e,t)=>{void 0!==e&&(this.logLevel=e),void 0!==t&&(this.logHandler=this.logErrorHandler=t)},this.logLevel=e.defaultLogLevel,this.logHandler=e.defaultLogHandler,this.logErrorHandler=e.defaultLogErrorHandler}static initLogHandlers(){var t;let n,s,[i,r]=("function"==typeof(null==(t=null==k?void 0:k.console)?void 0:t.log)?(n=function(...e){console.log.apply(console,e)},s=console.warn?function(...e){console.warn.apply(console,e)}:n):n=s=function(){},[n,s].map(M));this.defaultLogHandler=i,this.defaultLogErrorHandler=r,this.defaultLogger=new e}static logActionNoStrip(e,t,n,s){e.logAction(t,n,s)}logAction(e,t,n){this.shouldLog(e)&&(1===e?this.logErrorHandler:this.logHandler)("Ably: "+t+": "+n,e)}renamedClientOption(e,t){this.deprecationWarning(`The \`${e}\` client option has been renamed to \`${t}\`. Please update your code to use \`${t}\` instead. \`${e}\` will be removed in a future version.`)}renamedMethod(e,t,n){this.deprecationWarning(`\`${e}\`\u2019s \`${t}\` method has been renamed to \`${n}\`. Please update your code to use \`${n}\` instead. \`${t}\` will be removed in a future version.`)}deprecationWarning(e){this.shouldLog(1)&&this.logErrorHandler(`Ably: Deprecation warning - ${e}`,1)}};I.defaultLogLevel=1,I.LOG_NONE=0,I.LOG_ERROR=1,I.LOG_MAJOR=2,I.LOG_MINOR=3,I.LOG_MICRO=4,I.logAction=(e,t,n,s)=>{I.logActionNoStrip(e,t,n,s)};var _={};function E(e){let t="["+e.constructor.name;return e.message&&(t+=": "+e.message),e.statusCode&&(t+="; statusCode="+e.statusCode),e.code&&(t+="; code="+e.code),e.cause&&(t+="; cause="+ei(e.cause)),e.href&&!(e.message&&e.message.indexOf("help.ably.io")>-1)&&(t+="; see "+e.href+" "),t+="]"}R(_,{Format:()=>Z,allSame:()=>Y,allToLowerCase:()=>eg,allToUpperCase:()=>ep,arrChooseN:()=>el,arrDeleteValue:()=>z,arrEquals:()=>ew,arrIntersect:()=>F,arrIntersectOb:()=>J,arrPopRandomElement:()=>ee,arrWithoutValue:()=>$,cheapRandStr:()=>ea,containsValue:()=>W,copy:()=>U,createMissingPluginError:()=>eR,dataSizeBytes:()=>eo,decodeBody:()=>eu,encodeBody:()=>ed,ensureArray:()=>x,forInOwnNonNullProperties:()=>X,getBackoffCoefficient:()=>ef,getGlobalObject:()=>eb,getJitterCoefficient:()=>em,getRetryTime:()=>ey,inherits:()=>H,inspectBody:()=>er,inspectError:()=>ei,intersect:()=>V,isEmpty:()=>B,isErrorInfoOrPartialErrorInfo:()=>es,isNil:()=>q,isObject:()=>G,keysArray:()=>K,matchDerivedChannel:()=>eO,mixin:()=>N,parseQueryString:()=>en,prototypicalClone:()=>j,randomString:()=>ec,shallowClone:()=>D,shallowEquals:()=>ev,throwMissingPluginError:()=>eA,toBase64:()=>eC,toQueryString:()=>et,valuesArray:()=>Q,whenPromiseSettles:()=>eh,withTimeoutAsync:()=>eS});
1var P=class e extends Error{constructor(t,n,s,i){super(t),void 0!==Object.setPrototypeOf&&Object.setPrototypeOf(this,e.prototype),this.code=n,this.statusCode=s,this.cause=i}toString(){return E(this)}static fromValues(t){let{message:n,code:s,statusCode:i}=t;if("string"!=typeof n||"number"!=typeof s||"number"!=typeof i)throw Error("ErrorInfo.fromValues(): invalid values: "+S.Config.inspect(t));let r=Object.assign(new e(n,s,i),t);return r.code&&!r.href&&(r.href="https://help.ably.io/error/"+r.code),r}},L=class e extends Error{constructor(t,n,s,i){super(t),void 0!==Object.setPrototypeOf&&Object.setPrototypeOf(this,e.prototype),this.code=n,this.statusCode=s,this.cause=i}toString(){return E(this)}static fromValues(t){let{message:n,code:s,statusCode:i}=t;if("string"!=typeof n||!q(s)&&"number"!=typeof s||!q(i)&&"number"!=typeof i)throw Error("PartialErrorInfo.fromValues(): invalid values: "+S.Config.inspect(t));let r=Object.assign(new e(n,s,i),t);return r.code&&!r.href&&(r.href="https://help.ably.io/error/"+r.code),r}};function N(e,...t){for(let n=0;n<t.length;n++){let s=t[n];if(!s)break;for(let t in s)Object.prototype.hasOwnProperty.call(s,t)&&(e[t]=s[t])}return e}function U(e){return N({},e)}function x(e){return q(e)?[]:Array.isArray(e)?e:[e]}function G(e){return"[object Object]"==Object.prototype.toString.call(e)}function B(e){for(let t in e)return!1;return!0}function q(e){return null==e}function D(e){let t={};for(let n in e)t[n]=e[n];return t}function j(e,t){class n{}n.prototype=e;let s=new n;return t&&N(s,t),s}var H=function(e,t){S.Config.inherits?S.Config.inherits(e,t):(e.super_=t,e.prototype=j(t.prototype,{constructor:e}))};function W(e,t){for(let n in e)if(e[n]==t)return!0;return!1}function V(e,t){return Array.isArray(t)?F(e,t):J(e,t)}function F(e,t){let n=[];for(let s=0;s<e.length;s++){let i=e[s];-1!=t.indexOf(i)&&n.push(i)}return n}function J(e,t){let n=[];for(let s=0;s<e.length;s++){let i=e[s];i in t&&n.push(i)}return n}function z(e,t){let n=e.indexOf(t),s=-1!=n;return s&&e.splice(n,1),s}function $(e,t){let n=e.slice();return z(n,t),n}function K(e,t){let n=[];for(let s in e)(!t||Object.prototype.hasOwnProperty.call(e,s))&&n.push(s);return n}function Q(e,t){let n=[];for(let s in e)(!t||Object.prototype.hasOwnProperty.call(e,s))&&n.push(e[s]);return n}function X(e,t){for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&e[n]&&t(n)}function Y(e,t){if(0===e.length)return!0;let n=e[0][t];return e.every(function(e){return e[t]===n})}var Z=((n=Z||{}).msgpack="msgpack",n.json="json",n);function ee(e){return e.splice(Math.floor(Math.random()*e.length),1)[0]}function et(e){let t=[];if(e)for(let n in e)t.push(encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t.length?"?"+t.join("&"):""}function en(e){let t,n=/([^?&=]+)=?([^&]*)/g,s={};for(;t=n.exec(e);)s[decodeURIComponent(t[1])]=decodeURIComponent(t[2]);return s}function es(e){return"object"==typeof e&&null!==e&&(e instanceof P||e instanceof L)}function ei(e){var t,n;return e instanceof Error||(null==(t=null==e?void 0:e.constructor)?void 0:t.name)==="ErrorInfo"||(null==(n=null==e?void 0:e.constructor)?void 0:n.name)==="PartialErrorInfo"?e.toString():S.Config.inspect(e)}function er(e){return S.BufferUtils.isBuffer(e)?e.toString():"string"==typeof e?e:S.Config.inspect(e)}function eo(e){if(S.BufferUtils.isBuffer(e))return S.BufferUtils.byteLength(e);if("string"==typeof e)return S.Config.stringByteSize(e);if("number"==typeof e)return 8;if("boolean"==typeof e)return 1;throw Error(`Expected input of Utils.dataSizeBytes to be a string, a number, a boolean or a buffer, but was: ${typeof e}`)}function ea(){return String(Math.random()).substr(2)}var ec=async e=>{let t=await S.Config.getRandomArrayBuffer(e);return S.BufferUtils.base64Encode(t)};function el(e,t){let n=Math.min(t,e.length),s=e.slice(),i=[];for(let e=0;e<n;e++)i.push(ee(s));return i}function eh(e,t){e.then(e=>{null==t||t(null,e)}).catch(e=>{null==t||t(e)})}function eu(e,t,n){return"msgpack"==n?(t||eA("MsgPack"),t.decode(e)):JSON.parse(String(e))}function ed(e,t,n){return"msgpack"==n?(t||eA("MsgPack"),t.encode(e,!0)):JSON.stringify(e)}function eg(e){return e.map(function(e){return e&&e.toLowerCase()})}function ep(e){return e.map(function(e){return e&&e.toUpperCase()})}function ef(e){return Math.min((e+2)/3,2)}function em(){return 1-.2*Math.random()}function ey(e,t){return e*ef(t)*em()}function eb(){return e.g}function ev(e,t){return Object.keys(e).every(n=>e[n]===t[n])&&Object.keys(t).every(n=>t[n]===e[n])}function eO(e){let t=e.match(/^(\[([^?]*)(?:(.*))\])?(.+)$/);if(!t||!t.length||t.length<5)throw new P("regex match failed",400,40010);if(t[2])throw new P(`cannot use a derived option with a ${t[2]} channel`,400,40010);return{qualifierParam:t[3]||"",channelName:t[4]}}function eC(e){let t=S.BufferUtils,n=t.utf8Encode(e);return t.base64Encode(n)}function ew(e,t){return e.length===t.length&&e.every(function(e,n){return e===t[n]})}function eR(e){return new P(`${e} plugin not provided`,40019,400)}function eA(e){throw eR(e)}async function eS(e,t=5e3,n="Timeout expired"){let s=new P(n,5e4,500);
1return Promise.race([e,new Promise((e,n)=>setTimeout(()=>n(s),t))])}var ek="2.14.0",eT={ENDPOINT:"main",ENVIRONMENT:"",REST_HOST:"rest.ably.io",REALTIME_HOST:"realtime.ably.io",FALLBACK_HOSTS:["main.a.fallback.ably-realtime.com","main.b.fallback.ably-realtime.com","main.c.fallback.ably-realtime.com","main.d.fallback.ably-realtime.com","main.e.fallback.ably-realtime.com"],PORT:80,TLS_PORT:443,TIMEOUTS:{disconnectedRetryTimeout:15e3,suspendedRetryTimeout:3e4,httpRequestTimeout:1e4,httpMaxRetryDuration:15e3,channelRetryTimeout:15e3,fallbackRetryTimeout:6e5,connectionStateTtl:12e4,realtimeRequestTimeout:1e4,recvTimeout:9e4,webSocketConnectTimeout:1e4,webSocketSlowTimeout:4e3},httpMaxRetryCount:3,maxMessageSize:65536,version:ek,protocolVersion:4,agent:"ably-js/"+ek,getPort:function(e,t){return t||e.tls?e.tlsPort:e.port},getHttpScheme:function(e){return e.tls?"https://":"http://"},getPrimaryDomainFromEndpoint:eI,getEndpointFallbackHosts:e_,getFallbackHosts:eP,getHosts:function(e){return[e.primaryDomain].concat(eP(e))},checkHost:eL,objectifyOptions:function(e,t,n,s,i){let r;if(void 0===e){let e=t?`${n} must be initialized with either a client options object, an Ably API key, or an Ably Token`:`${n} must be initialized with a client options object`;throw I.logAction(s,I.LOG_ERROR,`${n}()`,e),Error(e)}if("string"==typeof e)if(-1==e.indexOf(":")){if(!t){let e=`${n} cannot be initialized with just an Ably Token; you must provide a client options object with a \`plugins\` property. (Set this Ably Token as the object\u2019s \`token\` property.)`;throw I.logAction(s,I.LOG_ERROR,`${n}()`,e),Error(e)}r={token:e}}else{if(!t){let e=`${n} cannot be initialized with just an Ably API key; you must provide a client options object with a \`plugins\` property. (Set this Ably API key as the object\u2019s \`key\` property.)`;throw I.logAction(s,I.LOG_ERROR,`${n}()`,e),Error(e)}r={key:e}}else r=e;return i&&(r=p(w({},r),m({plugins:w(w({},i),r.plugins)}))),r},normaliseOptions:function(e,t,n){let s=null!=n?n:I.defaultLogger;e.environment&&s.deprecated("The `environment` client option","Use the `endpoint` client option instead."),e.restHost&&s.deprecated("The `restHost` client option","Use the `endpoint` client option instead."),e.realtimeHost&&s.deprecated("The `realtimeHost` client option","Use the `endpoint` client option instead.");if(e.endpoint&&(e.environment||e.restHost||e.realtimeHost))throw new P("The `endpoint` option cannot be used in conjunction with the `environment`, `restHost`, or `realtimeHost` options.",40106,400);if(e.environment&&(e.restHost||e.realtimeHost))throw new P("The `environment` option cannot be used in conjunction with the `restHost`, or `realtimeHost` options.",40106,400);"function"==typeof e.recover&&!0===e.closeOnUnload&&(I.logAction(s,I.LOG_ERROR,"Defaults.normaliseOptions","closeOnUnload was true and a session recovery function was set - these are mutually exclusive, so unsetting the latter"),e.recover=void 0),"closeOnUnload"in e||(e.closeOnUnload=!e.recover),"queueMessages"in e||(e.queueMessages=!0);let i=e.endpoint||eT.ENDPOINT;e.fallbackHosts||e.restHost||e.realtimeHost||e.port||e.tlsPort||(e.fallbackHosts=e_(e.environment||i));let r=e.environment&&`${e.environment}.realtime.ably.net`,o=e.restHost||e.realtimeHost||r||eI(i);(e.fallbackHosts||[]).concat(o).forEach(eL),e.port=e.port||eT.PORT,e.tlsPort=e.tlsPort||eT.TLS_PORT,"tls"in e||(e.tls=!0);let a=function(e){let t={};for(let n in eT.TIMEOUTS)t[n]=e[n]||eT.TIMEOUTS[n];return t}(e);t?"useBinaryProtocol"in e?e.useBinaryProtocol=S.Config.supportsBinary&&e.useBinaryProtocol:e.useBinaryProtocol=S.Config.preferBinary:e.useBinaryProtocol=!1;let c={};e.clientId&&(c["X-Ably-ClientId"]=S.BufferUtils.base64Encode(S.BufferUtils.utf8Encode(e.clientId))),"idempotentRestPublishing"in e||(e.idempotentRestPublishing=!0);let l=null,h=e.connectivityCheckUrl;if(e.connectivityCheckUrl){let[t,n]=e.connectivityCheckUrl.split("?");l=n?en(n):{},-1===t.indexOf("://")&&(t="https://"+t),h=t}let u=e.wsConnectivityCheckUrl;return u&&-1===u.indexOf("://")&&(u="wss://"+u),p(w({},e),m({primaryDomain:o,maxMessageSize:e.maxMessageSize||eT.maxMessageSize,timeouts:a,connectivityCheckParams:l,connectivityCheckUrl:h,wsConnectivityCheckUrl:u,headers:c}))},defaultGetHeaders:function(e,{format:t=eG.format,protocolVersion:n=eG.protocolVersion}={}){return{accept:ex[t],"X-Ably-Version":n.toString(),"Ably-Agent":eN(e)}},defaultPostHeaders:function(e,{format:t=eG.format,protocolVersion:n=eG.protocolVersion}={}){let s;return{accept:s=ex[t],"content-type":s,"X-Ably-Version":n.toString(),"Ably-Agent":eN(e)}}};function eM(e){return e.includes(".")||e.includes("::")||"localhost"===e}function eI(e){if(eM(e))return e;if(e.startsWith("nonprod:")){let t=e.replace("nonprod:","");return`${t}.realtime.ably-nonprod.net`}return`${e}.realtime.ably.net`}function e_(e){return eM(e)?[]:e.startsWith("nonprod:")?eE(e.replace("nonprod:",""),"ably-realtime-nonprod.com"):eE(e,"ably-realtime.com")}function eE(e,t){return["a","b","c","d","e"].map(n=>`${e}.${n}.fallback.${t}`)}function eP(e){let t=e.fallbackHosts,n=void 0!==e.httpMaxRetryCount?e.httpMaxRetryCount:eT.httpMaxRetryCount;return t?el(t,n):[]}function eL(e){if("string"!=typeof e)throw new P("host must be a string; was a "+typeof e,4e4,400);if(!e.length)throw new P("host must not be zero-length",4e4,400)}function eN(e){let t=eT.agent;if(e.agents)for(var n in e.agents)t+=" "+n+"/"+e.agents[n];return t}
1function eU(e,t,n){let s=n||{};if(s.cipher){e||eA("Crypto");let n=e.getCipher(s.cipher,t);s.cipher=n.cipherParams,s.channelCipher=n.cipher}else"cipher"in s&&(s.cipher=void 0,s.channelCipher=null);return s}var ex={json:"application/json",xml:"application/xml",html:"text/html",msgpack:"application/x-msgpack",text:"text/plain"},eG={format:"json",protocolVersion:eT.protocolVersion},eB=class e{constructor(e,t){this.logger=e,this.members=t||[]}call(e,t){for(let n of this.members)if(n)try{n(e,t)}catch(e){I.logAction(this.logger,I.LOG_ERROR,"Multicaster multiple callback handler","Unexpected exception: "+e+"; stack = "+e.stack)}}push(...e){this.members.push(...e)}createPromise(){return new Promise((e,t)=>{this.push((n,s)=>{n?t(n):e(s)})})}resolveAll(e){this.call(null,e)}rejectAll(e){this.call(e)}static create(t,n){let s=new e(t,n);return Object.assign((e,t)=>s.call(e,t),{push:e=>s.push(e),createPromise:()=>s.createPromise(),resolveAll:e=>s.resolveAll(e),rejectAll:e=>s.rejectAll(e)})}},eq=((s=eq||{}).Get="get",s.Delete="delete",s.Post="post",s.Put="put",s.Patch="patch",s),eD=((i=eD||{})[i.Success=200]="Success",i[i.NoContent=204]="NoContent",i[i.BadRequest=400]="BadRequest",i[i.Unauthorized=401]="Unauthorized",i[i.Forbidden=403]="Forbidden",i[i.RequestTimeout=408]="RequestTimeout",i[i.InternalServerError=500]="InternalServerError",i);function ej(e){return es(e)?(e.code||(403===e.statusCode?e.code=40300:(e.code=40170,e.statusCode=401)),e):new P(ei(e),e.code||40170,e.statusCode||401)}function eH(e){if(!e)return"";"string"==typeof e&&(e=JSON.parse(e));let t=Object.create(null),n=K(e,!0);n.sort();for(let s=0;s<n.length;s++)t[n[s]]=e[n[s]].sort();return JSON.stringify(t)}function eW(e,t){if(e.authCallback)I.logAction(t,I.LOG_MINOR,"Auth()","using token auth with authCallback");else if(e.authUrl)I.logAction(t,I.LOG_MINOR,"Auth()","using token auth with authUrl");else if(e.key)I.logAction(t,I.LOG_MINOR,"Auth()","using token auth with client-side signing");else if(e.tokenDetails)I.logAction(t,I.LOG_MINOR,"Auth()","using token auth with supplied token only");else{let e="authOptions must include valid authentication parameters";throw I.logAction(t,I.LOG_ERROR,"Auth()",e),Error(e)}}function eV(e){return e.useTokenAuth||!("useTokenAuth"in e&&!e.useTokenAuth)&&(e.authCallback||e.authUrl||e.token||e.tokenDetails)}var eF=0,eJ=class{constructor(e,t){if(this.authOptions={},this.client=e,this.tokenParams=t.defaultTokenParams||{},this.currentTokenRequestId=null,this.waitingForTokenRequest=null,eV(t))(function(e){return!e.key&&!e.authCallback&&!e.authUrl})(t)&&I.logAction(this.logger,I.LOG_ERROR,"Auth()","Warning: library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),this._saveTokenOptions(t.defaultTokenParams,t),eW(this.authOptions,this.logger);else{if(!t.key){const e="No authentication options provided; need one of: key, authUrl, or authCallback (or for testing only, token or tokenDetails)";throw I.logAction(this.logger,I.LOG_ERROR,"Auth()",e),new P(e,40160,401)}I.logAction(this.logger,I.LOG_MINOR,"Auth()","anonymous, using basic auth"),this._saveBasicOptions(t)}}get logger(){return this.client.logger}async authorize(e,t){if(t&&t.key&&this.authOptions.key!==t.key)throw new P("Unable to update auth options with incompatible key",40102,401);try{let n=await this._forceNewToken(null!=e?e:null,null!=t?t:null);if(this.client.connection)return new Promise((e,t)=>{this.client.connection.connectionManager.onAuthUpdated(n,(n,s)=>n?t(n):e(s))});return n}catch(e){throw this.client.connection&&e.statusCode===eD.Forbidden&&this.client.connection.connectionManager.actOnErrorFromAuthorize(e),e}}async _forceNewToken(e,t){this.tokenDetails=null,this._saveTokenOptions(e,t),eW(this.authOptions,this.logger);try{return this._ensureValidAuthCredentials(!0)}finally{delete this.tokenParams.timestamp,delete this.authOptions.queryTime}}async requestToken(e,t){let n=t||this.authOptions,s=e||U(this.tokenParams),i,r=this.client;if(n.authCallback)I.logAction(this.logger,I.LOG_MINOR,"Auth.requestToken()","using token auth with authCallback"),i=n.authCallback;else if(n.authUrl)I.logAction(this.logger,I.LOG_MINOR,"Auth.requestToken()","using token auth with authUrl"),i=(e,t)=>{let s,i=N({accept:"application/json, text/plain"},n.authHeaders),r=n.authMethod&&"post"===n.authMethod.toLowerCase(),o=n.authUrl.indexOf("?");o>-1&&(s=en(n.authUrl.slice(o)),n.authUrl=n.authUrl.slice(0,o),r||(n.authParams=N(s,n.authParams)));let a=N({},n.authParams||{},e),c=e=>{var n,s;let i=null!=(n=e.body)?n:null,r=null;if(e.error)I.logAction(this.logger,I.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received Error: "+ei(e.error));else{let t=null!=(s=e.headers["content-type"])?s:null;r=Array.isArray(t)?t.join(", "):t,I.logAction(this.logger,I.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received;
1 content-type: "+r+"; body: "+er(i))}if(e.error)return void t(e.error,null);if(e.unpacked)return void t(null,i);if(S.BufferUtils.isBuffer(i)&&(i=i.toString()),!r)return void t(new P("authUrl response is missing a content-type header",40170,401),null);let o=r.indexOf("application/json")>-1,a=r.indexOf("text/plain")>-1||r.indexOf("application/jwt")>-1;if(!o&&!a)return void t(new P("authUrl responded with unacceptable content-type "+r+", should be either text/plain, application/jwt or application/json",40170,401),null);if(o){if(i.length>131072)return void t(new P("authUrl response exceeded max permitted length",40170,401),null);try{i=JSON.parse(i)}catch(e){t(new P("Unexpected error processing authURL response; err = "+e.message,40170,401),null);return}}t(null,i,r)};if(I.logAction(this.logger,I.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Requesting token from "+n.authUrl+"; Params: "+JSON.stringify(a)+"; method: "+(r?"POST":"GET")),r){let e=i||{};e["content-type"]="application/x-www-form-urlencoded";let t=et(a).slice(1);eh(this.client.http.doUri(eq.Post,n.authUrl,e,t,s),(e,t)=>e?c(e):c(t))}else eh(this.client.http.doUri(eq.Get,n.authUrl,i||{},null,a),(e,t)=>e?c(e):c(t))};else if(n.key)I.logAction(this.logger,I.LOG_MINOR,"Auth.requestToken()","using token auth with client-side signing"),i=(e,t)=>{eh(this.createTokenRequest(e,n),(e,n)=>t(e,null!=n?n:null))};else throw I.logAction(this.logger,I.LOG_ERROR,"Auth()","library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),new P("Need a new token, but authOptions does not include any way to request one (no authUrl, authCallback, or key)",40171,403);"capability"in s&&(s.capability=eH(s.capability));let o=(e,t)=>{let s="/keys/"+e.keyName+"/requestToken",i=eT.defaultPostHeaders(this.client.options);n.requestHeaders&&N(i,n.requestHeaders),I.logAction(this.logger,I.LOG_MICRO,"Auth.requestToken().requestToken","Sending POST to "+s+"; Token params: "+JSON.stringify(e)),eh(this.client.http.do(eq.Post,function(e){return r.baseUri(e)+s},i,JSON.stringify(e),null),(e,n)=>e?t(e):t(n.error,n.body,n.unpacked))};return new Promise((e,t)=>{let r=!1,a=this.client.options.timeouts.realtimeRequestTimeout,c=setTimeout(()=>{r=!0;let e="Token request callback timed out after "+a/1e3+" seconds";I.logAction(this.logger,I.LOG_ERROR,"Auth.requestToken()",e),t(new P(e,40170,401))},a);i(s,(s,i,a)=>{if(r)return;if(clearTimeout(c),s){I.logAction(this.logger,I.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+ei(s)),t(ej(s));return}if("string"==typeof i)return void(0===i.length?t(new P("Token string is empty",40170,401)):i.length>131072?t(new P("Token string exceeded max permitted length (was "+i.length+" bytes)",40170,401)):"undefined"===i||"null"===i?t(new P("Token string was literal null/undefined",40170,401)):"{"!==i[0]||a&&a.indexOf("application/jwt")>-1?e({token:i}):t(new P("Token was double-encoded; make sure you're not JSON-encoding an already encoded token request or details",40170,401)));if("object"!=typeof i||null===i){let e="Expected token request callback to call back with a token string or token request/details object, but got a "+typeof i;I.logAction(this.logger,I.LOG_ERROR,"Auth.requestToken()",e),t(new P(e,40170,401));return}let l=JSON.stringify(i).length;if(l>131072&&!n.suppressMaxLengthCheck)return void t(new P("Token request/details object exceeded max permitted stringified size (was "+l+" bytes)",40170,401));if("issued"in i)return void e(i);if(!("keyName"in i)){let e="Expected token request callback to call back with a token string, token request object, or token details object";I.logAction(this.logger,I.LOG_ERROR,"Auth.requestToken()",e),t(new P(e,40170,401));return}o(i,(n,s,i)=>{if(n){I.logAction(this.logger,I.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+ei(n)),t(ej(n));return}i||(s=JSON.parse(s)),I.logAction(this.logger,I.LOG_MINOR,"Auth.getToken()","token received"),e(s)})})})}async createTokenRequest(e,t){let n,s,i,r;t=t||this.authOptions,e=e||U(this.tokenParams);let o=t.key;if(!o)throw new P("No key specified",40101,403);let a=o.split(":"),c=a[0],l=a[1];if(!l)throw new P("Invalid key specified",40101,403);if(""===e.clientId)throw new P("clientId canât be an empty string",40012,400);"capability"in e&&(e.capability=eH(e.capability));let h=N({keyName:c},e),u=e.clientId||"",d=e.ttl||"",g=e.capability||"";h.timestamp||(h.timestamp=await this._getTimestamp(t&&t.queryTime));let p=h.nonce||(h.nonce=("000000"+Math.floor(1e16*Math.random())).slice(-16)),f=h.timestamp,m=h.keyName+"\n"+d+"\n"+g+"\n"+u+"\n"+f+"\n"+p+"\n";return h.mac=h.mac||(s=(n=S.BufferUtils).utf8Encode(m),i=n.utf8Encode(l),r=n.hmacSha256(s,i),n.base64Encode(r)),I.logAction(this.logger,I.LOG_MINOR,"Auth.getTokenRequest()","generated signed request"),h}
1async getAuthParams(){if("basic"==this.method)return{key:this.key};{let e=await this._ensureValidAuthCredentials(!1);if(!e)throw Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{access_token:e.token}}}async getAuthHeaders(){if("basic"==this.method)return{authorization:"Basic "+this.basicKey};{let e=await this._ensureValidAuthCredentials(!1);if(!e)throw Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{authorization:"Bearer "+eC(e.token)}}}_saveBasicOptions(e){this.method="basic",this.key=e.key,this.basicKey=eC(e.key),this.authOptions=e||{},"clientId"in e&&this._userSetClientId(e.clientId)}_saveTokenOptions(e,t){this.method="token",e&&(this.tokenParams=e),t&&(t.token&&(t.tokenDetails="string"==typeof t.token?{token:t.token}:t.token),t.tokenDetails&&(this.tokenDetails=t.tokenDetails),"clientId"in t&&this._userSetClientId(t.clientId),this.authOptions=t)}async _ensureValidAuthCredentials(e){let t=this.tokenDetails;if(t){if(this._tokenClientIdMismatch(t.clientId))throw new P("Mismatch between clientId in token ("+t.clientId+") and current clientId ("+this.clientId+")",40102,403);if(!this.client.isTimeOffsetSet()||!t.expires||t.expires>=this.client.getTimestampUsingOffset())return I.logAction(this.logger,I.LOG_MINOR,"Auth.getToken()","using cached token; expires = "+t.expires),t;I.logAction(this.logger,I.LOG_MINOR,"Auth.getToken()","deleting expired token"),this.tokenDetails=null}let n=(this.waitingForTokenRequest||(this.waitingForTokenRequest=eB.create(this.logger))).createPromise();if(null!==this.currentTokenRequestId&&!e)return n;let s=this.currentTokenRequestId=eF++,i,r=null;try{i=await this.requestToken(this.tokenParams,this.authOptions)}catch(e){r=e}if(this.currentTokenRequestId>s)return I.logAction(this.logger,I.LOG_MINOR,"Auth._ensureValidAuthCredentials()","Discarding token request response; overtaken by newer one"),n;this.currentTokenRequestId=null;let o=this.waitingForTokenRequest;return(this.waitingForTokenRequest=null,r)?null==o||o.rejectAll(r):null==o||o.resolveAll(this.tokenDetails=i),n}_userSetClientId(e){if("string"!=typeof e&&null!==e)throw new P("clientId must be either a string or null",40012,400);if("*"===e)throw new P('Canât use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, instantiate the library with {defaultTokenParams: {clientId: "*"}}), or if calling authorize(), pass it in as a tokenParam: authorize({clientId: "*"}, authOptions)',40012,400);{let t=this._uncheckedSetClientId(e);if(t)throw t}}_uncheckedSetClientId(e){if(!this._tokenClientIdMismatch(e))return this.clientId=this.tokenParams.clientId=e,null;{let t="Unexpected clientId mismatch: client has "+this.clientId+", requested "+e,n=new P(t,40102,401);return I.logAction(this.logger,I.LOG_ERROR,"Auth._uncheckedSetClientId()",t),n}}_tokenClientIdMismatch(e){return!!(this.clientId&&"*"!==this.clientId&&e&&"*"!==e&&this.clientId!==e)}static isTokenErr(e){return e.code&&e.code>=40140&&e.code<40150}revokeTokens(e,t){return this.client.rest.revokeTokens(e,t)}async _getTimestamp(e){return this.client.getTimestamp(e||!!this.authOptions.queryTime)}};function ez(e){let t=[];if(e)for(let n in e)t.push(n+"="+e[n]);return t.join("&")}function e$(e,t){return e+(t?"?":"")+ez(t)}var eK=class{constructor(e){this.client=e,this.platformHttp=new S.Http(e),this.checkConnectivity=this.platformHttp.checkConnectivity?()=>this.platformHttp.checkConnectivity():void 0}get logger(){var e,t;return null!=(t=null==(e=this.client)?void 0:e.logger)?t:I.defaultLogger}get supportsAuthHeaders(){return this.platformHttp.supportsAuthHeaders}get supportsLinkHeaders(){return this.platformHttp.supportsLinkHeaders}_getHosts(e){let t=e.connection,n=t&&t.connectionManager.host;return n?[n].concat(eT.getFallbackHosts(e.options)):eT.getHosts(e.options)}async do(e,t,n,s,i){try{let r=this.client;if(!r)return{error:new P("http.do called without client",5e4,500)};let o="function"==typeof t?t:function(e){return r.baseUri(e)+t},a=r._currentFallback;if(a)if(a.validUntil>Date.now()){let c=await this.doUri(e,o(a.host),n,s,i);if(c.error&&this.platformHttp.shouldFallback(c.error))return r._currentFallback=null,this.do(e,t,n,s,i);return c}else r._currentFallback=null;
1let c=this._getHosts(r);if(1===c.length)return this.doUri(e,o(c[0]),n,s,i);let l=null,h=async(t,a)=>{let c=t.shift();l=null!=l?l:new Date;let u=await this.doUri(e,o(c),n,s,i);return u.error&&this.platformHttp.shouldFallback(u.error)&&t.length?Date.now()-l.getTime()>r.options.timeouts.httpMaxRetryDuration?{error:new P(`Timeout for trying fallback hosts retries. Total elapsed time exceeded the ${r.options.timeouts.httpMaxRetryDuration}ms limit`,50003,500)}:h(t,!0):(a&&(r._currentFallback={host:c,validUntil:Date.now()+r.options.timeouts.fallbackRetryTimeout}),u)};return h(c)}catch(e){return{error:new P(`Unexpected error in Http.do: ${ei(e)}`,500,5e4)}}}async doUri(e,t,n,s,i){try{var r,o;(r=this.logger).shouldLog(I.LOG_MICRO)&&I.logActionNoStrip(r,I.LOG_MICRO,"Http."+e+"()","Sending; "+e$(t,i)+"; Body"+(S.BufferUtils.isBuffer(s)?" (Base64): "+S.BufferUtils.base64Encode(s):": "+s));let a=await this.platformHttp.doUri(e,t,n,s,i);return this.logger.shouldLog(I.LOG_MICRO)&&(o=this.logger,a.error?I.logActionNoStrip(o,I.LOG_MICRO,"Http."+e+"()","Received Error; "+e$(t,i)+"; Error: "+ei(a.error)):I.logActionNoStrip(o,I.LOG_MICRO,"Http."+e+"()","Received; "+e$(t,i)+"; Headers: "+ez(a.headers)+"; StatusCode: "+a.statusCode+"; Body"+(S.BufferUtils.isBuffer(a.body)?" (Base64): "+S.BufferUtils.base64Encode(a.body):": "+a.body))),a}catch(e){return{error:new P(`Unexpected error in Http.doUri: ${ei(e)}`,500,5e4)}}}};function eQ(e,t,n){let s,i,r;for(let o=0;o<e.length;o++)if(s=e[o],n&&(s=s[n]),Array.isArray(s)){for(;-1!==(i=s.indexOf(t));)s.splice(i,1);n&&0===s.length&&delete e[o][n]}else if(G(s))for(r in s)Object.prototype.hasOwnProperty.call(s,r)&&Array.isArray(s[r])&&eQ([s],t,r)}var eX=class{constructor(e){this.logger=e,this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null)}on(...e){if(1===e.length){let t=e[0];if("function"==typeof t)this.any.push(t);else throw Error("EventListener.on(): Invalid arguments: "+S.Config.inspect(e))}if(2===e.length){let[t,n]=e;if("function"!=typeof n)throw Error("EventListener.on(): Invalid arguments: "+S.Config.inspect(e));if(q(t))this.any.push(n);else if(Array.isArray(t))t.forEach(e=>{this.on(e,n)});else{if("string"!=typeof t)throw Error("EventListener.on(): Invalid arguments: "+S.Config.inspect(e));(this.events[t]||(this.events[t]=[])).push(n)}}}off(...e){if(0==e.length||q(e[0])&&q(e[1])){this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null);return}let[t,n]=e,s=null,i=null;if(1!==e.length&&n){if("function"!=typeof n)throw Error("EventEmitter.off(): invalid arguments:"+S.Config.inspect(e));[i,s]=[t,n]}else"function"==typeof t?s=t:i=t;if(s&&q(i))return void eQ([this.any,this.events,this.anyOnce,this.eventsOnce],s);if(Array.isArray(i))return void i.forEach(e=>{this.off(e,s)});if("string"!=typeof i)throw Error("EventEmitter.off(): invalid arguments:"+S.Config.inspect(e));s?eQ([this.events,this.eventsOnce],s,i):(delete this.events[i],delete this.eventsOnce[i])}listeners(e){if(e){let t=this.events[e]||[];return this.eventsOnce[e]&&Array.prototype.push.apply(t,this.eventsOnce[e]),t.length?t:null}return this.any.length?this.any:null}emit(e,...t){let n={event:e},s=[];this.anyOnce.length&&(Array.prototype.push.apply(s,this.anyOnce),this.anyOnce=[]),this.any.length&&Array.prototype.push.apply(s,this.any);let i=this.eventsOnce[e];i&&(Array.prototype.push.apply(s,i),delete this.eventsOnce[e]);let r=this.events[e];r&&Array.prototype.push.apply(s,r),s.forEach(e=>{var s=this.logger;try{e.apply(n,t)}catch(e){I.logAction(s,I.LOG_ERROR,"EventEmitter.emit()","Unexpected listener exception: "+e+"; stack = "+(e&&e.stack))}})}once(...e){let t=e.length;if(0===t||1===t&&"function"!=typeof e[0]){let t=e[0];return new Promise(e=>{this.once(t,e)})}let[n,s]=e;if(1===e.length&&"function"==typeof n)this.anyOnce.push(n);else if(q(n)){if("function"!=typeof s)throw Error("EventEmitter.once(): Invalid arguments:"+S.Config.inspect(e));this.anyOnce.push(s)}else if(Array.isArray(n)){let t=this,i=function(){let r=Array.prototype.slice.call(arguments);if(n.forEach(function(e){t.off(e,i)}),"function"!=typeof s)throw Error("EventEmitter.once(): Invalid arguments:"+S.Config.inspect(e));s.apply(this,r)};
1n.forEach(function(e){t.on(e,i)})}else{if("string"!=typeof n)throw Error("EventEmitter.once(): Invalid arguments:"+S.Config.inspect(e));let t=this.eventsOnce[n]||(this.eventsOnce[n]=[]);if(s){if("function"!=typeof s)throw Error("EventEmitter.once(): Invalid arguments:"+S.Config.inspect(e));t.push(s)}}}async whenState(e,t){if("string"!=typeof e||"string"!=typeof t)throw Error("whenState requires a valid state String argument");return e===t?null:this.once(e)}},eY={HEARTBEAT:0,ACK:1,NACK:2,CONNECT:3,CONNECTED:4,DISCONNECT:5,DISCONNECTED:6,CLOSE:7,CLOSED:8,ERROR:9,ATTACH:10,ATTACHED:11,DETACH:12,DETACHED:13,PRESENCE:14,MESSAGE:15,SYNC:16,AUTH:17,ACTIVATE:18,OBJECT:19,OBJECT_SYNC:20,ANNOTATION:21},eZ=[];Object.keys(eY).forEach(function(e){eZ[eY[e]]=e});var e0={HAS_PRESENCE:1,HAS_BACKLOG:2,RESUMED:4,TRANSIENT:16,ATTACH_RESUME:32,HAS_OBJECTS:128,PRESENCE:65536,PUBLISH:131072,SUBSCRIBE:262144,PRESENCE_SUBSCRIBE:524288,ANNOTATION_PUBLISH:2097152,ANNOTATION_SUBSCRIBE:4194304,OBJECT_SUBSCRIBE:0x1000000,OBJECT_PUBLISH:0x2000000},e1=Object.keys(e0);e0.MODE_ALL=e0.PRESENCE|e0.PUBLISH|e0.SUBSCRIBE|e0.PRESENCE_SUBSCRIBE|e0.ANNOTATION_PUBLISH|e0.ANNOTATION_SUBSCRIBE|e0.OBJECT_SUBSCRIBE|e0.OBJECT_PUBLISH;var e4=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE","ANNOTATION_PUBLISH","ANNOTATION_SUBSCRIBE","OBJECT_SUBSCRIBE","OBJECT_PUBLISH"];function e2(e,t,n){if(n&&n.cipher){e||eA("Crypto");let s=e.getCipher(n.cipher,t);return{cipher:s.cipherParams,channelCipher:s.cipher}}return null!=n?n:{}}async function e8(e,t){let{data:n,encoding:s}=await e3(e.data,e.encoding,t);return e.data=n,e.encoding=s,e}async function e3(e,t,n){let s=n.channelCipher,i=e,r=t?t+"/":"";return S.BufferUtils.isBuffer(i)||(i=S.BufferUtils.utf8Encode(String(i)),r+="utf-8/"),{data:await s.encrypt(i),encoding:r=r+"cipher+"+s.algorithm}}async function e6(e,t){let{data:n,encoding:s}=e5(e.data,e.encoding);return(e.data=n,e.encoding=s,null!=t&&t.cipher)?e8(e,t):e}function e5(e,t){if("string"==typeof e||S.BufferUtils.isBuffer(e)||null==e)return{data:e,encoding:t};if(G(e)||Array.isArray(e))return{data:JSON.stringify(e),encoding:t?t+"/json":"json"};throw new P("Data type is unsupported",40013,400)}async function e9(e,t){let{data:n,encoding:s,error:i}=await e7(e.data,e.encoding,t);if(e.data=n,e.encoding=s,i)throw i}async function e7(e,t,n){let s,i=n&&n.channelOptions?n:{channelOptions:n,plugins:{},baseEncodedPreviousPayload:void 0},r=e,o=e,a=t;if(t){let e,n=t.split("/"),c=n.length,l="";try{for(;(e=c)>0;){let t=n[--c].match(/([-\w]+)(\+([\w-]+))?/);if(!t)break;switch(l=t[1]){case"base64":o=S.BufferUtils.base64Decode(String(o)),e==n.length&&(r=o);continue;case"utf-8":o=S.BufferUtils.utf8Decode(o);continue;case"json":o=JSON.parse(o);continue;case"cipher":if(null!=i.channelOptions&&i.channelOptions.cipher&&i.channelOptions.channelCipher){let e=t[3],n=i.channelOptions.channelCipher;if(e!=n.algorithm)throw Error("Unable to decrypt message with given cipher; incompatible cipher params");o=await n.decrypt(o);continue}throw Error("Unable to decrypt message; not an encrypted channel");case"vcdiff":if(!i.plugins||!i.plugins.vcdiff)throw new P("Missing Vcdiff decoder (https://github.com/ably-forks/vcdiff-decoder)",40019,400);if("undefined"==typeof Uint8Array)throw new P("Delta decoding not supported on this browser (need ArrayBuffer & Uint8Array)",40020,400);try{let e=i.baseEncodedPreviousPayload;"string"==typeof e&&(e=S.BufferUtils.utf8Encode(e));let t=S.BufferUtils.toBuffer(e);o=S.BufferUtils.toBuffer(o),r=o=S.BufferUtils.arrayBufferViewToBuffer(i.plugins.vcdiff.decode(o,t))}catch(e){throw new P("Vcdiff delta decode failed with "+e,40018,400)}continue;default:throw Error("Unknown encoding")}}}catch(e){s=new P(`Error processing the ${l} encoding, decoder returned \u2018${e.message}\u2019`,e.code||40013,400)}finally{a=e<=0?null:n.slice(0,e).join("/")}}return s?{error:s,data:o,encoding:a}:(i.baseEncodedPreviousPayload=r,{data:o,encoding:a})}function te(...e){let t=e.length>0?"json":"msgpack",{data:n,encoding:s}=tt(this.data,this.encoding,t);return Object.assign({},this,{encoding:s,data:n})}function tt(e,t,n){return e&&S.BufferUtils.isBuffer(e)?"msgpack"===n?{data:S.BufferUtils.toBuffer(e),encoding:t}:{data:S.BufferUtils.base64Encode(e),encoding:t?t+"/base64":"base64"}:{data:e,encoding:t}}var tn={encryptData:e3,encodeData:e5,encodeDataForWire:tt,decodeData:e7};function ts(e){let t,{id:n,connectionId:s,timestamp:i}=e;switch(e.action){case eY.MESSAGE:t=e.messages;break;case eY.PRESENCE:case eY.SYNC:t=e.presence;break;case eY.ANNOTATION:t=e.annotations;break;case eY.OBJECT:case eY.OBJECT_SYNC:t=e.state;break;default:throw new P("Unexpected action "+e.action,4e4,400)}for(let e=0;e<t.length;e++){let r=t[e];r.connectionId||(r.connectionId=s),r.timestamp||(r.timestamp=i),n&&!r.id&&(r.id=n+":"+e)}}function ti(e,t){let n="["+t;for(let t in e)"data"===t?"string"==typeof e.data?n+="; data="+e.data:S.BufferUtils.isBuffer(e.data)?n+="; data (buffer)="+S.BufferUtils.base64Encode(e.data):void 0!==e.data&&(n+="; data (json)="+JSON.stringify(e.data)):t&&("extras"===t||"operation"===t)?n+="; "+t+"="+JSON.stringify(e[t]):"version"===t?n+="; version="+JSON.stringify(e[t]):"annotations"===t?n+="; annotations="+JSON.stringify(e[t]):void 0!==e[t]&&(n+="; "+t+"="+e[t]);return n+"]"}var tr=class{},to=class{constructor(e){var t,n,s,i,r,o,a,c,l,h;this.Platform=S,this.ErrorInfo=P,this.Logger=I,this.Defaults=eT,this.Utils=_,this.EventEmitter=eX,this.MessageEncoding=tn,this._additionalHTTPRequestImplementations=null!=(t=e.plugins)?t:null,this.logger=new I,this.logger.setLog(e.logLevel,e.logHandler),I.logAction(this.logger,I.LOG_MICRO,"BaseClient()","initialized with clientOptions "+S.Config.inspect(e)),this._MsgPack=null!=(s=null==(n=e.plugins)?void 0:n.MsgPack)?s:null;const u=this.options=eT.normaliseOptions(e,this._MsgPack,this.logger);
1if(u.key){const e=u.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!e){const e="invalid key parameter";throw I.logAction(this.logger,I.LOG_ERROR,"BaseClient()",e),new P(e,40400,404)}u.keyName=e[1],u.keySecret=e[2]}if("clientId"in u){if("string"!=typeof u.clientId&&null!==u.clientId)throw new P("clientId must be either a string or null",40012,400);else if("*"===u.clientId)throw new P('Canât use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, use {defaultTokenParams: {clientId: "*"}})',40012,400)}I.logAction(this.logger,I.LOG_MINOR,"BaseClient()","started; version = "+eT.version),this._currentFallback=null,this.serverTimeOffset=null,this.http=new eK(this),this.auth=new eJ(this,u),this._rest=(null==(i=e.plugins)?void 0:i.Rest)?new e.plugins.Rest(this):null,this._Crypto=null!=(o=null==(r=e.plugins)?void 0:r.Crypto)?o:null,this.__FilteredSubscriptions=null!=(c=null==(a=e.plugins)?void 0:a.MessageInteractions)?c:null,this._Annotations=null!=(h=null==(l=e.plugins)?void 0:l.Annotations)?h:null}get rest(){return this._rest||eA("Rest"),this._rest}get _FilteredSubscriptions(){return this.__FilteredSubscriptions||eA("MessageInteractions"),this.__FilteredSubscriptions}get channels(){return this.rest.channels}get push(){return this.rest.push}device(){var e;return(null==(e=this.options.plugins)?void 0:e.Push)&&this.push.LocalDevice||eA("Push"),this._device||(this._device=this.push.LocalDevice.load(this)),this._device}baseUri(e){return eT.getHttpScheme(this.options)+e+":"+eT.getPort(this.options,!1)}async stats(e){return this.rest.stats(e)}async time(e){return this.rest.time(e)}async request(e,t,n,s,i,r){return this.rest.request(e,t,n,s,i,r)}batchPublish(e){return this.rest.batchPublish(e)}batchPresence(e){return this.rest.batchPresence(e)}setLog(e){this.logger.setLog(e.level,e.handler)}async getTimestamp(e){return!this.isTimeOffsetSet()&&e?this.time():this.getTimestampUsingOffset()}getTimestampUsingOffset(){return Date.now()+(this.serverTimeOffset||0)}isTimeOffsetSet(){return null!==this.serverTimeOffset}};to.Platform=S;var ta=to,tc=class e{toJSON(){var e,t,n;return{id:this.id,deviceSecret:this.deviceSecret,platform:this.platform,formFactor:this.formFactor,clientId:this.clientId,metadata:this.metadata,deviceIdentityToken:this.deviceIdentityToken,push:{recipient:null==(e=this.push)?void 0:e.recipient,state:null==(t=this.push)?void 0:t.state,error:null==(n=this.push)?void 0:n.error}}}toString(){var e,t,n,s;let i="[DeviceDetails";return this.id&&(i+="; id="+this.id),this.platform&&(i+="; platform="+this.platform),this.formFactor&&(i+="; formFactor="+this.formFactor),this.clientId&&(i+="; clientId="+this.clientId),this.metadata&&(i+="; metadata="+this.metadata),this.deviceIdentityToken&&(i+="; deviceIdentityToken="+JSON.stringify(this.deviceIdentityToken)),(null==(e=this.push)?void 0:e.recipient)&&(i+="; push.recipient="+JSON.stringify(this.push.recipient)),(null==(t=this.push)?void 0:t.state)&&(i+="; push.state="+this.push.state),(null==(n=this.push)?void 0:n.error)&&(i+="; push.error="+JSON.stringify(this.push.error)),(null==(s=this.push)?void 0:s.metadata)&&(i+="; push.metadata="+this.push.metadata),i+="]"}static toRequestBody(e,t,n){return ed(e,t,n)}static fromResponseBody(t,n,s){return(s&&(t=eu(t,n,s)),Array.isArray(t))?e.fromValuesArray(t):e.fromValues(t)}static fromValues(t){return t.error=t.error&&P.fromValues(t.error),Object.assign(new e,t)}static fromLocalDevice(t){return Object.assign(new e,t)}static fromValuesArray(t){let n=t.length,s=Array(n);for(let i=0;i<n;i++)s[i]=e.fromValues(t[i]);return s}};async function tl(e,t,n,s){return e.http.supportsAuthHeaders?s(N(await e.auth.getAuthHeaders(),t),n):s(t,N(await e.auth.getAuthParams(),n))}var th=class e{static async get(t,n,s,i,r,o){return e.do(eq.Get,t,n,null,s,i,r,null!=o&&o)}static async delete(t,n,s,i,r,o){return e.do(eq.Delete,t,n,null,s,i,r,o)}static async post(t,n,s,i,r,o,a){return e.do(eq.Post,t,n,s,i,r,o,a)}static async patch(t,n,s,i,r,o,a){return e.do(eq.Patch,t,n,s,i,r,o,a)}static async put(t,n,s,i,r,o,a){return e.do(eq.Put,t,n,s,i,r,o,a)}static async do(e,t,n,s,i,r,o,a){var c,l;o&&((r=r||{}).envelope=o);let h=t.logger;async function u(i,r){var o;if(h.shouldLog(I.LOG_MICRO)){let a=s;if((null==(o=i["content-type"])?void 0:o.indexOf("msgpack"))>0)try{t._MsgPack||eA("MsgPack"),a=t._MsgPack.decode(s)}catch(t){I.logAction(h,I.LOG_MICRO,"Resource."+e+"()","Sending MsgPack Decoding Error: "+ei(t))}I.logAction(h,I.LOG_MICRO,"Resource."+e+"()","Sending; "+e$(n,r)+"; Body: "+a)}let a=await t.http.do(e,n,i,s,r);return a.error&&eJ.isTokenErr(a.error)?(await t.auth.authorize(null,null),tl(t,i,r,u)):{err:a.error,body:a.body,headers:a.headers,unpacked:a.unpacked,statusCode:a.statusCode}}let d=await tl(t,i,r,u);if(o&&(d=function(e,t,n){if(e.err&&!e.body)return{err:e.err};if(e.statusCode===eD.NoContent)return p(w({},e),m({body:[],unpacked:!0}));let s=e.body;if(!e.unpacked)try{s=eu(s,t,n)}catch(e){if(es(e))return{err:e};return{err:new L(ei(e),null)}}if(!s)return{err:new L("unenvelope(): Response body is missing",null)};let{statusCode:i,response:r,headers:o}=s;if(void 0===i)return p(w({},e),m({body:s,unpacked:!0}));if(i<200||i>=300){let t=r&&r.error||e.err;return t||((t=Error("Error in unenveloping "+s)).statusCode=i),{err:t,body:r,headers:o,unpacked:!0,statusCode:i}}return{err:e.err,body:r,headers:o,unpacked:!0,statusCode:i}}(d,t._MsgPack,o)),h.shouldLog(I.LOG_MICRO)&&(c=d,l=r,c.err?I.logAction(h,I.LOG_MICRO,"Resource."+e+"()","Received Error; "+e$(n,l)+"; Error: "+ei(c.err)):I.logAction(h,I.LOG_MICRO,"Resource."+e+"()","Received; "+e$(n,l)+"; Headers: "+ez(c.headers)+"; StatusCode: "+c.statusCode+"; Body: "+(S.BufferUtils.isBuffer(c.body)?" (Base64): "+S.BufferUtils.base64Encode(c.body):": "+S.Config.inspect(c.body)))),a)if(d.err)throw d.err;else{let e=w({},d);return delete e.err,e}return d}},tu=class{constructor(e,t,n,s,i,r){this.client=e,this.path=t,this.headers=n,this.envelope=null!=s?s:null,this.bodyHandler=i,this.useHttpPaginatedResponse=r||!1}get logger(){return this.client.logger}async get(e){let t=await th.get(this.client,this.path,this.headers,e,this.envelope,!1);return this.handlePage(t)}async delete(e){let t=await th.delete(this.client,this.path,this.headers,e,this.envelope,!1);return this.handlePage(t)}async post(e,t){let n=await th.post(this.client,this.path,t,this.headers,e,this.envelope,!1);return this.handlePage(n)}async put(e,t){let n=await th.put(this.client,this.path,t,this.headers,e,this.envelope,!1);return this.handlePage(n)}async patch(e,t){let n=await th.patch(this.client,this.path,t,this.headers,e,this.envelope,!1);return this.handlePage(n)}async handlePage(e){var t,n;let s,i,r;if(e.err&&(t=e.err,n=e.body,!(this.useHttpPaginatedResponse&&(n||"number"==typeof t.code))))throw I.logAction(this.logger,I.LOG_ERROR,"PaginatedResource.handlePage()","Unexpected error getting resource: err = "+ei(e.err)),e.err;try{s=e.statusCode==eD.NoContent?[]:await this.bodyHandler(e.body,e.headers||{},e.unpacked)}catch(t){throw e.err||t}return(e.headers&&(i=e.headers.Link||e.headers.link)&&(r=function(e){"string"==typeof e&&(e=e.split(","));let t={};for(let n=0;n<e.length;n++){let s=e[n].match(/^\s*<(.+)>;\s*rel="(\w+)"$/);if(s){let e=function(e){let t=e.match(/^\.\/(\w+)\?(.*)$/);return t&&t[2]&&en(t[2])}(s[1]);e&&(t[s[2]]=e)}}return t}(i)),this.useHttpPaginatedResponse)?new tg(this,s,e.headers||{},e.statusCode,r,e.err):new td(this,s,r)}},td=class{constructor(e,t,n){this.resource=e,this.items=t,this._relParams=n}async first(){if(this.hasFirst())return this.get(this._relParams.first);throw new P("No link to the first page of results",40400,404)}async current(){if(this.hasCurrent())return this.get(this._relParams.current);throw new P("No link to the current page of results",40400,404)}async next(){return this.hasNext()?this.get(this._relParams.next):null}hasFirst(){return null!=this._relParams&&"first"in this._relParams}hasCurrent(){return null!=this._relParams&&"current"in this._relParams}hasNext(){return null!=this._relParams&&"next"in this._relParams}isLast(){return!this.hasNext()}async get(e){let t=this.resource,n=await th.get(t.client,t.path,t.headers,e,t.envelope,!1);return t.handlePage(n)}},tg=class extends td{constructor(e,t,n,s,i,r){super(e,t,i),this.statusCode=s,this.success=s<300&&s>=200,this.headers=n,this.errorCode=r&&r.code,this.errorMessage=r&&r.message}toJSON(){return{items:this.items,statusCode:this.statusCode,success:this.success,headers:this.headers,errorCode:this.errorCode,errorMessage:this.errorMessage}}},tp=class e{toJSON(){return{channel:this.channel,deviceId:this.deviceId,clientId:this.clientId}}toString(){let e="[PushChannelSubscription";return this.channel&&(e+="; channel="+this.channel),this.deviceId&&(e+="; deviceId="+this.deviceId),this.clientId&&(e+="; clientId="+this.clientId),e+="]"}static fromResponseBody(t,n,s){return(s&&(t=eu(t,n,s)),Array.isArray(t))?e.fromValuesArray(t):e.fromValues(t)}static fromValues(t){return Object.assign(new e,t)}static fromValuesArray(t){let n=t.length,s=Array(n);for(let i=0;i<n;i++)s[i]=e.fromValues(t[i]);return s}};tp.toRequestBody=ed;var tf=class{constructor(e){var t;this.client=e,this.admin=new tm(e),S.Config.push&&(null==(t=e.options.plugins)?void 0:t.Push)&&(this.stateMachine=new e.options.plugins.Push.ActivationStateMachine(e),this.LocalDevice=e.options.plugins.Push.localDeviceFactory(tc))}async activate(e,t){await new Promise((n,s)=>{var i;(null==(i=this.client.options.plugins)?void 0:i.Push)?this.stateMachine?this.stateMachine.activatedCallback?s(new P("Activation already in progress",4e4,400)):(this.stateMachine.activatedCallback=e=>{e?s(e):n()},this.stateMachine.updateFailedCallback=t,this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledActivate(this.stateMachine,e))):s(new P("This platform is not supported as a target of push notifications",4e4,400)):s(eR("Push"))})}async deactivate(e){await new Promise((t,n)=>{var s;(null==(s=this.client.options.plugins)?void 0:s.Push)?this.stateMachine?this.stateMachine.deactivatedCallback?n(new P("Deactivation already in progress",4e4,400)):(this.stateMachine.deactivatedCallback=e=>{e?n(e):t()},this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledDeactivate(this.stateMachine,e))):n(new P("This platform is not supported as a target of push notifications",4e4,400)):n(eR("Push"))})}},tm=class{constructor(e){this.client=e,this.deviceRegistrations=new ty(e),this.channelSubscriptions=new tb(e)}async publish(e,t){let n=this.client,s=n.options.useBinaryProtocol?"msgpack":"json",i=eT.defaultPostHeaders(n.options,{format:s}),r={},o=N({recipient:e},t);N(i,n.options.headers),n.options.pushFullWait&&N(r,{fullWait:"true"});let a=ed(o,n._MsgPack,s);await th.post(n,"/push/publish",a,i,r,null,!0)}},ty=class{constructor(e){this.client=e}async save(e){let t=this.client,n=tc.fromValues(e),s=t.options.useBinaryProtocol?"msgpack":"json",i=eT.defaultPostHeaders(t.options,{format:s}),r={};N(i,t.options.headers),t.options.pushFullWait&&N(r,{fullWait:"true"});let o=ed(n,t._MsgPack,s),a=await th.put(t,"/push/deviceRegistrations/"+encodeURIComponent(e.id),o,i,r,null,!0);return tc.fromResponseBody(a.body,t._MsgPack,a.unpacked?void 0:s)}async get(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=eT.defaultGetHeaders(t.options,{format:n}),i=e.id||e;if("string"!=typeof i||!i.length)throw new P("First argument to DeviceRegistrations#get must be a deviceId string or DeviceDetails",4e4,400);N(s,t.options.headers);let r=await th.get(t,"/push/deviceRegistrations/"+encodeURIComponent(i),s,{},null,!0);return tc.fromResponseBody(r.body,t._MsgPack,r.unpacked?void 0:n)}async list(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=this.client.http.supportsLinkHeaders?void 0:n,i=eT.defaultGetHeaders(t.options,{format:n});return N(i,t.options.headers),new tu(t,"/push/deviceRegistrations",i,s,async function(e,s,i){return tc.fromResponseBody(e,t._MsgPack,i?void 0:n)}).get(e)}async remove(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=eT.defaultGetHeaders(t.options,{format:n}),i={},r=e.id||e;if("string"!=typeof r||!r.length)throw new P("First argument to DeviceRegistrations#remove must be a deviceId string or DeviceDetails",4e4,400);N(s,t.options.headers),t.options.pushFullWait&&N(i,{fullWait:"true"}),await th.delete(t,"/push/deviceRegistrations/"+encodeURIComponent(r),s,i,null,!0)}async removeWhere(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=eT.defaultGetHeaders(t.options,{format:n});N(s,t.options.headers),t.options.pushFullWait&&N(e,{fullWait:"true"}),await th.delete(t,"/push/deviceRegistrations",s,e,null,!0)}},tb=class e{constructor(t){this.remove=e.prototype.removeWhere,this.client=t}async save(e){let t=this.client,n=tp.fromValues(e),s=t.options.useBinaryProtocol?"msgpack":"json",i=eT.defaultPostHeaders(t.options,{format:s}),r={};N(i,t.options.headers),t.options.pushFullWait&&N(r,{fullWait:"true"});let o=ed(n,t._MsgPack,s),a=await th.post(t,"/push/channelSubscriptions",o,i,r,null,!0);return tp.fromResponseBody(a.body,t._MsgPack,a.unpacked?void 0:s)}async list(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=this.client.http.supportsLinkHeaders?void 0:n,i=eT.defaultGetHeaders(t.options,{format:n});return N(i,t.options.headers),new tu(t,"/push/channelSubscriptions",i,s,async function(e,s,i){return tp.fromResponseBody(e,t._MsgPack,i?void 0:n)}).get(e)}async removeWhere(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=eT.defaultGetHeaders(t.options,{format:n});N(s,t.options.headers),t.options.pushFullWait&&N(e,{fullWait:"true"}),await th.delete(t,"/push/channelSubscriptions",s,e,null,!0)}async listChannels(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=this.client.http.supportsLinkHeaders?void 0:n,i=eT.defaultGetHeaders(t.options,{format:n});return N(i,t.options.headers),t.options.pushFullWait&&N(e,{fullWait:"true"}),new tu(t,"/push/channels",i,s,async function(e,s,i){let r=!i&&n?eu(e,t._MsgPack,n):e;for(let e=0;e<r.length;e++)r[e]=String(r[e]);return r}).get(e)}},tv=["absent","present","enter","leave","update"];async function tO(e,t,n,s){let i=e2(t,e,null!=s?s:null);return tS.fromValues(n).decode(i,e)}async function tC(e,t,n,s){return Promise.all(n.map(function(n){return tO(e,t,n,s)}))}async function tw(e,t){return tS.fromValues(e).decode(t.channelOptions,t.logger)}async function tR(e,t){return Promise.all(e.map(function(e){return tw(e,t)}))}var tA=class e extends tr{isSynthesized(){return!this.id||!this.connectionId||this.id.substring(this.connectionId.length,0)!==this.connectionId}parseId(){if(!this.id)throw Error("parseId(): Presence message does not contain an id");let e=this.id.split(":");return{connectionId:e[0],msgSerial:parseInt(e[1],10),index:parseInt(e[2],10)}}async encode(e){return e6(Object.assign(new tS,this,{action:tv.indexOf(this.action||"present")}),e)}static fromValues(t){return Object.assign(new e,t)}static fromValuesArray(t){return t.map(t=>e.fromValues(t))}static fromData(t){return t instanceof e?t:e.fromValues({data:t})}toString(){return ti(this,"PresenceMessage")}},tS=class e extends tr{toJSON(...e){return te.call(this,...e)}static fromValues(t){return Object.assign(new e,t)}static fromValuesArray(t){return t.map(t=>e.fromValues(t))}async decode(e,t){let n=Object.assign(new tA,p(w({},this),m({action:tv[this.action]})));try{await e9(n,e)}catch(e){I.logAction(t,I.LOG_ERROR,"WirePresenceMessage.decode()",ei(e))}return n}toString(){return ti(this,"WirePresenceMessage")}},tk=tA,tT=class{constructor(e){this.channel=e}get logger(){return this.channel.logger}async get(e){I.logAction(this.logger,I.LOG_MICRO,"RestPresence.get()","channel = "+this.channel.name);let t=this.channel.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=this.channel.client.http.supportsLinkHeaders?void 0:n,i=eT.defaultGetHeaders(t.options,{format:n});return N(i,t.options.headers),new tu(t,this.channel.client.rest.presenceMixin.basePath(this),i,s,async(e,s,i)=>
1tR(i?e:eu(e,t._MsgPack,n),this.channel)).get(e)}async history(e){return I.logAction(this.logger,I.LOG_MICRO,"RestPresence.history()","channel = "+this.channel.name),this.channel.client.rest.presenceMixin.history(this,e)}},tM=["message.create","message.update","message.delete","meta","message.summary"];async function tI(e,t,n,s){let i=e2(t,e,null!=s?s:null);return tx.fromValues(n).decode(i,e)}async function t_(e,t,n,s){return Promise.all(n.map(function(n){return tI(e,t,n,s)}))}async function tE(e,t){return tx.fromValues(e).decode(t.channelOptions,t.logger)}async function tP(e,t){return Promise.all(e.map(function(e){return tE(e,t)}))}async function tL(e,t){return Promise.all(e.map(e=>e.encode(t)))}function tN(e){let t,n=0;for(let s=0;s<e.length;s++)n+=(t=e[s]).size||(t.size=function(e){let t=0;return e.name&&(t+=e.name.length),e.clientId&&(t+=e.clientId.length),e.extras&&(t+=JSON.stringify(e.extras).length),e.data&&(t+=eo(e.data)),t}(t));return n}var tU=class e extends tr{expandFields(){if(this.version||(this.version={}),!this.version.serial&&this.serial&&(this.version.serial=this.serial),!this.version.timestamp&&this.timestamp&&(this.version.timestamp=this.timestamp),this.annotations?this.annotations.summary||(this.annotations.summary={}):this.annotations={summary:{}},this.annotations&&this.annotations.summary)for(let[e,t]of Object.entries(this.annotations.summary))if(e.endsWith(":distinct.v1")||e.endsWith(":unique.v1")||e.endsWith(":multiple.v1"))for(let[,e]of Object.entries(t))e.clipped||(e.clipped=!1);else e.endsWith(":flag.v1")&&!t.clipped&&(t.clipped=!1)}async encode(e){return e6(Object.assign(new tx,this,{action:tM.indexOf(this.action||"message.create")}),e)}static fromValues(t){return Object.assign(new e,t)}static fromValuesArray(t){return t.map(t=>e.fromValues(t))}toString(){return ti(this,"Message")}},tx=class e extends tr{toJSON(...e){return te.call(this,...e)}static fromValues(t){return Object.assign(new e,t)}static fromValuesArray(t){return t.map(t=>e.fromValues(t))}async decodeWithErr(e,t){let n,s=Object.assign(new tU,p(w({},this),m({action:tM[this.action||0]||"unknown"})));try{await e9(s,e)}catch(e){I.logAction(t,I.LOG_ERROR,"WireMessage.decode()",ei(e)),n=e}return s.expandFields(),{decoded:s,err:n}}async decode(e,t){let{decoded:n}=await this.decodeWithErr(e,t);return n}toString(){return ti(this,"WireMessage")}},tG=tU,tB=class{constructor(e,t,n){var s,i;this._annotations=null,I.logAction(e.logger,I.LOG_MINOR,"RestChannel()","started; name = "+t),this.name=t,this.client=e,this.presence=new tT(this),this.channelOptions=eU(null!=(s=e._Crypto)?s:null,this.logger,n),(null==(i=e.options.plugins)?void 0:i.Push)&&(this._push=new e.options.plugins.Push.PushChannel(this)),e._Annotations&&(this._annotations=new e._Annotations.RestAnnotations(this))}get annotations(){return this._annotations||eA("Annotations"),this._annotations}get push(){return this._push||eA("Push"),this._push}get logger(){return this.client.logger}setOptions(e){var t;this.channelOptions=eU(null!=(t=this.client._Crypto)?t:null,this.logger,e)}async history(e){return I.logAction(this.logger,I.LOG_MICRO,"RestChannel.history()","channel = "+this.name),this.client.rest.channelMixin.history(this,e)}async publish(...e){let t,n,s=e[0],i=e[1];if("string"==typeof s||null===s)t=[tG.fromValues({name:s,data:i})],n=e[2];else if(G(s))t=[tG.fromValues(s)],n=e[1];else if(Array.isArray(s))t=tG.fromValuesArray(s),n=e[1];else throw new P("The single-argument form of publish() expects a message object or an array of message objects",40013,400);n||(n={});let r=this.client,o=r.options,a=o.useBinaryProtocol?"msgpack":"json",c=r.options.idempotentRestPublishing,l=eT.defaultPostHeaders(r.options,{format:a});if(N(l,o.headers),c&&t.every(function(e){return!e.id})){let e=await ec(9);t.forEach(function(t,n){t.id=e+":"+n.toString()})}let h=await tL(t,this.channelOptions),u=tN(h),d=o.maxMessageSize;if(u>d)throw new P(`Maximum size of messages that can be published at once exceeded (was ${u} bytes; limit is ${d} bytes)`,40009,400);await this._publish(ed(h,r._MsgPack,a),l,n)}async _publish(e,t,n){await th.post(this.client,this.client.rest.channelMixin.basePath(this)+"/messages",e,t,n,null,!0)}async status(){return this.client.rest.channelMixin.status(this)}},tq=class e{constructor(e){this.entries=e&&e.entries||void 0,this.schema=e&&e.schema||void 0,this.appId=e&&e.appId||void 0,this.inProgress=e&&e.inProgress||void 0,this.unit=e&&e.unit||void 0,this.intervalId=e&&e.intervalId||void 0}static fromValues(t){return new e(t)}},tD=class{static basePath(e){return"/channels/"+encodeURIComponent(e.name)}
1static history(e,t){let n=e.client,s=n.options.useBinaryProtocol?"msgpack":"json",i=e.client.http.supportsLinkHeaders?void 0:s,r=eT.defaultGetHeaders(n.options,{format:s});return N(r,n.options.headers),new tu(n,this.basePath(e)+"/messages",r,i,async function(t,i,r){return tP(r?t:eu(t,n._MsgPack,s),e)}).get(t)}static async status(e){let t=e.client.options.useBinaryProtocol?"msgpack":"json",n=eT.defaultPostHeaders(e.client.options,{format:t});return(await th.get(e.client,this.basePath(e),n,{},t,!0)).body}},tj=class{static basePath(e){return tD.basePath(e.channel)+"/presence"}static async history(e,t){let n=e.channel.client,s=n.options.useBinaryProtocol?"msgpack":"json",i=e.channel.client.http.supportsLinkHeaders?void 0:s,r=eT.defaultGetHeaders(n.options,{format:s});return N(r,n.options.headers),new tu(n,this.basePath(e)+"/history",r,i,async(t,i,r)=>tR(r?t:eu(t,n._MsgPack,s),e.channel)).get(t)}},tH=class{constructor(e){this.channelMixin=tD,this.presenceMixin=tj,this.Resource=th,this.PaginatedResource=tu,this.DeviceDetails=tc,this.PushChannelSubscription=tp,this.client=e,this.channels=new tW(this.client),this.push=new tf(this.client)}async stats(e){let t=eT.defaultGetHeaders(this.client.options),n=this.client.options.useBinaryProtocol?"msgpack":"json",s=this.client.http.supportsLinkHeaders?void 0:n;return N(t,this.client.options.headers),new tu(this.client,"/stats",t,s,function(e,t,n){let s=n?e:JSON.parse(e);for(let e=0;e<s.length;e++)s[e]=tq.fromValues(s[e]);return s}).get(e)}async time(e){let t=eT.defaultGetHeaders(this.client.options);this.client.options.headers&&N(t,this.client.options.headers);let n=e=>this.client.baseUri(e)+"/time",{error:s,body:i,unpacked:r}=await this.client.http.do(eq.Get,n,t,null,e);if(s)throw s;r||(i=JSON.parse(i));let o=i[0];if(!o)throw new P("Internal error (unexpected result type from GET /time)",5e4,500);return this.client.serverTimeOffset=o-Date.now(),o}async request(e,t,n,s,i,r){var o;let[a,c,l]=this.client.options.useBinaryProtocol?(this.client._MsgPack||eA("MsgPack"),[this.client._MsgPack.encode,this.client._MsgPack.decode,"msgpack"]):[JSON.stringify,JSON.parse,"json"],h=this.client.http.supportsLinkHeaders?void 0:l;s=s||{};let u=e.toLowerCase(),d="get"==u?eT.defaultGetHeaders(this.client.options,{format:l,protocolVersion:n}):eT.defaultPostHeaders(this.client.options,{format:l,protocolVersion:n});"string"!=typeof i&&(i=null!=(o=a(i))?o:null),N(d,this.client.options.headers),r&&N(d,r);let g=new tu(this.client,t,d,h,async function(e,t,n){return x(n?e:c(e))},!0);if(!S.Http.methods.includes(u))throw new P("Unsupported method "+u,40500,405);return S.Http.methodsWithBody.includes(u)?g[u](s,i):g[u](s)}async batchPublish(e){let t,n;Array.isArray(e)?(t=e,n=!1):(t=[e],n=!0);let s=this.client.options.useBinaryProtocol?"msgpack":"json",i=eT.defaultPostHeaders(this.client.options,{format:s});this.client.options.headers&&N(i,this.client.options.headers);let r=ed(t,this.client._MsgPack,s),o=await th.post(this.client,"/messages",r,i,{},null,!0),a=o.unpacked?o.body:eu(o.body,this.client._MsgPack,s);return n?a[0]:a}async batchPresence(e){let t=this.client.options.useBinaryProtocol?"msgpack":"json",n=eT.defaultPostHeaders(this.client.options,{format:t});this.client.options.headers&&N(n,this.client.options.headers);let s=e.join(","),i=await th.get(this.client,"/presence",n,{channels:s},null,!0);return i.unpacked?i.body:eu(i.body,this.client._MsgPack,t)}async revokeTokens(e,t){if(eV(this.client.options))throw new P("Cannot revoke tokens when using token auth",40162,401);let n=this.client.options.keyName,s=w({targets:e.map(e=>`${e.type}:${e.value}`)},null!=t?t:{}),i=this.client.options.useBinaryProtocol?"msgpack":"json",r=eT.defaultPostHeaders(this.client.options,{format:i});this.client.options.headers&&N(r,this.client.options.headers);let o=ed(s,this.client._MsgPack,i),a=await th.post(this.client,`/keys/${n}/revokeTokens`,o,r,{},null,!0);return a.unpacked?a.body:eu(a.body,this.client._MsgPack,i)}},tW=class{constructor(e){this.client=e,this.all=Object.create(null)}get(e,t){e=String(e);let n=this.all[e];return n?t&&n.setOptions(t):this.all[e]=n=new tB(this.client,e,t),n}release(e){delete this.all[String(e)]}},tV=class extends ta{constructor(e){super(eT.objectifyOptions(e,!1,"BaseRest",I.defaultLogger,{Rest:tH}
1))}},tF={Rest:tH},tJ=class extends tG{static async fromEncoded(e,t){return tI(I.defaultLogger,S.Crypto,e,t)}static async fromEncodedArray(e,t){return t_(I.defaultLogger,S.Crypto,e,t)}static fromValues(e){return tG.fromValues(e)}},tz=class extends tk{static async fromEncoded(e,t){return tO(I.defaultLogger,S.Crypto,e,t)}static async fromEncodedArray(e,t){return tC(I.defaultLogger,S.Crypto,e,t)}static fromValues(e){return tk.fromValues(e)}},t$=["annotation.create","annotation.delete"];async function tK(e,t,n){return t0.fromValues(t).decode(n||{},e)}async function tQ(e,t,n){return Promise.all(t.map(function(t){return tK(e,t,n)}))}async function tX(e,t){return t0.fromValues(e).decode(t.channelOptions,t.logger)}async function tY(e,t){return Promise.all(e.map(function(e){return tX(e,t)}))}var tZ=class e extends tr{async encode(){return e6(Object.assign(new t0,this,{action:t$.indexOf(this.action||"annotation.create")}),{})}static fromValues(t){return Object.assign(new e,t)}static fromValuesArray(t){return t.map(t=>e.fromValues(t))}toString(){return ti(this,"Annotation")}},t0=class e extends tr{toJSON(...e){return te.call(this,...e)}static fromValues(t){return Object.assign(new e,t)}static fromValuesArray(t){return t.map(t=>e.fromValues(t))}async decode(e,t){let n=Object.assign(new tZ,p(w({},this),m({action:t$[this.action]})));try{await e9(n,e)}catch(e){I.logAction(t,I.LOG_ERROR,"WireAnnotation.decode()",ei(e))}return n}toString(){return ti(this,"WireAnnotation")}},t1=tZ,t4=class extends t1{static async fromEncoded(e,t){return tK(I.defaultLogger,e,t)}static async fromEncodedArray(e,t){return tQ(I.defaultLogger,e,t)}static fromValues(e){return t1.fromValues(e)}};function t2(e){let t;switch(typeof e){case"string":t=e;break;case"object":t=e.serial}if(!t||"string"!=typeof t)throw new P("First argument of annotations.publish() must be either a Message (or at least an object with a string `serial` property) or a message serial (string)",40003,400);return t}function t8(e,t){let n=t2(e);if(!t||"object"!=typeof t)throw new P("Second argument of annotations.publish() must be an object (the intended annotation to publish)",40003,400);let s=t1.fromValues(t);return s.messageSerial=n,s.action||(s.action="annotation.create"),s}function t3(e,t){return e.client.rest.channelMixin.basePath(e)+"/messages/"+encodeURIComponent(t)+"/annotations"}var t6=class{constructor(e){this.channel=e}async publish(e,t){let n=t8(e,t),s=await n.encode(),i=this.channel.client,r=i.options.useBinaryProtocol?"msgpack":"json",o=eT.defaultPostHeaders(i.options,{format:r});N(o,i.options.headers);let a=ed([s],i._MsgPack,r);await th.post(i,t3(this.channel,n.messageSerial),a,o,{},null,!0)}async delete(e,t){return t.action="annotation.delete",this.publish(e,t)}async get(e,t){let n=this.channel.client,s=t2(e),i=n.options.useBinaryProtocol?"msgpack":"json",r=n.http.supportsLinkHeaders?void 0:i,o=eT.defaultGetHeaders(n.options,{format:i});return N(o,n.options.headers),new tu(n,t3(this.channel,s),o,r,async(e,t,s)=>tY(s?e:eu(e,n._MsgPack,i),this.channel)).get(t)}};function t5(e){let t=[];if(e)for(let n=0;n<e.length;n++)t.push(e[n].toString());return"[ "+t.join(", ")+" ]"}function t9(e,t,n,s){let i,r,o,a,c;return e.error&&(i=P.fromValues(e.error)),e.messages&&(r=tx.fromValuesArray(e.messages)),t&&e.presence&&(o=t.WirePresenceMessage.fromValuesArray(e.presence)),n&&e.annotations&&(a=n.WireAnnotation.fromValuesArray(e.annotations)),s&&e.state&&(c=s.WireObjectMessage.fromValuesArray(e.state,_,tn)),Object.assign(new nn,p(w({},e),m({presence:o,messages:r,annotations:a,state:c,error:i})))}function t7(e){return t=>{var n;return t9(t,{PresenceMessage:tk,WirePresenceMessage:tS},{Annotation:t1,WireAnnotation:t0,RealtimeAnnotations:na,RestAnnotations:t6},null!=(n=null==e?void 0:e.ObjectsPlugin)?n:null)}}function ne(e){return Object.assign(new nn,e)}function nt(e,t,n,s){let i,r="[ProtocolMessage";void 0!==e.action&&(r+="; action="+eZ[e.action]);let o=["id","channel","channelSerial","connectionId","count","msgSerial","timestamp"];for(let t=0;t<o.length;t++)void 0!==e[i=o[t]]&&(r+="; "+i+"="+e[i]);if(e.messages&&(r+="; messages="+t5(tx.fromValuesArray(e.messages))),e.presence&&t&&(r+="; presence="+t5(t.WirePresenceMessage.fromValuesArray(e.presence))),e.annotations&&n&&(r+="; annotations="+t5(n.WireAnnotation.fromValuesArray(e.annotations))),e.state&&s&&(r+=";
1 state="+t5(s.WireObjectMessage.fromValuesArray(e.state,_,tn))),e.error&&(r+="; error="+P.fromValues(e.error).toString()),e.auth&&e.auth.accessToken&&(r+="; token="+e.auth.accessToken),e.flags&&(r+="; flags="+e1.filter(e.hasFlag).join(",")),e.params){let t="";X(e.params,function(n){t.length>0&&(t+="; "),t+=n+"="+e.params[n]}),t.length>0&&(r+="; params=["+t+"]")}return r+"]"}var nn=class{constructor(){this.hasFlag=e=>(this.flags&e0[e])>0}setFlag(e){return this.flags=this.flags|e0[e]}getMode(){return(this.flags||0)&e0.MODE_ALL}encodeModesToFlags(e){e.forEach(e=>this.setFlag(e))}decodeModesFromFlags(){let e=[];return e4.forEach(t=>{this.hasFlag(t)&&e.push(t)}),e.length>0?e:void 0}},ns=class{constructor(e,t,n,s,i){this.previous=e,this.current=t,"attached"===t&&(this.resumed=n,this.hasBacklog=s),i&&(this.reason=i)}},ni=function(){},nr=class e extends eX{constructor(e,t,n){var s,i,r;super(e.logger),this._annotations=null,this._mode=0,this.retryCount=0,this.history=async function(e){I.logAction(this.logger,I.LOG_MICRO,"RealtimeChannel.history()","channel = "+this.name);let t=this.client.rest.channelMixin;if(e&&e.untilAttach){if("attached"!==this.state)throw new P("option untilAttach requires the channel to be attached",4e4,400);if(!this.properties.attachSerial)throw new P("untilAttach was specified and channel is attached, but attachSerial is not defined",4e4,400);delete e.untilAttach,e.from_serial=this.properties.attachSerial}return t.history(this,e)},this.whenState=e=>eX.prototype.whenState.call(this,e,this.state),I.logAction(this.logger,I.LOG_MINOR,"RealtimeChannel()","started; name = "+t),this.name=t,this.channelOptions=eU(null!=(s=e._Crypto)?s:null,this.logger,n),this.client=e,this._presence=e._RealtimePresence?new e._RealtimePresence.RealtimePresence(this):null,e._Annotations&&(this._annotations=new e._Annotations.RealtimeAnnotations(this)),this.connectionManager=e.connection.connectionManager,this.state="initialized",this.subscriptions=new eX(this.logger),this.syncChannelSerial=void 0,this.properties={attachSerial:void 0,channelSerial:void 0},this.setOptions(n),this.errorReason=null,this._attachResume=!1,this._decodingContext={channelOptions:this.channelOptions,plugins:e.options.plugins||{},baseEncodedPreviousPayload:void 0},this._lastPayload={messageId:null,protocolMessageChannelSerial:null,decodeFailureRecoveryInProgress:null},this._allChannelChanges=new eX(this.logger),(null==(i=e.options.plugins)?void 0:i.Push)&&(this._push=new e.options.plugins.Push.PushChannel(this)),(null==(r=e.options.plugins)?void 0:r.Objects)&&(this._objects=new e.options.plugins.Objects.Objects(this))}get presence(){return this._presence||eA("RealtimePresence"),this._presence}get annotations(){return this._annotations||eA("Annotations"),this._annotations}get push(){return this._push||eA("Push"),this._push}get objects(){return this._objects||eA("Objects"),this._objects}invalidStateError(){return new P("Channel operation failed as channel state is "+this.state,90001,400,this.errorReason||void 0)}static processListenerArgs(e){return"function"==typeof(e=Array.prototype.slice.call(e))[0]&&e.unshift(null),e}async setOptions(e){var t;let n=this.channelOptions,s=function(e){if(e&&"params"in e&&!G(e.params))return new P("options.params must be an object",4e4,400);if(e&&"modes"in e){if(!Array.isArray(e.modes))return new P("options.modes must be an array",4e4,400);for(let t=0;t<e.modes.length;t++){let n=e.modes[t];if(!n||"string"!=typeof n||!e4.includes(String.prototype.toUpperCase.call(n)))return new P("Invalid channel mode: "+n,4e4,400)}}}(e);if(s)throw s;if(this.channelOptions=eU(null!=(t=this.client._Crypto)?t:null,this.logger,e),this._decodingContext&&(this._decodingContext.channelOptions=this.channelOptions),this._shouldReattachToSetOptions(e,n))return this.attachImpl(),new Promise((e,t)=>{this._allChannelChanges.once(["attached","update","detached","failed"],function(n){switch(this.event){case"update":case"attached":e();break;default:t(n.reason)}})})}_shouldReattachToSetOptions(e,t){if("attached"!==this.state&&"attaching"!==this.state)return!1;if(null==e?void 0:e.params){let n=no(e.params),s=no(t.params);if(Object.keys(n).length!==Object.keys(s).length||!ev(s,n))return!0}return!(null==e||!e.modes||t.modes&&ew(e.modes,t.modes))}async publish(...e){let t;if(1==e.length)if(G(e[0]))t=[tG.fromValues(e[0])];else if(Array.isArray(e[0]))t=tG.fromValuesArray(e[0]);else throw new P("The single-argument form of publish() expects a message object or an array of message objects",40013,400);else t=[tG.fromValues({name:e[0],data:e[1]})];let n=this.client.options.maxMessageSize,s=await tL(t,this.channelOptions),i=tN(s);if(i>n)throw new P(`Maximum size of messages that can be published at once exceeded (was ${i} bytes; limit is ${n} bytes)`,40009,400);this.throwIfUnpublishableState(),I.logAction(this.logger,I.LOG_MICRO,"RealtimeChannel.publish()","sending message; channel state is "+this.state+", message count = "+s.length);let r=ne({action:eY.MESSAGE,channel:this.name,messages:s});return this.sendMessage(r)}throwIfUnpublishableState(){if(!this.connectionManager.activeState())throw this.connectionManager.getError();if("failed"===this.state||"suspended"===this.state)throw this.invalidStateError()}onEvent(e){I.logAction(this.logger,I.LOG_MICRO,"RealtimeChannel.onEvent()","received message");let t=this.subscriptions;for(let n=0;n<e.length;n++){let s=e[n];t.emit(s.name,s)}}async attach(){return"attached"===this.state?null:new Promise((e,t)=>
1{this._attach(!1,null,(n,s)=>n?t(n):e(s))})}_attach(e,t,n){n||(n=e=>{e&&I.logAction(this.logger,I.LOG_ERROR,"RealtimeChannel._attach()","Channel attach failed: "+e.toString())});let s=this.connectionManager;s.activeState()?(("attaching"!==this.state||e)&&this.requestState("attaching",t),this.once(function(e){switch(this.event){case"attached":null==n||n(null,e);break;case"detached":case"suspended":case"failed":null==n||n(e.reason||s.getError()||new P("Unable to attach; reason unknown; state = "+this.event,9e4,500));break;case"detaching":null==n||n(new P("Attach request superseded by a subsequent detach request",9e4,409))}})):n(s.getError())}attachImpl(){I.logAction(this.logger,I.LOG_MICRO,"RealtimeChannel.attachImpl()","sending ATTACH message");let e=ne({action:eY.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this.channelOptions.modes&&e.encodeModesToFlags(ep(this.channelOptions.modes)),this._attachResume&&e.setFlag("ATTACH_RESUME"),this._lastPayload.decodeFailureRecoveryInProgress&&(e.channelSerial=this._lastPayload.protocolMessageChannelSerial),this.sendMessage(e).catch(ni)}async detach(){let e=this.connectionManager;if(!e.activeState())throw e.getError();switch(this.state){case"suspended":this.notifyState("detached");return;case"detached":return;case"failed":throw new P("Unable to detach; channel state = failed",90001,400);default:this.requestState("detaching");case"detaching":return new Promise((t,n)=>{this.once(function(s){switch(this.event){case"detached":t();break;case"attached":case"suspended":case"failed":n(s.reason||e.getError()||new P("Unable to detach; reason unknown; state = "+this.event,9e4,500));break;case"attaching":n(new P("Detach request superseded by a subsequent attach request",9e4,409))}})})}}detachImpl(){I.logAction(this.logger,I.LOG_MICRO,"RealtimeChannel.detach()","sending DETACH message");let e=ne({action:eY.DETACH,channel:this.name});this.sendMessage(e).catch(ni)}async subscribe(...t){let[n,s]=e.processListenerArgs(t);if("failed"===this.state)throw P.fromValues(this.invalidStateError());return(n&&"object"==typeof n&&!Array.isArray(n)?this.client._FilteredSubscriptions.subscribeFilter(this,n,s):this.subscriptions.on(n,s),!1!==this.channelOptions.attachOnSubscribe)?this.attach():null}unsubscribe(...t){var n;let[s,i]=e.processListenerArgs(t);"object"==typeof s&&!i||(null==(n=this.filteredSubscriptions)?void 0:n.has(i))?this.client._FilteredSubscriptions.getAndDeleteFilteredSubscriptions(this,s,i).forEach(e=>this.subscriptions.off(e)):this.subscriptions.off(s,i)}sync(){switch(this.state){case"initialized":case"detaching":case"detached":throw new L("Unable to sync to channel; not attached",4e4)}let e=this.connectionManager;if(!e.activeState())throw e.getError();let t=ne({action:eY.SYNC,channel:this.name});this.syncChannelSerial&&(t.channelSerial=this.syncChannelSerial),e.send(t)}async sendMessage(e){return new Promise((t,n)=>{this.connectionManager.send(e,this.client.options.queueMessages,e=>{e?n(e):t()})})}async sendPresence(e){let t=ne({action:eY.PRESENCE,channel:this.name,presence:e});return this.sendMessage(t)}sendState(e){let t=ne({action:eY.OBJECT,channel:this.name,state:e});return this.sendMessage(t)}async processMessage(e){(e.action===eY.ATTACHED||e.action===eY.MESSAGE||e.action===eY.PRESENCE||e.action===eY.OBJECT||e.action===eY.ANNOTATION)&&this.setChannelSerial(e.channelSerial);let t,n=!1;switch(e.action){case eY.ATTACHED:{this.properties.attachSerial=e.channelSerial,this._mode=e.getMode(),this.params=e.params||{};let t=e.decodeModesFromFlags();this.modes=t&&eg(t)||void 0;let n=e.hasFlag("RESUMED"),s=e.hasFlag("HAS_PRESENCE"),i=e.hasFlag("HAS_BACKLOG"),r=e.hasFlag("HAS_OBJECTS");if("attached"===this.state){!n&&(this._presence&&this._presence.onAttached(s),this._objects&&this._objects.onAttached(r));let t=new ns(this.state,this.state,n,i,e.error);this._allChannelChanges.emit("update",t),(!n||this.channelOptions.updateOnAttached)&&this.emit("update",t)}else"detaching"===this.state?this.checkPendingState():this.notifyState("attached",e.error,n,s,i,r);break}case eY.DETACHED:{let t=e.error?P.fromValues(e.error):new P("Channel detached",90001,404);"detaching"===this.state?this.notifyState("detached",t):"attaching"===this.state?this.notifyState("suspended",t):("attached"===this.state||"suspended"===this.state)&&this.requestState("attaching",t);break}case eY.SYNC:if(n=!0,t=this.syncChannelSerial=e.channelSerial,!e.presence)break;case eY.PRESENCE:{if(!e.presence)break;ts(e);let s=this.channelOptions;if(this._presence){let i=await Promise.all(e.presence.map(e=>e.decode(s,this.logger)));this._presence.setPresence(i,n,t)}break}case eY.OBJECT:case eY.OBJECT_SYNC:{if(!this._objects||!e.state)return;ts(e);
1let t=this.client.connection.connectionManager.getActiveTransportFormat(),n=e.state.map(e=>e.decode(this.client,t));e.action===eY.OBJECT?this._objects.handleObjectMessages(n):this._objects.handleObjectSyncMessages(n,e.channelSerial);break}case eY.MESSAGE:{if("attached"!==this.state)return void I.logAction(this.logger,I.LOG_MAJOR,"RealtimeChannel.processMessage()",'Message "'+e.id+'" skipped as this channel "'+this.name+'" state is not "attached" (state is "'+this.state+'").');ts(e);let t=e.messages,n=t[0],s=t[t.length-1];if(n.extras&&n.extras.delta&&n.extras.delta.from!==this._lastPayload.messageId){let t='Delta message decode failure - previous message not available for message "'+e.id+'" on this channel "'+this.name+'".';I.logAction(this.logger,I.LOG_ERROR,"RealtimeChannel.processMessage()",t),this._startDecodeFailureRecovery(new P(t,40018,400));break}let i=[];for(let e=0;e<t.length;e++){let{decoded:n,err:s}=await t[e].decodeWithErr(this._decodingContext,this.logger);if(i[e]=n,s)switch(s.code){case 40018:this._startDecodeFailureRecovery(s);return;case 40019:case 40021:this.notifyState("failed",s);return}}this._lastPayload.messageId=s.id,this._lastPayload.protocolMessageChannelSerial=e.channelSerial,this.onEvent(i);break}case eY.ANNOTATION:{ts(e);let t=this.channelOptions;if(this._annotations){let n=await Promise.all((e.annotations||[]).map(e=>e.decode(t,this.logger)));this._annotations._processIncoming(n)}break}case eY.ERROR:{let t=e.error;t&&80016==t.code?this.checkPendingState():this.notifyState("failed",P.fromValues(t));break}default:I.logAction(this.logger,I.LOG_MAJOR,"RealtimeChannel.processMessage()","Protocol error: unrecognised message action ("+e.action+")")}}_startDecodeFailureRecovery(e){this._lastPayload.decodeFailureRecoveryInProgress||(I.logAction(this.logger,I.LOG_MAJOR,"RealtimeChannel.processMessage()","Starting decode failure recovery process."),this._lastPayload.decodeFailureRecoveryInProgress=!0,this._attach(!0,e,()=>{this._lastPayload.decodeFailureRecoveryInProgress=!1}))}onAttached(){I.logAction(this.logger,I.LOG_MINOR,"RealtimeChannel.onAttached","activating channel; name = "+this.name)}notifyState(e,t,n,s,i,r){if(I.logAction(this.logger,I.LOG_MICRO,"RealtimeChannel.notifyState","name = "+this.name+", current state = "+this.state+", notifying state "+e),this.clearStateTimer(),["detached","suspended","failed"].includes(e)&&(this.properties.channelSerial=null),e===this.state)return;this._presence&&this._presence.actOnChannelState(e,s,t),this._objects&&this._objects.actOnChannelState(e,r),"suspended"===e&&this.connectionManager.state.sendEvents?this.startRetryTimer():this.cancelRetryTimer(),t&&(this.errorReason=t);let o=new ns(this.state,e,n,i,t),a='Channel state for channel "'+this.name+'"',c=e+(t?"; reason: "+t:"");"failed"===e?I.logAction(this.logger,I.LOG_ERROR,a,c):I.logAction(this.logger,I.LOG_MAJOR,a,c),"attaching"!==e&&"suspended"!==e&&(this.retryCount=0),"attached"===e&&this.onAttached(),"attached"===e?this._attachResume=!0:("detaching"===e||"failed"===e)&&(this._attachResume=!1),this.state=e,this._allChannelChanges.emit(e,o),this.emit(e,o)}requestState(e,t){I.logAction(this.logger,I.LOG_MINOR,"RealtimeChannel.requestState","name = "+this.name+", state = "+e),this.notifyState(e,t),this.checkPendingState()}checkPendingState(){if(!this.connectionManager.state.sendEvents)return void I.logAction(this.logger,I.LOG_MINOR,"RealtimeChannel.checkPendingState","sendEvents is false; state is "+this.connectionManager.state.state);switch(I.logAction(this.logger,I.LOG_MINOR,"RealtimeChannel.checkPendingState","name = "+this.name+", state = "+this.state),this.state){case"attaching":this.startStateTimerIfNotRunning(),this.attachImpl();break;case"detaching":this.startStateTimerIfNotRunning(),this.detachImpl();break;case"attached":this.sync()}}timeoutPendingState(){switch(this.state){case"attaching":{let e=new P("Channel attach timed out",90007,408);this.notifyState("suspended",e);break}case"detaching":{let e=new P("Channel detach timed out",90007,408);this.notifyState("attached",e);break}default:this.checkPendingState()}}startStateTimerIfNotRunning(){this.stateTimer||(this.stateTimer=setTimeout(()=>{I.logAction(this.logger,I.LOG_MINOR,"RealtimeChannel.startStateTimerIfNotRunning","t
1imer expired"),this.stateTimer=null,this.timeoutPendingState()},this.client.options.timeouts.realtimeRequestTimeout))}clearStateTimer(){let e=this.stateTimer;e&&(clearTimeout(e),this.stateTimer=null)}startRetryTimer(){if(this.retryTimer)return;this.retryCount++;let e=ey(this.client.options.timeouts.channelRetryTimeout,this.retryCount);this.retryTimer=setTimeout(()=>{"suspended"===this.state&&this.connectionManager.state.sendEvents&&(this.retryTimer=null,I.logAction(this.logger,I.LOG_MINOR,"RealtimeChannel retry timer expired","attempting a new attach"),this.requestState("attaching"))},e)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}getReleaseErr(){let e=this.state;return"initialized"===e||"detached"===e||"failed"===e?null:new P("Can only release a channel in a state where there is no possibility of further updates from the server being received (initialized, detached, or failed); was "+e,90001,400)}setChannelSerial(e){I.logAction(this.logger,I.LOG_MICRO,"RealtimeChannel.setChannelSerial()","Updating channel serial; serial = "+e+"; previous = "+this.properties.channelSerial),e&&(this.properties.channelSerial=e)}async status(){return this.client.rest.channelMixin.status(this)}};function no(e){let t=e||{},{agent:n}=t;var s=t,i=["agent"],r={};for(var o in s)v.call(s,o)&&0>i.indexOf(o)&&(r[o]=s[o]);if(null!=s&&b)for(var o of b(s))0>i.indexOf(o)&&O.call(s,o)&&(r[o]=s[o]);return r}var na=class{constructor(e){this.channel=e,this.logger=e.logger,this.subscriptions=new eX(this.logger)}async publish(e,t){let n=this.channel.name,s=t8(e,t),i=await s.encode();this.channel.throwIfUnpublishableState(),I.logAction(this.logger,I.LOG_MICRO,"RealtimeAnnotations.publish()","channelName = "+n+", sending annotation with messageSerial = "+s.messageSerial+", type = "+s.type);let r=ne({action:eY.ANNOTATION,channel:n,annotations:[i]});return this.channel.sendMessage(r)}async delete(e,t){return t.action="annotation.delete",this.publish(e,t)}async subscribe(...e){let t=nr.processListenerArgs(e),n=t[0],s=t[1],i=this.channel;if("failed"===i.state)throw P.fromValues(i.invalidStateError());if(this.subscriptions.on(n,s),!1!==this.channel.channelOptions.attachOnSubscribe&&await i.attach(),0===("attached"===this.channel.state&&this.channel._mode&e0.ANNOTATION_SUBSCRIBE))throw new P("You are trying to add an annotation listener, but you haven't requested the annotation_subscribe channel mode in ChannelOptions, so this won't do anything (we only deliver annotations to clients who have explicitly requested them)",93001,400)}unsubscribe(...e){let t=nr.processListenerArgs(e),n=t[0],s=t[1];this.subscriptions.off(n,s)}_processIncoming(e){for(let t of e)this.subscriptions.emit(t.type||"",t)}async get(e,t){return t6.prototype.get.call(this,e,t)}},nc=class e extends tV{constructor(t){var n,s;if(!e._MsgPack)throw Error("Expected DefaultRest._MsgPack to have been set");super(eT.objectifyOptions(t,!0,"Rest",I.defaultLogger,p(w({},tF),m({Crypto:null!=(n=e.Crypto)?n:void 0,MsgPack:null!=(s=e._MsgPack)?s:void 0,Annotations:{Annotation:t1,WireAnnotation:t0,RealtimeAnnotations:na,RestAnnotations:t6}}))))}static get Crypto(){if(null===this._Crypto)throw Error("Encryption not enabled; use ably.encryption.js instead");return this._Crypto}static set Crypto(e){this._Crypto=e}};nc._Crypto=null,nc.Message=tJ,nc.PresenceMessage=tz,nc.Annotation=t4,nc._MsgPack=null,nc._Http=eK;var nl=nc,nh=class extends eX{constructor(e){super(e),this.messages=[]}count(){return this.messages.length}push(e){this.messages.push(e)}shift(){return this.messages.shift()}last(){return this.messages[this.messages.length-1]}copyAll(){return this.messages.slice()}append(e){this.messages.push.apply(this.messages,e)}prepend(e){this.messages.unshift.apply(this.messages,e)}completeMessages(e,t,n){I.logAction(this.logger,I.LOG_MICRO,"MessageQueue.completeMessages()","serial = "+e+"; count = "+t),n=n||null;let s=this.messages;if(0===s.length)throw Error("MessageQueue.completeMessages(): completeMessages called on any empty MessageQueue");let i=s[0];if(i){let r=i.message.msgSerial,o=e+t;if(o>r)for(let e of s.splice(0,o-r))e.callback(n);
10==s.length&&this.emit("idle")}}completeAllMessages(e){this.completeMessages(0,Number.MAX_SAFE_INTEGER||Number.MAX_VALUE,e)}resetSendAttempted(){for(let e of this.messages)e.sendAttempted=!1}clear(){I.logAction(this.logger,I.LOG_MICRO,"MessageQueue.clear()","clearing "+this.messages.length+" messages"),this.messages=[],this.emit("idle")}},nu=class{constructor(e,t){this.message=e,this.callback=t,this.merged=!1;const n=e.action;this.sendAttempted=!1,this.ackRequired="number"==typeof n&&[eY.MESSAGE,eY.PRESENCE,eY.ANNOTATION,eY.OBJECT].includes(n)}},nd=class extends eX{constructor(e){super(e.logger),this.transport=e,this.messageQueue=new nh(this.logger),e.on("ack",(e,t)=>{this.onAck(e,t)}),e.on("nack",(e,t,n)=>{this.onNack(e,t,n)})}onAck(e,t){I.logAction(this.logger,I.LOG_MICRO,"Protocol.onAck()","serial = "+e+"; count = "+t),this.messageQueue.completeMessages(e,t)}onNack(e,t,n){I.logAction(this.logger,I.LOG_ERROR,"Protocol.onNack()","serial = "+e+"; count = "+t+"; err = "+ei(n)),n||(n=new P("Unable to send message; channel not responding",50001,500)),this.messageQueue.completeMessages(e,t,n)}onceIdle(e){let t=this.messageQueue;0===t.count()?e():t.once("idle",e)}send(e){e.ackRequired&&this.messageQueue.push(e),this.logger.shouldLog(I.LOG_MICRO)&&I.logActionNoStrip(this.logger,I.LOG_MICRO,"Protocol.send()","sending msg; "+nt(e.message,this.transport.connectionManager.realtime._RealtimePresence,this.transport.connectionManager.realtime._Annotations,this.transport.connectionManager.realtime._objectsPlugin)),e.sendAttempted=!0,this.transport.send(e.message)}getTransport(){return this.transport}getPendingMessages(){return this.messageQueue.copyAll()}clearPendingMessages(){return this.messageQueue.clear()}finish(){let e=this.transport;this.onceIdle(function(){e.disconnect()})}},ng=class{constructor(e,t,n,s){this.previous=e,this.current=t,n&&(this.retryIn=n),s&&(this.reason=s)}},np={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001},nf={disconnected:()=>P.fromValues({statusCode:400,code:np.DISCONNECTED,message:"Connection to server temporarily unavailable"}),suspended:()=>P.fromValues({statusCode:400,code:np.SUSPENDED,message:"Connection to server unavailable"}),failed:()=>P.fromValues({statusCode:400,code:np.FAILED,message:"Connection failed or disconnected by server"}),closing:()=>P.fromValues({statusCode:400,code:np.CLOSING,message:"Connection closing"}),closed:()=>P.fromValues({statusCode:400,code:np.CLOSED,message:"Connection closed"}),unknownConnectionErr:()=>P.fromValues({statusCode:500,code:np.UNKNOWN_CONNECTION_ERR,message:"Internal connection error"}),unknownChannelErr:()=>P.fromValues({statusCode:500,code:np.UNKNOWN_CONNECTION_ERR,message:"Internal channel error"})},nm=ne({action:eY.CLOSE}),ny=ne({action:eY.DISCONNECT}),nb=class extends eX{constructor(e,t,n,s){super(e.logger),s&&(n.format=void 0,n.heartbeats=!0),this.connectionManager=e,this.auth=t,this.params=n,this.timeouts=n.options.timeouts,this.format=n.format,this.isConnected=!1,this.isFinished=!1,this.isDisposed=!1,this.maxIdleInterval=null,this.idleTimer=null,this.lastActivity=null}connect(){}close(){this.isConnected&&this.requestClose(),this.finish("closed",nf.closed())}disconnect(e){this.isConnected&&this.requestDisconnect(),this.finish("disconnected",e||nf.disconnected())}fail(e){this.isConnected&&this.requestDisconnect(),this.finish("failed",e||nf.failed())}finish(e,t){var n;this.isFinished||(this.isFinished=!0,this.isConnected=!1,this.maxIdleInterval=null,clearTimeout(null!=(n=this.idleTimer)?n:void 0),this.idleTimer=null,this.emit(e,t),this.dispose())}onProtocolMessage(e){switch(this.logger.shouldLog(I.LOG_MICRO)&&I.logActionNoStrip(this.logger,I.LOG_MICRO,"Transport.onProtocolMessage()","received on "+this.shortName+": "+nt(e,this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._objectsPlugin)+"; connectionId = "+this.connectionManager.connectionId),this.onActivity(),e.action){case eY.HEARTBEAT:I.logActionNoStrip(this.logger,I.LOG_MICRO,"Transport.onProtocolMe
1ssage()",this.shortName+" heartbeat; connectionId = "+this.connectionManager.connectionId),this.emit("heartbeat",e.id);break;case eY.CONNECTED:this.onConnect(e),this.emit("connected",e.error,e.connectionId,e.connectionDetails,e);break;case eY.CLOSED:this.onClose(e);break;case eY.DISCONNECTED:this.onDisconnect(e);break;case eY.ACK:this.emit("ack",e.msgSerial,e.count);break;case eY.NACK:this.emit("nack",e.msgSerial,e.count,e.error);break;case eY.SYNC:this.connectionManager.onChannelMessage(e,this);break;case eY.ACTIVATE:break;case eY.AUTH:eh(this.auth.authorize(),e=>{e&&I.logAction(this.logger,I.LOG_ERROR,"Transport.onProtocolMessage()","Ably requested re-authentication, but unable to obtain a new token: "+ei(e))});break;case eY.ERROR:if(I.logAction(this.logger,I.LOG_MINOR,"Transport.onProtocolMessage()","received error action; connectionId = "+this.connectionManager.connectionId+"; err = "+S.Config.inspect(e.error)+(e.channel?", channel: "+e.channel:"")),void 0===e.channel){this.onFatalError(e);break}this.connectionManager.onChannelMessage(e,this);break;default:this.connectionManager.onChannelMessage(e,this)}}onConnect(e){if(this.isConnected=!0,!e.connectionDetails)throw Error("Transport.onConnect(): Connect message recieved without connectionDetails");let t=e.connectionDetails.maxIdleInterval;t&&(this.maxIdleInterval=t+this.timeouts.realtimeRequestTimeout,this.onActivity())}onDisconnect(e){let t=e&&e.error;I.logAction(this.logger,I.LOG_MINOR,"Transport.onDisconnect()","err = "+ei(t)),this.finish("disconnected",t)}onFatalError(e){let t=e&&e.error;I.logAction(this.logger,I.LOG_MINOR,"Transport.onFatalError()","err = "+ei(t)),this.finish("failed",t)}onClose(e){let t=e&&e.error;I.logAction(this.logger,I.LOG_MINOR,"Transport.onClose()","err = "+ei(t)),this.finish("closed",t)}requestClose(){I.logAction(this.logger,I.LOG_MINOR,"Transport.requestClose()",""),this.send(nm)}requestDisconnect(){I.logAction(this.logger,I.LOG_MINOR,"Transport.requestDisconnect()",""),this.send(ny)}ping(e){let t={action:eY.HEARTBEAT};e&&(t.id=e),this.send(ne(t))}
1dispose(){I.logAction(this.logger,I.LOG_MINOR,"Transport.dispose()",""),this.isDisposed=!0,this.off()}onActivity(){this.maxIdleInterval&&(this.lastActivity=this.connectionManager.lastActivity=Date.now(),this.setIdleTimer(this.maxIdleInterval+100))}setIdleTimer(e){this.idleTimer||(this.idleTimer=setTimeout(()=>{this.onIdleTimerExpire()},e))}onIdleTimerExpire(){if(!this.lastActivity||!this.maxIdleInterval)throw Error("Transport.onIdleTimerExpire(): lastActivity/maxIdleInterval not set");this.idleTimer=null;let e=Date.now()-this.lastActivity,t=this.maxIdleInterval-e;if(t<=0){let t="No activity seen from realtime in "+e+"ms; assuming connection has dropped";I.logAction(this.logger,I.LOG_ERROR,"Transport.onIdleTimerExpire()",t),this.disconnect(new P(t,80003,408))}else this.setIdleTimer(t+100)}static tryConnect(e,t,n,s,i){let r,o=new e(t,n,s),a=function(e){clearTimeout(r),i({event:this.event,error:e})};return r=setTimeout(()=>{o.off(["preconnect","disconnected","failed"]),o.dispose(),a.call({event:"disconnected"},new P("Timeout waiting for transport to indicate itself viable",5e4,500))},t.options.timeouts.realtimeRequestTimeout),o.on(["failed","disconnected"],a),o.on("preconnect",function(){I.logAction(t.logger,I.LOG_MINOR,"Transport.tryConnect()","viable transport "+o),clearTimeout(r),o.off(["failed","disconnected"],a),i(null,o)}),o.connect(),o}static isAvailable(){throw new P("isAvailable not implemented for transport",5e4,500)}};(r=a||(a={})).WebSocket="web_socket",r.Comet="comet",r.XhrPolling="xhr_polling";var nv=e.g,nO=()=>{var e;return void 0!==S.WebStorage&&(null==(e=S.WebStorage)?void 0:e.localSupported)},nC=()=>{var e;return void 0!==S.WebStorage&&(null==(e=S.WebStorage)?void 0:e.sessionSupported)},nw=function(){},nR="ably-transport-preference";function nA(e){try{return JSON.parse(e)}catch(e){return null}}var nS=class{constructor(e,t,n,s){this.options=e,this.host=t,this.mode=n,this.connectionKey=s,this.format=e.useBinaryProtocol?"msgpack":"json"}getConnectParams(e){let t=e?U(e):{},n=this.options;switch(this.mode){case"resume":t.resume=this.connectionKey;break;case"recover":{let e=nA(n.recover);e&&(t.recover=e.connectionKey)}}return void 0!==n.clientId&&(t.clientId=n.clientId),!1===n.echoMessages&&(t.echo="false"),void 0!==this.format&&(t.format=this.format),void 0!==this.stream&&(t.stream=this.stream),void 0!==this.heartbeats&&(t.heartbeats=this.heartbeats),t.v=eT.protocolVersion,t.agent=eN(this.options),void 0!==n.transportParams&&N(t,n.transportParams),t}toString(){let e="[mode="+this.mode;return this.host&&(e+=",host="+this.host),this.connectionKey&&(e+=",connectionKey="+this.connectionKey),this.format&&(e+=",format="+this.format),e+="]"}},nk=class e extends eX{constructor(e,t){super(e.logger),this.supportedTransports={},this.disconnectedRetryCount=0,this.pendingChannelMessagesState={isProcessing:!1,queue:[]},this.realtime=e,this.initTransports(),this.options=t;const n=t.timeouts,s=n.webSocketConnectTimeout+n.realtimeRequestTimeout;if(this.states={initialized:{state:"initialized",terminal:!1,queueEvents:!0,sendEvents:!1,failState:"disconnected"},connecting:{state:"connecting",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:s,failState:"disconnected"},connected:{state:"connected",terminal:!1,queueEvents:!1,sendEvents:!0,failState:"disconnected"},disconnected:{state:"disconnected",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:n.disconnectedRetryTimeout,failState:"disconnected"},suspended:{state:"suspended",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:n.suspendedRetryTimeout,failState:"suspended"},closing:{state:"closing",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:n.realtimeRequestTimeout,failState:"closed"},closed:{state:"closed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"closed"},failed:{state:"failed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"failed"}},this.state=this.states.initialized,this.errorReason=null,this.queuedMessages=new nh(this.logger),this.msgSerial=0,this.connectionDetails=void 0,this.connectionId=void 0,this.connectionKey=void 0,this.connectionStateTtl=n.connectionStateTtl,this.maxIdleInterval=null,this.transports=V(t.transports||eT.defaultTransports,this.supportedTransports),this.transportPreference=null,this.transports.includes(a.WebSocket)&&(this.webSocketTransportAvailable=!0),this.transports.includes(a.XhrPolling)?this.baseTransport=a.XhrPolling:this.transports.includes(a.Comet)&&(this.baseTransport=a.Comet),this.domains=eT.getHosts(t),this.activeProtocol=null,this.host=null,this.lastAutoReconnectAttempt=null,this.lastActivity=null,this.forceFallbackHost=!1,this.connectCounter=0,this.wsCheckResult=null,this.webSocketSlowTimer=null,this.webSocketGiveUpTimer=null,this.abandonedWebSocket=!1,I.logAction(this.logger,I.LOG_MINOR,"Realtime.ConnectionManager()","started"),I.logAction(this.logger,I.LOG_MICRO,"Realtime.ConnectionManager()","requested transports = ["+(t.transports||eT.defaultTransports)+"]"),I.logAction(this.logger,I.LOG_MICRO,"Realtime.ConnectionManager()","available transports = ["+this.transports+"]"),I.logAction(this.logger,I.LOG_MICRO,"Realtime.ConnectionManager()","http domains = ["+this.domains+"]"),!this.transports.length){const e="no requested transports available";throw I.logAction(this.logger,I.LOG_ERROR,"realtime.ConnectionManager()",e),Error(e)}const i=S.Config.addEventListener;i&&(nC()&&"function"==typeof t.recover&&i("beforeunload",this.persist
1Connection.bind(this)),!0===t.closeOnUnload&&i("beforeunload",()=>{I.logAction(this.logger,I.LOG_MAJOR,"Realtime.ConnectionManager()","beforeunload event has triggered the connection to close as closeOnUnload is true"),this.requestState({state:"closing"})}),i("online",()=>{var e;this.state==this.states.disconnected||this.state==this.states.suspended?(I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager caught browser âonlineâ event","reattempting connection"),this.requestState({state:"connecting"})):this.state==this.states.connecting&&(null==(e=this.pendingTransport)||e.off(),this.disconnectAllTransports(),this.startConnect())}),i("offline",()=>{this.state==this.states.connected&&(I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager caught browser âofflineâ event","disconnecting active transport"),this.disconnectAllTransports())}))}static supportedTransports(e){let t={supportedTransports:{}};return this.initTransports(e,t),t.supportedTransports}static initTransports(e,t){let n=w(w({},S.Transports.bundledImplementations),e);[a.WebSocket,...S.Transports.order].forEach(e=>{let s=n[e];s&&s.isAvailable()&&(t.supportedTransports[e]=s)})}initTransports(){e.initTransports(this.realtime._additionalTransportImplementations,this)}createTransportParams(e,t){return new nS(this.options,e,t,this.connectionKey)}getTransportParams(e){(e=>{if(this.connectionKey)return e("resume");if("string"==typeof this.options.recover)return e("recover");let t=this.options.recover,n=this.getSessionRecoverData(),s=this.sessionRecoveryName();if(n&&"function"==typeof t){I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.getTransportParams()","Calling clientOptions-provided recover function with last session data (recovery scope: "+s+")"),t(n,t=>{t?(this.options.recover=n.recoveryKey,e("recover")):e("clean")});return}e("clean")})(t=>{let n=this.createTransportParams(null,t);if("recover"===t){I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport recovery mode = recover; recoveryKey = "+this.options.recover);let e=nA(this.options.recover);e&&(this.msgSerial=e.msgSerial)}else I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport params = "+n.toString());e(n)})}tryATransport(e,t,n){I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.tryATransport()","trying "+t),this.proposedTransport=nb.tryConnect(this.supportedTransports[t],this,this.realtime.auth,e,(s,i)=>{let r=this.state;if(r==this.states.closing||r==this.states.closed||r==this.states.failed){i&&(I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.tryATransport()","connection "+r.state+" while we were attempting the transport; closing "+i),i.close()),n(!0);return}if(s){if(I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.tryATransport()","transport "+t+" "+s.event+", err: "+s.error.toString()),eJ.isTokenErr(s.error)&&!(this.errorReason&&eJ.isTokenErr(this.errorReason)))this.errorReason=s.error,eh(this.realtime.auth._forceNewToken(null,null),s=>{s?this.actOnErrorFromAuthorize(s):this.tryATransport(e,t,n)});else if("failed"===s.event)this.notifyState({state:"failed",error:s.error}),n(!0);else if("disconnected"===s.event){var o;!(o=s.error).statusCode||!o.code||o.statusCode>=500||Object.values(np).includes(o.code)?n(!1):(this.notifyState({state:this.states.connecting.failState,error:s.error}),n(!0))}return}I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.tryATransport()","viable transport "+t+"; setting pending"),this.setTransportPending(i,e),n(null,i)})}setTransportPending(e,t){let n=t.mode;I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.setTransportPending()","transport = "+e+"; mode = "+n),this.pendingTransport=e,this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),e.once("connected",(t,s,i)=>{this.activateTransport(t,e,s,i),"recover"===n&&this.options.recover&&(delete this.options.recover,this.unpersistConnection())});let s=this;e.on(["disconnected","closed","failed"],function(t){s.deactivateTransport(e,this.event,t)}),this.emit("transport.pending",e)}activateTransport(e,t,n,s){I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.activateTransport()","transport = "+t),e&&I.logAction(this.logger,I.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+e),n&&I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.activateTransport()","connectionId = "+n),s&&I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.activateTransport()","connectionDetail
1s = "+JSON.stringify(s)),this.persistTransportPreference(t);let i=this.state,r=this.states.connected.state;if(I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.activateTransport()","current state = "+i.state),i.state==this.states.closing.state||i.state==this.states.closed.state||i.state==this.states.failed.state)return I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.activateTransport()","Disconnecting transport and abandoning"),t.disconnect(),!1;if(delete this.pendingTransport,!t.isConnected)return I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.activateTransport()","Declining to activate transport "+t+" since it appears to no longer be connected"),!1;let o=this.activeProtocol;this.activeProtocol=new nd(t),this.host=t.params.host;let a=s.connectionKey;if(a&&this.connectionKey!=a&&this.setConnection(n,s,!!e),this.onConnectionDetailsUpdate(s,t),S.Config.nextTick(()=>{t.on("connected",(e,n,s)=>{this.onConnectionDetailsUpdate(s,t),this.emit("update",new ng(r,r,null,e))})}),i.state===this.states.connected.state?e&&(this.errorReason=this.realtime.connection.errorReason=e,this.emit("update",new ng(r,r,null,e))):(this.notifyState({state:"connected",error:e}),this.errorReason=this.realtime.connection.errorReason=e||null),this.emit("transport.active",t),o)if(o.messageQueue.count()>0&&I.logAction(this.logger,I.LOG_ERROR,"ConnectionManager.activateTransport()","Previous active protocol (for transport "+o.transport.shortName+", new one is "+t.shortName+") finishing with "+o.messageQueue.count()+" messages still pending"),o.transport===t){let e="Assumption violated: activating a transport that was also the transport for the previous active protocol; transport = "+t.shortName+"; stack = "+Error().stack;I.logAction(this.logger,I.LOG_ERROR,"ConnectionManager.activateTransport()",e)}else o.finish();return!0}deactivateTransport(e,t,n){let s=this.activeProtocol,i=s&&s.getTransport()===e,r=e===this.pendingTransport,o=this.noTransportsScheduledForActivation();if(I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.deactivateTransport()","transport = "+e),I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.deactivateTransport()","state = "+t+(i?"; was active":r?"; was pending":"")+(o?"":"; another transport is scheduled for activation")),n&&n.message&&I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.deactivateTransport()","reason = "+n.message),i&&(I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.deactivateTransport()","Getting, clearing, and requeuing "+this.activeProtocol.messageQueue.count()+" pending messages"),this.queuePendingMessages(s.getPendingMessages()),s.clearPendingMessages(),this.activeProtocol=this.host=null),this.emit("transport.inactive",e),i&&o||i&&"failed"===t||"closed"===t||null===s&&r){if("disconnected"===t&&n&&n.statusCode>500&&this.domains.length>1){this.unpersistTransportPreference(),this.forceFallbackHost=!0,this.notifyState({state:t,error:n,retryImmediately:!0});return}let e="failed"===t&&eJ.isTokenErr(n)?"disconnected":t;this.notifyState({state:e,error:n});return}}noTransportsScheduledForActivation(){return!this.pendingTransport||!this.pendingTransport.isConnected}setConnection(e,t,n){let s=this.connectionId;(s&&s!==e||!s&&n)&&(I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.setConnection()","Resetting msgSerial"),this.msgSerial=0,this.queuedMessages.resetSendAttempted()),this.connectionId!==e&&I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.setConnection()","New connectionId; reattaching any attached channels"),this.realtime.connection.id=this.connectionId=e,this.realtime.connection.key=this.connectionKey=t.connectionKey}clearConnection(){this.realtime.connection.id=this.connectionId=void 0,this.realtime.connection.key=this.connectionKey=void 0,this.msgSerial=0,this.unpersistConnection()}createRecoveryKey(){return this.connectionKey?JSON.stringify({connectionKey:this.connectionKey,msgSerial:this.msgSerial,channelSerials:this.realtime.channels.channelSerials()}):null}checkConnectionStateFreshness(){if(!this.lastActivity||!this.connectionId)return;let e=Date.now()-this.lastActivity;e>this.connectionStateTtl+this.maxIdleInterval&&(I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.checkConnectionStateFreshness()","Last known activity from realtime was "+e+"ms ago; discarding connection state"),this.clearConnection(),this.states.connecting.failState="suspended")}persistConnection(){if(nC()){let e=this.createRecoveryKey();e&&this.setSessionRecoverData({recoveryKey:e,disconnectedAt:Date.now(),location:nv.location,clientId:this.realtime.auth.clientId})}}unpersistConnection(){this.clearSessionRecoverData()}
1getActiveTransportFormat(){var e;return null==(e=this.activeProtocol)?void 0:e.getTransport().format}getError(){if(this.errorReason){let e=L.fromValues(this.errorReason);return e.cause=this.errorReason,e}return this.getStateError()}getStateError(){var e;return null==(e=nf[this.state.state])?void 0:e.call(nf)}activeState(){return this.state.queueEvents||this.state.sendEvents}enactStateChange(e){let t="Connection state",n=e.current+(e.reason?"; reason: "+e.reason:"");"failed"===e.current?I.logAction(this.logger,I.LOG_ERROR,t,n):I.logAction(this.logger,I.LOG_MAJOR,t,n),I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.enactStateChange","setting new state: "+e.current+"; reason = "+(e.reason&&e.reason.message));let s=this.state=this.states[e.current];e.reason&&(this.errorReason=e.reason,this.realtime.connection.errorReason=e.reason),(s.terminal||"suspended"===s.state)&&this.clearConnection(),this.emit("connectionstate",e)}startTransitionTimer(e){I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.startTransitionTimer()","transitionState: "+e.state),this.transitionTimer&&(I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.startTransitionTimer()","clearing already-running timer"),clearTimeout(this.transitionTimer)),this.transitionTimer=setTimeout(()=>{this.transitionTimer&&(this.transitionTimer=null,I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager "+e.state+" timer expired","requesting new state: "+e.failState),this.notifyState({state:e.failState}))},e.retryDelay)}cancelTransitionTimer(){I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.cancelTransitionTimer()",""),this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)}startSuspendTimer(){this.suspendTimer||(this.suspendTimer=setTimeout(()=>{this.suspendTimer&&(this.suspendTimer=null,I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager suspend timer expired","requesting new state: suspended"),this.states.connecting.failState="suspended",this.notifyState({state:"suspended"}))},this.connectionStateTtl))}checkSuspendTimer(e){"disconnected"!==e&&"suspended"!==e&&"connecting"!==e&&this.cancelSuspendTimer()}cancelSuspendTimer(){this.states.connecting.failState="disconnected",this.suspendTimer&&(clearTimeout(this.suspendTimer),this.suspendTimer=null)}startRetryTimer(e){this.retryTimer=setTimeout(()=>{I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager retry timer expired","retrying"),this.retryTimer=null,this.requestState({state:"connecting"})},e)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}startWebSocketSlowTimer(){this.webSocketSlowTimer=setTimeout(()=>{I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager WebSocket slow timer","checking connectivity"),this.checkWsConnectivity().then(()=>{I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager WebSocket slow timer","ws connectivity check succeeded"),this.wsCheckResult=!0}).catch(()=>{I.logAction(this.logger,I.LOG_MAJOR,"ConnectionManager WebSocket slow timer","ws connectivity check failed"),this.wsCheckResult=!1}),this.realtime.http.checkConnectivity&&eh(this.realtime.http.checkConnectivity(),(e,t)=>{e||!t?(I.logAction(this.logger,I.LOG_MAJOR,"ConnectionManager WebSocket slow timer","http connectivity check failed"),this.cancelWebSocketGiveUpTimer(),this.notifyState({state:"disconnected",error:new P("Unable to connect (network unreachable)",80003,404)})):I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager WebSocket slow timer","http connectivity check succeeded")})},this.options.timeouts.webSocketSlowTimeout)}cancelWebSocketSlowTimer(){this.webSocketSlowTimer&&(clearTimeout(this.webSocketSlowTimer),this.webSocketSlowTimer=null)}startWebSocketGiveUpTimer(e){this.webSocketGiveUpTimer=setTimeout(()=>{var t,n;this.wsCheckResult||(I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager WebSocket give up timer","websocket connection took more than 10s; "+(this.baseTransport?"trying base transport":"")),this.baseTransport?(this.abandonedWebSocket=!0,null==(t=this.proposedTransport)||t.dispose(),null==(n=this.pendingTransport)||n.dispose(),this.connectBase(e,++this.connectCounter)):I.logAction(this.logger,I.LOG_MAJOR,"ConnectionManager WebSocket give up timer","websocket connectivity appears to be unavailable but no other transports to try"))},this.options.timeouts.webSocketConnectTimeout)}cancelWebSocketGiveUpTimer(){this.webSocketGiveUpTimer&&(clearTimeout(this.webSocketGiveUpTimer),this.webSocketGiveUpTimer=null)}notifyState(e){var t;let n=e.state,s="disconnected"===n&&(this.state===this.states.connected||e.retryImmediately||this.state===this.states.connecting&&e.error&&eJ.isTokenErr(e.error)&&!(this.errorReason&&eJ.isTokenErr(this.errorReason)));if(I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.notifyState()","new state: "+n+(s?"; will retry connection immediately":"")),n==this.state.state||(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.checkSuspendTimer(e.state),("suspended"===n||"connected"===n)&&(this.disconnectedRetryCount=0),this.state.terminal))return;let i=this.states[e.state],r=i.retryDelay;"disconnected"===i.state&&(this.disconnectedRetryCount++,r=ey(i.retryDelay,this.disconnectedRetryCount));let o=new ng(this.state.state,i.state,r,e.error||(null==(t=nf[i.state])?void 0:t.call(nf)));if(s){let e=()=>{this.state===this.states.disconnected&&(this.lastAutoReconnectAttempt=Date.now(),this.requestState({state:"connecting"}))},t=this.lastAutoReconnectAttempt&&Date.now()-this.lastAutoReconnectAttempt+1;t&&t<1e3?(I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.notifyState()","Last reconnect attempt was only "+t+"ms ago, waiting another "+(1e3-t)+"ms before trying again"),setTimeout(e,1e3-t)):S.Config.nextTick(e)}else("disconnected"===n||"suspended"===n)&&this.startRetryTimer(r);
1("disconnected"===n&&!s||"suspended"===n||i.terminal)&&S.Config.nextTick(()=>{this.disconnectAllTransports()}),"connected"!=n||this.activeProtocol||I.logAction(this.logger,I.LOG_ERROR,"ConnectionManager.notifyState()","Broken invariant: attempted to go into connected state, but there is no active protocol"),this.enactStateChange(o),this.state.sendEvents?this.sendQueuedMessages():this.state.queueEvents||(this.realtime.channels.propogateConnectionInterruption(n,o.reason),this.failQueuedMessages(o.reason))}requestState(e){var t;let n=e.state;if(I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.requestState()","requested state: "+n+"; current state: "+this.state.state),n==this.state.state||(this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(n),"connecting"==n&&"connected"==this.state.state||"closing"==n&&"closed"==this.state.state))return;let s=this.states[n],i=new ng(this.state.state,s.state,null,e.error||(null==(t=nf[s.state])?void 0:t.call(nf)));this.enactStateChange(i),"connecting"==n&&S.Config.nextTick(()=>{this.startConnect()}),"closing"==n&&this.closeImpl()}startConnect(){if(this.state!==this.states.connecting)return void I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.startConnect()","Must be in connecting state to connect, but was "+this.state.state);let e=this.realtime.auth,t=++this.connectCounter,n=()=>{this.checkConnectionStateFreshness(),this.getTransportParams(e=>{if("recover"===e.mode&&e.options.recover){let t=nA(e.options.recover);t&&this.realtime.channels.recoverChannels(t.channelSerials)}t===this.connectCounter&&this.connectImpl(e,t)})};if(I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.startConnect()","starting connection"),this.startSuspendTimer(),this.startTransitionTimer(this.states.connecting),"basic"===e.method)n();else{let s=e=>{t===this.connectCounter&&(e?this.actOnErrorFromAuthorize(e):n())};this.errorReason&&eJ.isTokenErr(this.errorReason)?eh(e._forceNewToken(null,null),s):eh(e._ensureValidAuthCredentials(!1),s)}}connectImpl(e,t){let n=this.state.state;if(n!==this.states.connecting.state)return void I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.connectImpl()","Must be in connecting state to connect, but was "+n);let s=this.getTransportPreference();s&&s===this.baseTransport&&this.webSocketTransportAvailable&&this.checkWsConnectivity().then(()=>{this.unpersistTransportPreference(),this.state===this.states.connecting&&(I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.connectImpl():","web socket connectivity available, cancelling connection attempt with "+this.baseTransport),this.disconnectAllTransports(),this.connectWs(e,++this.connectCounter))}).catch(nw),s&&s===this.baseTransport||this.baseTransport&&!this.webSocketTransportAvailable?this.connectBase(e,t):this.connectWs(e,t)}connectWs(e,t){I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.connectWs()"),this.wsCheckResult=null,this.abandonedWebSocket=!1,this.startWebSocketSlowTimer(),this.startWebSocketGiveUpTimer(e),this.tryTransportWithFallbacks("web_socket",e,!0,t,()=>!1!==this.wsCheckResult&&!this.abandonedWebSocket)}connectBase(e,t){I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.connectBase()"),this.baseTransport?this.tryTransportWithFallbacks(this.baseTransport,e,!1,t,()=>!0):this.notifyState({state:"disconnected",error:new P("No transports left to try",8e4,404)})}tryTransportWithFallbacks(e,t,n,s,i){I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.tryTransportWithFallbacks()",e);let r=e=>{this.notifyState({state:this.states.connecting.failState,error:e})},o=this.domains.slice(),a=(e,t)=>{if(s===this.connectCounter){if(!i()){t&&t.dispose();return}t||e||l()}},c=o.shift();if(!c)return void r(new P("Unable to connect (no available host)",80003,404));t.host=c;let l=()=>{o.length?this.realtime.http.checkConnectivity?eh(this.realtime.http.checkConnectivity(),(n,c)=>{if(s===this.connectCounter&&i()){if(n)return void r(n);if(!c)return void r(new P("Unable to connect (network unreachable)",80003,404));t.host=ee(o),this.tryATransport(t,e,a)}}):r(new L("Internal error: Http.checkConnectivity not set",null,500)):r(new P("Unable to connect (and no more fallback hosts to try)",80003,404))};if(this.forceFallbackHost&&o.length){this.forceFallbackHost=!1,l();return}this.tryATransport(t,e,a)}closeImpl(){I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.closeImpl()","closing connection"),this.cancelSuspendTimer(),this.startTransitionTimer(this.states.closing),this.pendingTransport&&(I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.closeImpl()","Closing pending transport: "+this.pendingTransport),this.pendingTransport.close()),this.activeProtocol&&(I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.closeImpl()","Closing active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().close()),this.notifyState({state:"closed"})}onAuthUpdated(e,t){var n;switch(this.state.state){case"connected":{I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Sending AUTH message on active transport");let s=null==(n=this.activeProtocol)?void 0:n.getTransport();s&&s.onAuthUpdated&&s.onAuthUpdated(e);let i=ne({action:eY.AUTH,auth:{accessToken:e.token}});this.send(i);let r=()=>{this.off(o),t(null,e)},o=e=>{"failed"===e.current&&(this.off(r),this.off(o),t(e.reason||this.get
1StateError()))};this.once("connectiondetails",r),this.on("connectionstate",o);break}case"connecting":I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Aborting current connection attempts in order to start again with the new auth details"),this.disconnectAllTransports();default:{I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Connection state is "+this.state.state+"; waiting until either connected or failed");let n=s=>{switch(s.current){case"connected":this.off(n),t(null,e);break;case"failed":case"closed":case"suspended":this.off(n),t(s.reason||this.getStateError())}};this.on("connectionstate",n),"connecting"===this.state.state?this.startConnect():this.requestState({state:"connecting"})}}}disconnectAllTransports(){I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.disconnectAllTransports()","Disconnecting all transports"),this.connectCounter++,this.pendingTransport&&(I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting pending transport: "+this.pendingTransport),this.pendingTransport.disconnect()),delete this.pendingTransport,this.proposedTransport&&(I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting proposed transport: "+this.pendingTransport),this.proposedTransport.disconnect()),delete this.pendingTransport,this.activeProtocol&&(I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().disconnect())}send(e,t,n){n=n||nw;let s=this.state;if(s.sendEvents){I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.send()","sending event"),this.sendImpl(new nu(e,n));return}if(!(t&&s.queueEvents)){let e="rejecting event, queueEvent was "+t+", state was "+s.state;I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.send()",e),n(this.errorReason||new P(e,9e4,400));return}this.logger.shouldLog(I.LOG_MICRO)&&I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.send()","queueing msg; "+nt(e,this.realtime._RealtimePresence,this.realtime._Annotations,this.realtime._objectsPlugin)),this.queue(e,n)}sendImpl(e){let t=e.message;e.ackRequired&&!e.sendAttempted&&(t.msgSerial=this.msgSerial++);try{this.activeProtocol.send(e)}catch(e){I.logAction(this.logger,I.LOG_ERROR,"ConnectionManager.sendImpl()","Unexpected exception in transport.send(): "+e.stack)}}queue(e,t){I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.queue()","queueing event");let n=this.queuedMessages.last(),s=this.options.maxMessageSize;n&&!n.sendAttempted&&function(e,t,n){let s;if(e.channel!==t.channel||(s=e.action)!==eY.PRESENCE&&s!==eY.MESSAGE||s!==t.action)return!1;let i=s===eY.PRESENCE?"presence":"messages",r=e[i].concat(t[i]);return!(tN(r)>n)&&!!Y(r,"clientId")&&!!r.every(function(e){return!e.id})&&(e[i]=r,!0)}(n.message,e,s)?(n.merged||(n.callback=eB.create(this.logger,[n.callback]),n.merged=!0),n.callback.push(t)):this.queuedMessages.push(new nu(e,t))}sendQueuedMessages(){let e;for(I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.sendQueuedMessages()","sending "+this.queuedMessages.count()+" queued messages");e=this.queuedMessages.shift();)this.sendImpl(e)}queuePendingMessages(e){e&&e.length&&(I.logAction(this.logger,I.LOG_MICRO,"ConnectionManager.queuePendingMessages()","queueing "+e.length+" pending messages"),this.queuedMessages.prepend(e))}failQueuedMessages(e){let t=this.queuedMessages.count();t>0&&(I.logAction(this.logger,I.LOG_ERROR,"ConnectionManager.failQueuedMessages()","failing "+t+" queued messages, err = "+ei(e)),this.queuedMessages.completeAllMessages(e))}onChannelMessage(e,t){this.pendingChannelMessagesState.queue.push({message:e,transport:t}),this.pendingChannelMessagesState.isProcessing||this.processNextPendingChannelMessage()}processNextPendingChannelMessage(){if(this.pendingChannelMessagesState.queue.length>0){this.pendingChannelMessagesState.isProcessing=!0;let e=this.pendingChannelMessagesState.queue.shift();this.processChannelMessage(e.message).catch(e=>{I.logAction(this.logger,I.LOG_ERROR,"ConnectionManager.processNextPendingChannelMessage() received error ",e)}).finally(()=>{this.pendingChannelMessagesState.isProcessing=!1,this.processNextPendingChannelMessage()})}}async processChannelMessage(e){await this.realtime.channels.processChannelMessage(e)}async ping(){var e;if("connected"!==this.state.state)throw new P("Unable to ping service; not connected",4e4,400);let t=null==(e=this.activeProtocol)?void 0:e.getTransport();
1if(!t)throw this.getStateError();I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.ping()","transport = "+t);let n=Date.now(),s=ea();return eS(new Promise(e=>{let i=r=>{r===s&&(t.off("heartbeat",i),e(Date.now()-n))};t.on("heartbeat",i),t.ping(s)}),this.options.timeouts.realtimeRequestTimeout,"Timeout waiting for heartbeat response")}abort(e){this.activeProtocol.getTransport().fail(e)}getTransportPreference(){var e,t;return this.transportPreference||nO()&&(null==(t=null==(e=S.WebStorage)?void 0:e.get)?void 0:t.call(e,nR))}persistTransportPreference(e){var t,n;this.transportPreference=e.shortName,nO()&&(null==(n=null==(t=S.WebStorage)?void 0:t.set)||n.call(t,nR,e.shortName))}unpersistTransportPreference(){var e,t;this.transportPreference=null,nO()&&(null==(t=null==(e=S.WebStorage)?void 0:e.remove)||t.call(e,nR))}actOnErrorFromAuthorize(e){if(40171===e.code)this.notifyState({state:"failed",error:e});else if(40102===e.code)this.notifyState({state:"failed",error:e});else if(e.statusCode===eD.Forbidden){let t="Client configured authentication provider returned 403; failing the connection";I.logAction(this.logger,I.LOG_ERROR,"ConnectionManager.actOnErrorFromAuthorize()",t),this.notifyState({state:"failed",error:new P(t,80019,403,e)})}else{let t="Client configured authentication provider request failed";I.logAction(this.logger,I.LOG_MINOR,"ConnectionManager.actOnErrorFromAuthorize",t),this.notifyState({state:this.state.failState,error:new P(t,80019,401,e)})}}onConnectionDetailsUpdate(e,t){if(!e)return;this.connectionDetails=e,e.maxMessageSize&&(this.options.maxMessageSize=e.maxMessageSize);let n=e.clientId;if(n){let e=this.realtime.auth._uncheckedSetClientId(n);if(e){I.logAction(this.logger,I.LOG_ERROR,"ConnectionManager.onConnectionDetailsUpdate()",e.message),t.fail(e);return}}let s=e.connectionStateTtl;s&&(this.connectionStateTtl=s),this.maxIdleInterval=e.maxIdleInterval,this.emit("connectiondetails",e)}checkWsConnectivity(){let e=this.options.wsConnectivityCheckUrl||eT.wsConnectivityCheckUrl,t=new S.Config.WebSocket(e);return new Promise((e,n)=>{let s=!1;t.onopen=()=>{s||(s=!0,e(),t.close())},t.onclose=t.onerror=()=>{s||(s=!0,n())}})}sessionRecoveryName(){return this.options.recoveryKeyStorageName||"ably-connection-recovery"}getSessionRecoverData(){var e,t;return nC()&&(null==(t=null==(e=S.WebStorage)?void 0:e.getSession)?void 0:t.call(e,this.sessionRecoveryName()))}setSessionRecoverData(e){var t,n;return nC()&&(null==(n=null==(t=S.WebStorage)?void 0:t.setSession)?void 0:n.call(t,this.sessionRecoveryName(),e))}clearSessionRecoverData(){var e,t;return nC()&&(null==(t=null==(e=S.WebStorage)?void 0:e.removeSession)?void 0:t.call(e,this.sessionRecoveryName()))}},nT=class extends eX{constructor(e,t){super(e.logger),this.whenState=e=>eX.prototype.whenState.call(this,e,this.state),this.ably=e,this.connectionManager=new nk(e,t),this.state=this.connectionManager.state.state,this.key=void 0,this.id=void 0,this.errorReason=null,this.connectionManager.on("connectionstate",e=>{let t=this.state=e.current;S.Config.nextTick(()=>{this.emit(t,e)})}),this.connectionManager.on("update",e=>{S.Config.nextTick(()=>{this.emit("update",e)})})}connect(){I.logAction(this.logger,I.LOG_MINOR,"Connection.connect()",""),this.connectionManager.requestState({state:"connecting"})}async ping(){return I.logAction(this.logger,I.LOG_MINOR,"Connection.ping()",""),this.connectionManager.ping()}close(){I.logAction(this.logger,I.LOG_MINOR,"Connection.close()","connectionKey = "+this.key),this.connectionManager.requestState({state:"closing"})}get recoveryKey(){return this.logger.deprecationWarning("The `Connection.recoveryKey` attribute has been replaced by the `Connection.createRecoveryKey()` method. Replace your usage of `recoveryKey` with the return value of `createRecoveryKey()`. `recoveryKey` will be removed in a future version."),this.createRecoveryKey()}createRecoveryKey(){return this.connectionManager.createRecoveryKey()}},nM=class e extends ta{constructor(t){var n,s,i,r;if(super(eT.objectifyOptions(t,!1,"BaseRealtime",I.defaultLogger)),I.logAction(this.logger,I.LOG_MINOR,"Realtime()",""),"string"==typeof EdgeRuntime)throw new P('Ably.Realtime instance cannot be used in Vercel Edge runtime. If you are running Vercel Edge functions, please replace your "new Ably.Realtime()" with "new Ably.Rest()" and use Ably Rest API instead of the Realtime API. If you are server-rendering your application in the Vercel Edge runtime, please use the condition "if (typeof EdgeRuntime === \'string\')" to prevent instantiating Ably.Realtime instance during SSR in the Vercel Edge runtime.',4e4,400);this._additionalTransportImplementations=e.transportImplementationsFromPlugins(this.options.plugins),this._RealtimePresence=null!=(s=null==(n=this.options.plugins)?void 0:n.RealtimePresence)?s:null,this._objectsPlugin=null!=(r=null==(i=this.options.plugins)?void 0:i.Objects)?r:null,this.connection=new nT(this,this.options),this._channels=new nI(this),!1!==this.options.autoConnect&&this.connect()}static transportImplementationsFromPlugins(e){let t={};return(null==e?void 0:e.WebSocketTransport)&&(t[a.WebSocket]=e.WebSocketTransport),(null==e?void 0:e.XHRPolling)&&(t[a.XhrPolling]=e.XHRPolling),t}get channels(){return this._channels}connect(){I.logAction(this.logger,I.LOG_MINOR,"Realtime.connect()",""),this.connection.connect()}close(){I.logAction(this.logger,I.LOG_MINOR,"Realtime.close()",""),this.connection.close()}};nM.EventEmitter=eX;var nI=class extends eX{constructor(e){super(e.logger),this.realtime=e,this.all=Object.create(null),e.connection.connectionManager.on("transport.active",()=>{this.onTransportActive()})}channelSerials(){let e={};for(let t of K(this.all,!0)){let n=this.all[t];n.properties.channelSerial&&(e[t]=n.properties.channelSerial)}return e}recoverChannels(e){for(let t of K(e,!0))this.get(t).properties.channelSerial=e[t]}async processChannelMessage(e){let t=e.channel;if(void 0===t)return void I.logAction(this.logger,I.LOG_ERROR,"Channels.processChannelMessage()","received event unspecified channel, action = "+e.action);let n=this.all[t];n?await n.processMessage(e):I.logAction(this.logger,I.LOG_ERROR,"Channels.processChannelMessage()","received event for non-existent channel: "+t)}onTransportActive(){for(let e in this.all){let t=this.all[e];"attaching"===t.state||"detaching"===t.state?t.checkPendingState():"suspended"===t.state?t._attach(!1,null):"attached"===t.state&&t.requestState("attaching")}}propogateConnectionInterruption(e,t){let n=["attaching","attached","detaching","suspended"],s={closing:"detached",closed:"detached",failed:"failed",suspended:"suspended"}[e];for(let e in this.all){let i=this.all[e];n.includes(i.state)&&i.notifyState(s,t)}}get(e,t){e=String(e);let n=this.all[e];if(n){if(t){if(n._shouldReattachToSetOptions(t,n.channelOptions))throw new P("Channels.get() cannot be used to set channel options that would cause the channel to reattach. Please, use RealtimeChannel.setOptions() instead.",4e4,400);n.setOptions(t)}}else n=this.all[e]=new nr(this.realtime,e,t);return n}getDerived(e,t,n){if(t.filter){let n=eC(t.filter),s=eO(e);e=`[filter=${n}${s.qualifierParam}]${s.channelName}`}return this.get(e,n)}release(e){e=String(e);let t=this.all[e];if(!t)return;let n=t.getReleaseErr();if(n)throw n;delete this.all[e]}},n_=nM;function nE(e,t){if(e.isSynthesized()||t.isSynthesized())return e.timestamp>=t.timestamp;let n=e.parseId(),s=t.parseId();return n.msgSerial===s.msgSerial?n.index>s.index:n.msgSerial>s.msgSerial}var nP=class extends eX{constructor(e,t,n=nE){super(e.logger),this.presence=e,this.map=Object.create(null),this.syncInProgress=!1,this.residualMembers=null,this.memberKey=t,this.newerThan=n}get(e){return this.map[e]}getClient(e){let t=this.map,n=[];for(let s in t){let i=t[s];i.clientId==e&&"absent"!=i.action&&n.push(i)}return n}list(e){let t=this.map,n=e&&e.clientId,s=e&&e.connectionId,i=[];for(let e in t){let r=t[e];"absent"!==r.action&&(!n||n==r.clientId)&&(s&&s!=r.connectionId||i.push(r))}return i}put(e){("enter"===e.action||"update"===e.action)&&((e=tk.fromValues(e)).action="present");let t=this.map,n=this.memberKey(e);this.residualMembers&&delete this.residualMembers[n];let s=t[n];
1return(!s||!!this.newerThan(e,s))&&(t[n]=e,!0)}values(){let e=this.map,t=[];for(let n in e){let s=e[n];"absent"!=s.action&&t.push(s)}return t}remove(e){let t=this.map,n=this.memberKey(e),s=t[n];return(!s||!!this.newerThan(e,s))&&(this.syncInProgress?((e=tk.fromValues(e)).action="absent",t[n]=e):delete t[n],!!s)}startSync(){let e=this.map,t=this.syncInProgress;I.logAction(this.logger,I.LOG_MINOR,"PresenceMap.startSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+t),this.syncInProgress||(this.residualMembers=U(e),this.setInProgress(!0))}endSync(){let e=this.map,t=this.syncInProgress;if(I.logAction(this.logger,I.LOG_MINOR,"PresenceMap.endSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+t),t){for(let t in e)"absent"===e[t].action&&delete e[t];for(let t in this.presence._synthesizeLeaves(Q(this.residualMembers)),this.residualMembers)delete e[t];this.residualMembers=null,this.setInProgress(!1)}this.emit("sync")}waitSync(e){let t=this.syncInProgress;(I.logAction(this.logger,I.LOG_MINOR,"PresenceMap.waitSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+t),t)?this.once("sync",e):e()}clear(){this.map={},this.setInProgress(!1),this.residualMembers=null}setInProgress(e){I.logAction(this.logger,I.LOG_MICRO,"PresenceMap.setInProgress()","inProgress = "+e),this.syncInProgress=e,this.presence.syncComplete=!e}};function nL(e){let t=e.channel.client,n=t.auth.clientId;return(!n||"*"===n)&&"connected"===t.connection.state}var nN=class extends eX{constructor(e){super(e.logger),this.channel=e,this.syncComplete=!1,this.members=new nP(this,e=>e.clientId+":"+e.connectionId),this._myMembers=new nP(this,e=>e.clientId),this.subscriptions=new eX(this.logger),this.pendingPresence=[]}async enter(e){if(nL(this))throw new P("clientId must be specified to enter a presence channel",40012,400);return this._enterOrUpdateClient(void 0,void 0,e,"enter")}async update(e){if(nL(this))throw new P("clientId must be specified to update presence data",40012,400);return this._enterOrUpdateClient(void 0,void 0,e,"update")}async enterClient(e,t){return this._enterOrUpdateClient(void 0,e,t,"enter")}async updateClient(e,t){return this._enterOrUpdateClient(void 0,e,t,"update")}async _enterOrUpdateClient(e,t,n,s){let i=this.channel;if(!i.connectionManager.activeState())throw i.connectionManager.getError();I.logAction(this.logger,I.LOG_MICRO,"RealtimePresence."+s+"Client()","channel = "+i.name+", id = "+e+", client = "+(t||"(implicit) "+this.channel.client.auth.clientId));let r=tk.fromData(n);r.action=s,e&&(r.id=e),t&&(r.clientId=t);let o=await r.encode(i.channelOptions);switch(i.state){case"attached":return i.sendPresence([o]);case"initialized":case"detached":i.attach();case"attaching":return new Promise((e,t)=>{this.pendingPresence.push({presence:o,callback:n=>n?t(n):e()})});default:{let e=new L("Unable to "+s+" presence channel while in "+i.state+" state",90001);throw e.code=90001,e}}}async leave(e){if(nL(this))throw new P("clientId must have been specified to enter or leave a presence channel",40012,400);return this.leaveClient(void 0,e)}async leaveClient(e,t){let n=this.channel;if(!n.connectionManager.activeState())throw n.connectionManager.getError();I.logAction(this.logger,I.LOG_MICRO,"RealtimePresence.leaveClient()","leaving; channel = "+this.channel.name+", client = "+e);let s=tk.fromData(t);s.action="leave",e&&(s.clientId=e);let i=await s.encode(n.channelOptions);switch(n.state){case"attached":return n.sendPresence([i]);case"attaching":return new Promise((e,t)=>{this.pendingPresence.push({presence:i,callback:n=>n?t(n):e()})});case"initialized":case"failed":throw new L("Unable to leave presence channel (incompatible state)",90001);default:throw n.invalidStateError()}}async get(e){let t=!e||!("waitForSync"in e)||e.waitForSync;return new Promise((n,s)=>{function i(t){n(e?t.list(e):t.values())}"suspended"===this.channel.state?t?s(P.fromValues({statusCode:400,code:91005,message:"Presence state is out of sync due to channel being in the SUSPENDED state"})):i(this.members):function(e,t,n){switch(e.state){case"attached":case"suspended":n();break;case"initialized":case"detached":case"detaching":case"attaching":eh(e.attach(),function(e){e?t(e):n()});break;default:t(P.fromValues(e.invalidStateError()))}}(this.channel,e=>s(e),()=>{let e=this.members;t?e.waitSync(function(){i(e)}):i(e)})})}async history(e){I.logAction(this.logger,I.LOG_MICRO,"RealtimePresence.history()","channel = "+this.name);let t=this.channel.client.rest.presenceMixin;
1if(e&&e.untilAttach)if("attached"===this.channel.state)delete e.untilAttach,e.from_serial=this.channel.properties.attachSerial;else throw new P("option untilAttach requires the channel to be attached, was: "+this.channel.state,4e4,400);return t.history(this,e)}setPresence(e,t,n){let s,i;I.logAction(this.logger,I.LOG_MICRO,"RealtimePresence.setPresence()","received presence for "+e.length+" participants; syncChannelSerial = "+n);let r=this.members,o=this._myMembers,a=[],c=this.channel.connectionManager.connectionId;for(let l of(t&&(this.members.startSync(),n&&(i=n.match(/^[\w-]+:(.*)$/))&&(s=i[1])),e))switch(l.action){case"leave":r.remove(l)&&a.push(l),l.connectionId!==c||l.isSynthesized()||o.remove(l);break;case"enter":case"present":case"update":r.put(l)&&a.push(l),l.connectionId===c&&o.put(l)}t&&!s&&(r.endSync(),this.channel.syncChannelSerial=null);for(let e=0;e<a.length;e++){let t=a[e];this.subscriptions.emit(t.action,t)}}onAttached(e){I.logAction(this.logger,I.LOG_MINOR,"RealtimePresence.onAttached()","channel = "+this.channel.name+", hasPresence = "+e),e?this.members.startSync():(this._synthesizeLeaves(this.members.values()),this.members.clear()),this._ensureMyMembersPresent();let t=this.pendingPresence,n=t.length;if(n){this.pendingPresence=[];let e=[],s=eB.create(this.logger);I.logAction(this.logger,I.LOG_MICRO,"RealtimePresence.onAttached","sending "+n+" queued presence messages");for(let i=0;i<n;i++){let n=t[i];e.push(n.presence),s.push(n.callback)}this.channel.sendPresence(e).then(()=>s()).catch(e=>s(e))}}actOnChannelState(e,t,n){switch(e){case"attached":this.onAttached(t);break;case"detached":case"failed":this._clearMyMembers(),this.members.clear();case"suspended":this.failPendingPresence(n)}}failPendingPresence(e){if(this.pendingPresence.length){I.logAction(this.logger,I.LOG_MINOR,"RealtimeChannel.failPendingPresence","channel; name = "+this.channel.name+", err = "+ei(e));for(let t=0;t<this.pendingPresence.length;t++)try{this.pendingPresence[t].callback(e)}catch(e){}this.pendingPresence=[]}}_clearMyMembers(){this._myMembers.clear()}_ensureMyMembersPresent(){let e=this._myMembers,t=this.channel.connectionManager.connectionId;for(let n in e.map){let s=e.map[n];I.logAction(this.logger,I.LOG_MICRO,"RealtimePresence._ensureMyMembersPresent()",'Auto-reentering clientId "'+s.clientId+'" into the presence set');let i=s.connectionId===t?s.id:void 0;this._enterOrUpdateClient(i,s.clientId,s.data,"enter").catch(e=>{let t=new P("Presence auto re-enter failed",91004,400,e);I.logAction(this.logger,I.LOG_ERROR,"RealtimePresence._ensureMyMembersPresent()","Presence auto re-enter failed; reason = "+ei(e));let n=new ns(this.channel.state,this.channel.state,!0,!1,t);this.channel.emit("update",n)})}}_synthesizeLeaves(e){let t=this.subscriptions;e.forEach(function(e){let n=tk.fromValues({action:"leave",connectionId:e.connectionId,clientId:e.clientId,data:e.data,encoding:e.encoding,timestamp:Date.now()});t.emit("leave",n)})}async subscribe(...e){let t=nr.processListenerArgs(e),n=t[0],s=t[1],i=this.channel;if("failed"===i.state)throw P.fromValues(i.invalidStateError());this.subscriptions.on(n,s),!1!==i.channelOptions.attachOnSubscribe&&await i.attach()}unsubscribe(...e){let t=nr.processListenerArgs(e),n=t[0],s=t[1];this.subscriptions.off(n,s)}},nU=a.WebSocket,nx=class extends nb{constructor(e,t,n){super(e,t,n),this.shortName=nU,n.heartbeats=S.Config.useProtocolHeartbeats,this.wsHost=n.host}static isAvailable(){return!!S.Config.WebSocket}createWebSocket(e,t){return this.uri=e+et(t),new S.Config.WebSocket(this.uri)}toString(){return"WebSocketTransport; uri="+this.uri}connect(){I.logAction(this.logger,I.LOG_MINOR,"WebSocketTransport.connect()","starting"),nb.prototype.connect.call(this);let e=this,t=this.params,n=t.options,s=(n.tls?"wss://":"ws://")+this.wsHost+":"+eT.getPort(n)+"/";I.logAction(this.logger,I.LOG_MINOR,"WebSocketTransport.connect()","uri: "+s),eh(this.auth.getAuthParams(),function(n,i){if(e.isDisposed)return;let r="";for(let e in i)r+=" "+e+": "+i[e]+";";if(I.logAction(e.logger,I.LOG_MINOR,"WebSocketTransport.connect()","authParams:"+r+" err: "+n),n)return void e.disconnect(n);
1let o=t.getConnectParams(i);try{let t=e.wsConnection=e.createWebSocket(s,o);t.binaryType=S.Config.binaryType,t.onopen=function(){e.onWsOpen()},t.onclose=function(t){e.onWsClose(t)},t.onmessage=function(t){e.onWsData(t.data)},t.onerror=function(t){e.onWsError(t)},t.on&&t.on("ping",function(){e.onActivity()})}catch(t){I.logAction(e.logger,I.LOG_ERROR,"WebSocketTransport.connect()","Unexpected exception creating websocket: err = "+(t.stack||t.message)),e.disconnect(t)}})}send(e){let t=this.wsConnection;if(!t)return void I.logAction(this.logger,I.LOG_ERROR,"WebSocketTransport.send()","No socket connection");try{t.send(ed(e,this.connectionManager.realtime._MsgPack,this.params.format))}catch(t){let e="Exception from ws connection when trying to send: "+ei(t);I.logAction(this.logger,I.LOG_ERROR,"WebSocketTransport.send()",e),this.finish("disconnected",new P(e,5e4,500))}}onWsData(e){I.logAction(this.logger,I.LOG_MICRO,"WebSocketTransport.onWsData()","data received; length = "+e.length+"; type = "+typeof e);try{var t,n,s,i,r;this.onProtocolMessage((t=this.connectionManager.realtime._MsgPack,n=this.connectionManager.realtime._RealtimePresence,s=this.connectionManager.realtime._Annotations,i=this.connectionManager.realtime._objectsPlugin,r=this.format,t9(eu(e,t,r),n,s,i)))}catch(e){I.logAction(this.logger,I.LOG_ERROR,"WebSocketTransport.onWsData()","Unexpected exception handing channel message: "+e.stack)}}onWsOpen(){I.logAction(this.logger,I.LOG_MINOR,"WebSocketTransport.onWsOpen()","opened WebSocket"),this.emit("preconnect")}onWsClose(e){let t,n;if("object"==typeof e?(n=e.code,t=e.wasClean||1e3===n):t=1e3==(n=e),delete this.wsConnection,t){I.logAction(this.logger,I.LOG_MINOR,"WebSocketTransport.onWsClose()","Cleanly closed WebSocket");let e=new P("Websocket closed",80003,400);this.finish("disconnected",e)}else{let e="Unclean disconnection of WebSocket ; code = "+n,t=new P(e,80003,400);I.logAction(this.logger,I.LOG_MINOR,"WebSocketTransport.onWsClose()",e),this.finish("disconnected",t)}
1this.emit("disposed")}onWsError(e){I.logAction(this.logger,I.LOG_MINOR,"WebSocketTransport.onError()","Error from WebSocket: "+e.message),S.Config.nextTick(()=>{this.disconnect(Error(e.message))})}dispose(){I.logAction(this.logger,I.LOG_MINOR,"WebSocketTransport.dispose()",""),this.isDisposed=!0;let e=this.wsConnection;e&&(e.onmessage=function(){},delete this.wsConnection,S.Config.nextTick(()=>{if(I.logAction(this.logger,I.LOG_MICRO,"WebSocketTransport.dispose()","closing websocket"),!e)throw Error("WebSocketTransport.dispose(): wsConnection is not defined");e.close()}))}},nG=class{static subscribeFilter(e,t,n){let s=e=>{var s,i,r,o,a,c;let l={name:e.name,refTimeserial:null==(i=null==(s=e.extras)?void 0:s.ref)?void 0:i.timeserial,refType:null==(o=null==(r=e.extras)?void 0:r.ref)?void 0:o.type,isRef:!!(null==(c=null==(a=e.extras)?void 0:a.ref)?void 0:c.timeserial),clientId:e.clientId};Object.entries(t).find(([e,t])=>void 0!==t&&l[e]!==t)||n(e)};this.addFilteredSubscription(e,t,n,s),e.subscriptions.on(s)}static addFilteredSubscription(e,t,n,s){var i;if(e.filteredSubscriptions||(e.filteredSubscriptions=new Map),e.filteredSubscriptions.has(n)){let r=e.filteredSubscriptions.get(n);r.set(t,(null==(i=null==r?void 0:r.get(t))?void 0:i.concat(s))||[s])}else e.filteredSubscriptions.set(n,new Map([[t,[s]]]))}static getAndDeleteFilteredSubscriptions(e,t,n){if(!e.filteredSubscriptions)return[];if(!n&&t)return Array.from(e.filteredSubscriptions.entries()).map(([n,s])=>{var i;let r=s.get(t);return s.delete(t),0===s.size&&(null==(i=e.filteredSubscriptions)||i.delete(n)),r}).reduce((e,t)=>t?e.concat(...t):e,[]);if(!n||!e.filteredSubscriptions.has(n))return[];let s=e.filteredSubscriptions.get(n);if(!t){let t=Array.from(s.values()).reduce((e,t)=>e.concat(...t),[]);return e.filteredSubscriptions.delete(n),t}let i=s.get(t);return s.delete(t),i||[]}},nB=class e extends n_{constructor(t){var n;const s=e._MsgPack;if(!s)throw Error("Expected DefaultRealtime._MsgPack to have been set");super(eT.objectifyOptions(t,!0,"Realtime",I.defaultLogger,p(w({},tF),m({Crypto:null!=(n=e.Crypto)?n:void 0,MsgPack:s,RealtimePresence:{RealtimePresence:nN,PresenceMessage:tk,WirePresenceMessage:tS},Annotations:{Annotation:t1,WireAnnotation:t0,RealtimeAnnotations:na,RestAnnotations:t6},WebSocketTransport:nx,MessageInteractions:nG}))))}static get Crypto(){if(null===this._Crypto)throw Error("Encryption not enabled; use ably.encryption.js instead");return this._Crypto}static set Crypto(e){this._Crypto=e}};nB.Utils=_,nB.ConnectionManager=nk,nB.ProtocolMessage=nn,nB._Crypto=null,nB.Message=tJ,nB.PresenceMessage=tz,nB.Annotation=t4,nB._MsgPack=null,nB._Http=eK,nB._PresenceMap=nP,nB._MessageEncoding=tn;var nq=nB,nD=Uint8Array,nj=Uint32Array,nH=Math.pow,nW=new nj(8),nV=[],nF=new nj(64);function nJ(e){return(e-(0|e))*nH(2,32)|0}for(var nz=2,n$=0;n$<64;){for(l=2,c=!0;l<=nz/2;l++)nz%l==0&&(c=!1);c&&(n$<8&&(nW[n$]=nJ(nH(nz,.5))),nV[n$]=nJ(nH(nz,1/3)),n$++),nz++}var nK=!!new nD(new nj([1]).buffer)[0];function nQ(e){return nK?e>>>24|(e>>>16&255)<<8|(65280&e)<<8|e<<24:e}function nX(e,t){return e>>>t|e<<32-t}function nY(e){var t=nW.slice(),n=e.length,s=8*n,i=512-(s+64)%512-1+s+65,r=new nD(i/8),o=new nj(r.buffer);r.set(e,0),r[n]=128,o[o.length-1]=nQ(s);for(var a=0;a<i/32;a+=16){var c=t.slice();for(l=0;l<64;l++){if(l<16)h=nQ(o[a+l]);else{var l,h,u=nF[l-15],d=nF[l-2];h=nF[l-7]+nF[l-16]+(nX(u,7)^nX(u,18)^u>>>3)+(nX(d,17)^nX(d,19)^d>>>10)}nF[l]=h|=0;for(var g=(nX(c[4],6)^nX(c[4],11)^nX(c[4],25))+(c[4]&c[5]^~c[4]&c[6])+c[7]+h+nV[l],p=(nX(c[0],2)^nX(c[0],13)^nX(c[0],22))+(c[0]&c[1]^c[2]&(c[0]^c[1])),f=7;f>0;f--)c[f]=c[f-1];c[0]=g+p|0,c[4]=c[4]+g|0}for(l=0;l<8;l++)t[l]=t[l]+c[l]|0}return new nD(new nj(t.map(function(e){return nQ(e)})).buffer)}var nZ=new class{constructor(){this.base64CharSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this.hexCharSet="0123456789abcdef"}uint8ViewToBase64(e){let t,n,s,i,r,o="",a=this.base64CharSet,c=e.byteLength,l=c%3,h=c-l;for(let c=0;c<h;c+=3)t=(0xfc0000&(r=e[c]<<16|e[c+1]<<8|e[c+2]))>>18,n=(258048&r)>>12,s=(4032&r)>>6,i=63&r,o+=a[t]+a[n]+a[s]+a[i];return 1==l?(t=(252&(r=e[h]))>>2,n=(3&r)<<4,o+=a[t]+a[n]+"=="):2==l&&(t=(64512&(r=e[h]<<8|e[h+1]))>>10,n=(1008&r)>>4,s=(15&r)<<2,o+=a[t]+a[n]+a[s]+"="),o}base64ToArrayBuffer(e){let t=null==atob?void 0:atob(e),n=t.length,s=new Uint8Array(n);for(let e=0;e<n;e++){let n=t.charCodeAt(e);s[e]=n}return this.toArrayBuffer(s)}isBuffer(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)}toBuffer(e){if(!ArrayBuffer)throw Error("Can't convert to Buffer: browser does not support the necessary types");if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(this.toArrayBuffer(e));throw Error("BufferUtils.toBuffer expected an ArrayBuffer or a view onto one")}toArrayBuffer(e){if(!ArrayBuffer)throw Error("Can't convert to ArrayBuffer: browser does not support the necessary types");if(e instanceof ArrayBuffer)return e;if(ArrayBuffer.isView(e))return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);throw Error("BufferUtils.toArrayBuffer expected an ArrayBuffer or a view onto one")}base64Encode(e){return this.uint8ViewToBase64(this.toBuffer(e))}base64UrlEncode(e){return this.base64Encode(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}base64Decode(e){if(ArrayBuffer&&S.Config.atob)return this.base64ToArrayBuffer(e);throw Error("Expected ArrayBuffer to exist and Platform.Config.atob to be configured")}hexEncode(e){return this.toBuffer(e).reduce((e,t)=>
1e+t.toString(16).padStart(2,"0"),"")}hexDecode(e){if(e.length%2!=0)throw Error("Can't create a byte array from a hex string of odd length");let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.slice(2*n,2*(n+1)),16);return this.toArrayBuffer(t)}utf8Encode(e){if(S.Config.TextEncoder){let t=new S.Config.TextEncoder().encode(e);return this.toArrayBuffer(t)}throw Error("Expected TextEncoder to be configured")}utf8Decode(e){if(!this.isBuffer(e))throw Error("Expected input of utf8decode to be an arraybuffer or typed array");if(TextDecoder)return new TextDecoder().decode(e);throw Error("Expected TextDecoder to be configured")}areBuffersEqual(e,t){if(!e||!t)return!1;let n=this.toArrayBuffer(e),s=this.toArrayBuffer(t);if(n.byteLength!=s.byteLength)return!1;let i=new Uint8Array(n),r=new Uint8Array(s);for(var o=0;o<i.length;o++)if(i[o]!=r[o])return!1;return!0}byteLength(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e.byteLength:-1}arrayBufferViewToBuffer(e){return this.toArrayBuffer(e)}concat(e){let t=new Uint8Array(e.reduce((e,t)=>e+t.byteLength,0)),n=0;for(let s of e){let e=this.toBuffer(s);t.set(e,n),n+=e.byteLength}return t.buffer}sha256(e){let t=nY(this.toBuffer(e));return this.toArrayBuffer(t)}hmacSha256(e,t){let n=function(e,t){if(e.length>64&&(e=nY(e)),e.length<64){let t=new Uint8Array(64);t.set(e,0),e=t}for(var n=new Uint8Array(64),s=new Uint8Array(64),i=0;i<64;i++)n[i]=54^e[i],s[i]=92^e[i];var r=new Uint8Array(t.length+64);r.set(n,0),r.set(t,64);var o=new Uint8Array(96);return o.set(s,0),o.set(nY(r),64),nY(o)}(this.toBuffer(t),this.toBuffer(e));return this.toArrayBuffer(n)}},n0=((o=n0||{})[o.REQ_SEND=0]="REQ_SEND",o[o.REQ_RECV=1]="REQ_RECV",o[o.REQ_RECV_POLL=2]="REQ_RECV_POLL",o[o.REQ_RECV_STREAM=3]="REQ_RECV_STREAM",o);function n1(){return new P("No HTTP request plugin provided. Provide at least one of the FetchRequest or XHRRequest plugins.",400,4e4)}var n4=((h=class{constructor(e){var t;this.checksInProgress=null,this.checkConnectivity=void 0,this.supportsAuthHeaders=!1,this.supportsLinkHeaders=!1,this.client=null!=e?e:null;const n=(null==e?void 0:e.options.connectivityCheckUrl)||eT.connectivityCheckUrl,s=null!=(t=null==e?void 0:e.options.connectivityCheckParams)?t:null,i=!(null==e?void 0:e.options.connectivityCheckUrl),r=w(w({},n4.bundledRequestImplementations),null==e?void 0:e._additionalHTTPRequestImplementations),o=r.XHRRequest,a=r.FetchRequest,c=!!(o||a);if(!c)throw n1();S.Config.xhrSupported&&o?(this.supportsAuthHeaders=!0,this.Request=async function(t,n,s,i,r){return new Promise(a=>{var c;let l=o.createRequest(n,s,i,r,n0.REQ_SEND,null!=(c=e&&e.options.timeouts)?c:null,this.logger,t);l.once("complete",(e,t,n,s,i)=>a({error:e,body:t,headers:n,unpacked:s,statusCode:i})),l.exec()})},(null==e?void 0:e.options.disableConnectivityCheck)?this.checkConnectivity=async function(){return!0}:this.checkConnectivity=async function(){var e,t;I.logAction(this.logger,I.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Sending; "+n);let r=await this.doUri(eq.Get,n,null,null,s),o=!1;return o=i?!r.error&&(null==(e=r.body)?void 0:e.replace(/\n/,""))=="yes":!r.error&&(t=r.statusCode)>=200&&t<400,I.logAction(this.logger,I.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Result: "+o),o}):S.Config.fetchSupported&&a?(this.supportsAuthHeaders=!0,this.Request=async(t,n,s,i,r)=>a(t,null!=e?e:null,n,s,i,r),(null==e?void 0:e.options.disableConnectivityCheck)?this.checkConnectivity=async function(){return!0}:this.checkConnectivity=async function(){var e;I.logAction(this.logger,I.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Sending; "+n);let t=await this.doUri(eq.Get,n,null,null,null),s=!t.error&&(null==(e=t.body)?void 0:e.replace(/\n/,""))=="yes";return I.logAction(this.logger,I.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Result: "+s),s}):this.Request=async()=>({error:c?new L("no supported HTTP transports available",null,400):n1()})}get logger(){var e,t;return null!=(t=null==(e=this.client)?void 0:e.logger)?t:I.defaultLogger}async doUri(e,t,n,s,i){return this.Request?this.Request(e,t,n,i,s):{error:new L("Request invoked before assigned to",null,500)}}shouldFallback(e){let t=e.statusCode;return 408===t&&!e.code||400===t&&!e.code||t>=500&&t<=504}}).methods=[eq.Get,eq.Delete,eq.Post,eq.Put,eq.Patch],h.methodsWithoutBody=[eq.Get,eq.Delete],h.methodsWithBody=[eq.Post,eq.Put,eq.Patch],h),n2="ablyjs-storage-test",n8=e.g,n3=new class{constructor(){try{n8.sessionStorage.setItem(n2,n2),n8.sessionStorage.removeItem(n2),this.sessionSupported=!0}
1catch(e){this.sessionSupported=!1}try{n8.localStorage.setItem(n2,n2),n8.localStorage.removeItem(n2),this.localSupported=!0}catch(e){this.localSupported=!1}}get(e){return this._get(e,!1)}getSession(e){return this._get(e,!0)}remove(e){return this._remove(e,!1)}removeSession(e){return this._remove(e,!0)}set(e,t,n){return this._set(e,t,n,!1)}setSession(e,t,n){return this._set(e,t,n,!0)}_set(e,t,n,s){let i={value:t};return n&&(i.expires=Date.now()+n),this.storageInterface(s).setItem(e,JSON.stringify(i))}_get(e,t){if(t&&!this.sessionSupported)throw Error("Session Storage not supported");if(!t&&!this.localSupported)throw Error("Local Storage not supported");let n=this.storageInterface(t).getItem(e);if(!n)return null;let s=JSON.parse(n);return s.expires&&s.expires<Date.now()?(this.storageInterface(t).removeItem(e),null):s.value}_remove(e,t){return this.storageInterface(t).removeItem(e)}storageInterface(e){return e?n8.sessionStorage:n8.localStorage}},n6=eb(),n5="string"==typeof EdgeRuntime;"undefined"!=typeof Window||"undefined"!=typeof WorkerGlobalScope||n5||console.log("Warning: this distribution of Ably is intended for browsers. On nodejs, please use the 'ably' package on npm");var n9={agent:"browser",logTimestamps:!0,userAgent:n6.navigator&&n6.navigator.userAgent.toString(),currentUrl:n6.location&&n6.location.href,binaryType:"arraybuffer",WebSocket:n6.WebSocket,fetchSupported:!!n6.fetch,xhrSupported:n6.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,allowComet:(t=n6.location,!n6.WebSocket||!t||!t.origin||t.origin.indexOf("http")>-1),useProtocolHeartbeats:!0,supportsBinary:!!n6.TextDecoder,preferBinary:!1,ArrayBuffer:n6.ArrayBuffer,atob:n6.atob,nextTick:"function"==typeof n6.queueMicrotask?e=>n6.queueMicrotask(e):e=>Promise.resolve().then(e),addEventListener:n6.addEventListener,inspect:JSON.stringify,stringByteSize:function(e){return n6.TextDecoder&&new n6.TextEncoder().encode(e).length||e.length},TextEncoder:n6.TextEncoder,TextDecoder:n6.TextDecoder,getRandomArrayBuffer:async function(e){let t=new Uint8Array(e);return n6.crypto.getRandomValues(t),t.buffer},isWebworker:!!("undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope),push:{platform:"browser",formFactor:"desktop",storage:n3}};function n7(e){return e.code&&!eJ.isTokenErr(e)&&([80015,80017,80030].includes(e.code)||e.code>=4e4&&e.code<5e4)?[ne({action:eY.ERROR,error:e})]:[ne({action:eY.DISCONNECTED,error:e})]}var se=class extends nb{constructor(e,t,n){super(e,t,n,!0),this.onAuthUpdated=e=>{this.authParams={access_token:e.token}},this.stream=!("stream"in n)||n.stream,this.sendRequest=null,this.recvRequest=null,this.pendingCallback=null,this.pendingItems=null}connect(){I.logAction(this.logger,I.LOG_MINOR,"CometTransport.connect()","starting"),nb.prototype.connect.call(this);let e=this.params,t=e.options,n=e.host||t.primaryDomain,s=eT.getPort(t),i=t.tls?"https://":"http://";this.baseUri=i+n+":"+s+"/comet/";let r=this.baseUri+"connect";I.logAction(this.logger,I.LOG_MINOR,"CometTransport.connect()","uri: "+r),eh(this.auth.getAuthParams(),(e,t)=>{if(e)return void this.disconnect(e);if(this.isDisposed)return;this.authParams=t;let n=this.params.getConnectParams(t);"stream"in n&&(this.stream=n.stream),I.logAction(this.logger,I.LOG_MINOR,"CometTransport.connect()","connectParams:"+et(n));
1let s=!1,i=this.recvRequest=this.createRequest(r,null,n,null,this.stream?n0.REQ_RECV_STREAM:n0.REQ_RECV);i.on("data",e=>{this.recvRequest&&(s||(s=!0,this.emit("preconnect")),this.onData(e))}),i.on("complete",e=>{(this.recvRequest||(e=e||new P("Request cancelled",80003,400)),this.recvRequest=null,s||e||(s=!0,this.emit("preconnect")),this.onActivity(),e)?e.code?this.onData(n7(e)):this.disconnect(e):S.Config.nextTick(()=>{this.recv()})}),i.exec()})}requestClose(){I.logAction(this.logger,I.LOG_MINOR,"CometTransport.requestClose()"),this._requestCloseOrDisconnect(!0)}requestDisconnect(){I.logAction(this.logger,I.LOG_MINOR,"CometTransport.requestDisconnect()"),this._requestCloseOrDisconnect(!1)}_requestCloseOrDisconnect(e){let t=e?this.closeUri:this.disconnectUri;if(t){let n=this.createRequest(t,null,this.authParams,null,n0.REQ_SEND);n.on("complete",t=>{t&&(I.logAction(this.logger,I.LOG_ERROR,"CometTransport.request"+(e?"Close()":"Disconnect()"),"request returned err = "+ei(t)),this.finish("disconnected",t))}),n.exec()}}dispose(){I.logAction(this.logger,I.LOG_MINOR,"CometTransport.dis
1pose()",""),this.isDisposed||(this.isDisposed=!0,this.recvRequest&&(I.logAction(this.logger,I.LOG_MINOR,"CometTransport.dispose()","aborting recv request"),this.recvRequest.abort(),this.recvRequest=null),this.finish("disconnected",nf.disconnected()),S.Config.nextTick(()=>{this.emit("disposed")}))}onConnect(e){var t;if(this.isDisposed)return;let n=null==(t=e.connectionDetails)?void 0:t.connectionKey;nb.prototype.onConnect.call(this,e);let s=this.baseUri+n;I.logAction(this.logger,I.LOG_MICRO,"CometTransport.onConnect()","baseUri = "+s),this.sendUri=s+"/send",this.recvUri=s+"/recv",this.closeUri=s+"/close",this.disconnectUri=s+"/disconnect"}send(e){if(this.sendRequest){this.pendingItems=this.pendingItems||[],this.pendingItems.push(e);return}let t=this.pendingItems||[];t.push(e),this.pendingItems=null,this.sendItems(t)}sendAnyPending(){let e=this.pendingItems;e&&(this.pendingItems=null,this.sendItems(e))}sendItems(e){let t=this.sendRequest=this.createRequest(this.sendUri,null,this.authParams,this.encodeRequest(e),n0.REQ_SEND);t.on("complete",(e,t)=>{(e&&I.logAction(this.logger,I.LOG_ERROR,"CometTransport.sendItems()","on complete: err = "+ei(e)),this.sendRequest=null,e)?e.code?this.onData(n7(e)):this.disconnect(e):(t&&this.onData(t),this.pendingItems&&S.Config.nextTick(()=>{this.sendRequest||this.sendAnyPending()}))}),t.exec()}recv(){if(this.recvRequest||!this.isConnected)return;let e=this.recvRequest=this.createRequest(this.recvUri,null,this.authParams,null,this.stream?n0.REQ_RECV_STREAM:n0.REQ_RECV_POLL);e.on("data",e=>{this.onData(e)}),e.on("complete",e=>{(this.recvRequest=null,this.onActivity(),e)?e.code?this.onData(n7(e)):this.disconnect(e):S.Config.nextTick(()=>{this.recv()})}),e.exec()}onData(e){try{let t=this.decodeResponse(e);if(t&&t.length)for(let e=0;e<t.length;e++)this.onProtocolMessage(t9(t[e],this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._objectsPlugin))}catch(e){I.logAction(this.logger,I.LOG_ERROR,"CometTransport.onData()","Unexpected exception handing channel event: "+e.stack)}}encodeRequest(e){return JSON.stringify(e)}decodeResponse(e){return"string"==typeof e?JSON.parse(e):e}},st=function(){},sn=0,ss={},si=class e extends eX{constructor(e,t,n,s,i,r,o,a){super(o),(n=n||{}).rnd=ea(),this.uri=e+et(n),this.headers=t||{},this.body=s,this.method=a?a.toUpperCase():q(s)?"GET":"POST",this.requestMode=i,this.timeouts=r,this.timedOut=!1,this.requestComplete=!1,this.id=String(++sn),ss[this.id]=this}static createRequest(t,n,s,i,r,o,a,c){let l=o||eT.TIMEOUTS;return new e(t,n,U(s),i,r,l,a,c)}complete(e,t,n,s,i){this.requestComplete||(this.requestComplete=!0,!e&&t&&this.emit("data",t),this.emit("complete",e,t,n,s,i),this.dispose())}abort(){this.dispose()}exec(){let e,t,n,s=this.headers,i=this.requestMode==n0.REQ_SEND?this.timeouts.httpRequestTimeout:this.timeouts.recvTimeout,r=this.timer=setTimeout(()=>{this.timedOut=!0,a.abort()},i),o=this.method,a=this.xhr=new XMLHttpRequest,c=s.accept,l=this.body,h="text";for(let e in c?0===c.indexOf("application/x-msgpack")&&(h="arraybuffer"):s.accept="application/json",l&&(s["content-type"]||(s["content-type"]="application/json")).indexOf("application/json")>-1&&"string"!=typeof l&&(l=JSON.stringify(l)),a.open(o,this.uri,!0),a.responseType=h,"authorization"in s&&(a.withCredentials=!0),s)a.setRequestHeader(e,s[e]);let u=(e,t,n,s)=>{var i;let r=t+" (event type: "+e.type+")";(null==(i=this==null?void 0:this.xhr)?void 0:i.statusText)&&(r+=", current statusText is "+this.xhr.statusText),I.logAction(this.logger,I.LOG_ERROR,"Request.on"+e.type+"()",r),this.complete(new L(r,n,s))};a.onerror=e=>{u(e,"XHR error occurred",null,400)},a.onabort=e=>{this.timedOut?u(e,"Request aborted due to request timeout expiring",null,408):u(e,"Request cancelled",null,400)},a.ontimeout=e=>{u(e,"Request timed out",null,408)};let d=0,g=!1,p=()=>{var s;(clearTimeout(r),n=t<400,204==t)?this.complete(null,null,null,null,t):e=this.requestMode==n0.REQ_RECV_STREAM&&n&&(s=a).getResponseHeader&&(s.getResponseHeader("transfer-encoding")||!s.getResponseHeader("content-length"))},f=()=>{let e;try{let i=a.getResponseHeader&&a.getResponseHeader("content-type");if(i?i.indexOf("application/json")>=0:"text"==a.responseType){let t="arraybuffer"===a.responseType?S.BufferUtils.utf8Decode(a.response):String(a.responseText);
1e=t.length?JSON.parse(t):t,g=!0}else e=a.response;void 0!==e.response?(n=(t=e.statusCode)<400,s=e.headers,e=e.response):s=function(e){let t=e.getAllResponseHeaders().trim().split("\r\n"),n={};for(let e=0;e<t.length;e++){let s=t[e].split(":").map(e=>e.trim());n[s[0].toLowerCase()]=s[1]}return n}(a)}catch(e){this.complete(new L("Malformed response body from server: "+e.message,null,400));return}if(n||Array.isArray(e))return void this.complete(null,e,s,g,t);let i=function(e,t){if(eg(K(t)).includes("x-ably-errorcode"))return e.error&&P.fromValues(e.error)}(e,s);i||(i=new L("Error response received from server: "+t+" body was: "+S.Config.inspect(e),null,t)),this.complete(i,e,s,g,t)};function m(){let e,t,n=a.responseText,s=n.length-1;for(;d<s&&(e=n.indexOf("\n",d))>-1;)t=n.slice(d,e),d=e+1,y(t)}let y=e=>{try{e=JSON.parse(e)}catch(e){this.complete(new L("Malformed response body from server: "+e.message,null,400));return}this.emit("data",e)},b=()=>{m(),this.streamComplete=!0,S.Config.nextTick(()=>{this.complete()})};a.onreadystatechange=()=>{let n=a.readyState;n<3||0!==a.status&&(void 0===t&&(t=a.status,p()),3==n&&e?m():4==n&&(e?b():f()))},a.send(l)}dispose(){let e=this.xhr;if(e){e.onreadystatechange=e.onerror=e.onabort=e.ontimeout=st,this.xhr=null;let t=this.timer;t&&(clearTimeout(t),this.timer=null),this.requestComplete||e.abort()}delete ss[this.id]}},sr=a.XhrPolling,so=class extends se{constructor(e,t,n){super(e,t,n),this.shortName=sr,n.stream=!1,this.shortName=sr}static isAvailable(){return!!(S.Config.xhrSupported&&S.Config.allowComet)}toString(){return"XHRPollingTransport; uri="+this.baseUri+"; isConnected="+this.isConnected}createRequest(e,t,n,s,i){return si.createRequest(e,t,n,s,i,this.timeouts,this.logger)}},sa={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",wsConnectivityCheckUrl:"wss://ws-up.ably-realtime.com",defaultTransports:[a.XhrPolling,a.WebSocket]};function sc(e,t,n){for(let s=0,i=n.length;s<i;s++){let i=n.charCodeAt(s);if(i<128){e.setUint8(t++,i>>>0&127);continue}if(i<2048){e.setUint8(t++,i>>>6&31|192),e.setUint8(t++,i>>>0&63|128);continue}if(i<65536){e.setUint8(t++,i>>>12&15|224),e.setUint8(t++,i>>>6&63|128),e.setUint8(t++,i>>>0&63|128);continue}if(i<1114112){e.setUint8(t++,i>>>18&7|240),e.setUint8(t++,i>>>12&63|128),e.setUint8(t++,i>>>6&63|128),e.setUint8(t++,i>>>0&63|128);continue}throw Error("bad codepoint "+i)}}function sl(e,t,n){let s="";for(let i=t,r=t+n;i<r;i++){let t=e.getUint8(i);if((128&t)==0){s+=String.fromCharCode(t);continue}if((224&t)==192){s+=String.fromCharCode((15&t)<<6|63&e.getUint8(++i));continue}if((240&t)==224){s+=String.fromCharCode((15&t)<<12|(63&e.getUint8(++i))<<6|63&e.getUint8(++i));continue}if((248&t)==240){s+=String.fromCharCode((7&t)<<18|(63&e.getUint8(++i))<<12|(63&e.getUint8(++i))<<6|63&e.getUint8(++i));continue}throw Error("Invalid byte "+t.toString(16))}return s}function sh(e){let t=0;for(let n=0,s=e.length;n<s;n++){let s=e.charCodeAt(n);if(s<128){t+=1;continue}if(s<2048){t+=2;continue}if(s<65536){t+=3;continue}if(s<1114112){t+=4;continue}throw Error("bad codepoint "+s)}return t}var su=class{constructor(e,t){this.map=e=>{let t={};for(let n=0;n<e;n++)t[this.parse()]=this.parse();return t},this.bin=e=>{let t=new ArrayBuffer(e);return new Uint8Array(t).set(new Uint8Array(this.view.buffer,this.offset,e),0),this.offset+=e,t},this.buf=this.bin,this.str=e=>{let t=sl(this.view,this.offset,e);return this.offset+=e,t},this.array=e=>{let t=Array(e);for(let n=0;n<e;n++)t[n]=this.parse();return t},this.ext=e=>(this.offset+=e,{type:this.view.getInt8(this.offset),data:this.buf(e)}),this.parse=()=>{var e,t,n,s;let i,r,o=this.view.getUint8(this.offset);if((128&o)==0)return this.offset++,o;if((240&o)==128)return r=15&o,this.offset++,this.map(r);if((240&o)==144)return r=15&o,this.offset++,this.array(r);if((224&o)==160)return r=31&o,this.offset++,this.str(r);if((224&o)==224)return i=this.view.getInt8(this.offset),this.offset++,i;switch(o){case 192:return this.offset++,null;case 193:this.offset++;return;case 194:return this.offset++,!1;case 195:return this.offset++,!0;case 196:return r=this.view.getUint8(this.offset+1),this.offset+=2,this.bin(r);case 197:return r=this.view.getUint16(this.offset+1),this.offset+=3,this.bin(r);case 198:return r=this.view.getUint32(this.offset+1),this.offset+=5,this.bin(r);case 199:return r=this.view.getUint8(this.offset+1),this.offset+=2,this.ext(r);case 200:return r=this.view.getUint16(this.offset+1),this.offset+=3,this.ext(r);case 201:return r=this.view.getUint32(this.offset+1),this.offset+=5,this.ext(r);case 202:return i=this.view.getFloat32(this.offset+1),this.offset+=5,i;case 203:return i=this.view.getFloat64(this.offset+1),this.offset+=9,i;case 204:return i=this.view.getUint8(this.offset+1),this.offset+=2,i;case 205:return i=this.view.getUint16(this.offset+1),this.offset+=3,i;case 206:return i=this.view.getUint32(this.offset+1),this.offset+=5,i;case 207:return e=this.view,t=(t=this.offset+1)||0,i=0x100000000*e.getUint32(t)+e.getUint32(t+4),this.offset+=9,i;case 208:return i=this.view.getInt8(this.offset+1),this.offset+=2,i;case 209:return i=this.view.getInt16(this.offset+1),this.offset+=3,i;case 210:return i=this.view.getInt32(this.offset+1),this.offset+=5,i;case 211:return n=this.view,s=(s=this.offset+1)||0,i=0x100000000*n.getInt32(s)+n.getUint32(s+4),this.offset+=9,i;case 212:return r=1,this.offset++,this.ext(r);case 213:return r=2,this.offset++,this.ext(r);case 214:return r=4,this.offset++,this.ext(r);case 215:return r=8,this.offset++,this.ext(r);case 216:return r=16,this.offset++,this.ext(r);case 217:return r=this.view.getUint8(this.offset+1),this.offset+=2,this.str(r);case 218:return r=this.view.getUint16(this.offset+1),this.offset+=3,this.str(r);case 219:return r=this.view.getUint32(this.offset+1),this.offset+=5,this.str(r);case 220:return r=this.view.getUint16(this.offset+1),this.offset+=3,this.array(r);case 221:return r=this.view.getUint32(this.offset+1),this.offset+=5,this.array(r);case 222:return r=this.view.getUint16(this.offset+1),this.offset+=3,this.map(r);case 223:return r=this.view.getUint32(this.offset+1),this.offset+=5,this.map(r)}throw Error("Unknown type 0x"+o.toString(16))},this.offset=t||0,this.view=e}};function sd(e,t){return Object.keys(e).filter(function(n){let s=e[n],i=typeof s;return(!t||null!=s)&&("function"!==i||!!s.toJSON)})}var sg={encode:function(e,t){let n=function e(t,n){let s=typeof t;if("string"===s){let e=sh(t);if(e<32)return 1+e;if(e<256)return 2+e;if(e<65536)return 3+e;if(e<0x100000000)return 5+e}if(ArrayBuffer.isView&&ArrayBuffer.isView(t)&&(t=t.buffer),t instanceof ArrayBuffer){let e=t.byteLength;if(e<256)return 2+e;if(e<65536)return 3+e;if(e<0x100000000)return 5+e}if("number"==typeof t){if(Math.floor(t)!==t)return 9;if(t>=0){if(t<128)return 1;if(t<256)return 2;if(t<65536)return 3;
1if(t<0x100000000)return 5;if(t<0xffffffffffffffff)return 9;throw Error("Number too big 0x"+t.toString(16))}if(t>=-32)return 1;if(t>=-128)return 2;if(t>=-32768)return 3;if(t>=-0x80000000)return 5;if(t>=-0x8000000000000000)return 9;throw Error("Number too small -0x"+t.toString(16).substr(1))}if("boolean"===s)return 1;if(null===t)return+!n;if(void 0===t)return 3*!n;if("function"==typeof t.toJSON)return e(t.toJSON(),n);if("object"===s){let s,i=0;if(Array.isArray(t)){s=t.length;for(let r=0;r<s;r++)i+=e(t[r],n)}else{let r=sd(t,n);s=r.length;for(let o=0;o<s;o++){let s=r[o];i+=e(s)+e(t[s],n)}}if(s<16)return 1+i;if(s<65536)return 3+i;if(s<0x100000000)return 5+i;throw Error("Array or object too long 0x"+s.toString(16))}if("function"===s)return 0;throw Error("Unknown type "+s)}(e,t);if(0===n)return;let s=new ArrayBuffer(n);return function e(t,n,s,i){let r=typeof t;if("string"==typeof t){let e=sh(t);if(e<32)return n.setUint8(s,160|e),sc(n,s+1,t),1+e;if(e<256)return n.setUint8(s,217),n.setUint8(s+1,e),sc(n,s+2,t),2+e;if(e<65536)return n.setUint8(s,218),n.setUint16(s+1,e),sc(n,s+3,t),3+e;if(e<0x100000000)return n.setUint8(s,219),n.setUint32(s+1,e),sc(n,s+5,t),5+e}if(ArrayBuffer.isView&&ArrayBuffer.isView(t)&&(t=t.buffer),t instanceof ArrayBuffer){let e=t.byteLength;if(e<256)return n.setUint8(s,196),n.setUint8(s+1,e),new Uint8Array(n.buffer).set(new Uint8Array(t),s+2),2+e;if(e<65536)return n.setUint8(s,197),n.setUint16(s+1,e),new Uint8Array(n.buffer).set(new Uint8Array(t),s+3),3+e;if(e<0x100000000)return n.setUint8(s,198),n.setUint32(s+1,e),new Uint8Array(n.buffer).set(new Uint8Array(t),s+5),5+e}if("number"==typeof t){var o,a,c,l;if(Math.floor(t)!==t)return n.setUint8(s,203),n.setFloat64(s+1,t),9;if(t>=0){if(t<128)return n.setUint8(s,t),1;if(t<256)return n.setUint8(s,204),n.setUint8(s+1,t),2;if(t<65536)return n.setUint8(s,205),n.setUint16(s+1,t),3;if(t<0x100000000)return n.setUint8(s,206),n.setUint32(s+1,t),5;if(t<0xffffffffffffffff)return n.setUint8(s,207),o=s+1,(a=t)<0xffffffffffffffff?(n.setUint32(o,Math.floor(23283064365386963e-26*a)),n.setInt32(o+4,-1&a)):(n.setUint32(o,0xffffffff),n.setUint32(o+4,0xffffffff)),9;throw Error("Number too big 0x"+t.toString(16))}if(t>=-32)return n.setInt8(s,t),1;if(t>=-128)return n.setUint8(s,208),n.setInt8(s+1,t),2;if(t>=-32768)return n.setUint8(s,209),n.setInt16(s+1,t),3;if(t>=-0x80000000)return n.setUint8(s,210),n.setInt32(s+1,t),5;if(t>=-0x8000000000000000)return n.setUint8(s,211),c=s+1,(l=t)<0x8000000000000000?(n.setInt32(c,Math.floor(23283064365386963e-26*l)),n.setInt32(c+4,-1&l)):(n.setUint32(c,0x7fffffff),n.setUint32(c+4,0x7fffffff)),9;throw Error("Number too small -0x"+(-t).toString(16).substr(1))}if("undefined"===r)return i?0:(n.setUint8(s,212),n.setUint8(s+1,0),n.setUint8(s+2,0),3);if(null===t)return i?0:(n.setUint8(s,192),1);if("boolean"===r)return n.setUint8(s,t?195:194),1;if("function"==typeof t.toJSON)return e(t.toJSON(),n,s,i);if("object"===r){let r,o,a=0,c=Array.isArray(t);if((o=c?t.length:(r=sd(t,i)).length)<16?(n.setUint8(s,o|(c?144:128)),a=1):o<65536?(n.setUint8(s,c?220:222),n.setUint16(s+1,o),a=3):o<0x100000000&&(n.setUint8(s,c?221:223),n.setUint32(s+1,o),a=5),c)for(let r=0;r<o;r++)a+=e(t[r],n,s+a,i);else if(r)for(let c=0;c<o;c++){let o=r[c];a+=e(o,n,s+a),a+=e(t[o],n,s+a,i)}return a}if("function"===r)return 0;throw Error("Unknown type "+r)}(e,new DataView(s),0,t),s},decode:function(e){let t=new su(new DataView(e)),n=t.parse();if(t.offset!==e.byteLength)throw Error(e.byteLength-t.offset+" trailing bytes");return n},inspect:function(e){let t,n;if(void 0===e)return"undefined";if(e instanceof ArrayBuffer?(n="ArrayBuffer",t=new DataView(e)):e instanceof DataView&&(n="DataView",t=e),!t)return JSON.stringify(e);let s=[];for(let n=0;n<e.byteLength;n++){if(n>20){s.push("...");break}let e=t.getUint8(n).toString(16);1===e.length&&(e="0"+e),s.push(e)}return"<"+n+" "+s.join(" ")+">"},utf8Write:sc,utf8Read:sl,utf8ByteCount:sh};async function sp(e,t,n,s,i,r){let o,a=new Headers(s||{}),c=e?e.toUpperCase():q(r)?"GET":"POST",l=new AbortController,h=new Promise(e=>{o=setTimeout(()=>{l.abort(),e({error:new L("Request timed out",null,408)})},t?t.options.timeouts.httpRequestTimeout:eT.TIMEOUTS.httpRequestTimeout)}),u={method:c,headers:a,body:r,signal:l.signal};S.Config.isWebworker||(u.credentials=a.has("authorization")?"include":"same-origin");let d=(async()=>{try{var e;
1let t,s,r=new URLSearchParams(i||{});r.set("rnd",ea());let a=n+"?"+r,c=await eb().fetch(a,u);if(clearTimeout(o),204==c.status)return{error:null,statusCode:c.status};let l=c.headers.get("Content-Type");t=l&&l.indexOf("application/x-msgpack")>-1?await c.arrayBuffer():l&&l.indexOf("application/json")>-1?await c.json():await c.text();let h=!!l&&-1===l.indexOf("application/x-msgpack"),d=(e=c.headers,s={},e.forEach((e,t)=>{s[t]=e}),s);if(!c.ok)return{error:function(e,t){if(t.get("x-ably-errorcode"))return e.error&&P.fromValues(e.error)}(t,c.headers)||new L("Error response received from server: "+c.status+" body was: "+S.Config.inspect(t),null,c.status),body:t,headers:d,unpacked:h,statusCode:c.status};return{error:null,body:t,headers:d,unpacked:h,statusCode:c.status}}catch(e){return clearTimeout(o),{error:e}}})();return Promise.race([h,d])}var sf=function(e,t){class n{constructor(e,t,n,s){this.algorithm=e,this.keyLength=t,this.mode=n,this.key=s}}class s{static getDefaultParams(e){if(!e.key)throw Error("Crypto.getDefaultParams: a key is required");var s="string"==typeof e.key?t.toArrayBuffer(t.base64Decode(e.key.replace("_","/").replace("-","+"))):e.key instanceof ArrayBuffer?e.key:t.toArrayBuffer(e.key),i=new n(e.algorithm||"aes",8*s.byteLength,e.mode||"cbc",s);if(e.keyLength&&e.keyLength!==i.keyLength)throw Error("Crypto.getDefaultParams: a keyLength of "+e.keyLength+" was specified, but the key actually has length "+i.keyLength);if("aes"===i.algorithm&&"cbc"===i.mode&&128!==i.keyLength&&256!==i.keyLength)throw Error("Unsupported key length "+i.keyLength+" for aes-cbc encryption. Encryption key must be 128 or 256 bits (16 or 32 ASCII characters)");return i}static async generateRandomKey(t){try{return e.getRandomArrayBuffer((t||256)/8)}catch(e){throw new P("Failed to generate random key: "+e.message,400,5e4,e)}}static getCipher(e,t){var s,r=e instanceof n?e:this.getDefaultParams(e);return{cipherParams:r,cipher:new i(r,null!=(s=e.iv)?s:null,t)}}}s.CipherParams=n;class i{constructor(e,n,s){if(this.logger=s,!crypto.subtle)if(isSecureContext)throw Error("Crypto operations are not possible since the browserâs SubtleCrypto class is unavailable (reason unknown).");else throw Error("Crypto operations are is not possible since the current environment is a non-secure context and hence the browserâs SubtleCrypto class is not available.");this.algorithm=e.algorithm+"-"+String(e.keyLength)+"-"+e.mode,this.webCryptoAlgorithm=e.algorithm+"-"+e.mode,this.key=t.toArrayBuffer(e.key),this.iv=n?t.toArrayBuffer(n):null}concat(e,n){let s=new ArrayBuffer(e.byteLength+n.byteLength),i=new DataView(s),r=new DataView(t.toArrayBuffer(e));for(let e=0;e<r.byteLength;e++)i.setInt8(e,r.getInt8(e));let o=new DataView(t.toArrayBuffer(n));for(let e=0;e<o.byteLength;e++)i.setInt8(r.byteLength+e,o.getInt8(e));return s}async encrypt(e){I.logAction(this.logger,I.LOG_MICRO,"CBCCipher.encrypt()","");let t=await this.getIv(),n=await crypto.subtle.importKey("raw",this.key,this.webCryptoAlgorithm,!1,["encrypt"]),s=await crypto.subtle.encrypt({name:this.webCryptoAlgorithm,iv:t},n,e);return this.concat(t,s)}async decrypt(e){I.logAction(this.logger,I.LOG_MICRO,"CBCCipher.decrypt()","");let n=t.toArrayBuffer(e),s=n.slice(0,16),i=n.slice(16),r=await crypto.subtle.importKey("raw",this.key,this.webCryptoAlgorithm,!1,["decrypt"]);return crypto.subtle.decrypt({name:this.webCryptoAlgorithm,iv:s},r,i)}async getIv(){if(this.iv){var n=this.iv;return this.iv=null,n}let s=await e.getRandomArrayBuffer(16);return t.toArrayBuffer(s)}}return s}(n9,nZ);for(let e of(S.Crypto=sf,S.BufferUtils=nZ,S.Http=n4,S.Config=n9,S.Transports={order:["xhr_polling"],bundledImplementations:{web_socket:nx,xhr_polling:so}},S.WebStorage=n3,[nl,nq]))e.Crypto=sf,e._MsgPack=sg;n4.bundledRequestImplementations={XHRRequest:si,FetchRequest:sp},I.initLogHandlers(),S.Defaults=Object.assign(eT,sa),S.Config.agent&&(S.Defaults.agent+=" "+S.Config.agent);var sm={ErrorInfo:P,Rest:nl,Realtime:nq,msgpack:sg,makeProtocolMessageFromDeserialized:t7};return"object"==typeof d.exports&&(d.exports=((e,t,n,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of Object.getOwnPropertyNames(t))Object.prototype.hasOwnProperty.call(e,i)||i===n||Object.defineProperty(e,i,{get:()=>t[i],enumerable:!(s=Object.getOwnPropertyDescriptor(t,i))||s.enumerable});return e})(d.exports,u)),d.exports})()},300896,e=>{"use strict";var t=e.i(890022),n=e.i(431231),s=e.i(882503),i=e.i(430769);let r=(0,n.createContext)(null),o=null,a=null,c=null,l=!1;function h({children:e}){let{data:h}
1=(0,s.useSession)(),[u,d]=(0,n.useState)(null),[g,p]=(0,n.useState)(!1),[f,m]=(0,n.useState)("disconnected"),y=(0,n.useRef)(new Map),b=(0,n.useRef)(!1);(0,n.useEffect)(()=>{if(!h?.user)return;let e=h.user.id;if(o&&c===e){console.log("â»ï¸ [Ably] Reutilizando instancia global existente"),d(o),"connected"===o.connection.state&&(p(!0),m("connected"));return}if(a&&l){console.log("â³ [Ably] Esperando inicialización en progreso..."),a.then(()=>{o&&c===e&&d(o)}).catch(()=>{});return}if(!l||c!==e)return l=!0,b.current=!0,a=(async()=>{try{console.log("ð [Ably] Inicializando instancia única de Ably...");let t=await fetch("/api/chat/ably-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userId:e,clientId:`user_${e}`})});if(!t.ok)throw Error("Error obteniendo token de Ably");let{token:n}=await t.json();o&&c!==e&&(console.log("ð [Ably] Cerrando instancia anterior de otro usuario"),o.close(),o=null);let s=new i.default.Realtime({authUrl:"/api/chat/ably-token",authMethod:"POST",clientId:`user_${e}`,token:n,disconnectedRetryTimeout:15e3,suspendedRetryTimeout:3e4,realtimeRequestTimeout:1e4,connectionStateTtl:12e4,httpMaxRetryCount:3,httpMaxRetryDuration:1e4});s.connection.on("update",e=>{e.reason&&console.log(`ð [Ably Debug] Estado cambiado: ${e.current} -> ${e.previous}, raz\xf3n: ${e.reason}`)}),o=s,c=e,s.connection.on("connected",()=>{console.log("ð [Ably] Conectado"),p(!0),m("connected")}),s.connection.on("disconnected",()=>{console.log("ð [Ably] Desconectado"),p(!1),m("disconnected")}),s.connection.on("failed",()=>{console.log("â [Ably] Conexión fallida"),p(!1),m("failed")}),s.connection.on("suspended",()=>{console.log("â¸ï¸ [Ably] Conexión suspendida"),p(!1),m("suspended")}),d(s),a=null,console.log("â
[Ably] Instancia inicializada correctamente")}catch(t){console.error("Error inicializando Ably:",t),m("failed"),b.current=!1,a=null,l=!1,o&&c===e&&(o.close(),o=null,c=null)}})(),()=>{y.current.forEach(e=>{e.unsubscribe()}),y.current.clear(),u&&u!==o&&d(null)}},[h?.user?.id]);let v=(0,n.useCallback)((e,t)=>{let n=u||o;if(!n)return console.warn("Ably no está inicializado"),()=>{};if(y.current.has(e)){let n=y.current.get(e);return n.subscribe(t),()=>n.unsubscribe(t)}let s=n.channels.get(e);return s.subscribe(t),y.current.set(e,s),console.log(`ð¡ [Ably] Suscrito al canal: ${e}`),()=>{s.unsubscribe(t),0===s.listeners.length&&(y.current.delete(e),console.log(`ð¡ [Ably] Desuscrito del canal: ${e}`))}},[u]),O=(0,n.useCallback)(e=>{let t=y.current.get(e);t&&(t.unsubscribe(),y.current.delete(e),console.log(`ð¡ [Ably] Desuscrito del canal: ${e}`))},[]),C=(0,n.useCallback)(async(e,t)=>{let n=u||o;if(!n)throw Error("Ably no está inicializado");let s=n.channels.get(e),i={...t,id:`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,timestamp:new Date().toISOString()};await s.publish("message",i),console.log(`ð¤ [Ably] Mensaje publicado en canal ${e}:`,i)},[u]);return(0,t.jsx)(r.Provider,{value:{ablyClient:u,isConnected:g,connectionState:f,subscribe:v,unsubscribe:O,publish:C},children:e})}function u(e){let{subscribe:t,isConnected:s}=function(e={}){let t=(0,n.useContext)(r);if(!t)return{isConnected:!1,connectionState:"disconnected",subscribe:()=>()=>{},unsubscribe:()=>{},publish:async()=>{}};let{isConnected:s,connectionState:i,subscribe:o,unsubscribe:a,publish:c}=t,{channels:l=[]}=e;return(0,n.useEffect)(()=>{if(l.length>0&&s){let e=l.map(e=>o(e,()=>{}));return()=>{e.forEach(e=>e())}}},[l.join(","),s,o]),{isConnected:s,connectionState:i,subscribe:o,unsubscribe:a,publish:c}}({enabled:!0}),i=(0,n.useRef)(t);(0,n.useEffect)(()=>{i.current=t},[t]);let o=(0,n.useCallback)(t=>e?i.current(`conversation:${e}`,t):()=>{},[e]);return{isConnected:s,subscribeToConversation:o,subscribeToAllConversations:(0,n.useCallback)(e=>i.current("conversations:all",e),[]),subscribeToMessageStatus:(0,n.useCallback)(e=>i.current("messages:status",e),[])}}e.s(["AblyProvider",()=>h,"useChatEvents",()=>u])}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.