bit-office 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +5075 -0
- package/dist/index.js.map +1 -0
- package/dist/web/out/404.html +7 -0
- package/dist/web/out/Office Tileset/LICENSE.txt +14 -0
- package/dist/web/out/Office Tileset/Office Designs/Office Level 1.png +0 -0
- package/dist/web/out/Office Tileset/Office Designs/Office Level 2.png +0 -0
- package/dist/web/out/Office Tileset/Office Designs/Office Level 3.5.png +0 -0
- package/dist/web/out/Office Tileset/Office Designs/Office Level 3.jpeg +0 -0
- package/dist/web/out/Office Tileset/Office Designs/Office Level 3.png +0 -0
- package/dist/web/out/Office Tileset/Office Designs/Office Level 4.png +0 -0
- package/dist/web/out/Office Tileset/Office Palette/Office Palette Large.png +0 -0
- package/dist/web/out/Office Tileset/Office Palette/Office Palette Medium.png +0 -0
- package/dist/web/out/Office Tileset/Office Palette/Office Palette Small.png +0 -0
- package/dist/web/out/Office Tileset/Office Tileset All 16x16 no shadow.png +0 -0
- package/dist/web/out/Office Tileset/Office Tileset All 16x16.png +0 -0
- package/dist/web/out/Office Tileset/Office Tileset All 32x32 no shadow.png +0 -0
- package/dist/web/out/Office Tileset/Office Tileset All 32x32.png +0 -0
- package/dist/web/out/Office Tileset/Office Tileset All 48x48 no shadow.png +0 -0
- package/dist/web/out/Office Tileset/Office Tileset All 48x48.png +0 -0
- package/dist/web/out/Office Tileset/Office VX Ace/A2 Office Floors.png +0 -0
- package/dist/web/out/Office Tileset/Office VX Ace/A4 Office Walls.png +0 -0
- package/dist/web/out/Office Tileset/Office VX Ace/A5 Office Floors & Walls.png +0 -0
- package/dist/web/out/Office Tileset/Office VX Ace/B-C-D-E Office 1 No Shadows.png +0 -0
- package/dist/web/out/Office Tileset/Office VX Ace/B-C-D-E Office 1.png +0 -0
- package/dist/web/out/Office Tileset/Office VX Ace/B-C-D-E Office 2 No Shadows.png +0 -0
- package/dist/web/out/Office Tileset/Office VX Ace/B-C-D-E Office 2.png +0 -0
- package/dist/web/out/Office Tileset/Office VX Ace/README.txt +2 -0
- package/dist/web/out/_next/static/chunks/176.7af67c16b9732441.js +1 -0
- package/dist/web/out/_next/static/chunks/29.3e7650727aadf8c2.js +1 -0
- package/dist/web/out/_next/static/chunks/290.d0fe5fb72a5068b2.js +1 -0
- package/dist/web/out/_next/static/chunks/325ca9c7-f84e7e4973790fdf.js +1 -0
- package/dist/web/out/_next/static/chunks/4d67e943-e6a0fd3b5c397505.js +1 -0
- package/dist/web/out/_next/static/chunks/757.6b9b9f11f348e673.js +1 -0
- package/dist/web/out/_next/static/chunks/810.44213c6355518b0b.js +1 -0
- package/dist/web/out/_next/static/chunks/904.8b3ff312a1556d6a.js +1 -0
- package/dist/web/out/_next/static/chunks/977-26ddf708be8caf79.js +1 -0
- package/dist/web/out/_next/static/chunks/989-f3ebca68e0b5e7ee.js +1 -0
- package/dist/web/out/_next/static/chunks/app/_not-found/page-0f7c77f58dea5cf2.js +1 -0
- package/dist/web/out/_next/static/chunks/app/layout-7ca1be140a482711.js +1 -0
- package/dist/web/out/_next/static/chunks/app/office/page-880d13f3a18654a9.js +1 -0
- package/dist/web/out/_next/static/chunks/app/page-94da9de9b62f4f4d.js +1 -0
- package/dist/web/out/_next/static/chunks/app/pair/page-389c78f078318d25.js +1 -0
- package/dist/web/out/_next/static/chunks/framework-bec628f2b7cc8f6d.js +1 -0
- package/dist/web/out/_next/static/chunks/main-3ed3b5510eeb64f8.js +1 -0
- package/dist/web/out/_next/static/chunks/main-app-4f4b0701adf58469.js +1 -0
- package/dist/web/out/_next/static/chunks/pages/_app-f4d560c9dbc22e4e.js +1 -0
- package/dist/web/out/_next/static/chunks/pages/_error-492bd157be5771d5.js +1 -0
- package/dist/web/out/_next/static/chunks/polyfills-42372ed130431b0a.js +1 -0
- package/dist/web/out/_next/static/chunks/webpack-1075fa19d83199c2.js +1 -0
- package/dist/web/out/_next/static/y7YWx1Z8eZ7VPIAjor5oQ/_buildManifest.js +1 -0
- package/dist/web/out/_next/static/y7YWx1Z8eZ7VPIAjor5oQ/_ssgManifest.js +1 -0
- package/dist/web/out/assets/characters/char_0.png +0 -0
- package/dist/web/out/assets/characters/char_1.png +0 -0
- package/dist/web/out/assets/characters/char_2.png +0 -0
- package/dist/web/out/assets/characters/char_3.png +0 -0
- package/dist/web/out/assets/characters/char_4.png +0 -0
- package/dist/web/out/assets/characters/char_5.png +0 -0
- package/dist/web/out/assets/walls.png +0 -0
- package/dist/web/out/icons/icon-192.png +0 -0
- package/dist/web/out/icons/icon-512.png +0 -0
- package/dist/web/out/index.html +7 -0
- package/dist/web/out/index.txt +18 -0
- package/dist/web/out/manifest.json +13 -0
- package/dist/web/out/office.html +7 -0
- package/dist/web/out/office.txt +18 -0
- package/dist/web/out/pair.html +7 -0
- package/dist/web/out/pair.txt +18 -0
- package/dist/web/out/pixel-agents-layout.json +2802 -0
- package/dist/web/out/sw.js +1 -0
- package/dist/web/out/workbox-5194662c.js +1 -0
- package/package.json +41 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[284],{9984:function(e,t,n){e.exports=(()=>{"use strict";var e,t,s,i,r,o,a,l,c,h={},u={exports:h},d=Object.defineProperty,g=Object.defineProperties,p=Object.getOwnPropertyDescriptor,f=Object.getOwnPropertyDescriptors,m=Object.getOwnPropertyNames,y=Object.getOwnPropertySymbols,v=Object.prototype.hasOwnProperty,b=Object.prototype.propertyIsEnumerable,O=(e,t,n)=>t in e?d(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)&&O(e,n,t[n]);if(y)for(var n of y(t))b.call(t,n)&&O(e,n,t[n]);return e},C=(e,t)=>g(e,f(t)),R=(e,t)=>{for(var n in t)d(e,n,{get:t[n],enumerable:!0})},A=function(e,t){this[0]=e,this[1]=t},S={};R(S,{ErrorInfo:()=>L,Realtime:()=>nH,Rest:()=>nd,default:()=>sb,makeProtocolMessageFromDeserialized:()=>ns,msgpack:()=>sm}),u.exports=((e,t,n,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of m(t))v.call(e,i)||i===n||d(e,i,{get:()=>t[i],enumerable:!(s=p(t,i))||s.enumerable});return e})(d({},"__esModule",{value:!0}),S);var k=class{},M=void 0!==n.g?n.g:"undefined"!=typeof window?window:self;function T(e,t){return`${e}`.padStart(t?3:2,"0")}function I(e){return k.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 _=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==M?void 0:M.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(I));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)}};_.defaultLogLevel=1,_.LOG_NONE=0,_.LOG_ERROR=1,_.LOG_MAJOR=2,_.LOG_MINOR=3,_.LOG_MICRO=4,_.logAction=(e,t,n,s)=>{_.logActionNoStrip(e,t,n,s)};var P={};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="+eo(e.cause)),e.href&&!(e.message&&e.message.indexOf("help.ably.io")>-1)&&(t+="; see "+e.href+" "),t+="]"}R(P,{Format:()=>ee,allSame:()=>Z,allToLowerCase:()=>ef,allToUpperCase:()=>em,arrChooseN:()=>eu,arrDeleteValue:()=>K,arrEquals:()=>eA,arrIntersect:()=>J,arrIntersectOb:()=>z,arrPopRandomElement:()=>et,arrWithoutValue:()=>$,cheapRandStr:()=>ec,containsValue:()=>W,copy:()=>x,createMissingPluginError:()=>eS,dataSizeBytes:()=>el,decodeBody:()=>eg,encodeBody:()=>ep,ensureArray:()=>G,forInOwnNonNullProperties:()=>Y,getBackoffCoefficient:()=>ey,getGlobalObject:()=>eO,getJitterCoefficient:()=>ev,getRetryTime:()=>eb,inherits:()=>V,inspectBody:()=>ea,inspectError:()=>eo,intersect:()=>F,isEmpty:()=>q,isErrorInfoOrPartialErrorInfo:()=>er,isNil:()=>D,isObject:()=>B,keysArray:()=>Q,listenerToAsyncIterator:()=>eT,matchDerivedChannel:()=>eC,mixin:()=>U,parseQueryString:()=>ei,prototypicalClone:()=>H,randomString:()=>eh,shallowClone:()=>j,shallowEquals:()=>ew,stringifyValues:()=>es,throwMissingPluginError:()=>ek,toBase64:()=>eR,toQueryString:()=>en,valuesArray:()=>X,whenPromiseSettles:()=>ed,withTimeoutAsync:()=>eM});var 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||"number"!=typeof s||"number"!=typeof i)throw Error("ErrorInfo.fromValues(): invalid values: "+k.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}},N=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||!D(s)&&"number"!=typeof s||!D(i)&&"number"!=typeof i)throw Error("PartialErrorInfo.fromValues(): invalid values: "+k.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 U(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 x(e){return U({},e)}function G(e){return D(e)?[]:Array.isArray(e)?e:[e]}function B(e){return"[object Object]"==Object.prototype.toString.call(e)}function q(e){for(let t in e)return!1;return!0}function D(e){return null==e}function j(e){let t={};for(let n in e)t[n]=e[n];return t}function H(e,t){class n{}n.prototype=e;let s=new n;return t&&U(s,t),s}var V=function(e,t){if(k.Config.inherits)return void k.Config.inherits(e,t);e.super_=t,e.prototype=H(t.prototype,{constructor:e})};function W(e,t){for(let n in e)if(e[n]==t)return!0;return!1}function F(e,t){return Array.isArray(t)?J(e,t):z(e,t)}function J(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 z(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 K(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 K(n,t),n}function Q(e,t){let n=[];for(let s in e)(!t||Object.prototype.hasOwnProperty.call(e,s))&&n.push(s);return n}function X(e,t){let n=[];for(let s in e)(!t||Object.prototype.hasOwnProperty.call(e,s))&&n.push(e[s]);return n}function Y(e,t){for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&e[n]&&t(n)}function Z(e,t){if(0===e.length)return!0;let n=e[0][t];return e.every(function(e){return e[t]===n})}var ee=((e=ee||{}).msgpack="msgpack",e.json="json",e);function et(e){return e.splice(Math.floor(Math.random()*e.length),1)[0]}function en(e){let t=[];if(e)for(let n in e)t.push(encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t.length?"?"+t.join("&"):""}function es(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,String(t)]))}function ei(e){let t,n=/([^?&=]+)=?([^&]*)/g,s={};for(;t=n.exec(e);)s[decodeURIComponent(t[1])]=decodeURIComponent(t[2]);return s}function er(e){return"object"==typeof e&&null!==e&&(e instanceof L||e instanceof N)}function eo(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():k.Config.inspect(e)}function ea(e){return k.BufferUtils.isBuffer(e)?e.toString():"string"==typeof e?e:k.Config.inspect(e)}function el(e){if(k.BufferUtils.isBuffer(e))return k.BufferUtils.byteLength(e);if("string"==typeof e)return k.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 ec(){return String(Math.random()).substr(2)}var eh=async e=>{let t=await k.Config.getRandomArrayBuffer(e);return k.BufferUtils.base64Encode(t)};function eu(e,t){let n=Math.min(t,e.length),s=e.slice(),i=[];for(let e=0;e<n;e++)i.push(et(s));return i}function ed(e,t){e.then(e=>{null==t||t(null,e)}).catch(e=>{null==t||t(e)})}function eg(e,t,n){return"msgpack"==n?(t||ek("MsgPack"),t.decode(e)):JSON.parse(String(e))}function ep(e,t,n){return"msgpack"==n?(t||ek("MsgPack"),t.encode(e,!0)):JSON.stringify(e)}function ef(e){return e.map(function(e){return e&&e.toLowerCase()})}function em(e){return e.map(function(e){return e&&e.toUpperCase()})}function ey(e){return Math.min((e+2)/3,2)}function ev(){return 1-.2*Math.random()}function eb(e,t){return e*ey(t)*ev()}function eO(){return void 0!==n.g?n.g:"undefined"!=typeof window?window:self}function ew(e,t){return Object.keys(e).every(n=>e[n]===t[n])&&Object.keys(t).every(n=>t[n]===e[n])}function eC(e){let t=e.match(/^(\[([^?]*)(?:(.*))\])?(.+)$/);if(!t||!t.length||t.length<5)throw new L("regex match failed",400,40010);if(t[2])throw new L(`cannot use a derived option with a ${t[2]} channel`,400,40010);return{qualifierParam:t[3]||"",channelName:t[4]}}function eR(e){let t=k.BufferUtils,n=t.utf8Encode(e);return t.base64Encode(n)}function eA(e,t){return e.length===t.length&&e.every(function(e,n){return e===t[n]})}function eS(e){return new L(`${e} plugin not provided`,40019,400)}function ek(e){throw eS(e)}async function eM(e,t=5e3,n="Timeout expired"){let s=new L(n,5e4,500);return Promise.race([e,new Promise((e,n)=>setTimeout(()=>n(s),t))])}function eT(e){var t,n,s,i;return t=function*(){let t=[],n=null,s=e(e=>{if(n){let t=n;n=null,t(e)}else t.push(e)});try{for(;;)if(t.length>0)yield t.shift();else{if(n)throw new L("Concurrent next() calls are not supported",4e4,400);let e=yield new A(new Promise(e=>{n=e}));yield e}}finally{s()}},n=(e,s,i,r)=>{try{var o=t[e](s),a=(s=o.value)instanceof A,l=o.done;Promise.resolve(a?s[0]:s).then(t=>a?n("return"===e?e:"next",s[1]?{done:t.done,value:t.value}:t,i,r):i({value:t,done:l})).catch(e=>n("throw",e,i,r))}catch(e){r(e)}},s=e=>i[e]=t=>new Promise((s,i)=>n(e,t,s,i)),i={},t=t.apply(this,null),i[Symbol.asyncIterator]=()=>i,s("next"),s("throw"),s("return"),i}var eI="2.18.0",e_={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:eI,protocolVersion:5,agent:"ably-js/"+eI,getPort:function(e,t){return t||e.tls?e.tlsPort:e.port},getHttpScheme:function(e){return e.tls?"https://":"http://"},getPrimaryDomainFromEndpoint:eE,getEndpointFallbackHosts:eL,getFallbackHosts:eU,getHosts:function(e){return[e.primaryDomain].concat(eU(e))},checkHost:ex,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 _.logAction(s,_.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 _.logAction(s,_.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 _.logAction(s,_.LOG_ERROR,`${n}()`,e),Error(e)}r={key:e}}else r=e;return i&&(r=C(w({},r),{plugins:w(w({},i),r.plugins)})),r},normaliseOptions:function(e,t,n){let s=null!=n?n:_.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 L("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 L("The `environment` option cannot be used in conjunction with the `restHost`, or `realtimeHost` options.",40106,400);"function"==typeof e.recover&&!0===e.closeOnUnload&&(_.logAction(s,_.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||e_.ENDPOINT;e.fallbackHosts||e.restHost||e.realtimeHost||e.port||e.tlsPort||(e.fallbackHosts=eL(e.environment||i));let r=e.environment&&`${e.environment}.realtime.ably.net`,o=e.restHost||e.realtimeHost||r||eE(i);(e.fallbackHosts||[]).concat(o).forEach(ex),e.port=e.port||e_.PORT,e.tlsPort=e.tlsPort||e_.TLS_PORT,"tls"in e||(e.tls=!0);let a=function(e){let t={};for(let n in e_.TIMEOUTS)t[n]=e[n]||e_.TIMEOUTS[n];return t}(e);t?"useBinaryProtocol"in e?e.useBinaryProtocol=k.Config.supportsBinary&&e.useBinaryProtocol:e.useBinaryProtocol=k.Config.preferBinary:e.useBinaryProtocol=!1;let l={};e.clientId&&(l["X-Ably-ClientId"]=k.BufferUtils.base64Encode(k.BufferUtils.utf8Encode(e.clientId))),"idempotentRestPublishing"in e||(e.idempotentRestPublishing=!0);let c=null,h=e.connectivityCheckUrl;if(e.connectivityCheckUrl){let[t,n]=e.connectivityCheckUrl.split("?");c=n?ei(n):{},-1===t.indexOf("://")&&(t="https://"+t),h=t}let u=e.wsConnectivityCheckUrl;return u&&-1===u.indexOf("://")&&(u="wss://"+u),C(w({},e),{primaryDomain:o,maxMessageSize:e.maxMessageSize||e_.maxMessageSize,timeouts:a,connectivityCheckParams:c,connectivityCheckUrl:h,wsConnectivityCheckUrl:u,headers:l})},defaultGetHeaders:function(e,{format:t,protocolVersion:n=eD.protocolVersion}={}){return{accept:eq[null!=t?t:e.useBinaryProtocol?"msgpack":"json"],"X-Ably-Version":n.toString(),"Ably-Agent":eG(e)}},defaultPostHeaders:function(e,{format:t,protocolVersion:n=eD.protocolVersion}={}){let s=eq[null!=t?t:e.useBinaryProtocol?"msgpack":"json"];return{accept:s,"content-type":s,"X-Ably-Version":n.toString(),"Ably-Agent":eG(e)}}};function eP(e){return e.includes(".")||e.includes("::")||"localhost"===e}function eE(e){if(eP(e))return e;if(e.startsWith("nonprod:")){let t=e.replace("nonprod:","");return`${t}.realtime.ably-nonprod.net`}return`${e}.realtime.ably.net`}function eL(e){return eP(e)?[]:e.startsWith("nonprod:")?eN(e.replace("nonprod:",""),"ably-realtime-nonprod.com"):eN(e,"ably-realtime.com")}function eN(e,t){return["a","b","c","d","e"].map(n=>`${e}.${n}.fallback.${t}`)}function eU(e){let t=e.fallbackHosts,n=void 0!==e.httpMaxRetryCount?e.httpMaxRetryCount:e_.httpMaxRetryCount;return t?eu(t,n):[]}function ex(e){if("string"!=typeof e)throw new L("host must be a string; was a "+typeof e,4e4,400);if(!e.length)throw new L("host must not be zero-length",4e4,400)}function eG(e){let t=e_.agent;if(e.agents)for(var n in e.agents)t+=" "+n+"/"+e.agents[n];return t}function eB(e,t,n){let s=n||{};if(s.cipher){e||ek("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 eq={json:"application/json",xml:"application/xml",html:"text/html",msgpack:"application/x-msgpack",text:"text/plain"},eD={format:"json",protocolVersion:e_.protocolVersion},ej=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){_.logAction(this.logger,_.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)})}},eH=((t=eH||{}).Get="get",t.Delete="delete",t.Post="post",t.Put="put",t.Patch="patch",t),eV=((s=eV||{})[s.Success=200]="Success",s[s.NoContent=204]="NoContent",s[s.BadRequest=400]="BadRequest",s[s.Unauthorized=401]="Unauthorized",s[s.Forbidden=403]="Forbidden",s[s.RequestTimeout=408]="RequestTimeout",s[s.InternalServerError=500]="InternalServerError",s);function eW(e){return er(e)?(e.code||(403===e.statusCode?e.code=40300:(e.code=40170,e.statusCode=401)),e):new L(eo(e),e.code||40170,e.statusCode||401)}function eF(e){if(!e)return"";"string"==typeof e&&(e=JSON.parse(e));let t=Object.create(null),n=Q(e,!0);if(!n)return"";n.sort();for(let s=0;s<n.length;s++)t[n[s]]=e[n[s]].sort();return JSON.stringify(t)}function eJ(e,t){if(e.authCallback)_.logAction(t,_.LOG_MINOR,"Auth()","using token auth with authCallback");else if(e.authUrl)_.logAction(t,_.LOG_MINOR,"Auth()","using token auth with authUrl");else if(e.key)_.logAction(t,_.LOG_MINOR,"Auth()","using token auth with client-side signing");else if(e.tokenDetails)_.logAction(t,_.LOG_MINOR,"Auth()","using token auth with supplied token only");else{let e="authOptions must include valid authentication parameters";throw _.logAction(t,_.LOG_ERROR,"Auth()",e),Error(e)}}function ez(e){return e.useTokenAuth||!("useTokenAuth"in e&&!e.useTokenAuth)&&(e.authCallback||e.authUrl||e.token||e.tokenDetails)}var eK=0,e$=class{constructor(e,t){if(this.authOptions={},this.client=e,this.tokenParams=t.defaultTokenParams||{},this.currentTokenRequestId=null,this.waitingForTokenRequest=null,ez(t))(function(e){return!e.key&&!e.authCallback&&!e.authUrl})(t)&&_.logAction(this.logger,_.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),eJ(this.authOptions,this.logger);else{if(!t.key){let e="No authentication options provided; need one of: key, authUrl, or authCallback (or for testing only, token or tokenDetails)";throw _.logAction(this.logger,_.LOG_ERROR,"Auth()",e),new L(e,40160,401)}_.logAction(this.logger,_.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 L("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===eV.Forbidden&&this.client.connection.connectionManager.actOnErrorFromAuthorize(e),e}}async _forceNewToken(e,t){this.tokenDetails=null,this._saveTokenOptions(e,t),eJ(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||x(this.tokenParams),i,r=this.client;if(n.authCallback)_.logAction(this.logger,_.LOG_MINOR,"Auth.requestToken()","using token auth with authCallback"),i=n.authCallback;else if(n.authUrl)_.logAction(this.logger,_.LOG_MINOR,"Auth.requestToken()","using token auth with authUrl"),i=(e,t)=>{let s,i=U({accept:"application/json, text/plain"},n.authHeaders),r=n.authMethod&&"post"===n.authMethod.toLowerCase(),o=n.authUrl.indexOf("?");o>-1&&(s=ei(n.authUrl.slice(o)),n.authUrl=n.authUrl.slice(0,o),r||(n.authParams=U(s,n.authParams)));let a=U({},n.authParams||{},e),l=e=>{var n,s;let i=null!=(n=e.body)?n:null,r=null;if(e.error)_.logAction(this.logger,_.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received Error: "+eo(e.error));else{let t=null!=(s=e.headers["content-type"])?s:null;r=Array.isArray(t)?t.join(", "):t,_.logAction(this.logger,_.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received; content-type: "+r+"; body: "+ea(i))}if(e.error)return void t(e.error,null);if(e.unpacked)return void t(null,i);if(k.BufferUtils.isBuffer(i)&&(i=i.toString()),!r)return void t(new L("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 L("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 L("authUrl response exceeded max permitted length",40170,401),null);try{i=JSON.parse(i)}catch(e){t(new L("Unexpected error processing authURL response; err = "+e.message,40170,401),null);return}}t(null,i,r)};if(_.logAction(this.logger,_.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=en(a).slice(1);ed(this.client.http.doUri(eH.Post,n.authUrl,e,t,s),(e,t)=>e?l(e):l(t))}else ed(this.client.http.doUri(eH.Get,n.authUrl,i||{},null,a),(e,t)=>e?l(e):l(t))};else if(n.key)_.logAction(this.logger,_.LOG_MINOR,"Auth.requestToken()","using token auth with client-side signing"),i=(e,t)=>{ed(this.createTokenRequest(e,n),(e,n)=>t(e,null!=n?n:null))};else throw _.logAction(this.logger,_.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 L("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=eF(s.capability));let o=(e,t)=>{let s="/keys/"+e.keyName+"/requestToken",i=e_.defaultPostHeaders(this.client.options,{format:"json"});n.requestHeaders&&U(i,n.requestHeaders),_.logAction(this.logger,_.LOG_MICRO,"Auth.requestToken().requestToken","Sending POST to "+s+"; Token params: "+JSON.stringify(e)),ed(this.client.http.do(eH.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,l=setTimeout(()=>{r=!0;let e="Token request callback timed out after "+a/1e3+" seconds";_.logAction(this.logger,_.LOG_ERROR,"Auth.requestToken()",e),t(new L(e,40170,401))},a);i(s,(s,i,a)=>{if(r)return;if(clearTimeout(l),s){_.logAction(this.logger,_.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+eo(s)),t(eW(s));return}if("string"==typeof i)return void(0===i.length?t(new L("Token string is empty",40170,401)):i.length>131072?t(new L("Token string exceeded max permitted length (was "+i.length+" bytes)",40170,401)):"undefined"===i||"null"===i?t(new L("Token string was literal null/undefined",40170,401)):"{"!==i[0]||a&&a.indexOf("application/jwt")>-1?e({token:i}):t(new L("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;_.logAction(this.logger,_.LOG_ERROR,"Auth.requestToken()",e),t(new L(e,40170,401));return}let c=JSON.stringify(i).length;if(c>131072&&!n.suppressMaxLengthCheck)return void t(new L("Token request/details object exceeded max permitted stringified size (was "+c+" 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";_.logAction(this.logger,_.LOG_ERROR,"Auth.requestToken()",e),t(new L(e,40170,401));return}o(i,(n,s,i)=>{if(n){_.logAction(this.logger,_.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+eo(n)),t(eW(n));return}i||(s=JSON.parse(s)),_.logAction(this.logger,_.LOG_MINOR,"Auth.getToken()","token received"),e(s)})})})}async createTokenRequest(e,t){t=t||this.authOptions,e=e||x(this.tokenParams);let n=t.key;if(!n)throw new L("No key specified",40101,403);let s=n.split(":"),i=s[0],r=s[1];if(!r)throw new L("Invalid key specified",40101,403);if(""===e.clientId)throw new L("clientId can’t be an empty string",40012,400);"capability"in e&&(e.capability=eF(e.capability));let o=U({keyName:i},e),a=e.clientId||"",l=e.ttl||"",c=e.capability||"";o.timestamp||(o.timestamp=await this._getTimestamp(t&&t.queryTime));let h=o.nonce||(o.nonce=("000000"+Math.floor(1e16*Math.random())).slice(-16)),u=o.timestamp,d=o.keyName+"\n"+l+"\n"+c+"\n"+a+"\n"+u+"\n"+h+"\n";return o.mac=o.mac||((e,t)=>{let n=k.BufferUtils,s=n.utf8Encode(e),i=n.utf8Encode(t),r=n.hmacSha256(s,i);return n.base64Encode(r)})(d,r),_.logAction(this.logger,_.LOG_MINOR,"Auth.getTokenRequest()","generated signed request"),o}async 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 "+eR(e.token)}}}_saveBasicOptions(e){this.method="basic",this.key=e.key,this.basicKey=eR(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 L("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 _.logAction(this.logger,_.LOG_MINOR,"Auth.getToken()","using cached token; expires = "+t.expires),t;_.logAction(this.logger,_.LOG_MINOR,"Auth.getToken()","deleting expired token"),this.tokenDetails=null}let n=(this.waitingForTokenRequest||(this.waitingForTokenRequest=ej.create(this.logger))).createPromise();if(null!==this.currentTokenRequestId&&!e)return n;let s=this.currentTokenRequestId=eK++,i,r=null;try{i=await this.requestToken(this.tokenParams,this.authOptions)}catch(e){r=e}if(this.currentTokenRequestId>s)return _.logAction(this.logger,_.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 L("clientId must be either a string or null",40012,400);if("*"===e)throw new L('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 L(t,40102,401);return _.logAction(this.logger,_.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 eQ(e){let t=[];if(e)for(let n in e)t.push(n+"="+e[n]);return t.join("&")}function eX(e,t){return e+(t?"?":"")+eQ(t)}var eY=class{constructor(e){this.client=e,this.platformHttp=new k.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:_.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(e_.getFallbackHosts(e.options)):e_.getHosts(e.options)}async do(e,t,n,s,i){try{let r=this.client;if(!r)return{error:new L("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 l=await this.doUri(e,o(a.host),n,s,i);if(l.error&&this.platformHttp.shouldFallback(l.error))return r._currentFallback=null,this.do(e,t,n,s,i);return l}else r._currentFallback=null;let l=this._getHosts(r);if(1===l.length)return this.doUri(e,o(l[0]),n,s,i);let c=null,h=async(t,a)=>{let l=t.shift();c=null!=c?c:new Date;let u=await this.doUri(e,o(l),n,s,i);return u.error&&this.platformHttp.shouldFallback(u.error)&&t.length?Date.now()-c.getTime()>r.options.timeouts.httpMaxRetryDuration?{error:new L(`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:l,validUntil:Date.now()+r.options.timeouts.fallbackRetryTimeout}),u)};return h(l)}catch(e){return{error:new L(`Unexpected error in Http.do: ${eo(e)}`,500,5e4)}}}async doUri(e,t,n,s,i){try{var r,o;(r=this.logger).shouldLog(_.LOG_MICRO)&&_.logActionNoStrip(r,_.LOG_MICRO,"Http."+e+"()","Sending; "+eX(t,i)+"; Body"+(k.BufferUtils.isBuffer(s)?" (Base64): "+k.BufferUtils.base64Encode(s):": "+s));let a=await this.platformHttp.doUri(e,t,n,s,i);return this.logger.shouldLog(_.LOG_MICRO)&&(o=this.logger,a.error?_.logActionNoStrip(o,_.LOG_MICRO,"Http."+e+"()","Received Error; "+eX(t,i)+"; Error: "+eo(a.error)):_.logActionNoStrip(o,_.LOG_MICRO,"Http."+e+"()","Received; "+eX(t,i)+"; Headers: "+eQ(a.headers)+"; StatusCode: "+a.statusCode+"; Body"+(k.BufferUtils.isBuffer(a.body)?" (Base64): "+k.BufferUtils.base64Encode(a.body):": "+a.body))),a}catch(e){return{error:new L(`Unexpected error in Http.doUri: ${eo(e)}`,500,5e4)}}}};function eZ(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(B(s))for(r in s)Object.prototype.hasOwnProperty.call(s,r)&&Array.isArray(s[r])&&eZ([s],t,r)}var e0=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: "+k.Config.inspect(e))}if(2===e.length){let[t,n]=e;if("function"!=typeof n)throw Error("EventListener.on(): Invalid arguments: "+k.Config.inspect(e));if(D(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: "+k.Config.inspect(e));(this.events[t]||(this.events[t]=[])).push(n)}}}off(...e){if(0==e.length||D(e[0])&&D(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:"+k.Config.inspect(e));[i,s]=[t,n]}else"function"==typeof t?s=t:i=t;if(s&&D(i))return void eZ([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:"+k.Config.inspect(e));s?eZ([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){_.logAction(s,_.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(D(n)){if("function"!=typeof s)throw Error("EventEmitter.once(): Invalid arguments:"+k.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:"+k.Config.inspect(e));s.apply(this,r)};n.forEach(function(e){t.on(e,i)})}else{if("string"!=typeof n)throw Error("EventEmitter.once(): Invalid arguments:"+k.Config.inspect(e));let t=this.eventsOnce[n]||(this.eventsOnce[n]=[]);if(s){if("function"!=typeof s)throw Error("EventEmitter.once(): Invalid arguments:"+k.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)}},e1={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},e4=[];Object.keys(e1).forEach(function(e){e4[e1[e]]=e});var e2={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},e8=Object.keys(e2);e2.MODE_ALL=e2.PRESENCE|e2.PUBLISH|e2.SUBSCRIBE|e2.PRESENCE_SUBSCRIBE|e2.ANNOTATION_PUBLISH|e2.ANNOTATION_SUBSCRIBE|e2.OBJECT_SUBSCRIBE|e2.OBJECT_PUBLISH;var e3=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE","ANNOTATION_PUBLISH","ANNOTATION_SUBSCRIBE","OBJECT_SUBSCRIBE","OBJECT_PUBLISH"];function e6(e,t,n){if(n&&n.cipher){e||ek("Crypto");let s=e.getCipher(n.cipher,t);return{cipher:s.cipherParams,channelCipher:s.cipher}}return null!=n?n:{}}async function e5(e,t){let{data:n,encoding:s}=await e9(e.data,e.encoding,t);return e.data=n,e.encoding=s,e}async function e9(e,t,n){let s=n.channelCipher,i=e,r=t?t+"/":"";return k.BufferUtils.isBuffer(i)||(i=k.BufferUtils.utf8Encode(String(i)),r+="utf-8/"),{data:await s.encrypt(i),encoding:r=r+"cipher+"+s.algorithm}}async function e7(e,t){let{data:n,encoding:s}=te(e.data,e.encoding);return(e.data=n,e.encoding=s,null!=t&&t.cipher)?e5(e,t):e}function te(e,t){if("string"==typeof e||k.BufferUtils.isBuffer(e)||null==e)return{data:e,encoding:t};if(B(e)||Array.isArray(e))return{data:JSON.stringify(e),encoding:t?t+"/json":"json"};throw new L("Data type is unsupported",40013,400)}async function tt(e,t){let{data:n,encoding:s,error:i}=await tn(e.data,e.encoding,t);if(e.data=n,e.encoding=s,i)throw i}async function tn(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("/"),l=n.length,c="";try{for(;(e=l)>0;){let t=n[--l].match(/([-\w]+)(\+([\w-]+))?/);if(!t)break;switch(c=t[1]){case"base64":o=k.BufferUtils.base64Decode(String(o)),e==n.length&&(r=o);continue;case"utf-8":o=k.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 L("Missing Vcdiff decoder (https://github.com/ably-forks/vcdiff-decoder)",40019,400);if("undefined"==typeof Uint8Array)throw new L("Delta decoding not supported on this browser (need ArrayBuffer & Uint8Array)",40020,400);try{let e=i.baseEncodedPreviousPayload;"string"==typeof e&&(e=k.BufferUtils.utf8Encode(e));let t=k.BufferUtils.toBuffer(e);o=k.BufferUtils.toBuffer(o),r=o=k.BufferUtils.arrayBufferViewToBuffer(i.plugins.vcdiff.decode(o,t))}catch(e){throw new L("Vcdiff delta decode failed with "+e,40018,400)}continue;default:throw Error("Unknown encoding")}}}catch(e){s=new L(`Error processing the ${c} 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 ts(...e){let t=e.length>0?"json":"msgpack",{data:n,encoding:s}=ti(this.data,this.encoding,t);return Object.assign({},this,{encoding:s,data:n})}function ti(e,t,n){return e&&k.BufferUtils.isBuffer(e)?"msgpack"===n?{data:k.BufferUtils.toBuffer(e),encoding:t}:{data:k.BufferUtils.base64Encode(e),encoding:t?t+"/base64":"base64"}:{data:e,encoding:t}}var tr={encryptData:e9,encodeData:te,encodeDataForWire:ti,decodeData:tn};function to(e){let t,{id:n,connectionId:s,timestamp:i}=e;switch(e.action){case e1.MESSAGE:t=e.messages;break;case e1.PRESENCE:case e1.SYNC:t=e.presence;break;case e1.ANNOTATION:t=e.annotations;break;case e1.OBJECT:case e1.OBJECT_SYNC:t=e.state;break;default:throw new L("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 ta(e,t){let n="["+t;for(let t in e)"data"===t?"string"==typeof e.data?n+="; data="+e.data:k.BufferUtils.isBuffer(e.data)?n+="; data (buffer)="+k.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 tl=class{},tc=class{constructor(e){var t,n,s,i,r,o,a,l,c,h;this.Platform=k,this.ErrorInfo=L,this.Logger=_,this.Defaults=e_,this.Utils=P,this.EventEmitter=e0,this.MessageEncoding=tr,this._additionalHTTPRequestImplementations=null!=(t=e.plugins)?t:null,this.logger=new _,this.logger.setLog(e.logLevel,e.logHandler),_.logAction(this.logger,_.LOG_MICRO,"BaseClient()","initialized with clientOptions "+k.Config.inspect(e)),this._MsgPack=null!=(s=null==(n=e.plugins)?void 0:n.MsgPack)?s:null;let u=this.options=e_.normaliseOptions(e,this._MsgPack,this.logger);if(u.key){let e=u.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!e){let e="invalid key parameter";throw _.logAction(this.logger,_.LOG_ERROR,"BaseClient()",e),new L(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 L("clientId must be either a string or null",40012,400);else if("*"===u.clientId)throw new L('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)}_.logAction(this.logger,_.LOG_MINOR,"BaseClient()","started; version = "+e_.version),this._currentFallback=null,this.serverTimeOffset=null,this.http=new eY(this),this.auth=new e$(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!=(l=null==(a=e.plugins)?void 0:a.MessageInteractions)?l:null,this._Annotations=null!=(h=null==(c=e.plugins)?void 0:c.Annotations)?h:null}get rest(){return this._rest||ek("Rest"),this._rest}get _FilteredSubscriptions(){return this.__FilteredSubscriptions||ek("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||ek("Push"),this._device||(this._device=this.push.LocalDevice.load(this)),this._device}baseUri(e){return e_.getHttpScheme(this.options)+e+":"+e_.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}};tc.Platform=k;var th=tc,tu=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 ep(e,t,n)}static fromResponseBody(t,n,s){return(s&&(t=eg(t,n,s)),Array.isArray(t))?e.fromValuesArray(t):e.fromValues(t)}static fromValues(t){return t.error=t.error&&L.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 td(e,t,n,s){return e.http.supportsAuthHeaders?s(U(await e.auth.getAuthHeaders(),t),n):s(t,U(await e.auth.getAuthParams(),n))}var tg=class e{static async get(t,n,s,i,r,o){return e.do(eH.Get,t,n,null,s,i,r,null!=o&&o)}static async delete(t,n,s,i,r,o){return e.do(eH.Delete,t,n,null,s,i,r,o)}static async post(t,n,s,i,r,o,a){return e.do(eH.Post,t,n,s,i,r,o,a)}static async patch(t,n,s,i,r,o,a){return e.do(eH.Patch,t,n,s,i,r,o,a)}static async put(t,n,s,i,r,o,a){return e.do(eH.Put,t,n,s,i,r,o,a)}static async do(e,t,n,s,i,r,o,a){var l,c;o&&((r=r||{}).envelope=o);let h=t.logger;async function u(i,r){var o;if(h.shouldLog(_.LOG_MICRO)){let a=s;if((null==(o=i["content-type"])?void 0:o.indexOf("msgpack"))>0)try{t._MsgPack||ek("MsgPack"),a=t._MsgPack.decode(s)}catch(t){_.logAction(h,_.LOG_MICRO,"Resource."+e+"()","Sending MsgPack Decoding Error: "+eo(t))}_.logAction(h,_.LOG_MICRO,"Resource."+e+"()","Sending; "+eX(n,r)+"; Body: "+a)}let a=await t.http.do(e,n,i,s,r);return a.error&&e$.isTokenErr(a.error)?(await t.auth.authorize(null,null),td(t,i,r,u)):{err:a.error,body:a.body,headers:a.headers,unpacked:a.unpacked,statusCode:a.statusCode}}let d=await td(t,i,r,u);if(o&&(d=function(e,t,n){if(e.err&&!e.body)return{err:e.err};if(e.statusCode===eV.NoContent)return C(w({},e),{body:[],unpacked:!0});let s=e.body;if(!e.unpacked)try{s=eg(s,t,n)}catch(e){if(er(e))return{err:e};return{err:new N(eo(e),null)}}if(!s)return{err:new N("unenvelope(): Response body is missing",null)};let{statusCode:i,response:r,headers:o}=s;if(void 0===i)return C(w({},e),{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(_.LOG_MICRO)&&(l=d,c=r,l.err?_.logAction(h,_.LOG_MICRO,"Resource."+e+"()","Received Error; "+eX(n,c)+"; Error: "+eo(l.err)):_.logAction(h,_.LOG_MICRO,"Resource."+e+"()","Received; "+eX(n,c)+"; Headers: "+eQ(l.headers)+"; StatusCode: "+l.statusCode+"; Body: "+(k.BufferUtils.isBuffer(l.body)?" (Base64): "+k.BufferUtils.base64Encode(l.body):": "+k.Config.inspect(l.body)))),a)if(d.err)throw d.err;else{let e=w({},d);return delete e.err,e}return d}},tp=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 tg.get(this.client,this.path,this.headers,e,this.envelope,!1);return this.handlePage(t)}async delete(e){let t=await tg.delete(this.client,this.path,this.headers,e,this.envelope,!1);return this.handlePage(t)}async post(e,t){let n=await tg.post(this.client,this.path,t,this.headers,e,this.envelope,!1);return this.handlePage(n)}async put(e,t){let n=await tg.put(this.client,this.path,t,this.headers,e,this.envelope,!1);return this.handlePage(n)}async patch(e,t){let n=await tg.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 _.logAction(this.logger,_.LOG_ERROR,"PaginatedResource.handlePage()","Unexpected error getting resource: err = "+eo(e.err)),e.err;try{s=e.statusCode==eV.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]&&ei(t[2])}(s[1]);e&&(t[s[2]]=e)}}return t}(i)),this.useHttpPaginatedResponse)?new tm(this,s,e.headers||{},e.statusCode,r,e.err):new tf(this,s,r)}},tf=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 L("No link to the first page of results",40400,404)}async current(){if(this.hasCurrent())return this.get(this._relParams.current);throw new L("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 tg.get(t.client,t.path,t.headers,e,t.envelope,!1);return t.handlePage(n)}},tm=class extends tf{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}}},ty=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=eg(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}};ty.toRequestBody=ep;var tv=class{constructor(e){var t;this.client=e,this.admin=new tb(e),k.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(tu))}async activate(e,t){await new Promise((n,s)=>{var i;return(null==(i=this.client.options.plugins)?void 0:i.Push)?this.stateMachine?this.stateMachine.activatedCallback?void s(new L("Activation already in progress",4e4,400)):void(this.stateMachine.activatedCallback=e=>{if(e)return void s(e);n()},this.stateMachine.updateFailedCallback=t,this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledActivate(this.stateMachine,e))):void s(new L("This platform is not supported as a target of push notifications",4e4,400)):void s(eS("Push"))})}async deactivate(e){await new Promise((t,n)=>{var s;return(null==(s=this.client.options.plugins)?void 0:s.Push)?this.stateMachine?this.stateMachine.deactivatedCallback?void n(new L("Deactivation already in progress",4e4,400)):void(this.stateMachine.deactivatedCallback=e=>{if(e)return void n(e);t()},this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledDeactivate(this.stateMachine,e))):void n(new L("This platform is not supported as a target of push notifications",4e4,400)):void n(eS("Push"))})}},tb=class{constructor(e){this.client=e,this.deviceRegistrations=new tO(e),this.channelSubscriptions=new tw(e)}async publish(e,t){let n=this.client,s=n.options.useBinaryProtocol?"msgpack":"json",i=e_.defaultPostHeaders(n.options),r={},o=U({recipient:e},t);U(i,n.options.headers),n.options.pushFullWait&&U(r,{fullWait:"true"});let a=ep(o,n._MsgPack,s);await tg.post(n,"/push/publish",a,i,r,null,!0)}},tO=class{constructor(e){this.client=e}async save(e){let t=this.client,n=tu.fromValues(e),s=t.options.useBinaryProtocol?"msgpack":"json",i=e_.defaultPostHeaders(t.options),r={};U(i,t.options.headers),t.options.pushFullWait&&U(r,{fullWait:"true"});let o=ep(n,t._MsgPack,s),a=await tg.put(t,"/push/deviceRegistrations/"+encodeURIComponent(e.id),o,i,r,null,!0);return tu.fromResponseBody(a.body,t._MsgPack,a.unpacked?void 0:s)}async get(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=e_.defaultGetHeaders(t.options),i=e.id||e;if("string"!=typeof i||!i.length)throw new L("First argument to DeviceRegistrations#get must be a deviceId string or DeviceDetails",4e4,400);U(s,t.options.headers);let r=await tg.get(t,"/push/deviceRegistrations/"+encodeURIComponent(i),s,{},null,!0);return tu.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=e_.defaultGetHeaders(t.options);return U(i,t.options.headers),new tp(t,"/push/deviceRegistrations",i,s,async function(e,s,i){return tu.fromResponseBody(e,t._MsgPack,i?void 0:n)}).get(e)}async remove(e){let t=this.client,n=e_.defaultGetHeaders(t.options),s={},i=e.id||e;if("string"!=typeof i||!i.length)throw new L("First argument to DeviceRegistrations#remove must be a deviceId string or DeviceDetails",4e4,400);U(n,t.options.headers),t.options.pushFullWait&&U(s,{fullWait:"true"}),await tg.delete(t,"/push/deviceRegistrations/"+encodeURIComponent(i),n,s,null,!0)}async removeWhere(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=e_.defaultGetHeaders(t.options,{format:n});U(s,t.options.headers),t.options.pushFullWait&&U(e,{fullWait:"true"}),await tg.delete(t,"/push/deviceRegistrations",s,e,null,!0)}},tw=class e{constructor(t){this.remove=e.prototype.removeWhere,this.client=t}async save(e){let t=this.client,n=ty.fromValues(e),s=t.options.useBinaryProtocol?"msgpack":"json",i=e_.defaultPostHeaders(t.options),r={};U(i,t.options.headers),t.options.pushFullWait&&U(r,{fullWait:"true"});let o=ep(n,t._MsgPack,s),a=await tg.post(t,"/push/channelSubscriptions",o,i,r,null,!0);return ty.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=e_.defaultGetHeaders(t.options);return U(i,t.options.headers),new tp(t,"/push/channelSubscriptions",i,s,async function(e,s,i){return ty.fromResponseBody(e,t._MsgPack,i?void 0:n)}).get(e)}async removeWhere(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=e_.defaultGetHeaders(t.options,{format:n});U(s,t.options.headers),t.options.pushFullWait&&U(e,{fullWait:"true"}),await tg.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=e_.defaultGetHeaders(t.options);return U(i,t.options.headers),t.options.pushFullWait&&U(e,{fullWait:"true"}),new tp(t,"/push/channels",i,s,async function(e,s,i){let r=!i&&n?eg(e,t._MsgPack,n):e;for(let e=0;e<r.length;e++)r[e]=String(r[e]);return r}).get(e)}},tC=["absent","present","enter","leave","update"];async function tR(e,t,n,s){let i=e6(t,e,null!=s?s:null);return tT.fromValues(n).decode(i,e)}async function tA(e,t,n,s){return Promise.all(n.map(function(n){return tR(e,t,n,s)}))}async function tS(e,t){return tT.fromValues(e).decode(t.channelOptions,t.logger)}async function tk(e,t){return Promise.all(e.map(function(e){return tS(e,t)}))}var tM=class e extends tl{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 e7(Object.assign(new tT,this,{action:tC.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 ta(this,"PresenceMessage")}},tT=class e extends tl{toJSON(...e){return ts.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 tM,C(w({},this),{action:tC[this.action]}));try{await tt(n,e)}catch(e){_.logAction(t,_.LOG_ERROR,"WirePresenceMessage.decode()",eo(e))}return n}toString(){return ta(this,"WirePresenceMessage")}},tI=tM,t_=class{constructor(e){this.channel=e}get logger(){return this.channel.logger}async get(e){_.logAction(this.logger,_.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=e_.defaultGetHeaders(t.options);return U(i,t.options.headers),new tp(t,this.channel.client.rest.presenceMixin.basePath(this),i,s,async(e,s,i)=>tk(i?e:eg(e,t._MsgPack,n),this.channel)).get(e)}async history(e){return _.logAction(this.logger,_.LOG_MICRO,"RestPresence.history()","channel = "+this.channel.name),this.channel.client.rest.presenceMixin.history(this,e)}},tP=["message.create","message.update","message.delete","meta","message.summary","message.append"];async function tE(e,t,n,s){let i=e6(t,e,null!=s?s:null);return tD.fromValues(n).decode(i,e)}async function tL(e,t,n,s){return Promise.all(n.map(function(n){return tE(e,t,n,s)}))}async function tN(e,t){return tD.fromValues(e).decode(t.channelOptions,t.logger)}async function tU(e,t){return Promise.all(e.map(function(e){return tN(e,t)}))}async function tx(e,t){return Promise.all(e.map(e=>e.encode(t)))}var tG=ep;function tB(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+=el(e.data)),t}(t));return n}var tq=class e extends tl{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 e7(Object.assign(new tD,this,{action:tP.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 ta(this,"Message")}},tD=class e extends tl{toJSON(...e){return ts.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 tq,C(w({},this),{action:tP[this.action||0]||"unknown"}));try{await tt(s,e)}catch(e){_.logAction(t,_.LOG_ERROR,"WireMessage.decode()",eo(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 ta(this,"WireMessage")}},tj=tq,tH=class{constructor(e,t,n){var s,i;this._annotations=null,_.logAction(e.logger,_.LOG_MINOR,"RestChannel()","started; name = "+t),this.name=t,this.client=e,this.presence=new t_(this),this.channelOptions=eB(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||ek("Annotations"),this._annotations}get push(){return this._push||ek("Push"),this._push}get logger(){return this.client.logger}setOptions(e){var t;this.channelOptions=eB(null!=(t=this.client._Crypto)?t:null,this.logger,e)}async history(e){return _.logAction(this.logger,_.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=[tj.fromValues({name:s,data:i})],n=e[2];else if(B(s))t=[tj.fromValues(s)],n=e[1];else if(Array.isArray(s))t=tj.fromValuesArray(s),n=e[1];else throw new L("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",l=r.options.idempotentRestPublishing,c=e_.defaultPostHeaders(r.options);if(U(c,o.headers),l&&t.every(function(e){return!e.id})){let e=await eh(9);t.forEach(function(t,n){t.id=e+":"+n.toString()})}let h=await tx(t,this.channelOptions),u=tB(h),d=o.maxMessageSize;if(u>d)throw new L(`Maximum size of messages that can be published at once exceeded (was ${u} bytes; limit is ${d} bytes)`,40009,400);return this._publish(tG(h,r._MsgPack,a),c,n)}async _publish(e,t,n){let s=this.client,i=s.options.useBinaryProtocol?"msgpack":"json",{body:r,unpacked:o}=await tg.post(s,s.rest.channelMixin.basePath(this)+"/messages",e,t,n,null,!0),a=(o?r:eg(r,s._MsgPack,i))||{};return delete a.channel,delete a.messageId,a}async status(){return this.client.rest.channelMixin.status(this)}async getMessage(e){return _.logAction(this.logger,_.LOG_MICRO,"RestChannel.getMessage()","channel = "+this.name),this.client.rest.channelMixin.getMessage(this,e)}async updateMessage(e,t,n){return _.logAction(this.logger,_.LOG_MICRO,"RestChannel.updateMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.update",e,t,n)}async deleteMessage(e,t,n){return _.logAction(this.logger,_.LOG_MICRO,"RestChannel.deleteMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.delete",e,t,n)}async appendMessage(e,t,n){return _.logAction(this.logger,_.LOG_MICRO,"RestChannel.appendMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.append",e,t,n)}async getMessageVersions(e,t){return _.logAction(this.logger,_.LOG_MICRO,"RestChannel.getMessageVersions()","channel = "+this.name),this.client.rest.channelMixin.getMessageVersions(this,e,t)}},tV=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)}},tW=class{static basePath(e){return"/channels/"+encodeURIComponent(e.name)}static history(e,t){let n=e.client,s=n.options.useBinaryProtocol?"msgpack":"json",i=e.client.http.supportsLinkHeaders?void 0:s,r=e_.defaultGetHeaders(n.options);return U(r,n.options.headers),new tp(n,this.basePath(e)+"/messages",r,i,async function(t,i,r){return tU(r?t:eg(t,n._MsgPack,s),e)}).get(t)}static async status(e){let t=e.client.options.useBinaryProtocol?"msgpack":"json",n=e_.defaultPostHeaders(e.client.options);return(await tg.get(e.client,this.basePath(e),n,{},t,!0)).body}static async getMessage(e,t){let n="string"==typeof t?t:t.serial;if(!n)throw new L('This message lacks a serial. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);let s=e.client,i=s.options.useBinaryProtocol?"msgpack":"json",r=e_.defaultGetHeaders(s.options);U(r,s.options.headers);let{body:o,unpacked:a}=await tg.get(s,this.basePath(e)+"/messages/"+encodeURIComponent(n),r,{},null,!0);return tN(a?o:eg(o,s._MsgPack,i),e)}static async updateDeleteMessage(e,t,n,s,i){if(!n.serial)throw new L('This message lacks a serial and cannot be updated. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);let r=e.client,o=r.options.useBinaryProtocol?"msgpack":"json",a=e_.defaultPostHeaders(r.options);U(a,r.options.headers);let l=tj.fromValues(n);l.action=t,l.version=s;let c=tG(await l.encode(e.channelOptions),r._MsgPack,o),h=tg.patch,{body:u,unpacked:d}=await h(r,this.basePath(e)+"/messages/"+encodeURIComponent(n.serial),c,a,i||{},null,!0);return(d?u:eg(u,r._MsgPack,o))||{versionSerial:null}}static getMessageVersions(e,t,n){let s="string"==typeof t?t:t.serial;if(!s)throw new L('This message lacks a serial. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);let i=e.client,r=i.options.useBinaryProtocol?"msgpack":"json",o=e.client.http.supportsLinkHeaders?void 0:r,a=e_.defaultGetHeaders(i.options);return U(a,i.options.headers),new tp(i,this.basePath(e)+"/messages/"+encodeURIComponent(s)+"/versions",a,o,async(t,n,s)=>tU(s?t:eg(t,i._MsgPack,r),e)).get(n||{})}},tF=class{static basePath(e){return tW.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=e_.defaultGetHeaders(n.options);return U(r,n.options.headers),new tp(n,this.basePath(e)+"/history",r,i,async(t,i,r)=>tk(r?t:eg(t,n._MsgPack,s),e.channel)).get(t)}},tJ=class{constructor(e){this.channelMixin=tW,this.presenceMixin=tF,this.Resource=tg,this.PaginatedResource=tp,this.DeviceDetails=tu,this.PushChannelSubscription=ty,this.client=e,this.channels=new tz(this.client),this.push=new tv(this.client)}async stats(e){let t=e_.defaultGetHeaders(this.client.options),n=this.client.options.useBinaryProtocol?"msgpack":"json",s=this.client.http.supportsLinkHeaders?void 0:n;return U(t,this.client.options.headers),new tp(this.client,"/stats",t,s,async(e,t,s)=>{let i=s?e:eg(e,this.client._MsgPack,n);for(let e=0;e<i.length;e++)i[e]=tV.fromValues(i[e]);return i}).get(e)}async time(e){let t=e_.defaultGetHeaders(this.client.options,{format:"json"});this.client.options.headers&&U(t,this.client.options.headers);let n=e=>this.client.baseUri(e)+"/time",{error:s,body:i,unpacked:r}=await this.client.http.do(eH.Get,n,t,null,e);if(s)throw s;r||(i=JSON.parse(i));let o=i[0];if(!o)throw new L("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,l,c]=this.client.options.useBinaryProtocol?(this.client._MsgPack||ek("MsgPack"),[this.client._MsgPack.encode,this.client._MsgPack.decode,"msgpack"]):[JSON.stringify,JSON.parse,"json"],h=this.client.http.supportsLinkHeaders?void 0:c;s=s||{};let u=e.toLowerCase(),d="get"==u?e_.defaultGetHeaders(this.client.options,{format:c,protocolVersion:n}):e_.defaultPostHeaders(this.client.options,{format:c,protocolVersion:n});"string"!=typeof i&&(i=null!=(o=a(i))?o:null),U(d,this.client.options.headers),r&&U(d,r);let g=new tp(this.client,t,d,h,async function(e,t,n){return G(n?e:l(e))},!0);if(!k.Http.methods.includes(u))throw new L("Unsupported method "+u,40500,405);return k.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=e_.defaultPostHeaders(this.client.options);this.client.options.headers&&U(i,this.client.options.headers);let r=ep(t,this.client._MsgPack,s),o=await tg.post(this.client,"/messages",r,i,{},null,!0),a=o.unpacked?o.body:eg(o.body,this.client._MsgPack,s);return n?a[0]:a}async batchPresence(e){let t=this.client.options.useBinaryProtocol?"msgpack":"json",n=e_.defaultGetHeaders(this.client.options);this.client.options.headers&&U(n,this.client.options.headers);let s=e.join(","),i=await tg.get(this.client,"/presence",n,{channels:s},null,!0);return i.unpacked?i.body:eg(i.body,this.client._MsgPack,t)}async revokeTokens(e,t){if(ez(this.client.options))throw new L("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=e_.defaultPostHeaders(this.client.options);this.client.options.headers&&U(r,this.client.options.headers);let o=ep(s,this.client._MsgPack,i),a=await tg.post(this.client,`/keys/${n}/revokeTokens`,o,r,{},null,!0);return a.unpacked?a.body:eg(a.body,this.client._MsgPack,i)}},tz=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 tH(this.client,e,t),n}release(e){delete this.all[String(e)]}},tK=class extends th{constructor(e){super(e_.objectifyOptions(e,!1,"BaseRest",_.defaultLogger,{Rest:tJ}))}},t$={Rest:tJ},tQ=class extends tj{static async fromEncoded(e,t){return tE(_.defaultLogger,k.Crypto,e,t)}static async fromEncodedArray(e,t){return tL(_.defaultLogger,k.Crypto,e,t)}static fromValues(e){return tj.fromValues(e)}},tX=class extends tI{static async fromEncoded(e,t){return tR(_.defaultLogger,k.Crypto,e,t)}static async fromEncodedArray(e,t){return tA(_.defaultLogger,k.Crypto,e,t)}static fromValues(e){return tI.fromValues(e)}},tY=["annotation.create","annotation.delete"];async function tZ(e,t,n){return t8.fromValues(t).decode(n||{},e)}async function t0(e,t,n){return Promise.all(t.map(function(t){return tZ(e,t,n)}))}async function t1(e,t){return t8.fromValues(e).decode(t.channelOptions,t.logger)}async function t4(e,t){return Promise.all(e.map(function(e){return t1(e,t)}))}var t2=class e extends tl{async encode(){return e7(Object.assign(new t8,this,{action:tY.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 ta(this,"Annotation")}},t8=class e extends tl{toJSON(...e){return ts.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 t2,C(w({},this),{action:tY[this.action]}));try{await tt(n,e)}catch(e){_.logAction(t,_.LOG_ERROR,"WireAnnotation.decode()",eo(e))}return n}toString(){return ta(this,"WireAnnotation")}},t3=t2,t6=class extends t3{static async fromEncoded(e,t){return tZ(_.defaultLogger,e,t)}static async fromEncodedArray(e,t){return t0(_.defaultLogger,e,t)}static fromValues(e){return t3.fromValues(e)}};function t5(e){let t;switch(typeof e){case"string":t=e;break;case"object":t=e.serial}if(!t||"string"!=typeof t)throw new L("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 t9(e,t){let n=t5(e);if(!t||"object"!=typeof t)throw new L("Second argument of annotations.publish() must be an object (the intended annotation to publish)",40003,400);let s=t3.fromValues(t);return s.messageSerial=n,s.action||(s.action="annotation.create"),s}function t7(e,t){return e.client.rest.channelMixin.basePath(e)+"/messages/"+encodeURIComponent(t)+"/annotations"}var ne=class{constructor(e){this.channel=e}async publish(e,t){let n=t9(e,t),s=await n.encode(),i=this.channel.client,r=i.options.useBinaryProtocol?"msgpack":"json",o=e_.defaultPostHeaders(i.options);U(o,i.options.headers);let a=ep([s],i._MsgPack,r);await tg.post(i,t7(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=t5(e),i=n.options.useBinaryProtocol?"msgpack":"json",r=n.http.supportsLinkHeaders?void 0:i,o=e_.defaultGetHeaders(n.options);return U(o,n.options.headers),new tp(n,t7(this.channel,s),o,r,async(e,t,s)=>t4(s?e:eg(e,n._MsgPack,i),this.channel)).get(t)}};function nt(e){let t=[];if(e)for(let n=0;n<e.length;n++)t.push(e[n].toString());return"[ "+t.join(", ")+" ]"}function nn(e,t,n,s){let i,r,o,a,l;return e.error&&(i=L.fromValues(e.error)),e.messages&&(r=tD.fromValuesArray(e.messages)),t&&e.presence&&(o=t.WirePresenceMessage.fromValuesArray(e.presence)),n&&e.annotations&&(a=n.WireAnnotation.fromValuesArray(e.annotations)),s&&e.state&&(l=s.WireObjectMessage.fromValuesArray(e.state,P,tr)),Object.assign(new no,C(w({},e),{presence:o,messages:r,annotations:a,state:l,error:i}))}function ns(e){return t=>{var n;return nn(t,{PresenceMessage:tI,WirePresenceMessage:tT},{Annotation:t3,WireAnnotation:t8,RealtimeAnnotations:nh,RestAnnotations:ne},null!=(n=null==e?void 0:e.LiveObjectsPlugin)?n:null)}}function ni(e){return Object.assign(new no,e)}function nr(e,t,n,s){let i,r="[ProtocolMessage";void 0!==e.action&&(r+="; action="+e4[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="+nt(tD.fromValuesArray(e.messages))),e.presence&&t&&(r+="; presence="+nt(t.WirePresenceMessage.fromValuesArray(e.presence))),e.annotations&&n&&(r+="; annotations="+nt(n.WireAnnotation.fromValuesArray(e.annotations))),e.state&&s&&(r+="; state="+nt(s.WireObjectMessage.fromValuesArray(e.state,P,tr))),e.error&&(r+="; error="+L.fromValues(e.error).toString()),e.auth&&e.auth.accessToken&&(r+="; token="+e.auth.accessToken),e.flags&&(r+="; flags="+e8.filter(e.hasFlag).join(",")),e.params){let t="";Y(e.params,function(n){t.length>0&&(t+="; "),t+=n+"="+e.params[n]}),t.length>0&&(r+="; params=["+t+"]")}return r+"]"}var no=class{constructor(){this.hasFlag=e=>(this.flags&e2[e])>0}setFlag(e){return this.flags=this.flags|e2[e]}getMode(){return(this.flags||0)&e2.MODE_ALL}encodeModesToFlags(e){e.forEach(e=>this.setFlag(e))}decodeModesFromFlags(){let e=[];return e3.forEach(t=>{this.hasFlag(t)&&e.push(t)}),e.length>0?e:void 0}},na=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)}},nl=class e extends e0{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){_.logAction(this.logger,_.LOG_MICRO,"RealtimeChannel.history()","channel = "+this.name);let t=this.client.rest.channelMixin;if(e&&e.untilAttach){if("attached"!==this.state)throw new L("option untilAttach requires the channel to be attached",4e4,400);if(!this.properties.attachSerial)throw new L("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=>e0.prototype.whenState.call(this,e,this.state),_.logAction(this.logger,_.LOG_MINOR,"RealtimeChannel()","started; name = "+t),this.name=t,this.channelOptions=eB(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 e0(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._attachedReceived=new e0(this.logger),this.internalStateChanges=new e0(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.LiveObjects)&&(this._object=new e.options.plugins.LiveObjects.RealtimeObject(this))}get presence(){return this._presence||ek("RealtimePresence"),this._presence}get annotations(){return this._annotations||ek("Annotations"),this._annotations}get push(){return this._push||ek("Push"),this._push}get object(){return this._object||ek("LiveObjects"),this._object}emit(e,...t){super.emit(e,...t),this.internalStateChanges.emit(e,...t)}invalidStateError(){return new L("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&&!B(e.params))return new L("options.params must be an object",4e4,400);if(e&&"modes"in e){if(!Array.isArray(e.modes))return new L("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||!e3.includes(String.prototype.toUpperCase.call(n)))return new L("Invalid channel mode: "+n,4e4,400)}}}(e);if(s)throw s;if(this.channelOptions=eB(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)=>{let n=()=>{this._attachedReceived.off(s),this.internalStateChanges.off(i)},s=()=>{n(),e()},i=e=>{n(),t(e.reason)};this._attachedReceived.once("attached",s),this.internalStateChanges.once(["detached","failed"],i)})}_shouldReattachToSetOptions(e,t){if("attached"!==this.state&&"attaching"!==this.state)return!1;if(null==e?void 0:e.params){let n=nc(e.params),s=nc(t.params);if(Object.keys(n).length!==Object.keys(s).length||!ew(s,n))return!0}return!(null==e||!e.modes||t.modes&&eA(e.modes,t.modes))}async publish(...e){let t,n,s=e[0],i=e[1];if("string"==typeof s||null==s)t=[tj.fromValues({name:s,data:i})],n=e[2];else if(B(s))t=[tj.fromValues(s)],n=e[1];else if(Array.isArray(s))t=tj.fromValuesArray(s),n=e[1];else throw new L("The single-argument form of publish() expects a message object or an array of message objects",40013,400);let r=this.client.options.maxMessageSize,o=await tx(t,this.channelOptions),a=tB(o);if(a>r)throw new L(`Maximum size of messages that can be published at once exceeded (was ${a} bytes; limit is ${r} bytes)`,40009,400);this.throwIfUnpublishableState(),_.logAction(this.logger,_.LOG_MICRO,"RealtimeChannel.publish()","sending message; channel state is "+this.state+", message count = "+o.length);let l=ni({action:e1.MESSAGE,channel:this.name,messages:o,params:n?es(n):void 0});return this.sendAndAwaitAck(l)}throwIfUnpublishableState(){if(!this.connectionManager.activeState())throw this.connectionManager.getError();if("failed"===this.state||"suspended"===this.state)throw this.invalidStateError()}onEvent(e){_.logAction(this.logger,_.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)=>{this._attach(!1,null,(n,s)=>n?t(n):e(s))})}_attach(e,t,n){n||(n=e=>{e&&_.logAction(this.logger,_.LOG_ERROR,"RealtimeChannel._attach()","Channel attach failed: "+e.toString())});let s=this.connectionManager;if(!s.activeState())return void n(s.getError());("attaching"!==this.state||e)&&this.requestState("attaching",t),this.internalStateChanges.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 L("Unable to attach; reason unknown; state = "+this.event,9e4,500));break;case"detaching":null==n||n(new L("Attach request superseded by a subsequent detach request",9e4,409))}})}attachImpl(){_.logAction(this.logger,_.LOG_MICRO,"RealtimeChannel.attachImpl()","sending ATTACH message");let e=ni({action:e1.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this.channelOptions.modes&&e.encodeModesToFlags(em(this.channelOptions.modes)),this._attachResume&&e.setFlag("ATTACH_RESUME"),this._lastPayload.decodeFailureRecoveryInProgress&&(e.channelSerial=this._lastPayload.protocolMessageChannelSerial),this.send(e)}async detach(){let e=this.connectionManager;switch(this.state){case"suspended":this.notifyState("detached");return;case"detached":return;case"failed":throw new L("Unable to detach; channel state = failed",90001,400);default:if("connected"!==e.state.state)return void this.notifyState("detached");this.requestState("detaching");case"detaching":return new Promise((t,n)=>{this.internalStateChanges.once(function(s){switch(this.event){case"detached":t();break;case"attached":case"suspended":case"failed":n(s.reason||e.getError()||new L("Unable to detach; reason unknown; state = "+this.event,9e4,500));break;case"attaching":n(new L("Detach request superseded by a subsequent attach request",9e4,409))}})})}}detachImpl(){_.logAction(this.logger,_.LOG_MICRO,"RealtimeChannel.detach()","sending DETACH message");let e=ni({action:e1.DETACH,channel:this.name});this.send(e)}async subscribe(...t){let[n,s]=e.processListenerArgs(t);if("failed"===this.state)throw L.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);if("object"==typeof s&&!i||(null==(n=this.filteredSubscriptions)?void 0:n.has(i)))return void 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 N("Unable to sync to channel; not attached",4e4)}let e=this.connectionManager;if(!e.activeState())throw e.getError();let t=ni({action:e1.SYNC,channel:this.name});this.syncChannelSerial&&(t.channelSerial=this.syncChannelSerial),e.send(t)}send(e){this.connectionManager.send(e)}async sendAndAwaitAck(e){return new Promise((t,n)=>{this.connectionManager.send(e,this.client.options.queueMessages,(e,s)=>{e?n(e):t(s)})})}async sendPresence(e){let t=ni({action:e1.PRESENCE,channel:this.name,presence:e});await this.sendAndAwaitAck(t)}async sendState(e){let t=ni({action:e1.OBJECT,channel:this.name,state:e});return this.sendAndAwaitAck(t)}async processMessage(e){(e.action===e1.ATTACHED||e.action===e1.MESSAGE||e.action===e1.PRESENCE||e.action===e1.OBJECT||e.action===e1.ANNOTATION)&&this.setChannelSerial(e.channelSerial);let t,n=!1;switch(e.action){case e1.ATTACHED:{this.properties.attachSerial=e.channelSerial,this._mode=e.getMode(),this.params=e.params||{};let t=e.decodeModesFromFlags();this.modes=t&&ef(t)||void 0;let n=e.hasFlag("RESUMED"),s=e.hasFlag("HAS_PRESENCE"),i=e.hasFlag("HAS_BACKLOG"),r=e.hasFlag("HAS_OBJECTS");if(this._attachedReceived.emit("attached"),"attached"===this.state){!n&&(this._presence&&this._presence.onAttached(s),this._object&&this._object.onAttached(r));let t=new na(this.state,this.state,n,i,e.error);(!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 e1.DETACHED:{let t=e.error?L.fromValues(e.error):new L("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 e1.SYNC:if(n=!0,t=this.syncChannelSerial=e.channelSerial,!e.presence)break;case e1.PRESENCE:{if(!e.presence)break;to(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 e1.OBJECT:case e1.OBJECT_SYNC:{if(!this._object||!e.state)return;to(e);let t=this.client.connection.connectionManager.getActiveTransportFormat(),n=e.state.map(e=>e.decode(this.client,t));e.action===e1.OBJECT?this._object.handleObjectMessages(n):this._object.handleObjectSyncMessages(n,e.channelSerial);break}case e1.MESSAGE:{if("attached"!==this.state)return void _.logAction(this.logger,_.LOG_MAJOR,"RealtimeChannel.processMessage()",'Message "'+e.id+'" skipped as this channel "'+this.name+'" state is not "attached" (state is "'+this.state+'").');to(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+'".';_.logAction(this.logger,_.LOG_ERROR,"RealtimeChannel.processMessage()",t),this._startDecodeFailureRecovery(new L(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 e1.ANNOTATION:{to(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 e1.ERROR:{let t=e.error;t&&80016==t.code?this.checkPendingState():this.notifyState("failed",L.fromValues(t));break}default:_.logAction(this.logger,_.LOG_MAJOR,"RealtimeChannel.processMessage()","Protocol error: unrecognised message action ("+e.action+")")}}_startDecodeFailureRecovery(e){this._lastPayload.decodeFailureRecoveryInProgress||(_.logAction(this.logger,_.LOG_MAJOR,"RealtimeChannel.processMessage()","Starting decode failure recovery process."),this._lastPayload.decodeFailureRecoveryInProgress=!0,this._attach(!0,e,()=>{this._lastPayload.decodeFailureRecoveryInProgress=!1}))}onAttached(){_.logAction(this.logger,_.LOG_MINOR,"RealtimeChannel.onAttached","activating channel; name = "+this.name)}notifyState(e,t,n,s,i,r){if(_.logAction(this.logger,_.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._object&&this._object.actOnChannelState(e,r),"suspended"===e&&this.connectionManager.state.sendEvents?this.startRetryTimer():this.cancelRetryTimer(),t&&(this.errorReason=t);let o=new na(this.state,e,n,i,t),a='Channel state for channel "'+this.name+'"',l=e+(t?"; reason: "+t:"");"failed"===e?_.logAction(this.logger,_.LOG_ERROR,a,l):_.logAction(this.logger,_.LOG_MAJOR,a,l),"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.emit(e,o)}requestState(e,t){_.logAction(this.logger,_.LOG_MINOR,"RealtimeChannel.requestState","name = "+this.name+", state = "+e),this.notifyState(e,t),this.checkPendingState()}checkPendingState(){if(!this.connectionManager.state.sendEvents)return void _.logAction(this.logger,_.LOG_MINOR,"RealtimeChannel.checkPendingState","sendEvents is false; state is "+this.connectionManager.state.state);switch(_.logAction(this.logger,_.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 L("Channel attach timed out",90007,408);this.notifyState("suspended",e);break}case"detaching":{let e=new L("Channel detach timed out",90007,408);this.notifyState("attached",e);break}default:this.checkPendingState()}}startStateTimerIfNotRunning(){this.stateTimer||(this.stateTimer=setTimeout(()=>{_.logAction(this.logger,_.LOG_MINOR,"RealtimeChannel.startStateTimerIfNotRunning","timer 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=eb(this.client.options.timeouts.channelRetryTimeout,this.retryCount);this.retryTimer=setTimeout(()=>{"suspended"===this.state&&this.connectionManager.state.sendEvents&&(this.retryTimer=null,_.logAction(this.logger,_.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 L("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){_.logAction(this.logger,_.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)}async getMessage(e){return _.logAction(this.logger,_.LOG_MICRO,"RealtimeChannel.getMessage()","channel = "+this.name),this.client.rest.channelMixin.getMessage(this,e)}async updateMessage(e,t,n){return _.logAction(this.logger,_.LOG_MICRO,"RealtimeChannel.updateMessage()","channel = "+this.name),this.sendUpdate(e,"message.update",t,n)}async deleteMessage(e,t,n){return _.logAction(this.logger,_.LOG_MICRO,"RealtimeChannel.deleteMessage()","channel = "+this.name),this.sendUpdate(e,"message.delete",t,n)}async appendMessage(e,t,n){return _.logAction(this.logger,_.LOG_MICRO,"RealtimeChannel.appendMessage()","channel = "+this.name),this.sendUpdate(e,"message.append",t,n)}async sendUpdate(e,t,n,s){var i;if(!e.serial)throw new L('This message lacks a serial and cannot be updated. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);this.throwIfUnpublishableState();let r=tj.fromValues(C(w({},e),{action:t,version:n})),o=await r.encode(this.channelOptions),a=ni({action:e1.MESSAGE,channel:this.name,messages:[o],params:s?es(s):void 0});return{versionSerial:null!=(i=(await this.sendAndAwaitAck(a)).serials[0])?i:null}}async getMessageVersions(e,t){return _.logAction(this.logger,_.LOG_MICRO,"RealtimeChannel.getMessageVersions()","channel = "+this.name),this.client.rest.channelMixin.getMessageVersions(this,e,t)}async ensureAttached(){switch(this.state){case"attached":case"suspended":break;case"initialized":case"detached":case"detaching":case"attaching":await this.attach();break;default:throw L.fromValues(this.invalidStateError())}}};function nc(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&&y)for(var o of y(s))0>i.indexOf(o)&&b.call(s,o)&&(r[o]=s[o]);return r}var nh=class{constructor(e){this.channel=e,this.logger=e.logger,this.subscriptions=new e0(this.logger)}async publish(e,t){let n=this.channel.name,s=t9(e,t),i=await s.encode();this.channel.throwIfUnpublishableState(),_.logAction(this.logger,_.LOG_MICRO,"RealtimeAnnotations.publish()","channelName = "+n+", sending annotation with messageSerial = "+s.messageSerial+", type = "+s.type);let r=ni({action:e1.ANNOTATION,channel:n,annotations:[i]});await this.channel.sendAndAwaitAck(r)}async delete(e,t){t.action="annotation.delete",await this.publish(e,t)}async subscribe(...e){let t=nl.processListenerArgs(e),n=t[0],s=t[1],i=this.channel;if("failed"===i.state)throw L.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&e2.ANNOTATION_SUBSCRIBE))throw new L("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=nl.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 ne.prototype.get.call(this,e,t)}},nu=class e extends tK{constructor(t){var n,s;if(!e._MsgPack)throw Error("Expected DefaultRest._MsgPack to have been set");super(e_.objectifyOptions(t,!0,"Rest",_.defaultLogger,C(w({},t$),{Crypto:null!=(n=e.Crypto)?n:void 0,MsgPack:null!=(s=e._MsgPack)?s:void 0,Annotations:{Annotation:t3,WireAnnotation:t8,RealtimeAnnotations:nh,RestAnnotations:ne}})))}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}};nu._Crypto=null,nu.Message=tQ,nu.PresenceMessage=tX,nu.Annotation=t6,nu._MsgPack=null,nu._Http=eY;var nd=nu,ng=class extends e0{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){_.logAction(this.logger,_.LOG_MICRO,"MessageQueue.completeMessages()","all"==e?"(all)":"serial = "+e.serial+"; count = "+e.count),t=t||null;let s=this.messages;if(0===s.length)throw Error("MessageQueue.completeMessages(): completeMessages called on any empty MessageQueue");let i=[];if("all"===e)i=s.splice(0);else{let t=s[0];if(t){let n=t.message.msgSerial,r=e.serial+e.count;r>n&&(i=s.splice(0,r-n))}}for(let e=0;e<i.length;e++){let s=i[e],r=null==n?void 0:n[e];s.callback(t,r)}0==s.length&&this.emit("idle")}completeAllMessages(e){this.completeMessages("all",e)}resetSendAttempted(){for(let e of this.messages)e.sendAttempted=!1}clear(){_.logAction(this.logger,_.LOG_MICRO,"MessageQueue.clear()","clearing "+this.messages.length+" messages"),this.messages=[],this.emit("idle")}},np=class{constructor(e,t){this.message=e,this.callback=t,this.merged=!1;let n=e.action;this.sendAttempted=!1,this.ackRequired="number"==typeof n&&[e1.MESSAGE,e1.PRESENCE,e1.ANNOTATION,e1.OBJECT].includes(n)}},nf=class extends e0{constructor(e){super(e.logger),this.transport=e,this.messageQueue=new ng(this.logger),e.on("ack",(e,t,n)=>{this.onAck(e,t,n)}),e.on("nack",(e,t,n)=>{this.onNack(e,t,n)})}onAck(e,t,n){_.logAction(this.logger,_.LOG_MICRO,"Protocol.onAck()","serial = "+e+"; count = "+t),this.messageQueue.completeMessages({serial:e,count:t},null,n)}onNack(e,t,n){_.logAction(this.logger,_.LOG_ERROR,"Protocol.onNack()","serial = "+e+"; count = "+t+"; err = "+eo(n)),n||(n=new L("Unable to send message; channel not responding",50001,500)),this.messageQueue.completeMessages({serial:e,count:t},n)}onceIdle(e){let t=this.messageQueue;if(0===t.count())return void e();t.once("idle",e)}send(e){e.ackRequired&&this.messageQueue.push(e),this.logger.shouldLog(_.LOG_MICRO)&&_.logActionNoStrip(this.logger,_.LOG_MICRO,"Protocol.send()","sending msg; "+nr(e.message,this.transport.connectionManager.realtime._RealtimePresence,this.transport.connectionManager.realtime._Annotations,this.transport.connectionManager.realtime._liveObjectsPlugin)),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()})}},nm=class{constructor(e,t,n,s){this.previous=e,this.current=t,n&&(this.retryIn=n),s&&(this.reason=s)}},ny={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001},nv={disconnected:()=>L.fromValues({statusCode:400,code:ny.DISCONNECTED,message:"Connection to server temporarily unavailable"}),suspended:()=>L.fromValues({statusCode:400,code:ny.SUSPENDED,message:"Connection to server unavailable"}),failed:()=>L.fromValues({statusCode:400,code:ny.FAILED,message:"Connection failed or disconnected by server"}),closing:()=>L.fromValues({statusCode:400,code:ny.CLOSING,message:"Connection closing"}),closed:()=>L.fromValues({statusCode:400,code:ny.CLOSED,message:"Connection closed"}),unknownConnectionErr:()=>L.fromValues({statusCode:500,code:ny.UNKNOWN_CONNECTION_ERR,message:"Internal connection error"}),unknownChannelErr:()=>L.fromValues({statusCode:500,code:ny.UNKNOWN_CONNECTION_ERR,message:"Internal channel error"})},nb=ni({action:e1.CLOSE}),nO=ni({action:e1.DISCONNECT}),nw=class extends e0{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",nv.closed())}disconnect(e){this.isConnected&&this.requestDisconnect(),this.finish("disconnected",e||nv.disconnected())}fail(e){this.isConnected&&this.requestDisconnect(),this.finish("failed",e||nv.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(_.LOG_MICRO)&&_.logActionNoStrip(this.logger,_.LOG_MICRO,"Transport.onProtocolMessage()","received on "+this.shortName+": "+nr(e,this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin)+"; connectionId = "+this.connectionManager.connectionId),this.onActivity(),e.action){case e1.HEARTBEAT:_.logActionNoStrip(this.logger,_.LOG_MICRO,"Transport.onProtocolMessage()",this.shortName+" heartbeat; connectionId = "+this.connectionManager.connectionId),this.emit("heartbeat",e.id);break;case e1.CONNECTED:this.onConnect(e),this.emit("connected",e.error,e.connectionId,e.connectionDetails,e);break;case e1.CLOSED:this.onClose(e);break;case e1.DISCONNECTED:this.onDisconnect(e);break;case e1.ACK:this.emit("ack",e.msgSerial,e.count,e.res);break;case e1.NACK:this.emit("nack",e.msgSerial,e.count,e.error);break;case e1.SYNC:this.connectionManager.onChannelMessage(e,this);break;case e1.ACTIVATE:break;case e1.AUTH:ed(this.auth.authorize(),e=>{e&&_.logAction(this.logger,_.LOG_ERROR,"Transport.onProtocolMessage()","Ably requested re-authentication, but unable to obtain a new token: "+eo(e))});break;case e1.ERROR:if(_.logAction(this.logger,_.LOG_MINOR,"Transport.onProtocolMessage()","received error action; connectionId = "+this.connectionManager.connectionId+"; err = "+k.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;_.logAction(this.logger,_.LOG_MINOR,"Transport.onDisconnect()","err = "+eo(t)),this.finish("disconnected",t)}onFatalError(e){let t=e&&e.error;_.logAction(this.logger,_.LOG_MINOR,"Transport.onFatalError()","err = "+eo(t)),this.finish("failed",t)}onClose(e){let t=e&&e.error;_.logAction(this.logger,_.LOG_MINOR,"Transport.onClose()","err = "+eo(t)),this.finish("closed",t)}requestClose(){_.logAction(this.logger,_.LOG_MINOR,"Transport.requestClose()",""),this.send(nb)}requestDisconnect(){_.logAction(this.logger,_.LOG_MINOR,"Transport.requestDisconnect()",""),this.send(nO)}ping(e){let t={action:e1.HEARTBEAT};e&&(t.id=e),this.send(ni(t))}dispose(){_.logAction(this.logger,_.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";_.logAction(this.logger,_.LOG_ERROR,"Transport.onIdleTimerExpire()",t),this.disconnect(new L(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 L("Timeout waiting for transport to indicate itself viable",5e4,500))},t.options.timeouts.realtimeRequestTimeout),o.on(["failed","disconnected"],a),o.on("preconnect",function(){_.logAction(t.logger,_.LOG_MINOR,"Transport.tryConnect()","viable transport "+o),clearTimeout(r),o.off(["failed","disconnected"],a),i(null,o)}),o.connect(),o}static isAvailable(){throw new L("isAvailable not implemented for transport",5e4,500)}};(i=o||(o={})).WebSocket="web_socket",i.Comet="comet",i.XhrPolling="xhr_polling";var nC=void 0!==n.g?n.g:"undefined"!=typeof window?window:self,nR=()=>{var e;return void 0!==k.WebStorage&&(null==(e=k.WebStorage)?void 0:e.localSupported)},nA=()=>{var e;return void 0!==k.WebStorage&&(null==(e=k.WebStorage)?void 0:e.sessionSupported)},nS=function(){},nk="ably-transport-preference";function nM(e){try{return JSON.parse(e)}catch(e){return null}}var nT=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?x(e):{},n=this.options;switch(this.mode){case"resume":t.resume=this.connectionKey;break;case"recover":{let e=nM(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=e_.protocolVersion,t.agent=eG(this.options),void 0!==n.transportParams&&U(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+="]"}},nI=class e extends e0{constructor(e,t){super(e.logger),this.supportedTransports={},this.disconnectedRetryCount=0,this.pendingChannelMessagesState={isProcessing:!1,queue:[]},this.realtime=e,this.initTransports(),this.options=t;let 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 ng(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=F(t.transports||e_.defaultTransports,this.supportedTransports),this.transportPreference=null,this.transports.includes(o.WebSocket)&&(this.webSocketTransportAvailable=!0),this.transports.includes(o.XhrPolling)?this.baseTransport=o.XhrPolling:this.transports.includes(o.Comet)&&(this.baseTransport=o.Comet),this.domains=e_.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,_.logAction(this.logger,_.LOG_MINOR,"Realtime.ConnectionManager()","started"),_.logAction(this.logger,_.LOG_MICRO,"Realtime.ConnectionManager()","requested transports = ["+(t.transports||e_.defaultTransports)+"]"),_.logAction(this.logger,_.LOG_MICRO,"Realtime.ConnectionManager()","available transports = ["+this.transports+"]"),_.logAction(this.logger,_.LOG_MICRO,"Realtime.ConnectionManager()","http domains = ["+this.domains+"]"),!this.transports.length){let e="no requested transports available";throw _.logAction(this.logger,_.LOG_ERROR,"realtime.ConnectionManager()",e),Error(e)}let i=k.Config.addEventListener;i&&(nA()&&"function"==typeof t.recover&&i("beforeunload",this.persistConnection.bind(this)),!0===t.closeOnUnload&&i("beforeunload",()=>{_.logAction(this.logger,_.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?(_.logAction(this.logger,_.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&&(_.logAction(this.logger,_.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({},k.Transports.bundledImplementations),e);[o.WebSocket,...k.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 nT(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){_.logAction(this.logger,_.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){_.logAction(this.logger,_.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport recovery mode = recover; recoveryKey = "+this.options.recover);let e=nM(this.options.recover);e&&(this.msgSerial=e.msgSerial)}else _.logAction(this.logger,_.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport params = "+n.toString());e(n)})}tryATransport(e,t,n){_.logAction(this.logger,_.LOG_MICRO,"ConnectionManager.tryATransport()","trying "+t),this.proposedTransport=nw.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&&(_.logAction(this.logger,_.LOG_MINOR,"ConnectionManager.tryATransport()","connection "+r.state+" while we were attempting the transport; closing "+i),i.close()),n(!0);return}if(s){if(_.logAction(this.logger,_.LOG_MINOR,"ConnectionManager.tryATransport()","transport "+t+" "+s.event+", err: "+s.error.toString()),e$.isTokenErr(s.error)&&!(this.errorReason&&e$.isTokenErr(this.errorReason)))this.errorReason=s.error,ed(this.realtime.auth._forceNewToken(null,null),s=>{if(s)return void 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(ny).includes(o.code)?n(!1):(this.notifyState({state:this.states.connecting.failState,error:s.error}),n(!0))}return}_.logAction(this.logger,_.LOG_MICRO,"ConnectionManager.tryATransport()","viable transport "+t+"; setting pending"),this.setTransportPending(i,e),n(null,i)})}setTransportPending(e,t){let n=t.mode;_.logAction(this.logger,_.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){_.logAction(this.logger,_.LOG_MINOR,"ConnectionManager.activateTransport()","transport = "+t),e&&_.logAction(this.logger,_.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+e),n&&_.logAction(this.logger,_.LOG_MICRO,"ConnectionManager.activateTransport()","connectionId = "+n),s&&_.logAction(this.logger,_.LOG_MICRO,"ConnectionManager.activateTransport()","connectionDetails = "+JSON.stringify(s)),this.persistTransportPreference(t);let i=this.state,r=this.states.connected.state;if(_.logAction(this.logger,_.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 _.logAction(this.logger,_.LOG_MINOR,"ConnectionManager.activateTransport()","Disconnecting transport and abandoning"),t.disconnect(),!1;if(delete this.pendingTransport,!t.isConnected)return _.logAction(this.logger,_.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 nf(t),this.host=t.params.host;let a=s.connectionKey;if(a&&this.connectionKey!=a&&this.setConnection(n,s,!!e),this.onConnectionDetailsUpdate(s,t),k.Config.nextTick(()=>{t.on("connected",(e,n,s)=>{this.onConnectionDetailsUpdate(s,t),this.emit("update",new nm(r,r,null,e))})}),i.state===this.states.connected.state?e&&(this.errorReason=this.realtime.connection.errorReason=e,this.emit("update",new nm(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&&_.logAction(this.logger,_.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;_.logAction(this.logger,_.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(_.logAction(this.logger,_.LOG_MINOR,"ConnectionManager.deactivateTransport()","transport = "+e),_.logAction(this.logger,_.LOG_MINOR,"ConnectionManager.deactivateTransport()","state = "+t+(i?"; was active":r?"; was pending":"")+(o?"":"; another transport is scheduled for activation")),n&&n.message&&_.logAction(this.logger,_.LOG_MICRO,"ConnectionManager.deactivateTransport()","reason = "+n.message),i&&(_.logAction(this.logger,_.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&&e$.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)&&(_.logAction(this.logger,_.LOG_MINOR,"ConnectionManager.setConnection()","Resetting msgSerial"),this.msgSerial=0,this.queuedMessages.resetSendAttempted()),this.connectionId!==e&&_.logAction(this.logger,_.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.queuedMessages.resetSendAttempted(),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&&(_.logAction(this.logger,_.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(nA()){let e=this.createRecoveryKey();e&&this.setSessionRecoverData({recoveryKey:e,disconnectedAt:Date.now(),location:nC.location,clientId:this.realtime.auth.clientId})}}unpersistConnection(){this.clearSessionRecoverData()}getActiveTransportFormat(){var e;return null==(e=this.activeProtocol)?void 0:e.getTransport().format}getError(){if(this.errorReason){let e=N.fromValues(this.errorReason);return e.cause=this.errorReason,e}return this.getStateError()}getStateError(){var e;return null==(e=nv[this.state.state])?void 0:e.call(nv)}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?_.logAction(this.logger,_.LOG_ERROR,t,n):_.logAction(this.logger,_.LOG_MAJOR,t,n),_.logAction(this.logger,_.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){_.logAction(this.logger,_.LOG_MINOR,"ConnectionManager.startTransitionTimer()","transitionState: "+e.state),this.transitionTimer&&(_.logAction(this.logger,_.LOG_MINOR,"ConnectionManager.startTransitionTimer()","clearing already-running timer"),clearTimeout(this.transitionTimer)),this.transitionTimer=setTimeout(()=>{this.transitionTimer&&(this.transitionTimer=null,_.logAction(this.logger,_.LOG_MINOR,"ConnectionManager "+e.state+" timer expired","requesting new state: "+e.failState),this.notifyState({state:e.failState}))},e.retryDelay)}cancelTransitionTimer(){_.logAction(this.logger,_.LOG_MINOR,"ConnectionManager.cancelTransitionTimer()",""),this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)}startSuspendTimer(){this.suspendTimer||(this.suspendTimer=setTimeout(()=>{this.suspendTimer&&(this.suspendTimer=null,_.logAction(this.logger,_.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(()=>{_.logAction(this.logger,_.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(()=>{_.logAction(this.logger,_.LOG_MINOR,"ConnectionManager WebSocket slow timer","checking connectivity"),this.checkWsConnectivity().then(()=>{_.logAction(this.logger,_.LOG_MINOR,"ConnectionManager WebSocket slow timer","ws connectivity check succeeded"),this.wsCheckResult=!0}).catch(()=>{_.logAction(this.logger,_.LOG_MAJOR,"ConnectionManager WebSocket slow timer","ws connectivity check failed"),this.wsCheckResult=!1}),this.realtime.http.checkConnectivity&&ed(this.realtime.http.checkConnectivity(),(e,t)=>{e||!t?(_.logAction(this.logger,_.LOG_MAJOR,"ConnectionManager WebSocket slow timer","http connectivity check failed"),this.cancelWebSocketGiveUpTimer(),this.notifyState({state:"disconnected",error:new L("Unable to connect (network unreachable)",80003,404)})):_.logAction(this.logger,_.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||(_.logAction(this.logger,_.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)):_.logAction(this.logger,_.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&&e$.isTokenErr(e.error)&&!(this.errorReason&&e$.isTokenErr(this.errorReason)));if(_.logAction(this.logger,_.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=eb(i.retryDelay,this.disconnectedRetryCount));let o=new nm(this.state.state,i.state,r,e.error||(null==(t=nv[i.state])?void 0:t.call(nv)));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?(_.logAction(this.logger,_.LOG_MICRO,"ConnectionManager.notifyState()","Last reconnect attempt was only "+t+"ms ago, waiting another "+(1e3-t)+"ms before trying again"),setTimeout(e,1e3-t)):k.Config.nextTick(e)}else("disconnected"===n||"suspended"===n)&&this.startRetryTimer(r);("disconnected"===n&&!s||"suspended"===n||i.terminal)&&k.Config.nextTick(()=>{this.disconnectAllTransports()}),"connected"!=n||this.activeProtocol||_.logAction(this.logger,_.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(_.logAction(this.logger,_.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 nm(this.state.state,s.state,null,e.error||(null==(t=nv[s.state])?void 0:t.call(nv)));this.enactStateChange(i),"connecting"==n&&k.Config.nextTick(()=>{this.startConnect()}),"closing"==n&&this.closeImpl()}startConnect(){if(this.state!==this.states.connecting)return void _.logAction(this.logger,_.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=nM(e.options.recover);t&&this.realtime.channels.recoverChannels(t.channelSerials)}t===this.connectCounter&&this.connectImpl(e,t)})};if(_.logAction(this.logger,_.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&&e$.isTokenErr(this.errorReason)?ed(e._forceNewToken(null,null),s):ed(e._ensureValidAuthCredentials(!1),s)}}connectImpl(e,t){let n=this.state.state;if(n!==this.states.connecting.state)return void _.logAction(this.logger,_.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&&(_.logAction(this.logger,_.LOG_MINOR,"ConnectionManager.connectImpl():","web socket connectivity available, cancelling connection attempt with "+this.baseTransport),this.disconnectAllTransports(),this.connectWs(e,++this.connectCounter))}).catch(nS),s&&s===this.baseTransport||this.baseTransport&&!this.webSocketTransportAvailable?this.connectBase(e,t):this.connectWs(e,t)}connectWs(e,t){_.logAction(this.logger,_.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){_.logAction(this.logger,_.LOG_MICRO,"ConnectionManager.connectBase()"),this.baseTransport?this.tryTransportWithFallbacks(this.baseTransport,e,!1,t,()=>!0):this.notifyState({state:"disconnected",error:new L("No transports left to try",8e4,404)})}tryTransportWithFallbacks(e,t,n,s,i){_.logAction(this.logger,_.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||c()}},l=o.shift();if(!l)return void r(new L("Unable to connect (no available host)",80003,404));t.host=l;let c=()=>o.length?this.realtime.http.checkConnectivity?void ed(this.realtime.http.checkConnectivity(),(n,l)=>{if(s===this.connectCounter&&i()){if(n)return void r(n);if(!l)return void r(new L("Unable to connect (network unreachable)",80003,404));t.host=et(o),this.tryATransport(t,e,a)}}):void r(new N("Internal error: Http.checkConnectivity not set",null,500)):void r(new L("Unable to connect (and no more fallback hosts to try)",80003,404));if(this.forceFallbackHost&&o.length){this.forceFallbackHost=!1,c();return}this.tryATransport(t,e,a)}closeImpl(){_.logAction(this.logger,_.LOG_MINOR,"ConnectionManager.closeImpl()","closing connection"),this.cancelSuspendTimer(),this.startTransitionTimer(this.states.closing),this.pendingTransport&&(_.logAction(this.logger,_.LOG_MICRO,"ConnectionManager.closeImpl()","Closing pending transport: "+this.pendingTransport),this.pendingTransport.close()),this.activeProtocol&&(_.logAction(this.logger,_.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":{_.logAction(this.logger,_.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=ni({action:e1.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.getStateError()))};this.once("connectiondetails",r),this.on("connectionstate",o);break}case"connecting":_.logAction(this.logger,_.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Aborting current connection attempts in order to start again with the new auth details"),this.disconnectAllTransports();default:{_.logAction(this.logger,_.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(){_.logAction(this.logger,_.LOG_MINOR,"ConnectionManager.disconnectAllTransports()","Disconnecting all transports"),this.connectCounter++,this.pendingTransport&&(_.logAction(this.logger,_.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting pending transport: "+this.pendingTransport),this.pendingTransport.disconnect()),delete this.pendingTransport,this.proposedTransport&&(_.logAction(this.logger,_.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting proposed transport: "+this.pendingTransport),this.proposedTransport.disconnect()),delete this.pendingTransport,this.activeProtocol&&(_.logAction(this.logger,_.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().disconnect())}send(e,t,n){n=n||nS;let s=this.state;if(s.sendEvents){_.logAction(this.logger,_.LOG_MICRO,"ConnectionManager.send()","sending event"),this.sendImpl(new np(e,n));return}if(!(t&&s.queueEvents)){let e="rejecting event, queueEvent was "+t+", state was "+s.state;_.logAction(this.logger,_.LOG_MICRO,"ConnectionManager.send()",e),n(this.errorReason||new L(e,9e4,400));return}this.logger.shouldLog(_.LOG_MICRO)&&_.logAction(this.logger,_.LOG_MICRO,"ConnectionManager.send()","queueing msg; "+nr(e,this.realtime._RealtimePresence,this.realtime._Annotations,this.realtime._liveObjectsPlugin)),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){_.logAction(this.logger,_.LOG_ERROR,"ConnectionManager.sendImpl()","Unexpected exception in transport.send(): "+e.stack)}}queue(e,t){_.logAction(this.logger,_.LOG_MICRO,"ConnectionManager.queue()","queueing event"),this.queuedMessages.push(new np(e,t))}sendQueuedMessages(){let e;for(_.logAction(this.logger,_.LOG_MICRO,"ConnectionManager.sendQueuedMessages()","sending "+this.queuedMessages.count()+" queued messages");e=this.queuedMessages.shift();)this.sendImpl(e)}queuePendingMessages(e){e&&e.length&&(_.logAction(this.logger,_.LOG_MICRO,"ConnectionManager.queuePendingMessages()","queueing "+e.length+" pending messages"),this.queuedMessages.prepend(e))}failQueuedMessages(e){let t=this.queuedMessages.count();t>0&&(_.logAction(this.logger,_.LOG_ERROR,"ConnectionManager.failQueuedMessages()","failing "+t+" queued messages, err = "+eo(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=>{_.logAction(this.logger,_.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 L("Unable to ping service; not connected",4e4,400);let t=null==(e=this.activeProtocol)?void 0:e.getTransport();if(!t)throw this.getStateError();_.logAction(this.logger,_.LOG_MINOR,"ConnectionManager.ping()","transport = "+t);let n=Date.now(),s=ec();return eM(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||nR()&&(null==(t=null==(e=k.WebStorage)?void 0:e.get)?void 0:t.call(e,nk))}persistTransportPreference(e){var t,n;this.transportPreference=e.shortName,nR()&&(null==(n=null==(t=k.WebStorage)?void 0:t.set)||n.call(t,nk,e.shortName))}unpersistTransportPreference(){var e,t;this.transportPreference=null,nR()&&(null==(t=null==(e=k.WebStorage)?void 0:e.remove)||t.call(e,nk))}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===eV.Forbidden){let t="Client configured authentication provider returned 403; failing the connection";_.logAction(this.logger,_.LOG_ERROR,"ConnectionManager.actOnErrorFromAuthorize()",t),this.notifyState({state:"failed",error:new L(t,80019,403,e)})}else{let t="Client configured authentication provider request failed";_.logAction(this.logger,_.LOG_MINOR,"ConnectionManager.actOnErrorFromAuthorize",t),this.notifyState({state:this.state.failState,error:new L(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){_.logAction(this.logger,_.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||e_.wsConnectivityCheckUrl,t=new k.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 nA()&&(null==(t=null==(e=k.WebStorage)?void 0:e.getSession)?void 0:t.call(e,this.sessionRecoveryName()))}setSessionRecoverData(e){var t,n;return nA()&&(null==(n=null==(t=k.WebStorage)?void 0:t.setSession)?void 0:n.call(t,this.sessionRecoveryName(),e))}clearSessionRecoverData(){var e,t;return nA()&&(null==(t=null==(e=k.WebStorage)?void 0:e.removeSession)?void 0:t.call(e,this.sessionRecoveryName()))}},n_=class extends e0{constructor(e,t){super(e.logger),this.whenState=e=>e0.prototype.whenState.call(this,e,this.state),this.ably=e,this.connectionManager=new nI(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;k.Config.nextTick(()=>{this.emit(t,e)})}),this.connectionManager.on("update",e=>{k.Config.nextTick(()=>{this.emit("update",e)})})}connect(){_.logAction(this.logger,_.LOG_MINOR,"Connection.connect()",""),this.connectionManager.requestState({state:"connecting"})}async ping(){return _.logAction(this.logger,_.LOG_MINOR,"Connection.ping()",""),this.connectionManager.ping()}close(){_.logAction(this.logger,_.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()}},nP=class e extends th{constructor(t){var n,s,i,r;if(super(e_.objectifyOptions(t,!1,"BaseRealtime",_.defaultLogger)),_.logAction(this.logger,_.LOG_MINOR,"Realtime()",""),"string"==typeof EdgeRuntime)throw new L('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._liveObjectsPlugin=null!=(r=null==(i=this.options.plugins)?void 0:i.LiveObjects)?r:null,this.connection=new n_(this,this.options),this._channels=new nE(this),!1!==this.options.autoConnect&&this.connect()}static transportImplementationsFromPlugins(e){let t={};return(null==e?void 0:e.WebSocketTransport)&&(t[o.WebSocket]=e.WebSocketTransport),(null==e?void 0:e.XHRPolling)&&(t[o.XhrPolling]=e.XHRPolling),t}get channels(){return this._channels}get clientId(){return this.auth.clientId}connect(){_.logAction(this.logger,_.LOG_MINOR,"Realtime.connect()",""),this.connection.connect()}close(){_.logAction(this.logger,_.LOG_MINOR,"Realtime.close()",""),this.connection.close()}};nP.EventEmitter=e0;var nE=class extends e0{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 Q(this.all,!0)){let n=this.all[t];n.properties.channelSerial&&(e[t]=n.properties.channelSerial)}return e}recoverChannels(e){for(let t of Q(e,!0))this.get(t).properties.channelSerial=e[t]}async processChannelMessage(e){let t=e.channel;if(void 0===t)return void _.logAction(this.logger,_.LOG_ERROR,"Channels.processChannelMessage()","received event unspecified channel, action = "+e.action);let n=this.all[t];if(!n)return void _.logAction(this.logger,_.LOG_ERROR,"Channels.processChannelMessage()","received event for non-existent channel: "+t);await n.processMessage(e)}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 L("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 nl(this.realtime,e,t);return n}getDerived(e,t,n){if(t.filter){let n=eR(t.filter),s=eC(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]}},nL=nP;function nN(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 nU=class extends e0{constructor(e,t,n=nN){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=tI.fromValues(e)).action="present");let t=this.map,n=this.memberKey(e);this.residualMembers&&delete this.residualMembers[n];let s=t[n];return(!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=tI.fromValues(e)).action="absent",t[n]=e):delete t[n],!!s)}startSync(){let e=this.map,t=this.syncInProgress;_.logAction(this.logger,_.LOG_MINOR,"PresenceMap.startSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+t),this.syncInProgress||(this.residualMembers=x(e),this.setInProgress(!0))}endSync(){let e=this.map,t=this.syncInProgress;if(_.logAction(this.logger,_.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(X(this.residualMembers)),this.residualMembers)delete e[t];this.residualMembers=null,this.setInProgress(!1)}this.emit("sync")}async waitSync(){let e=this.syncInProgress;_.logAction(this.logger,_.LOG_MINOR,"PresenceMap.waitSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+e),e&&await this.once("sync")}clear(){this.map={},this.setInProgress(!1),this.residualMembers=null}setInProgress(e){_.logAction(this.logger,_.LOG_MICRO,"PresenceMap.setInProgress()","inProgress = "+e),this.syncInProgress=e,this.presence.syncComplete=!e}};function nx(e){let t=e.channel.client,n=t.auth.clientId;return(!n||"*"===n)&&"connected"===t.connection.state}var nG=class extends e0{constructor(e){super(e.logger),this.channel=e,this.syncComplete=!1,this.members=new nU(this,e=>e.clientId+":"+e.connectionId),this._myMembers=new nU(this,e=>e.clientId),this.subscriptions=new e0(this.logger),this.pendingPresence=[]}async enter(e){if(nx(this))throw new L("clientId must be specified to enter a presence channel",40012,400);return this._enterOrUpdateClient(void 0,void 0,e,"enter")}async update(e){if(nx(this))throw new L("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();_.logAction(this.logger,_.LOG_MICRO,"RealtimePresence."+s+"Client()","channel = "+i.name+", id = "+e+", client = "+(t||"(implicit) "+this.channel.client.auth.clientId));let r=tI.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 N("Unable to "+s+" presence channel while in "+i.state+" state",90001);throw e.code=90001,e}}}async leave(e){if(nx(this))throw new L("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();_.logAction(this.logger,_.LOG_MICRO,"RealtimePresence.leaveClient()","leaving; channel = "+this.channel.name+", client = "+e);let s=tI.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 N("Unable to leave presence channel (incompatible state)",90001);default:throw n.invalidStateError()}}async get(e){let t=!e||!("waitForSync"in e)||e.waitForSync;function n(t){return e?t.list(e):t.values()}if("suspended"===this.channel.state){if(t)throw L.fromValues({statusCode:400,code:91005,message:"Presence state is out of sync due to channel being in the SUSPENDED state"});return n(this.members)}await this.channel.ensureAttached();let s=this.members;return t&&await s.waitSync(),n(this.members)}async history(e){_.logAction(this.logger,_.LOG_MICRO,"RealtimePresence.history()","channel = "+this.name);let t=this.channel.client.rest.presenceMixin;if(e&&e.untilAttach)if("attached"===this.channel.state)delete e.untilAttach,e.from_serial=this.channel.properties.attachSerial;else throw new L("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;_.logAction(this.logger,_.LOG_MICRO,"RealtimePresence.setPresence()","received presence for "+e.length+" participants; syncChannelSerial = "+n);let r=this.members,o=this._myMembers,a=[],l=this.channel.connectionManager.connectionId;for(let c of(t&&(this.members.startSync(),n&&(i=n.match(/^[\w-]+:(.*)$/))&&(s=i[1])),e))switch(c.action){case"leave":r.remove(c)&&a.push(c),c.connectionId!==l||c.isSynthesized()||o.remove(c);break;case"enter":case"present":case"update":r.put(c)&&a.push(c),c.connectionId===l&&o.put(c)}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){_.logAction(this.logger,_.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=ej.create(this.logger);_.logAction(this.logger,_.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){_.logAction(this.logger,_.LOG_MINOR,"RealtimeChannel.failPendingPresence","channel; name = "+this.channel.name+", err = "+eo(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];_.logAction(this.logger,_.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 L("Presence auto re-enter failed",91004,400,e);_.logAction(this.logger,_.LOG_ERROR,"RealtimePresence._ensureMyMembersPresent()","Presence auto re-enter failed; reason = "+eo(e));let n=new na(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=tI.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=nl.processListenerArgs(e),n=t[0],s=t[1],i=this.channel;if("failed"===i.state)throw L.fromValues(i.invalidStateError());this.subscriptions.on(n,s),!1!==i.channelOptions.attachOnSubscribe&&await i.attach()}unsubscribe(...e){let t=nl.processListenerArgs(e),n=t[0],s=t[1];this.subscriptions.off(n,s)}},nB=o.WebSocket,nq=class extends nw{constructor(e,t,n){super(e,t,n),this.shortName=nB,n.heartbeats=k.Config.useProtocolHeartbeats,this.wsHost=n.host}static isAvailable(){return!!k.Config.WebSocket}createWebSocket(e,t){return this.uri=e+en(t),new k.Config.WebSocket(this.uri)}toString(){return"WebSocketTransport; uri="+this.uri}connect(){_.logAction(this.logger,_.LOG_MINOR,"WebSocketTransport.connect()","starting"),nw.prototype.connect.call(this);let e=this,t=this.params,n=t.options,s=(n.tls?"wss://":"ws://")+this.wsHost+":"+e_.getPort(n)+"/";_.logAction(this.logger,_.LOG_MINOR,"WebSocketTransport.connect()","uri: "+s),ed(this.auth.getAuthParams(),function(n,i){if(e.isDisposed)return;let r="";for(let e in i)r+=" "+e+": "+i[e]+";";if(_.logAction(e.logger,_.LOG_MINOR,"WebSocketTransport.connect()","authParams:"+r+" err: "+n),n)return void e.disconnect(n);let o=t.getConnectParams(i);try{let t=e.wsConnection=e.createWebSocket(s,o);t.binaryType=k.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){_.logAction(e.logger,_.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 _.logAction(this.logger,_.LOG_ERROR,"WebSocketTransport.send()","No socket connection");try{t.send(ep(e,this.connectionManager.realtime._MsgPack,this.params.format))}catch(t){let e="Exception from ws connection when trying to send: "+eo(t);_.logAction(this.logger,_.LOG_ERROR,"WebSocketTransport.send()",e),this.finish("disconnected",new L(e,5e4,500))}}onWsData(e){_.logAction(this.logger,_.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._liveObjectsPlugin,r=this.format,nn(eg(e,t,r),n,s,i)))}catch(e){_.logAction(this.logger,_.LOG_ERROR,"WebSocketTransport.onWsData()","Unexpected exception handing channel message: "+e.stack)}}onWsOpen(){_.logAction(this.logger,_.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){_.logAction(this.logger,_.LOG_MINOR,"WebSocketTransport.onWsClose()","Cleanly closed WebSocket");let e=new L("Websocket closed",80003,400);this.finish("disconnected",e)}else{let e="Unclean disconnection of WebSocket ; code = "+n,t=new L(e,80003,400);_.logAction(this.logger,_.LOG_MINOR,"WebSocketTransport.onWsClose()",e),this.finish("disconnected",t)}this.emit("disposed")}onWsError(e){_.logAction(this.logger,_.LOG_MINOR,"WebSocketTransport.onError()","Error from WebSocket: "+e.message),k.Config.nextTick(()=>{this.disconnect(Error(e.message))})}dispose(){_.logAction(this.logger,_.LOG_MINOR,"WebSocketTransport.dispose()",""),this.isDisposed=!0;let e=this.wsConnection;e&&(e.onmessage=function(){},delete this.wsConnection,k.Config.nextTick(()=>{if(_.logAction(this.logger,_.LOG_MICRO,"WebSocketTransport.dispose()","closing websocket"),!e)throw Error("WebSocketTransport.dispose(): wsConnection is not defined");e.close()}))}},nD=class{static subscribeFilter(e,t,n){let s=e=>{var s,i,r,o,a,l;let c={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==(l=null==(a=e.extras)?void 0:a.ref)?void 0:l.timeserial),clientId:e.clientId};Object.entries(t).find(([e,t])=>void 0!==t&&c[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||[]}},nj=class e extends nL{constructor(t){var n;let s=e._MsgPack;if(!s)throw Error("Expected DefaultRealtime._MsgPack to have been set");super(e_.objectifyOptions(t,!0,"Realtime",_.defaultLogger,C(w({},t$),{Crypto:null!=(n=e.Crypto)?n:void 0,MsgPack:s,RealtimePresence:{RealtimePresence:nG,PresenceMessage:tI,WirePresenceMessage:tT},Annotations:{Annotation:t3,WireAnnotation:t8,RealtimeAnnotations:nh,RestAnnotations:ne},WebSocketTransport:nq,MessageInteractions:nD})))}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}};nj.Utils=P,nj.ConnectionManager=nI,nj.ProtocolMessage=no,nj._Crypto=null,nj.Message=tQ,nj.PresenceMessage=tX,nj.Annotation=t6,nj._MsgPack=null,nj._Http=eY,nj._PresenceMap=nU,nj._MessageEncoding=tr;var nH=nj,nV=Uint8Array,nW=Uint32Array,nF=Math.pow,nJ=new nW(8),nz=[],nK=new nW(64);function n$(e){return(e-(0|e))*nF(2,32)|0}for(var nQ=2,nX=0;nX<64;){for(l=2,a=!0;l<=nQ/2;l++)nQ%l==0&&(a=!1);a&&(nX<8&&(nJ[nX]=n$(nF(nQ,.5))),nz[nX]=n$(nF(nQ,1/3)),nX++),nQ++}var nY=!!new nV(new nW([1]).buffer)[0];function nZ(e){return nY?e>>>24|(e>>>16&255)<<8|(65280&e)<<8|e<<24:e}function n0(e,t){return e>>>t|e<<32-t}function n1(e){var t=nJ.slice(),n=e.length,s=8*n,i=512-(s+64)%512-1+s+65,r=new nV(i/8),o=new nW(r.buffer);r.set(e,0),r[n]=128,o[o.length-1]=nZ(s);for(var a=0;a<i/32;a+=16){var l=t.slice();for(c=0;c<64;c++){if(c<16)h=nZ(o[a+c]);else{var c,h,u=nK[c-15],d=nK[c-2];h=nK[c-7]+nK[c-16]+(n0(u,7)^n0(u,18)^u>>>3)+(n0(d,17)^n0(d,19)^d>>>10)}nK[c]=h|=0;for(var g=(n0(l[4],6)^n0(l[4],11)^n0(l[4],25))+(l[4]&l[5]^~l[4]&l[6])+l[7]+h+nz[c],p=(n0(l[0],2)^n0(l[0],13)^n0(l[0],22))+(l[0]&l[1]^l[2]&(l[0]^l[1])),f=7;f>0;f--)l[f]=l[f-1];l[0]=g+p|0,l[4]=l[4]+g|0}for(c=0;c<8;c++)t[c]=t[c]+l[c]|0}return new nV(new nW(t.map(function(e){return nZ(e)})).buffer)}var n4=new class{constructor(){this.base64CharSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this.hexCharSet="0123456789abcdef"}uint8ViewToBase64(e){let t,n,s,i,r,o="",a=this.base64CharSet,l=e.byteLength,c=l%3,h=l-c;for(let l=0;l<h;l+=3)t=(0xfc0000&(r=e[l]<<16|e[l+1]<<8|e[l+2]))>>18,n=(258048&r)>>12,s=(4032&r)>>6,i=63&r,o+=a[t]+a[n]+a[s]+a[i];return 1==c?(t=(252&(r=e[h]))>>2,n=(3&r)<<4,o+=a[t]+a[n]+"=="):2==c&&(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&&k.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)=>e+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(k.Config.TextEncoder){let t=new k.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=n1(this.toBuffer(e));return this.toArrayBuffer(t)}hmacSha256(e,t){let n=function(e,t){if(e.length>64&&(e=n1(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(n1(r),64),n1(o)}(this.toBuffer(t),this.toBuffer(e));return this.toArrayBuffer(n)}},n2=((r=n2||{})[r.REQ_SEND=0]="REQ_SEND",r[r.REQ_RECV=1]="REQ_RECV",r[r.REQ_RECV_POLL=2]="REQ_RECV_POLL",r[r.REQ_RECV_STREAM=3]="REQ_RECV_STREAM",r);function n8(){return new L("No HTTP request plugin provided. Provide at least one of the FetchRequest or XHRRequest plugins.",400,4e4)}var n3=((c=class{constructor(e){var t;this.checksInProgress=null,this.checkConnectivity=void 0,this.supportsAuthHeaders=!1,this.supportsLinkHeaders=!1,this.client=null!=e?e:null;let n=(null==e?void 0:e.options.connectivityCheckUrl)||e_.connectivityCheckUrl,s=null!=(t=null==e?void 0:e.options.connectivityCheckParams)?t:null,i=!(null==e?void 0:e.options.connectivityCheckUrl),r=w(w({},n3.bundledRequestImplementations),null==e?void 0:e._additionalHTTPRequestImplementations),o=r.XHRRequest,a=r.FetchRequest,l=!!(o||a);if(!l)throw n8();k.Config.xhrSupported&&o?(this.supportsAuthHeaders=!0,this.Request=async function(t,n,s,i,r){return new Promise(a=>{var l;let c=o.createRequest(n,s,i,r,n2.REQ_SEND,null!=(l=e&&e.options.timeouts)?l:null,this.logger,t);c.once("complete",(e,t,n,s,i)=>a({error:e,body:t,headers:n,unpacked:s,statusCode:i})),c.exec()})},(null==e?void 0:e.options.disableConnectivityCheck)?this.checkConnectivity=async function(){return!0}:this.checkConnectivity=async function(){var e,t;_.logAction(this.logger,_.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Sending; "+n);let r=await this.doUri(eH.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,_.logAction(this.logger,_.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Result: "+o),o}):k.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;_.logAction(this.logger,_.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Sending; "+n);let t=await this.doUri(eH.Get,n,null,null,null),s=!t.error&&(null==(e=t.body)?void 0:e.replace(/\n/,""))=="yes";return _.logAction(this.logger,_.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Result: "+s),s}):this.Request=async()=>({error:l?new N("no supported HTTP transports available",null,400):n8()})}get logger(){var e,t;return null!=(t=null==(e=this.client)?void 0:e.logger)?t:_.defaultLogger}async doUri(e,t,n,s,i){return this.Request?this.Request(e,t,n,i,s):{error:new N("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=[eH.Get,eH.Delete,eH.Post,eH.Put,eH.Patch],c.methodsWithoutBody=[eH.Get,eH.Delete],c.methodsWithBody=[eH.Post,eH.Put,eH.Patch],c),n6="ablyjs-storage-test",n5=void 0!==n.g?n.g:"undefined"!=typeof window?window:self,n9=new class{constructor(){try{n5.sessionStorage.setItem(n6,n6),n5.sessionStorage.removeItem(n6),this.sessionSupported=!0}catch(e){this.sessionSupported=!1}try{n5.localStorage.setItem(n6,n6),n5.localStorage.removeItem(n6),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?n5.sessionStorage:n5.localStorage}},n7=eO(),se="string"==typeof EdgeRuntime;"undefined"!=typeof Window||"undefined"!=typeof WorkerGlobalScope||se||console.log("Warning: this distribution of Ably is intended for browsers. On nodejs, please use the 'ably' package on npm");var st={agent:"browser",logTimestamps:!0,userAgent:n7.navigator&&n7.navigator.userAgent.toString(),currentUrl:n7.location&&n7.location.href,binaryType:"arraybuffer",WebSocket:n7.WebSocket,fetchSupported:!!n7.fetch,xhrSupported:n7.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,allowComet:function(){let e=n7.location;return!n7.WebSocket||!e||!e.origin||e.origin.indexOf("http")>-1}(),useProtocolHeartbeats:!0,supportsBinary:!!n7.TextDecoder,preferBinary:!1,ArrayBuffer:n7.ArrayBuffer,atob:n7.atob,nextTick:"function"==typeof n7.queueMicrotask?e=>n7.queueMicrotask(e):e=>Promise.resolve().then(e),addEventListener:n7.addEventListener,inspect:JSON.stringify,stringByteSize:function(e){return n7.TextDecoder&&new n7.TextEncoder().encode(e).length||e.length},TextEncoder:n7.TextEncoder,TextDecoder:n7.TextDecoder,getRandomArrayBuffer:async function(e){let t=new Uint8Array(e);return n7.crypto.getRandomValues(t),t.buffer},isWebworker:!!("undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope),push:{platform:"browser",formFactor:"desktop",storage:n9}};function sn(e){return e.code&&!e$.isTokenErr(e)&&([80015,80017,80030].includes(e.code)||e.code>=4e4&&e.code<5e4)?[ni({action:e1.ERROR,error:e})]:[ni({action:e1.DISCONNECTED,error:e})]}var ss=class extends nw{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(){_.logAction(this.logger,_.LOG_MINOR,"CometTransport.connect()","starting"),nw.prototype.connect.call(this);let e=this.params,t=e.options,n=e.host||t.primaryDomain,s=e_.getPort(t),i=t.tls?"https://":"http://";this.baseUri=i+n+":"+s+"/comet/";let r=this.baseUri+"connect";_.logAction(this.logger,_.LOG_MINOR,"CometTransport.connect()","uri: "+r),ed(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),_.logAction(this.logger,_.LOG_MINOR,"CometTransport.connect()","connectParams:"+en(n));let s=!1,i=this.recvRequest=this.createRequest(r,null,n,null,this.stream?n2.REQ_RECV_STREAM:n2.REQ_RECV);i.on("data",e=>{this.recvRequest&&(s||(s=!0,this.emit("preconnect")),this.onData(e))}),i.on("complete",e=>{if(this.recvRequest||(e=e||new L("Request cancelled",80003,400)),this.recvRequest=null,s||e||(s=!0,this.emit("preconnect")),this.onActivity(),e)return void(e.code?this.onData(sn(e)):this.disconnect(e));k.Config.nextTick(()=>{this.recv()})}),i.exec()})}requestClose(){_.logAction(this.logger,_.LOG_MINOR,"CometTransport.requestClose()"),this._requestCloseOrDisconnect(!0)}requestDisconnect(){_.logAction(this.logger,_.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,n2.REQ_SEND);n.on("complete",t=>{t&&(_.logAction(this.logger,_.LOG_ERROR,"CometTransport.request"+(e?"Close()":"Disconnect()"),"request returned err = "+eo(t)),this.finish("disconnected",t))}),n.exec()}}dispose(){_.logAction(this.logger,_.LOG_MINOR,"CometTransport.dispose()",""),this.isDisposed||(this.isDisposed=!0,this.recvRequest&&(_.logAction(this.logger,_.LOG_MINOR,"CometTransport.dispose()","aborting recv request"),this.recvRequest.abort(),this.recvRequest=null),this.finish("disconnected",nv.disconnected()),k.Config.nextTick(()=>{this.emit("disposed")}))}onConnect(e){var t;if(this.isDisposed)return;let n=null==(t=e.connectionDetails)?void 0:t.connectionKey;nw.prototype.onConnect.call(this,e);let s=this.baseUri+n;_.logAction(this.logger,_.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),n2.REQ_SEND);t.on("complete",(e,t)=>{if(e&&_.logAction(this.logger,_.LOG_ERROR,"CometTransport.sendItems()","on complete: err = "+eo(e)),this.sendRequest=null,e)return void(e.code?this.onData(sn(e)):this.disconnect(e));t&&this.onData(t),this.pendingItems&&k.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?n2.REQ_RECV_STREAM:n2.REQ_RECV_POLL);e.on("data",e=>{this.onData(e)}),e.on("complete",e=>{if(this.recvRequest=null,this.onActivity(),e)return void(e.code?this.onData(sn(e)):this.disconnect(e));k.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(nn(t[e],this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin))}catch(e){_.logAction(this.logger,_.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}},si=function(){},sr=0,so={},sa=class e extends e0{constructor(e,t,n,s,i,r,o,a){super(o),(n=n||{}).rnd=ec(),this.uri=e+en(n),this.headers=t||{},this.body=s,this.method=a?a.toUpperCase():D(s)?"GET":"POST",this.requestMode=i,this.timeouts=r,this.timedOut=!1,this.requestComplete=!1,this.id=String(++sr),so[this.id]=this}static createRequest(t,n,s,i,r,o,a,l){let c=o||e_.TIMEOUTS;return new e(t,n,x(s),i,r,c,a,l)}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==n2.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,l=s.accept,c=this.body,h="text";for(let e in l?0===l.indexOf("application/x-msgpack")&&(h="arraybuffer"):s.accept="application/json",c&&(s["content-type"]||(s["content-type"]="application/json")).indexOf("application/json")>-1&&"string"!=typeof c&&(c=JSON.stringify(c)),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),_.logAction(this.logger,_.LOG_ERROR,"Request.on"+e.type+"()",r),this.complete(new N(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;if(clearTimeout(r),n=t<400,204==t)return void this.complete(null,null,null,null,t);e=this.requestMode==n2.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?k.BufferUtils.utf8Decode(a.response):String(a.responseText);e=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 N("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(ef(Q(t)).includes("x-ably-errorcode"))return e.error&&L.fromValues(e.error)}(e,s);i||(i=new N("Error response received from server: "+t+" body was: "+k.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 N("Malformed response body from server: "+e.message,null,400));return}this.emit("data",e)},v=()=>{m(),this.streamComplete=!0,k.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?v():f()))},a.send(c)}dispose(){let e=this.xhr;if(e){e.onreadystatechange=e.onerror=e.onabort=e.ontimeout=si,this.xhr=null;let t=this.timer;t&&(clearTimeout(t),this.timer=null),this.requestComplete||e.abort()}delete so[this.id]}},sl=o.XhrPolling,sc=class extends ss{constructor(e,t,n){super(e,t,n),this.shortName=sl,n.stream=!1,this.shortName=sl}static isAvailable(){return!!(k.Config.xhrSupported&&k.Config.allowComet)}toString(){return"XHRPollingTransport; uri="+this.baseUri+"; isConnected="+this.isConnected}createRequest(e,t,n,s,i){return sa.createRequest(e,t,n,s,i,this.timeouts,this.logger)}},sh={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",wsConnectivityCheckUrl:"wss://ws-up.ably-realtime.com",defaultTransports:[o.XhrPolling,o.WebSocket]};function su(e,t,n){let s=new TextEncoder().encode(n);for(let n=0;n<s.length;n++)e.setUint8(t+n,s[n])}function sd(e,t,n){return new TextDecoder().decode(e.buffer.slice(t,t+n))}function sg(e){return new TextEncoder().encode(e).length}var sp=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=sd(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=()=>{let e,t,n=this.view.getUint8(this.offset);if((128&n)==0)return this.offset++,n;if((240&n)==128)return t=15&n,this.offset++,this.map(t);if((240&n)==144)return t=15&n,this.offset++,this.array(t);if((224&n)==160)return t=31&n,this.offset++,this.str(t);if((224&n)==224)return e=this.view.getInt8(this.offset),this.offset++,e;switch(n){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 t=this.view.getUint8(this.offset+1),this.offset+=2,this.bin(t);case 197:return t=this.view.getUint16(this.offset+1),this.offset+=3,this.bin(t);case 198:return t=this.view.getUint32(this.offset+1),this.offset+=5,this.bin(t);case 199:return t=this.view.getUint8(this.offset+1),this.offset+=2,this.ext(t);case 200:return t=this.view.getUint16(this.offset+1),this.offset+=3,this.ext(t);case 201:return t=this.view.getUint32(this.offset+1),this.offset+=5,this.ext(t);case 202:return e=this.view.getFloat32(this.offset+1),this.offset+=5,e;case 203:return e=this.view.getFloat64(this.offset+1),this.offset+=9,e;case 204:return e=this.view.getUint8(this.offset+1),this.offset+=2,e;case 205:return e=this.view.getUint16(this.offset+1),this.offset+=3,e;case 206:return e=this.view.getUint32(this.offset+1),this.offset+=5,e;case 207:return e=function(e,t){return t=t||0,0x100000000*e.getUint32(t)+e.getUint32(t+4)}(this.view,this.offset+1),this.offset+=9,e;case 208:return e=this.view.getInt8(this.offset+1),this.offset+=2,e;case 209:return e=this.view.getInt16(this.offset+1),this.offset+=3,e;case 210:return e=this.view.getInt32(this.offset+1),this.offset+=5,e;case 211:return e=function(e,t){return t=t||0,0x100000000*e.getInt32(t)+e.getUint32(t+4)}(this.view,this.offset+1),this.offset+=9,e;case 212:return t=1,this.offset++,this.ext(t);case 213:return t=2,this.offset++,this.ext(t);case 214:return t=4,this.offset++,this.ext(t);case 215:return t=8,this.offset++,this.ext(t);case 216:return t=16,this.offset++,this.ext(t);case 217:return t=this.view.getUint8(this.offset+1),this.offset+=2,this.str(t);case 218:return t=this.view.getUint16(this.offset+1),this.offset+=3,this.str(t);case 219:return t=this.view.getUint32(this.offset+1),this.offset+=5,this.str(t);case 220:return t=this.view.getUint16(this.offset+1),this.offset+=3,this.array(t);case 221:return t=this.view.getUint32(this.offset+1),this.offset+=5,this.array(t);case 222:return t=this.view.getUint16(this.offset+1),this.offset+=3,this.map(t);case 223:return t=this.view.getUint32(this.offset+1),this.offset+=5,this.map(t)}throw Error("Unknown type 0x"+n.toString(16))},this.offset=t||0,this.view=e}};function sf(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 sm={encode:function(e,t){let n=function e(t,n){let s=typeof t;if("string"===s){let e=sg(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;if(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=sf(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=sg(t);if(e<32)return n.setUint8(s,160|e),su(n,s+1,t),1+e;if(e<256)return n.setUint8(s,217),n.setUint8(s+1,e),su(n,s+2,t),2+e;if(e<65536)return n.setUint8(s,218),n.setUint16(s+1,e),su(n,s+3,t),3+e;if(e<0x100000000)return n.setUint8(s,219),n.setUint32(s+1,e),su(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,l,c;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),l=s+1,(c=t)<0x8000000000000000?(n.setInt32(l,Math.floor(23283064365386963e-26*c)),n.setInt32(l+4,-1&c)):(n.setUint32(l,0x7fffffff),n.setUint32(l+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,l=Array.isArray(t);if((o=l?t.length:(r=sf(t,i)).length)<16?(n.setUint8(s,o|(l?144:128)),a=1):o<65536?(n.setUint8(s,l?220:222),n.setUint16(s+1,o),a=3):o<0x100000000&&(n.setUint8(s,l?221:223),n.setUint32(s+1,o),a=5),l)for(let r=0;r<o;r++)a+=e(t[r],n,s+a,i);else if(r)for(let l=0;l<o;l++){let o=r[l];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 sp(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:su,utf8Read:sd,utf8ByteCount:sg};async function sy(e,t,n,s,i,r){let o,a=new Headers(s||{}),l=e?e.toUpperCase():D(r)?"GET":"POST",c=new AbortController,h=new Promise(e=>{o=setTimeout(()=>{c.abort(),e({error:new N("Request timed out",null,408)})},t?t.options.timeouts.httpRequestTimeout:e_.TIMEOUTS.httpRequestTimeout)}),u={method:l,headers:a,body:r,signal:c.signal};k.Config.isWebworker||(u.credentials=a.has("authorization")?"include":"same-origin");let d=(async()=>{try{let e,t=new URLSearchParams(i||{});t.set("rnd",ec());let s=n+"?"+t,r=await eO().fetch(s,u);if(clearTimeout(o),204==r.status)return{error:null,statusCode:r.status};let a=r.headers.get("Content-Type");e=a&&a.indexOf("application/x-msgpack")>-1?await r.arrayBuffer():a&&a.indexOf("application/json")>-1?await r.json():await r.text();let l=!!a&&-1===a.indexOf("application/x-msgpack"),c=function(e){let t={};return e.forEach((e,n)=>{t[n]=e}),t}(r.headers);if(!r.ok)return{error:function(e,t){if(t.get("x-ably-errorcode"))return e.error&&L.fromValues(e.error)}(e,r.headers)||new N("Error response received from server: "+r.status+" body was: "+k.Config.inspect(e),null,r.status),body:e,headers:c,unpacked:l,statusCode:r.status};return{error:null,body:e,headers:c,unpacked:l,statusCode:r.status}}catch(e){return clearTimeout(o),{error:e}}})();return Promise.race([h,d])}var sv=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 L("Failed to generate random key: "+e.message,400,5e4)}}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){_.logAction(this.logger,_.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){_.logAction(this.logger,_.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}(st,n4);for(let e of(k.Crypto=sv,k.BufferUtils=n4,k.Http=n3,k.Config=st,k.Transports={order:["xhr_polling"],bundledImplementations:{web_socket:nq,xhr_polling:sc}},k.WebStorage=n9,[nd,nH]))e.Crypto=sv,e._MsgPack=sm;n3.bundledRequestImplementations={XHRRequest:sa,FetchRequest:sy},_.initLogHandlers(),k.Defaults=Object.assign(e_,sh),k.Config.agent&&(k.Defaults.agent+=" "+k.Config.agent);var sb={ErrorInfo:L,Rest:nd,Realtime:nH,msgpack:sm,makeProtocolMessageFromDeserialized:ns};return"object"==typeof u.exports&&(u.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})(u.exports,h)),u.exports})()}}]);
|