text: 'use strict';
  /*
   Copyright 2020, Ably
  
   Ably JavaScript Library v1.1.25
   https://github.com/ably/ably-js
  
   Ably Realtime Messaging
   https://www.ably.io
  
   Released under the Apache Licence v2.0
  */
  (function(){function ja(f){if("string"!==typeof f)throw new p("host must be a string; was a "+typeof f,4E4,400);if(!f.length)throw new p("host must not be zero-length",4E4,400);}var r="object"===typeof window&&window||"object"===typeof self&&self,W=r.Ably=this,G=G||function(f,b){var d={},a=d.lib={},c=a.Base=function(){function a(){}return{extend:function(g){a.prototype=this;var c=new a;g&&c.mixIn(g);c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=
  c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var g in a)a.hasOwnProperty(g)&&(this[g]=a[g]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),n=a.WordArray=c.extend({init:function(a,g){a=this.words=a||[];this.sigBytes=g!=b?g:4*a.length},toString:function(a){return(a||m).stringify(this)},concat:function(a){var g=this.words,c=a.words,e=
  this.sigBytes;a=a.sigBytes;this.clamp();if(e%4)for(var h=0;h<a;h++)g[e+h>>>2]|=(c[h>>>2]>>>24-h%4*8&255)<<24-(e+h)%4*8;else if(65535<c.length)for(h=0;h<a;h+=4)g[e+h>>>2]=c[h>>>2];else g.push.apply(g,c);this.sigBytes+=a;return this},clamp:function(){var a=this.words,g=this.sigBytes;a[g>>>2]&=4294967295<<32-g%4*8;a.length=f.ceil(g/4)},clone:function(){var a=c.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){function g(a){var g=987654321;return function(){g=36969*(g&65535)+(g>>
  16)&4294967295;a=18E3*(a&65535)+(a>>16)&4294967295;return(((g<<16)+a&4294967295)/4294967296+.5)*(.5<f.random()?1:-1)}}for(var c=[],h=0,e;h<a;h+=4){var b=g(4294967296*(e||f.random()));e=987654071*b();c.push(4294967296*b()|0)}return new n.init(c,a)}}),e=d.enc={},m=e.Hex={stringify:function(a){var g=a.words;a=a.sigBytes;for(var c=[],h=0;h<a;h++){var e=g[h>>>2]>>>24-h%4*8&255;c.push((e>>>4).toString(16));c.push((e&15).toString(16))}return c.join("")},parse:function(a){for(var g=a.length,c=[],h=0;h<g;h+=
  2)c[h>>>3]|=parseInt(a.substr(h,2),16)<<24-h%8*4;return new n.init(c,g/2)}},t=e.Latin1={stringify:function(a){var g=a.words;a=a.sigBytes;for(var c=[],h=0;h<a;h++)c.push(String.fromCharCode(g[h>>>2]>>>24-h%4*8&255));return c.join("")},parse:function(a){for(var g=a.length,c=[],h=0;h<g;h++)c[h>>>2]|=(a.charCodeAt(h)&255)<<24-h%4*8;return new n.init(c,g)}},h=e.Utf8={stringify:function(a){try{return decodeURIComponent(escape(t.stringify(a)))}catch(H){throw Error("Malformed UTF-8 data");}},parse:function(a){return t.parse(unescape(encodeURIComponent(a)))}},
  u=a.BufferedBlockAlgorithm=c.extend({reset:function(){this._data=new n.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=h.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var g=this._data,c=g.words,h=g.sigBytes,e=this.blockSize,b=h/(4*e);b=a?f.ceil(b):f.max((b|0)-this._minBufferSize,0);a=b*e;h=f.min(4*a,h);if(a){for(var d=0;d<a;d+=e)this._doProcessBlock(c,d);d=c.splice(0,a);g.sigBytes-=h}return new n.init(d,h)},clone:function(){var a=c.clone.call(this);
  a._data=this._data.clone();return a},_minBufferSize:0});a.Hasher=u.extend({cfg:c.extend(),init:function(a){this.cfg=this.cfg.extend(a);this.reset()},reset:function(){u.reset.call(this);this._doReset()},update:function(a){this._append(a);this._process();return this},finalize:function(a){a&&this._append(a);return this._doFinalize()},blockSize:16,_createHelper:function(a){return function(g,c){return(new a.init(c)).finalize(g)}},_createHmacHelper:function(a){return function(c,h){return(new g.HMAC.init(a,
  h)).finalize(c)}}});var g=d.algo={};return d}(Math);(function(b){var f=G,d=f.lib,a=d.WordArray,c=d.Hasher;d=f.algo;var n=[],e=[];(function(){function a(a){for(var g=b.sqrt(a),c=2;c<=g;c++)if(!(a%c))return!1;return!0}function c(a){return 4294967296*(a-(a|0))|0}for(var f=2,g=0;64>g;)a(f)&&(8>g&&(n[g]=c(b.pow(f,.5))),e[g]=c(b.pow(f,1/3)),g++),f++})();var m=[];d=d.SHA256=c.extend({_doReset:function(){this._hash=new a.init(n.slice(0))},_doProcessBlock:function(a,c){for(var h=this._hash.words,g=h[0],b=
  h[1],f=h[2],d=h[3],n=h[4],t=h[5],l=h[6],k=h[7],p=0;64>p;p++){if(16>p)m[p]=a[c+p]|0;else{var C=m[p-15],q=m[p-2];m[p]=((C<<25|C>>>7)^(C<<14|C>>>18)^C>>>3)+m[p-7]+((q<<15|q>>>17)^(q<<13|q>>>19)^q>>>10)+m[p-16]}C=k+((n<<26|n>>>6)^(n<<21|n>>>11)^(n<<7|n>>>25))+(n&t^~n&l)+e[p]+m[p];q=((g<<30|g>>>2)^(g<<19|g>>>13)^(g<<10|g>>>22))+(g&b^g&f^b&f);k=l;l=t;t=n;n=d+C|0;d=f;f=b;b=g;g=C+q|0}h[0]=h[0]+g|0;h[1]=h[1]+b|0;h[2]=h[2]+f|0;h[3]=h[3]+d|0;h[4]=h[4]+n|0;h[5]=h[5]+t|0;h[6]=h[6]+l|0;h[7]=h[7]+k|0},_doFinalize:function(){var a=
  this._data,c=a.words,e=8*this._nDataBytes,g=8*a.sigBytes;c[g>>>5]|=128<<24-g%32;c[(g+64>>>9<<4)+14]=b.floor(e/4294967296);c[(g+64>>>9<<4)+15]=e;a.sigBytes=4*c.length;this._process();return this._hash},clone:function(){var a=c.clone.call(this);a._hash=this._hash.clone();return a}});f.SHA256=c._createHelper(d);f.HmacSHA256=c._createHmacHelper(d)})(Math);(function(){var b=G,l=b.enc.Utf8;b.algo.HMAC=b.lib.Base.extend({init:function(b,a){b=this._hasher=new b.init;"string"==typeof a&&(a=l.parse(a));var c=
  b.blockSize,f=4*c;a.sigBytes>f&&(a=b.finalize(a));a.clamp();for(var e=this._oKey=a.clone(),d=this._iKey=a.clone(),t=e.words,h=d.words,u=0;u<c;u++)t[u]^=1549556828,h[u]^=909522486;e.sigBytes=d.sigBytes=f;this.reset()},reset:function(){var b=this._hasher;b.reset();b.update(this._iKey)},update:function(b){this._hasher.update(b);return this},finalize:function(b){var a=this._hasher;b=a.finalize(b);a.reset();return a.finalize(this._oKey.clone().concat(b))}})})();(function(){var b=G,l=b.lib.WordArray;b.enc.Base64=
  {stringify:function(b){var a=b.words,c=b.sigBytes,f=this._map;b.clamp();b=[];for(var e=0;e<c;e+=3)for(var d=(a[e>>>2]>>>24-e%4*8&255)<<16|(a[e+1>>>2]>>>24-(e+1)%4*8&255)<<8|a[e+2>>>2]>>>24-(e+2)%4*8&255,t=0;4>t&&e+.75*t<c;t++)b.push(f.charAt(d>>>6*(3-t)&63));if(a=f.charAt(64))for(;b.length%4;)b.push(a);return b.join("")},parse:function(b){var a=b.length,c=this._map,f=c.charAt(64);f&&(f=b.indexOf(f),-1!=f&&(a=f));f=[];for(var e=0,d=0;d<a;d++)if(d%4){var t=c.indexOf(b.charAt(d-1))<<d%4*2,h=c.indexOf(b.charAt(d))>>>
  6-d%4*2;f[e>>>2]|=(t|h)<<24-e%4*8;e++}return l.create(f,e)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})();var da=function(){function b(){}b.addListener=function(b,f,a){b.addEventListener?b.addEventListener(f,a,!1):b.attachEvent("on"+f,function(){a.apply(b,arguments)})};b.removeListener=function(b,f,a){b.removeEventListener?b.removeEventListener(f,a,!1):b.detachEvent("on"+f,function(){a.apply(b,arguments)})};b.addMessageListener=function(f,d){b.addListener(f,"message",
  d)};b.removeMessageListener=function(f,d){b.removeListener(f,"message",d)};b.addUnloadListener=function(f){b.addListener(r,"unload",f)};return b}(),ea=function(){function b(a,c,g){for(var h=0,e=g.length;h<e;h++){var b=g.charCodeAt(h);if(128>b)a.setUint8(c++,b>>>0&127|0);else if(2048>b)a.setUint8(c++,b>>>6&31|192),a.setUint8(c++,b>>>0&63|128);else if(65536>b)a.setUint8(c++,b>>>12&15|224),a.setUint8(c++,b>>>6&63|128),a.setUint8(c++,b>>>0&63|128);else if(1114112>b)a.setUint8(c++,b>>>18&7|240),a.setUint8(c++,
  b>>>12&63|128),a.setUint8(c++,b>>>6&63|128),a.setUint8(c++,b>>>0&63|128);else throw Error("bad codepoint "+b);}}function l(a,c,g){var h="",e=c;for(c+=g;e<c;e++)if(g=a.getUint8(e),0===(g&128))h+=String.fromCharCode(g);else if(192===(g&224))h+=String.fromCharCode((g&15)<<6|a.getUint8(++e)&63);else if(224===(g&240))h+=String.fromCharCode((g&15)<<12|(a.getUint8(++e)&63)<<6|(a.getUint8(++e)&63)<<0);else if(240===(g&248))h+=String.fromCharCode((g&7)<<18|(a.getUint8(++e)&63)<<12|(a.getUint8(++e)&63)<<6|
  (a.getUint8(++e)&63)<<0);else throw Error("Invalid byte "+g.toString(16));return h}function d(a){for(var c=0,g=0,h=a.length;g<h;g++){var e=a.charCodeAt(g);if(128>e)c+=1;else if(2048>e)c+=2;else if(65536>e)c+=3;else if(1114112>e)c+=4;else throw Error("bad codepoint "+e);}return c}function a(a,c){this.offset=c||0;this.view=a}function c(a,c){return k.keysArray(a,!0).filter(function(g){g=a[g];return(!c||void 0!==g&&null!==g)&&("function"!==typeof g||!!g.toJSON)})}function n(a,e,g,f){var h=typeof a;if("string"===
  h){var m=d(a);if(32>m)return e.setUint8(g,m|160),b(e,g+1,a),1+m;if(256>m)return e.setUint8(g,217),e.setUint8(g+1,m),b(e,g+2,a),2+m;if(65536>m)return e.setUint8(g,218),e.setUint16(g+1,m),b(e,g+3,a),3+m;if(4294967296>m)return e.setUint8(g,219),e.setUint32(g+1,m),b(e,g+5,a),5+m}ArrayBuffer.isView&&ArrayBuffer.isView(a)&&(a=a.buffer);if(a instanceof ArrayBuffer){m=a.byteLength;if(256>m)return e.setUint8(g,196),e.setUint8(g+1,m),(new Uint8Array(e.buffer)).set(new Uint8Array(a),g+2),2+m;if(65536>m)return e.setUint8(g,
  197),e.setUint16(g+1,m),(new Uint8Array(e.buffer)).set(new Uint8Array(a),g+3),3+m;if(4294967296>m)return e.setUint8(g,198),e.setUint32(g+1,m),(new Uint8Array(e.buffer)).set(new Uint8Array(a),g+5),5+m}if("number"===h){if(Math.floor(a)!==a)return e.setUint8(g,203),e.setFloat64(g+1,a),9;if(0<=a){if(128>a)return e.setUint8(g,a),1;if(256>a)return e.setUint8(g,204),e.setUint8(g+1,a),2;if(65536>a)return e.setUint8(g,205),e.setUint16(g+1,a),3;if(4294967296>a)return e.setUint8(g,206),e.setUint32(g+1,a),5;
  if(1.8446744073709552E19>a)return e.setUint8(g,207),g+=1,1.8446744073709552E19>a?(e.setUint32(g,Math.floor(a*t)),e.setInt32(g+4,a&-1)):(e.setUint32(g,4294967295),e.setUint32(g+4,4294967295)),9;throw Error("Number too big 0x"+a.toString(16));}if(-32<=a)return e.setInt8(g,a),1;if(-128<=a)return e.setUint8(g,208),e.setInt8(g+1,a),2;if(-32768<=a)return e.setUint8(g,209),e.setInt16(g+1,a),3;if(-2147483648<=a)return e.setUint8(g,210),e.setInt32(g+1,a),5;if(-9223372036854775808<=a)return e.setUint8(g,211),
  g+=1,0x7fffffffffffffff>a?(e.setInt32(g,Math.floor(a*t)),e.setInt32(g+4,a&-1)):(e.setUint32(g,2147483647),e.setUint32(g+4,2147483647)),9;throw Error("Number too small -0x"+(-a).toString(16).substr(1));}if("undefined"===h){if(f)return 0;e.setUint8(g,212);e.setUint8(g+1,0);e.setUint8(g+2,0);return 3}if(null===a){if(f)return 0;e.setUint8(g,192);return 1}if("boolean"===h)return e.setUint8(g,a?195:194),1;if("function"===typeof a.toJSON)return n(a.toJSON(),e,g,f);if("object"===h){h=0;var w=Array.isArray(a);
  if(w)m=a.length;else{var u=c(a,f);m=u.length}16>m?(e.setUint8(g,m|(w?144:128)),h=1):65536>m?(e.setUint8(g,w?220:222),e.setUint16(g+1,m),h=3):4294967296>m&&(e.setUint8(g,w?221:223),e.setUint32(g+1,m),h=5);if(w)for(w=0;w<m;w++)h+=n(a[w],e,g+h,f);else for(w=0;w<m;w++){var l=u[w];h+=n(l,e,g+h);h+=n(a[l],e,g+h,f)}return h}if("function"===h)return 0;throw Error("Unknown type "+h);}function e(a,b){var g=typeof a;if("string"===g){var h=d(a);if(32>h)return 1+h;if(256>h)return 2+h;if(65536>h)return 3+h;if(4294967296>
  h)return 5+h}ArrayBuffer.isView&&ArrayBuffer.isView(a)&&(a=a.buffer);if(a instanceof ArrayBuffer){h=a.byteLength;if(256>h)return 2+h;if(65536>h)return 3+h;if(4294967296>h)return 5+h}if("number"===g){if(Math.floor(a)!==a)return 9;if(0<=a){if(128>a)return 1;if(256>a)return 2;if(65536>a)return 3;if(4294967296>a)return 5;if(1.8446744073709552E19>a)return 9;throw Error("Number too big 0x"+a.toString(16));}if(-32<=a)return 1;if(-128<=a)return 2;if(-32768<=a)return 3;if(-2147483648<=a)return 5;if(-9223372036854775808<=
  a)return 9;throw Error("Number too small -0x"+a.toString(16).substr(1));}if("boolean"===g)return 1;if(null===a)return b?0:1;if(void 0===a)return b?0:3;if("function"===typeof a.toJSON)return e(a.toJSON(),b);if("object"===g){g=0;if(Array.isArray(a)){h=a.length;for(var f=0;f<h;f++)g+=e(a[f],b)}else{var n=c(a,b);h=n.length;for(f=0;f<h;f++){var m=n[f];g+=e(m)+e(a[m],b)}}if(16>h)return 1+g;if(65536>h)return 3+g;if(4294967296>h)return 5+g;throw Error("Array or object too long 0x"+h.toString(16));}if("function"===
  g)return 0;throw Error("Unknown type "+g);}var m={inspect:function(a){if(void 0===a)return"undefined";if(a instanceof ArrayBuffer){var c="ArrayBuffer";var g=new DataView(a)}else a instanceof DataView&&(c="DataView",g=a);if(!g)return JSON.stringify(a);for(var e=[],b=0;b<a.byteLength;b++){if(20<b){e.push("...");break}var h=g.getUint8(b).toString(16);1===h.length&&(h="0"+h);e.push(h)}return"<"+c+" "+e.join(" ")+">"}};m.utf8Write=b;m.utf8Read=l;m.utf8ByteCount=d;m.encode=function(a,c){var g=e(a,c);if(0!=
  g){g=new ArrayBuffer(g);var b=new DataView(g);n(a,b,0,c);return g}};m.decode=function(c){var e=new DataView(c);e=new a(e);var g=e.parse();if(e.offset!==c.byteLength)throw Error(c.byteLength-e.offset+" trailing bytes");return g};var t=1/4294967296;a.prototype.map=function(a){for(var c={},g=0;g<a;g++){var e=this.parse();c[e]=this.parse()}return c};a.prototype.bin=a.prototype.buf=function(a){var c=new ArrayBuffer(a);(new Uint8Array(c)).set(new Uint8Array(this.view.buffer,this.offset,a),0);this.offset+=
  a;return c};a.prototype.str=function(a){var c=l(this.view,this.offset,a);this.offset+=a;return c};a.prototype.array=function(a){for(var c=Array(a),g=0;g<a;g++)c[g]=this.parse();return c};a.prototype.ext=function(a){var c={};c.type=this.view.getInt8(this.offset);this.offset++;c.data=this.buf(a);this.offset+=a;return c};a.prototype.parse=function(){var a=this.view.getUint8(this.offset);if(0===(a&128))return this.offset++,a;if(128===(a&240))return this.offset++,this.map(a&15);if(144===(a&240))return this.offset++,
  this.array(a&15);if(160===(a&224))return this.offset++,this.str(a&31);if(224===(a&224))return a=this.view.getInt8(this.offset),this.offset++,a;switch(a){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 a=this.view.getUint8(this.offset+1),this.offset+=2,this.bin(a);case 197:return a=this.view.getUint16(this.offset+1),this.offset+=3,this.bin(a);case 198:return a=this.view.getUint32(this.offset+1),this.offset+=
  5,this.bin(a);case 199:return a=this.view.getUint8(this.offset+1),this.offset+=2,this.ext(a);case 200:return a=this.view.getUint16(this.offset+1),this.offset+=3,this.ext(a);case 201:return a=this.view.getUint32(this.offset+1),this.offset+=5,this.ext(a);case 202:return a=this.view.getFloat32(this.offset+1),this.offset+=5,a;case 203:return a=this.view.getFloat64(this.offset+1),this.offset+=9,a;case 204:return a=this.view.getUint8(this.offset+1),this.offset+=2,a;case 205:return a=this.view.getUint16(this.offset+
  1),this.offset+=3,a;case 206:return a=this.view.getUint32(this.offset+1),this.offset+=5,a;case 207:a=this.view;var c=this.offset+1;c=c||0;a=4294967296*a.getUint32(c)+a.getUint32(c+4);this.offset+=9;return a;case 208:return a=this.view.getInt8(this.offset+1),this.offset+=2,a;case 209:return a=this.view.getInt16(this.offset+1),this.offset+=3,a;case 210:return a=this.view.getInt32(this.offset+1),this.offset+=5,a;case 211:return a=this.view,c=(c=this.offset+1)||0,a=4294967296*a.getInt32(c)+a.getUint32(c+
  4),this.offset+=9,a;case 212:return this.offset++,this.ext(1);case 213:return this.offset++,this.ext(2);case 214:return this.offset++,this.ext(4);case 215:return this.offset++,this.ext(8);case 216:return this.offset++,this.ext(16);case 217:return a=this.view.getUint8(this.offset+1),this.offset+=2,this.str(a);case 218:return a=this.view.getUint16(this.offset+1),this.offset+=3,this.str(a);case 219:return a=this.view.getUint32(this.offset+1),this.offset+=5,this.str(a);case 220:return a=this.view.getUint16(this.offset+
  1),this.offset+=3,this.array(a);case 221:return a=this.view.getUint32(this.offset+1),this.offset+=5,this.array(a);case 222:return a=this.view.getUint16(this.offset+1),this.offset+=3,this.map(a);case 223:return a=this.view.getUint32(this.offset+1),this.offset+=5,this.map(a)}throw Error("Unknown type 0x"+a.toString(16));};return m}();"undefined"===typeof Window&&"undefined"===typeof WorkerGlobalScope&&console.log("Warning: this distribution of Ably is intended for browsers. On nodejs, please use the 'ably' package on npm");
  var X=r.navigator&&r.navigator.userAgent.toString(),v={libver:"js-web",logTimestamps:!0,userAgent:X,currentUrl:r.location&&r.location.href,noUpgrade:X&&X.match(/MSIE\s8\.0/),binaryType:"arraybuffer",WebSocket:r.WebSocket||r.MozWebSocket,xhrSupported:r.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,jsonpSupported:"undefined"!==typeof document,allowComet:function(){var b=r.location;return!r.WebSocket||!b||!b.origin||-1<b.origin.indexOf("http")}(),streamingSupported:!0,useProtocolHeartbeats:!0,
  createHmac:null,msgpack:ea,supportsBinary:!!r.TextDecoder,preferBinary:!1,ArrayBuffer:r.ArrayBuffer,atob:r.atob,nextTick:function(b){setTimeout(b,0)},addEventListener:r.addEventListener,inspect:JSON.stringify,stringByteSize:function(b){return r.TextDecoder&&(new r.TextEncoder).encode(b).length||b.length},TextEncoder:r.TextEncoder,TextDecoder:r.TextDecoder,Promise:r.Promise,getRandomValues:function(b){if(void 0!==b)return function(f,d){b.getRandomValues(f);d&&d(null)}}(r.crypto||r.msCrypto)},J=function(){function b(){}
  function l(a){return a?r.sessionStorage:r.localStorage}function d(a,c,b,f){c={value:c};b&&(c.expires=k.now()+b);return l(f).setItem(a,JSON.stringify(c))}function a(a,c){var e=l(c).getItem(a);if(!e)return null;e=JSON.parse(e);return e.expires&&e.expires<k.now()?(l(c).removeItem(a),null):e.value}try{r.sessionStorage.setItem("ablyjs-storage-test","ablyjs-storage-test");r.sessionStorage.removeItem("ablyjs-storage-test");var c=!0}catch(e){c=!1}try{r.localStorage.setItem("ablyjs-storage-test","ablyjs-storage-test");
  r.localStorage.removeItem("ablyjs-storage-test");var n=!0}catch(e){n=!1}n&&(b.set=function(a,c,b){return d(a,c,b,!1)},b.get=function(c){return a(c,!1)},b.remove=function(a){return l(!1).removeItem(a)});c&&(b.setSession=function(a,c,b){return d(a,c,b,!0)},b.getSession=function(c){return a(c,!0)},b.removeSession=function(a){return l(!0).removeItem(a)});return b}(),q={internetUpUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",jsonpInternetUpUrl:"https://internet-up.ably-realtime.com/is-the-internet-up-0-9.js",
  defaultTransports:["xhr_polling","xhr_streaming","jsonp","web_socket"],baseTransportOrder:["xhr_polling","xhr_streaming","jsonp","web_socket"],transportPreferenceOrder:["jsonp","xhr_polling","xhr_streaming","web_socket"],upgradeTransports:["xhr_streaming","web_socket"]};v.noUpgrade&&(q.upgradeTransports=[]);var A=function(){function b(a){return null!==a&&void 0!==a&&void 0!==a.sigBytes}function l(a){return null!==a&&void 0!==a&&a.constructor===n}function d(a){return n&&n.isView&&n.isView(a)}function a(){}
  var c=G.lib.WordArray,n=v.ArrayBuffer,e=v.atob,m=v.TextEncoder,t=v.TextDecoder;a.base64CharSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";a.hexCharSet="0123456789abcdef";var h=a.isBuffer=function(a){return l(a)||b(a)||d(a)},u=a.toBuffer=function(a){if(!n)throw Error("Can't convert to Buffer: browser does not support the necessary types");if(l(a))return new Uint8Array(a);if(d(a))return new Uint8Array(a.buffer);if(b(a)){var c=new n(a.sigBytes);c=new Uint8Array(c);for(var g=0;g<
  a.sigBytes;g++)c[g]=a.words[g>>>2]>>>24-g%4*8&255;return c}throw Error("BufferUtils.toBuffer expected an arraybuffer, typed array, or CryptoJS wordarray");};a.toArrayBuffer=function(a){return l(a)?a:u(a).buffer};a.toWordArray=function(a){d(a)&&(a=a.buffer);return b(a)?a:c.create(a)};a.base64Encode=function(a){if(b(a))return G.enc.Base64.stringify(a);a=u(a);var c="",g=a.byteLength,e=g%3;g-=e;for(var f,h,d,n,m=0;m<g;m+=3)n=a[m]<<16|a[m+1]<<8|a[m+2],f=(n&16515072)>>18,h=(n&258048)>>12,d=(n&4032)>>6,
  n&=63,c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[f]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[h]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[d]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[n];1==e?(n=a[g],c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n&252)>>2]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n&3)<<4]+"=="):2==e&&(n=a[g]<<8|a[g+1],c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n&
  64512)>>10]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n&1008)>>4]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n&15)<<2]+"=");return c};a.base64Decode=function(a){if(n&&e){a=e(a);for(var c=a.length,g=new Uint8Array(c),b=0;b<c;b++){var f=a.charCodeAt(b);g[b]=f}return g.buffer}return G.enc.Base64.parse(a)};a.hexEncode=function(c){c=a.toWordArray(c);return G.enc.Hex.stringify(c)};a.hexDecode=function(c){c=G.enc.Hex.parse(c);return n?a.toArrayBuffer(c):
  c};a.utf8Encode=function(a){return m?(new m).encode(a).buffer:G.enc.Utf8.parse(a)};a.utf8Decode=function(c){if(!h(c))throw Error("Expected input of utf8decode to be an arraybuffer, typed array, or CryptoJS wordarray");if(t&&!b(c))return(new t).decode(c);c=a.toWordArray(c);return G.enc.Utf8.stringify(c)};a.bufferCompare=function(c,e){if(!c)return-1;if(!e)return 1;c=a.toWordArray(c);e=a.toWordArray(e);c.clamp();e.clamp();var g=c.sigBytes-e.sigBytes;if(0!=g)return g;c=c.words;e=e.words;for(var b=0;b<
  c.length;b++)if(g=c[b]-e[b],0!=g)return g;return 0};a.byteLength=function(a){if(l(a)||d(a))return a.byteLength;if(b(a))return a.sigBytes};return a}(),k=function(){function b(){}var l=v.msgpack;b.mixin=function(a){for(var c=1;c<arguments.length;c++){var b=arguments[c];if(!b)break;var e=b.hasOwnProperty,d;for(d in b)if(!e||e.call(b,d))a[d]=b[d]}return a};b.copy=function(a){return b.mixin({},a)};b.isArray=Array.isArray||function(a){return"[object Array]"==Object.prototype.toString.call(a)};b.ensureArray=
  function(a){return b.isEmptyArg(a)?[]:b.isArray(a)?a:[a]};b.isObject=function(a){return"[object Object]"==Object.prototype.toString.call(a)};b.isEmpty=function(a){for(var c in a)return!1;return!0};b.isOnlyPropIn=function(a,c){for(var b in a)if(b!==c)return!1;return!0};b.isEmptyArg=function(a){return null===a||void 0===a};b.shallowClone=function(a){var c={},b;for(b in a)c[b]=a[b];return c};b.prototypicalClone=function(a,c){function d(){}d.prototype=a;var e=new d;c&&b.mixin(e,c);return e};b.inherits=
  v.inherits||function(a,c){a.super_=c;a.prototype=b.prototypicalClone(c.prototype,{constructor:a})};b.containsValue=function(a,c){for(var b in a)if(a[b]==c)return!0;return!1};b.intersect=function(a,c){return b.isArray(c)?b.arrIntersect(a,c):b.arrIntersectOb(a,c)};b.arrIntersect=function(a,c){for(var d=[],e=0;e<a.length;e++){var m=a[e];-1!=b.arrIndexOf(c,m)&&d.push(m)}return d};b.arrIntersectOb=function(a,c){for(var b=[],e=0;e<a.length;e++){var d=a[e];d in c&&b.push(d)}return b};b.arrSubtract=function(a,
  c){for(var d=[],e=0;e<a.length;e++){var m=a[e];-1==b.arrIndexOf(c,m)&&d.push(m)}return d};b.arrIndexOf=Array.prototype.indexOf?function(a,c,b){return a.indexOf(c,b)}:function(a,c,b){b=b||0;for(var e=a.length;b<e;b++)if(a[b]===c)return b;return-1};b.arrIn=function(a,c){return-1!==b.arrIndexOf(a,c)};b.arrDeleteValue=function(a,c){var d=b.arrIndexOf(a,c),e=-1!=d;e&&a.splice(d,1);return e};b.arrWithoutValue=function(a,c){var d=a.slice();b.arrDeleteValue(d,c);return d};b.keysArray=function(a,c){var b=
  [],e;for(e in a)c&&!a.hasOwnProperty(e)||b.push(e);return b};b.valuesArray=function(a,c){var b=[],e;for(e in a)c&&!a.hasOwnProperty(e)||b.push(a[e]);return b};b.arrForEach=Array.prototype.forEach?function(a,c){a.forEach(c)}:function(a,c){for(var b=a.length,e=0;e<b;e++)c(a[e],e,a)};b.safeArrForEach=function(a,c){return b.arrForEach(a.slice(),c)};b.arrMap=Array.prototype.map?function(a,c){return a.map(c)}:function(a,c){for(var b=[],e=a.length,d=0;d<e;d++)b.push(c(a[d],d,a));return b};b.arrFilter=Array.prototype.filter?
  function(a,c){return a.filter(c)}:function(a,c){for(var b=[],e=a.length,d=0;d<e;d++)c(a[d])&&b.push(a[d]);return b};b.arrEvery=Array.prototype.every?function(a,c){return a.every(c)}:function(a,c){for(var b=a.length,e=0;e<b;e++)if(!c(a[e],e,a))return!1;return!0};b.allSame=function(a,c){if(0===a.length)return!0;var d=a[0][c];return b.arrEvery(a,function(a){return a[c]===d})};b.nextTick=v.nextTick;var d={json:"application/json",jsonp:"application/javascript",xml:"application/xml",html:"text/html",msgpack:"application/x-msgpack"};
  b.defaultGetHeaders=function(a){return{accept:d[a||"json"],"X-Ably-Version":q.apiVersion,"X-Ably-Lib":q.libstring}};b.defaultPostHeaders=function(a){var c;return{accept:c=d[a||"json"],"content-type":c,"X-Ably-Version":q.apiVersion,"X-Ably-Lib":q.libstring}};b.arrPopRandomElement=function(a){return a.splice(Math.floor(Math.random()*a.length),1)[0]};b.toQueryString=function(a){var c=[];if(a)for(var b in a)c.push(encodeURIComponent(b)+"="+encodeURIComponent(a[b]));return c.length?"?"+c.join("&"):""};
  b.parseQueryString=function(a){for(var c,b=/([^?&=]+)=?([^&]*)/g,e={};c=b.exec(a);)e[decodeURIComponent(c[1])]=decodeURIComponent(c[2]);return e};b.now=Date.now||function(){return(new Date).getTime()};b.inspect=v.inspect;b.isErrorInfo=function(a){return"ErrorInfo"==a.constructor.name};b.inspectError=function(a){return a&&(b.isErrorInfo(a)||"Error"==a.constructor.name||a instanceof Error)?a.toString():b.inspect(a)};b.inspectBody=function(a){return A.isBuffer(a)?a.toString():"string"===typeof a?a:v.inspect(a)};
  b.dataSizeBytes=function(a){if(A.isBuffer(a))return A.byteLength(a);if("string"===typeof a)return v.stringByteSize(a);throw Error("Expected input of Utils.dataSizeBytes to be a buffer or string, but was: "+typeof a);};b.cheapRandStr=function(){return String(Math.random()).substr(2)};b.randomString=v.getRandomValues&&"undefined"!==typeof Uint8Array?function(a){a=new Uint8Array(a);v.getRandomValues(a);return A.base64Encode(a)}:function(a){var c=A.base64CharSet;a=Math.round(4*a/3);for(var b="",e=0;e<
  a;e++)b+=c[Math.floor(Math.random()*c.length)];return b};b.randomHexString=v.getRandomValues&&"undefined"!==typeof Uint8Array?function(a){a=new Uint8Array(a);v.getRandomValues(a);return A.hexEncode(a)}:function(a){var c=A.hexCharSet;a*=2;for(var b="",e=0;e<a;e++)b+=c[Math.floor(Math.random()*c.length)];return b};b.arrChooseN=function(a,c){for(var d=Math.min(c,a.length),e=a.slice(),m=[],f=0;f<d;f++)m.push(b.arrPopRandomElement(e));return m};b.trim=String.prototype.trim?function(a){return a.trim()}:
  function(a){return a.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")};b.promisify=function(a,c,b){return new Promise(function(e,d){a[c].apply(a,Array.prototype.slice.call(b).concat(function(a,c){a?d(a):e(c)}))})};b.decodeBody=function(a,c){return"msgpack"==c?l.decode(a):JSON.parse(String(a))};b.encodeBody=function(a,c){return"msgpack"==c?l.encode(a,!0):JSON.stringify(a)};return b}(),x=function(){function b(){}function l(){}function d(a){var c=a.statusCode;return 408===c&&!a.code||400===c&&!a.code||
  500<=c&&504>=c}function a(a){var c=a.connection;return(c=c&&c.connectionManager.host)?[c].concat(q.getFallbackHosts(a.options)):q.getHosts(a.options)}var c=Date.now||function(){return(new Date).getTime()};l._getHosts=a;l.methods=["get","delete","post","put","patch"];l.methodsWithoutBody=["get","delete"];l.methodsWithBody=k.arrSubtract(l.methods,l.methodsWithoutBody);k.arrForEach(l.methodsWithoutBody,function(a){l[a]=function(c,b,d,h,f){l["do"](a,c,b,d,null,h,f)};l[a+"Uri"]=function(c,b,d,h,f){l.doUri(a,
  c,b,d,null,h,f)}});k.arrForEach(l.methodsWithBody,function(a){l[a]=function(c,b,d,h,f,g){l["do"](a,c,b,d,h,f,g)};l[a+"Uri"]=function(c,b,d,h,f,g){l.doUri(a,c,b,d,h,f,g)}});l["do"]=function(f,e,m,t,h,u,g){g=g||b;var n="function"==typeof m?m:function(a){return e.baseUri(a)+m},H=arguments,k=e._currentFallback;if(k){if(k.validUntil>c()){l.Request(f,e,n(k.host),t,u,h,function(a){a&&d(a)?(e._currentFallback=null,l["do"].apply(l,H)):g.apply(null,arguments)});return}e._currentFallback=null}k=a(e);if(1==k.length)l.doUri(f,
  e,n(k[0]),t,h,u,g);else{var ca=function(a,b){var m=a.shift();l.doUri(f,e,n(m),t,h,u,function(h){h&&d(h)&&a.length?ca(a,!0):(b&&(e._currentFallback={host:m,validUntil:c()+e.options.timeouts.fallbackRetryTimeout}),g.apply(null,arguments))})};ca(k)}};l.doUri=function(a,c,b,d,h,f,g){l.Request(a,c,b,d,f,h,g)};l.supportsAuthHeaders=!1;l.supportsLinkHeaders=!1;return l}(),la=function(){function b(){this.buffer=[]}function l(a){this._input=a;this._index=-1;this._buffer=[]}function d(a){this._input=a;this._index=
  -1;this._buffer=[]}b.prototype.append=function(a){this.buffer.push(a);return this};b.prototype.toString=function(){return this.buffer.join("")};var a={codex:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(c){var d=new b,e=a.codex;for(c=new l(c);c.moveNext();){var f=c.current;c.moveNext();var t=c.current;c.moveNext();var h=c.current,u=f>>2;f=(f&3)<<4|t>>4;var g=(t&15)<<2|h>>6,w=h&63;isNaN(t)?g=w=64:isNaN(h)&&(w=64);d.append(e.charAt(u)+e.charAt(f)+e.charAt(g)+e.charAt(w))}return d.toString()},
  decode:function(a){var c=new b;for(a=new d(a);a.moveNext();){var e=a.current;if(128>e)c.append(String.fromCharCode(e));else if(191<e&&224>e){a.moveNext();var f=a.current;c.append(String.fromCharCode((e&31)<<6|f&63))}else a.moveNext(),f=a.current,a.moveNext(),c.append(String.fromCharCode((e&15)<<12|(f&63)<<6|a.current&63))}return c.toString()}};l.prototype={current:Number.NaN,moveNext:function(){if(0<this._buffer.length)return this.current=this._buffer.shift(),!0;if(this._index>=this._input.length-
  1)return this.current=Number.NaN,!1;var a=this._input.charCodeAt(++this._index);13==a&&10==this._input.charCodeAt(this._index+1)&&(a=10,this._index+=2);128>a?this.current=a:(127<a&&2048>a?this.current=a>>6|192:(this.current=a>>12|224,this._buffer.push(a>>6&63|128)),this._buffer.push(a&63|128));return!0}};d.prototype={current:64,moveNext:function(){if(0<this._buffer.length)return this.current=this._buffer.shift(),!0;if(this._index>=this._input.length-1)return this.current=64,!1;var c=a.codex.indexOf(this._input.charAt(++this._index)),
  b=a.codex.indexOf(this._input.charAt(++this._index)),e=a.codex.indexOf(this._input.charAt(++this._index)),d=a.codex.indexOf(this._input.charAt(++this._index)),f=(e&3)<<6|d;this.current=c<<2|b>>4;64!=e&&this._buffer.push((b&15)<<4|e>>2);64!=d&&this._buffer.push(f);return!0}};return a}();q.ENVIRONMENT="";q.REST_HOST="rest.ably.io";q.REALTIME_HOST="realtime.ably.io";q.FALLBACK_HOSTS=["A.ably-realtime.com","B.ably-realtime.com","C.ably-realtime.com","D.ably-realtime.com","E.ably-realtime.com"];q.PORT=
  80;q.TLS_PORT=443;q.TIMEOUTS={disconnectedRetryTimeout:15E3,suspendedRetryTimeout:3E4,httpRequestTimeout:15E3,channelRetryTimeout:15E3,fallbackRetryTimeout:6E5,connectionStateTtl:12E4,realtimeRequestTimeout:1E4,recvTimeout:9E4,preferenceConnectTimeout:6E3,parallelUpgradeDelay:6E3};q.httpMaxRetryCount=3;q.maxMessageSize=65536;q.errorReportingUrl="https://errors.ably.io/api/15/store/";q.errorReportingHeaders={"X-Sentry-Auth":"Sentry sentry_version=7, sentry_key=a04e33c8674c451f8a310fbec029acf5, sentry_client=ably-js/0.1",
  "Content-Type":"application/json"};q.version="1.1.25";q.libstring=v.libver+"-"+q.version;q.apiVersion="1.1";q.getHost=function(b,l,d){return l=d?l==b.restHost&&b.realtimeHost||l||b.realtimeHost:l||b.restHost};q.getPort=function(b,l){return l||b.tls?b.tlsPort:b.port};q.getHttpScheme=function(b){return b.tls?"https://":"http://"};q.getFallbackHosts=function(b){var f=b.fallbackHosts;b="undefined"!==typeof b.httpMaxRetryCount?b.httpMaxRetryCount:q.httpMaxRetryCount;return f?k.arrChooseN(f,b):[]};q.getHosts=
  function(b){return[b.restHost].concat(q.getFallbackHosts(b))};q.objectifyOptions=function(b){return"string"==typeof b?-1==b.indexOf(":")?{token:b}:{key:b}:b};q.normaliseOptions=function(f){f.host&&(b.deprecated("host","restHost"),f.restHost=f.host);f.wsHost&&(b.deprecated("wsHost","realtimeHost"),f.realtimeHost=f.wsHost);f.queueEvents&&(b.deprecated("queueEvents","queueMessages"),f.queueMessages=f.queueEvents);!0===f.recover&&(b.deprecated("{recover: true}","{recover: function(lastConnectionDetails, cb) { cb(true); }}"),
  f.recover=function(a,b){b(!0)});"function"===typeof f.recover&&!0===f.closeOnUnload&&(b.logAction(b.LOG_ERROR,"Defaults.normaliseOptions","closeOnUnload was true and a session recovery function was set - these are mutually exclusive, so unsetting the latter"),f.recover=null);"closeOnUnload"in f||(f.closeOnUnload=!f.recover);f.transports&&k.arrIn(f.transports,"xhr")&&(b.deprecated('transports: ["xhr"]','transports: ["xhr_streaming"]'),k.arrDeleteValue(f.transports,"xhr"),f.transports.push("xhr_streaming"));
  "queueMessages"in f||(f.queueMessages=!0);var l=!1;if(f.restHost)f.realtimeHost=f.realtimeHost||f.restHost;else{var d=f.environment&&String(f.environment).toLowerCase()||q.ENVIRONMENT;l=!d||"production"===d;f.restHost=l?q.REST_HOST:d+"-"+q.REST_HOST;f.realtimeHost=l?q.REALTIME_HOST:d+"-"+q.REALTIME_HOST}f.fallbackHosts=l||f.fallbackHostsUseDefault?q.FALLBACK_HOSTS:f.fallbackHosts;k.arrForEach((f.fallbackHosts||[]).concat(f.restHost,f.realtimeHost),ja);f.port=f.port||q.PORT;f.tlsPort=f.tlsPort||q.TLS_PORT;
  f.maxMessageSize=f.maxMessageSize||q.maxMessageSize;"tls"in f||(f.tls=!0);f.timeouts={};for(var a in q.TIMEOUTS)f.timeouts[a]=f[a]||q.TIMEOUTS[a];f.useBinaryProtocol="useBinaryProtocol"in f?v.supportsBinary&&f.useBinaryProtocol:v.preferBinary;f.clientId&&((f.headers=f.headers||{})["X-Ably-ClientId"]=A.base64Encode(A.utf8Encode(f.clientId)));"idempotentRestPublishing"in f||(f.idempotentRestPublishing=!1);f.promises&&!v.Promise&&(b.logAction(b.LOG_ERROR,"Defaults.normaliseOptions","{promises: true} was specified, but no Promise constructor found; disabling promises"),
  f.promises=!1);return f};var z=function(){function f(){this.any=[];this.events={};this.anyOnce=[];this.eventsOnce={}}function l(a,c,d){try{c.apply(a,d)}catch(e){b.logAction(b.LOG_ERROR,"EventEmitter.emit()","Unexpected listener exception: "+e+"; stack = "+(e&&e.stack))}}function d(a,c,b){var e,f,n;for(n=0;n<a.length;n++){var h=a[n];b&&(h=h[b]);if(k.isArray(h)){for(;-1!==(e=k.arrIndexOf(h,c));)h.splice(e,1);b&&0===h.length&&delete a[n][b]}else if(k.isObject(h))for(f in h)h.hasOwnProperty(f)&&k.isArray(h[f])&&
  d([h],c,f)}}f.prototype.on=function(a,b){if(1==arguments.length&&"function"==typeof a)this.any.push(a);else if(k.isEmptyArg(a))this.any.push(b);else if(k.isArray(a)){var c=this;k.arrForEach(a,function(a){c.on(a,b)})}else(this.events[a]||(this.events[a]=[])).push(b)};f.prototype.off=function(a,b){if(0==arguments.length||k.isEmptyArg(a)&&k.isEmptyArg(b))this.any=[],this.events={},this.anyOnce=[],this.eventsOnce={};else if(1==arguments.length&&"function"==typeof a&&(b=a,a=null),b&&k.isEmptyArg(a))d([this.any,
  this.events,this.anyOnce,this.eventsOnce],b);else{if(k.isArray(a)){var c=this;k.arrForEach(a,function(a){c.off(a,b)})}b?d([this.events,this.eventsOnce],b,a):(delete this.events[a],delete this.eventsOnce[a])}};f.prototype.listeners=function(a){if(a){var b=this.events[a]||[];this.eventsOnce[a]&&Array.prototype.push.apply(b,this.eventsOnce[a]);return b.length?b:null}return this.any.length?this.any:null};f.prototype.emit=function(a){var b=Array.prototype.slice.call(arguments,1),d={event:a},e=[];this.anyOnce.length&&
  (Array.prototype.push.apply(e,this.anyOnce),this.anyOnce=[]);this.any.length&&Array.prototype.push.apply(e,this.any);var f=this.eventsOnce[a];f&&(Array.prototype.push.apply(e,f),delete this.eventsOnce[a]);(f=this.events[a])&&Array.prototype.push.apply(e,f);k.arrForEach(e,function(a){l(d,a,b)})};f.prototype.once=function(a,b){var c=arguments.length,e=this;if((0===c||1===c&&"function"!==typeof a)&&v.Promise)return new v.Promise(function(b){e.once(a,b)});if(1==arguments.length&&"function"==typeof a)this.anyOnce.push(a);
  else if(k.isEmptyArg(a))this.anyOnce.push(b);else{if(k.isArray(a))throw"Arrays of events can only be used with on(), not once()";(this.eventsOnce[a]||(this.eventsOnce[a]=[])).push(b)}};f.prototype.whenState=function(a,b,d){var c={event:a},m=this,n=Array.prototype.slice.call(arguments,3);if("string"!==typeof a||"string"!==typeof b)throw"whenState requires a valid event String argument";if("function"!==typeof d&&v.Promise)return new v.Promise(function(c){f.prototype.whenState.apply(m,[a,b,c].concat(n))});
  if(a===b)l(c,d,n);else this.once(a,d)};return f}(),b=function(){function b(a,b){return("000"+a).slice(-2-(b||0))}function l(a){return v.logTimestamps?function(c){var e=new Date;a(b(e.getHours())+":"+b(e.getMinutes())+":"+b(e.getSeconds())+"."+b(e.getMilliseconds(),!0)+" "+c)}:a}function d(){}if("undefined"===typeof Window&&"undefined"===typeof WorkerGlobalScope||r.console&&r.console.log&&"function"===typeof r.console.log.apply){var a=function(){console.log.apply(console,arguments)};var c=console.warn?
  function(){console.warn.apply(console,arguments)}:a}else a=r.console&&r.console.log?c=function(){Function.prototype.apply.call(console.log,console,arguments)}:c=function(){};var n=1,e=l(a),m=l(c);d.LOG_NONE=0;d.LOG_ERROR=1;d.LOG_MAJOR=2;d.LOG_MINOR=3;d.LOG_MICRO=4;d.LOG_DEFAULT=1;d.LOG_DEBUG=4;d.logAction=function(a,b,c){d.shouldLog(a)&&(1===a?m:e)("Ably: "+b+": "+c)};d.deprecated=function(a,b){d.shouldLog(1)&&m("Ably: Deprecation warning - '"+a+"' is deprecated and will be removed from a future version. Please use '"+
  b+"' instead.")};d.shouldLog=function(a){return a<=n};d.setLog=function(a,b){void 0!==a&&(n=a);void 0!==b&&(e=m=b)};return d}(),Y=function(){return function(f){function l(){for(var d=0;d<f.length;d++){var a=f[d];if(a)try{a.apply(null,arguments)}catch(c){b.logAction(b.LOG_ERROR,"Multicaster multiple callback handler","Unexpected exception: "+c+"; stack = "+c.stack)}}}f=f||[];l.push=function(){Array.prototype.push.apply(f,arguments)};return l}}(),S=function(){function f(){}f.levels=["fatal","error",
  "warning","info","debug"];f.report=function(f,d,a,c){f={event_id:k.randomHexString(16),tags:k.mixin({lib:v.libver},c),platform:"javascript",level:f,release:q.version,fingerprint:a&&[a],message:d,request:{headers:{"User-Agent":v.userAgent},url:v.currentUrl}};b.logAction(b.LOG_MICRO,"ErrorReporter","POSTing to error reporter: "+d);x.postUri(null,q.errorReportingUrl,q.errorReportingHeaders,JSON.stringify(f),{},function(a,c){b.logAction(b.LOG_MICRO,"ErrorReporter","POSTing to error reporter resulted in: "+
  (a?k.inspectError(a):k.inspectBody(c)))})};return f}(),p=function(){function b(b,d,a,c){this.message=b;this.code=d;this.statusCode=a;this.cause=c;this.href=void 0}b.prototype.toString=function(){var b="["+this.constructor.name;this.message&&(b+=": "+this.message);this.statusCode&&(b+="; statusCode="+this.statusCode);this.code&&(b+="; code="+this.code);this.cause&&(b+="; cause="+k.inspectError(this.cause));!this.href||this.message&&-1<this.message.indexOf("help.ably.io")||(b+="; see "+this.href+" ");
  return b+"]"};b.fromValues=function(f){var d=k.mixin(new b,f);f instanceof Error&&(d.message=f.message);d.code&&!d.href&&(d.href="https://help.ably.io/error/"+d.code);return d};return b}(),B=function(){function f(){this.size=this.extras=this.encoding=this.data=this.connectionKey=this.connectionId=this.clientId=this.timestamp=this.id=this.name=void 0}function l(b){if(b&&b.cipher&&!b.cipher.channelCipher){if(!Crypto)throw Error("Encryption not enabled; use ably.encryption.js instead");var a=Crypto.getCipher(b.cipher);
  b.cipher=a.cipherParams;b.channelCipher=a.cipher}}f.prototype.toJSON=function(){var b={name:this.name,id:this.id,clientId:this.clientId,connectionId:this.connectionId,connectionKey:this.connectionKey,encoding:this.encoding,extras:this.extras},a=this.data;if(a&&A.isBuffer(a))if(0<arguments.length){var c=this.encoding;b.encoding=c?c+"/base64":"base64";a=A.base64Encode(a)}else a=A.toBuffer(a);b.data=a;return b};f.prototype.toString=function(){var b="[Message";this.name&&(b+="; name="+this.name);this.id&&
  (b+="; id="+this.id);this.timestamp&&(b+="; timestamp="+this.timestamp);this.clientId&&(b+="; clientId="+this.clientId);this.connectionId&&(b+="; connectionId="+this.connectionId);this.encoding&&(b+="; encoding="+this.encoding);this.extras&&(b+="; extras ="+JSON.stringify(this.extras));this.data&&(b="string"==typeof this.data?b+("; data="+this.data):A.isBuffer(this.data)?b+("; data (buffer)="+A.base64Encode(this.data)):b+("; data (json)="+JSON.stringify(this.data)));this.extras&&(b+="; extras="+JSON.stringify(this.extras));
  return b+"]"};f.encrypt=function(b,a,c){var d=b.data,e=b.encoding,f=a.channelCipher;e=e?e+"/":"";A.isBuffer(d)||(d=A.utf8Encode(String(d)),e+="utf-8/");f.encrypt(d,function(a,d){a?c(a):(b.data=d,b.encoding=e+"cipher+"+f.algorithm,c(null,b))})};f.encode=function(b,a,c){var d=b.data,e;if("string"!=typeof d&&!A.isBuffer(d)&&null!==d&&void 0!==d)if(k.isObject(d)||k.isArray(d))b.data=JSON.stringify(d),b.encoding=(e=b.encoding)?e+"/json":"json";else throw new p("Data type is unsupported",40013,400);null!=
  a&&a.cipher?f.encrypt(b,a,c):c(null,b)};f.encodeArray=function(b,a,c){for(var d=0,e=0;e<b.length;e++)f.encode(b[e],a,function(a){a?c(a):(d++,d==b.length&&c(null,b))})};f.serialize=k.encodeBody;f.decode=function(b,a){var c=b.encoding;if(c){c=c.split("/");var d,e=c.length,f=b.data;try{for(;0<(d=e);){var l=c[--e].match(/([\-\w]+)(\+([\w\-]+))?/);if(!l)break;var h=l[1];switch(h){case "base64":f=A.base64Decode(String(f));continue;case "utf-8":f=A.utf8Decode(f);continue;case "json":f=JSON.parse(f);continue;
  case "cipher":if(null!=a&&a.cipher){var u=a.channelCipher;if(l[3]!=u.algorithm)throw Error("Unable to decrypt message with given cipher; incompatible cipher params");f=u.decrypt(f);continue}else throw Error("Unable to decrypt message; not an encrypted channel");default:throw Error("Unknown encoding");}}}catch(g){throw new p("Error processing the "+h+" encoding, decoder returned \u2018"+g.message+"\u2019",40013,400);}finally{b.encoding=0>=d?null:c.slice(0,d).join("/"),b.data=f}}};f.fromResponseBody=
  function(d,a,c){c&&(d=k.decodeBody(d,c));for(c=0;c<d.length;c++){var n=d[c]=f.fromValues(d[c]);try{f.decode(n,a)}catch(e){b.logAction(b.LOG_ERROR,"Message.fromResponseBody()",e.toString())}}return d};f.fromValues=function(b){return k.mixin(new f,b)};f.fromValuesArray=function(b){for(var a=b.length,c=Array(a),d=0;d<a;d++)c[d]=f.fromValues(b[d]);return c};f.fromEncoded=function(d,a){var c=f.fromValues(d);l(a);try{f.decode(c,a)}catch(n){b.logAction(b.LOG_ERROR,"Message.fromEncoded()",n.toString())}return c};
  f.fromEncodedArray=function(b,a){l(a);return k.arrMap(b,function(b){return f.fromEncoded(b,a)})};f.getMessagesSize=function(b){for(var a,c=0,d=0;d<b.length;d++){a=b[d];var e;if(!(e=a.size)){e=a;var f=0;a.name&&(f+=a.name.length);a.clientId&&(f+=a.clientId.length);a.extras&&(f+=JSON.stringify(a.extras).length);a.data&&(f+=k.dataSizeBytes(a.data));e=e.size=f}c+=e}return c};return f}(),F=function(){function f(){this.size=this.encoding=this.data=this.connectionId=this.clientId=this.timestamp=this.id=
  this.action=void 0}f.Actions=["absent","present","enter","leave","update"];f.prototype.isSynthesized=function(){return this.id.substring(this.connectionId.length,0)!==this.connectionId};f.prototype.parseId=function(){var b=this.id.split(":");return{connectionId:b[0],msgSerial:parseInt(b[1],10),index:parseInt(b[2],10)}};f.prototype.toJSON=function(){var b={clientId:this.clientId,action:k.arrIndexOf(f.Actions,this.action),encoding:this.encoding},d=this.data;if(d&&A.isBuffer(d))if(0<arguments.length){var a=
  this.encoding;b.encoding=a?a+"/base64":"base64";d=A.base64Encode(d)}else d=A.toBuffer(d);b.data=d;return b};f.prototype.toString=function(){var b="[PresenceMessage; action="+this.action;this.id&&(b+="; id="+this.id);this.timestamp&&(b+="; timestamp="+this.timestamp);this.clientId&&(b+="; clientId="+this.clientId);this.connectionId&&(b+="; connectionId="+this.connectionId);this.encoding&&(b+="; encoding="+this.encoding);this.data&&(b="string"==typeof this.data?b+("; data="+this.data):A.isBuffer(this.data)?
  b+("; data (buffer)="+A.base64Encode(this.data)):b+("; data (json)="+JSON.stringify(this.data)));return b+"]"};f.encode=B.encode;f.decode=B.decode;f.fromResponseBody=function(l,d,a){a&&(l=k.decodeBody(l,a));for(a=0;a<l.length;a++){var c=l[a]=f.fromValues(l[a],!0);try{f.decode(c,d)}catch(n){b.logAction(b.LOG_ERROR,"PresenceMessage.fromResponseBody()",n.toString())}}return l};f.fromValues=function(b,d){d&&(b.action=f.Actions[b.action]);return k.mixin(new f,b)};f.fromValuesArray=function(b){for(var d=
  b.length,a=Array(d),c=0;c<d;c++)a[c]=f.fromValues(b[c]);return a};f.fromEncoded=function(l,d){var a=f.fromValues(l,!0);try{f.decode(a,d)}catch(c){b.logAction(b.LOG_ERROR,"PresenceMessage.fromEncoded()",c.toString())}return a};f.fromEncodedArray=function(b,d){return k.arrMap(b,function(a){return f.fromEncoded(a,d)})};f.getMessagesSize=B.getMessagesSize;return f}(),y=function(){function b(){this.auth=this.presence=this.messages=this.msgSerial=this.channelSerial=this.channel=this.connectionSerial=this.connectionKey=
  this.connectionId=this.error=this.count=this.timestamp=this.id=this.flags=this.action=void 0}function l(a){var b=[];if(a)for(var c=0;c<a.length;c++)b.push(a[c].toString());return"[ "+b.join(", ")+" ]"}var d=b.Action={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};b.ActionName=[];k.arrForEach(k.keysArray(b.Action,!0),function(a){b.ActionName[d[a]]=a});var a={HAS_PRESENCE:1,
  HAS_BACKLOG:2,RESUMED:4,TRANSIENT:16,PRESENCE:65536,PUBLISH:131072,SUBSCRIBE:262144,PRESENCE_SUBSCRIBE:524288},c=k.keysArray(a);a.MODE_ALL=a.PRESENCE|a.PUBLISH|a.SUBSCRIBE|a.PRESENCE_SUBSCRIBE;b.prototype.hasFlag=function(b){return 0<(this.flags&a[b])};b.prototype.setFlag=function(b){return this.flags|=a[b]};b.prototype.getMode=function(){return this.flags&&this.flags&a.MODE_ALL};b.serialize=k.encodeBody;b.deserialize=function(a,c){var e=k.decodeBody(a,c);return b.fromDeserialized(e)};b.fromDeserialized=
  function(a){var c=a.error;c&&(a.error=p.fromValues(c));var e=a.messages;if(e)for(c=0;c<e.length;c++)e[c]=B.fromValues(e[c]);if(e=a.presence)for(c=0;c<e.length;c++)e[c]=F.fromValues(e[c],!0);return k.mixin(new b,a)};b.fromValues=function(a){return k.mixin(new b,a)};var n="id channel channelSerial connectionId connectionKey connectionSerial count msgSerial timestamp".split(" ");b.stringify=function(a){var e="[ProtocolMessage";void 0!==a.action&&(e+="; action="+b.ActionName[a.action]||a.action);for(var d,
  h=0;h<n.length;h++)d=n[h],void 0!==a[d]&&(e+="; "+d+"="+a[d]);a.messages&&(e+="; messages="+l(B.fromValuesArray(a.messages)));a.presence&&(e+="; presence="+l(F.fromValuesArray(a.presence)));a.error&&(e+="; error="+p.fromValues(a.error).toString());a.auth&&a.auth.accessToken&&(e+="; token="+a.auth.accessToken);a.flags&&(e+="; flags="+k.arrFilter(c,function(b){return a.hasFlag(b)}).join(","));return e+"]"};b.isDuplicate=function(a,b){return a&&b&&(a.action===d.MESSAGE||a.action===d.PRESENCE)&&a.action===
  b.action&&a.channel===b.channel&&a.id===b.id};return b}(),ma=function(){function b(a){this.count=a&&a.count||0;this.data=a&&a.data||0;this.uncompressedData=a&&a.uncompressedData||0;this.failed=a&&a.failed||0;this.refused=a&&a.refused||0}function l(a){b.call(this,a);this.category=void 0;if(a&&a.category){this.category={};for(var c in a.category){var g=a.category[c];Object.prototype.hasOwnProperty.call(a.category,c)&&g&&(this.category[c]=new b(g))}}}function d(a){this.peak=a&&a.peak||0;this.min=a&&
  a.min||0;this.mean=a&&a.mean||0;this.opened=a&&a.opened||0;this.refused=a&&a.refused||0}function a(a){this.succeeded=a&&a.succeeded||0;this.failed=a&&a.failed||0;this.refused=a&&a.refused||0}function c(a){this.plain=new d(a&&a.plain);this.tls=new d(a&&a.tls);this.all=new d(a&&a.all)}function n(a){this.messages=new l(a&&a.messages);this.presence=new l(a&&a.presence);this.all=new l(a&&a.all)}function e(a){this.realtime=new n(a&&a.realtime);this.rest=new n(a&&a.rest);this.webhook=new n(a&&a.webhook);
  this.sharedQueue=new n(a&&a.sharedQueue);this.externalQueue=new n(a&&a.externalQueue);this.httpEvent=new n(a&&a.httpEvent);this.push=new n(a&&a.push);this.all=new n(a&&a.all)}function m(a){this.all=new n(a&&a.all);this.inbound=new e(a&&a.inbound);this.outbound=new e(a&&a.outbound)}function k(a){this.all=new n(a&&a.all);this.producerPaid=new m(a&&a.producerPaid);this.consumerPaid=new m(a&&a.consumerPaid)}function h(a){this.messages=a&&a.messages||0;var b=a&&a.notifications;this.notifications={invalid:b&&
  b.invalid||0,attempted:b&&b.attempted||0,successful:b&&b.successful||0,failed:b&&b.failed||0};this.directPublishes=a&&a.directPublishes||0}function u(a){this.succeeded=a&&a.succeeded||0;this.skipped=a&&a.skipped||0;this.failed=a&&a.failed||0}function g(a){this.delta=void 0;if(a&&a.delta){this.delta={};for(var b in a.delta){var c=a.delta[b];Object.prototype.hasOwnProperty.call(a.delta,b)&&c&&(this.delta[b]=new u(c))}}}function w(b){m.call(this,b);this.persisted=new n(b&&b.persisted);this.connections=
  new c(b&&b.connections);this.channels=new d(b&&b.channels);this.apiRequests=new a(b&&b.apiRequests);this.tokenRequests=new a(b&&b.tokenRequests);this.xchgProducer=new k(b&&b.xchgProducer);this.xchgConsumer=new k(b&&b.xchgConsumer);this.push=new h(b&&b.pushStats);this.processed=new g(b&&b.processed);this.inProgress=b&&b.inProgress||void 0;this.unit=b&&b.unit||void 0;this.intervalId=b&&b.intervalId||void 0}w.fromValues=function(a){return new w(a)};return w}(),T=function(){function b(){this.deviceIdentityToken=
  this.metadata=this.clientId=this.formFactor=this.platform=this.deviceSecret=this.id=void 0;this.push={recipient:void 0,state:void 0,errorReason:void 0}}b.prototype.toJSON=function(){return{id:this.id,deviceSecret:this.deviceSecret,platform:this.platform,formFactor:this.formFactor,clientId:this.clientId,metadata:this.metadata,deviceIdentityToken:this.deviceIdentityToken,push:{recipient:this.push.recipient,state:this.push.state,errorReason:this.push.errorReason}}};b.prototype.toString=function(){var b=
  "[DeviceDetails";this.id&&(b+="; id="+this.id);this.platform&&(b+="; platform="+this.platform);this.formFactor&&(b+="; formFactor="+this.formFactor);this.clientId&&(b+="; clientId="+this.clientId);this.metadata&&(b+="; metadata="+this.metadata);this.deviceIdentityToken&&(b+="; deviceIdentityToken="+JSON.stringify(this.deviceIdentityToken));this.push.recipient&&(b+="; push.recipient="+JSON.stringify(this.push.recipient));this.push.state&&(b+="; push.state="+this.push.state);this.push.errorReason&&
  (b+="; push.errorReason="+this.push.errorReason);this.push.metadata&&(b+="; push.metadata="+this.push.metadata);return b+"]"};b.toRequestBody=k.encodeBody;b.fromResponseBody=function(f,d){d&&(f=k.decodeBody(f,d));return k.isArray(f)?b.fromValuesArray(f):b.fromValues(f)};b.fromValues=function(f){return k.mixin(new b,f)};b.fromValuesArray=function(f){for(var d=f.length,a=Array(d),c=0;c<d;c++)a[c]=b.fromValues(f[c]);return a};return b}(),Z=function(){function b(){this.clientId=this.deviceId=this.channel=
  void 0}b.prototype.toJSON=function(){return{channel:this.channel,deviceId:this.deviceId,clientId:this.clientId}};b.prototype.toString=function(){var b="[PushChannelSubscription";this.channel&&(b+="; channel="+this.channel);this.deviceId&&(b+="; deviceId="+this.deviceId);this.clientId&&(b+="; clientId="+this.clientId);return b+"]"};b.toRequestBody=k.encodeBody;b.fromResponseBody=function(f,d){d&&(f=k.decodeBody(f,d));return k.isArray(f)?b.fromValuesArray(f):b.fromValues(f)};b.fromValues=function(f){return k.mixin(new b,
  f)};b.fromValuesArray=function(f){for(var d=f.length,a=Array(d),c=0;c<d;c++)a[c]=b.fromValues(f[c]);return a};return b}(),K={disconnected:p.fromValues({statusCode:400,code:80003,message:"Connection to server temporarily unavailable"}),suspended:p.fromValues({statusCode:400,code:80002,message:"Connection to server unavailable"}),failed:p.fromValues({statusCode:400,code:8E4,message:"Connection failed or disconnected by server"}),closing:p.fromValues({statusCode:400,code:80017,message:"Connection closing"}),
  closed:p.fromValues({statusCode:400,code:80017,message:"Connection closed"}),unknownConnectionErr:p.fromValues({statusCode:500,code:50002,message:"Internal connection error"}),unknownChannelErr:p.fromValues({statusCode:500,code:50001,message:"Internal channel error"})},fa=function(){function f(){z.call(this);this.messages=[]}k.inherits(f,z);f.prototype.count=function(){return this.messages.length};f.prototype.push=function(b){this.messages.push(b)};f.prototype.shift=function(){return this.messages.shift()};
  f.prototype.last=function(){return this.messages[this.messages.length-1]};f.prototype.copyAll=function(){return this.messages.slice()};f.prototype.append=function(b){this.messages.push.apply(this.messages,b)};f.prototype.prepend=function(b){this.messages.unshift.apply(this.messages,b)};f.prototype.completeMessages=function(f,d,a){b.logAction(b.LOG_MICRO,"MessageQueue.completeMessages()","serial = "+f+"; count = "+d);a=a||null;var c=this.messages,n=c[0];if(n){n=n.message.msgSerial;f+=d;if(f>n)for(f=
  c.splice(0,f-n),d=0;d<f.length;d++)f[d].callback(a);0==c.length&&this.emit("idle")}};f.prototype.completeAllMessages=function(b){this.completeMessages(0,Number.MAX_SAFE_INTEGER||Number.MAX_VALUE,b)};f.prototype.clear=function(){b.logAction(b.LOG_MICRO,"MessageQueue.clear()","clearing "+this.messages.length+" messages");this.messages=[];this.emit("idle")};return f}(),ha=function(){function f(b){z.call(this);this.transport=b;this.messageQueue=new fa;var a=this;b.on("ack",function(b,d){a.onAck(b,d)});
  b.on("nack",function(b,d,e){a.onNack(b,d,e)})}var l=y.Action;k.inherits(f,z);f.prototype.onAck=function(d,a){b.logAction(b.LOG_MICRO,"Protocol.onAck()","serial = "+d+"; count = "+a);this.messageQueue.completeMessages(d,a)};f.prototype.onNack=function(d,a,c){b.logAction(b.LOG_ERROR,"Protocol.onNack()","serial = "+d+"; count = "+a+"; err = "+k.inspectError(c));c||(c=new p("Unable to send message; channel not responding",50001,500));this.messageQueue.completeMessages(d,a,c)};f.prototype.onceIdle=function(b){var a=
  this.messageQueue;if(0===a.count())b();else a.once("idle",b)};f.prototype.send=function(d){d.ackRequired&&this.messageQueue.push(d);b.shouldLog(b.LOG_MICRO)&&b.logAction(b.LOG_MICRO,"Protocol.send()","sending msg; "+y.stringify(d.message));d.sendAttempted=!0;this.transport.send(d.message)};f.prototype.getTransport=function(){return this.transport};f.prototype.getPendingMessages=function(){return this.messageQueue.copyAll()};f.prototype.clearPendingMessages=function(){return this.messageQueue.clear()};
  f.prototype.finish=function(){var b=this.transport;this.onceIdle(function(){b.disconnect()})};f.PendingMessage=function(b,a){this.message=b;this.callback=a;this.merged=!1;var c=b.action;this.sendAttempted=!1;this.ackRequired=c==l.MESSAGE||c==l.PRESENCE};return f}(),N=function(){function f(){}function l(a,b){return k.arrIndexOf(h,a.shortName)>k.arrIndexOf(h,b.shortName)}function d(a,b,c,e){this.options=a;this.host=b;this.mode=c;this.connectionKey=e;this.format=a.useBinaryProtocol?"msgpack":"json";
  this.timeSerial=this.connectionSerial=void 0}function a(c,d){z.call(this);this.realtime=c;this.options=d;var g=d.timeouts,h=this;this.states={initialized:{state:"initialized",terminal:!1,queueEvents:!0,sendEvents:!1,failState:"disconnected"},connecting:{state:"connecting",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:g.preferenceConnectTimeout+g.realtimeRequestTimeout,failState:"disconnected"},connected:{state:"connected",terminal:!1,queueEvents:!1,sendEvents:!0,failState:"disconnected"},synchronizing:{state:"connected",
  terminal:!1,queueEvents:!0,sendEvents:!1,forceQueueEvents:!0,failState:"disconnected"},disconnected:{state:"disconnected",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:g.disconnectedRetryTimeout,failState:"disconnected"},suspended:{state:"suspended",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:g.suspendedRetryTimeout,failState:"suspended"},closing:{state:"closing",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:g.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 fa;this.msgSerial=0;this.connectionSerial=this.timeSerial=this.connectionKey=this.connectionId=this.connectionDetails=void 0;this.connectionStateTtl=g.connectionStateTtl;this.maxIdleInterval=null;this.transports=k.intersect(d.transports||q.defaultTransports,a.supportedTransports);this.baseTransport=
  k.intersect(q.baseTransportOrder,this.transports)[0];this.upgradeTransports=k.intersect(this.transports,q.upgradeTransports);this.transportPreference=null;this.httpHosts=q.getHosts(d);this.activeProtocol=null;this.proposedTransports=[];this.pendingTransports=[];this.mostRecentMsg=this.lastActivity=this.lastAutoReconnectAttempt=this.host=null;this.forceFallbackHost=!1;this.connectCounter=0;b.logAction(b.LOG_MINOR,"Realtime.ConnectionManager()","started");b.logAction(b.LOG_MICRO,"Realtime.ConnectionManager()",
  "requested transports = ["+(d.transports||q.defaultTransports)+"]");b.logAction(b.LOG_MICRO,"Realtime.ConnectionManager()","available transports = ["+this.transports+"]");b.logAction(b.LOG_MICRO,"Realtime.ConnectionManager()","http hosts = ["+this.httpHosts+"]");if(!this.transports.length)throw b.logAction(b.LOG_ERROR,"realtime.ConnectionManager()","no requested transports available"),Error("no requested transports available");if(g=v.addEventListener)e&&"function"===typeof d.recover&&g("beforeunload",
  this.persistConnection.bind(this)),!0===d.closeOnUnload&&g("beforeunload",function(){b.logAction(b.LOG_MAJOR,"Realtime.ConnectionManager()","beforeunload event has triggered the connection to close as closeOnUnload is true");h.requestState({state:"closing"})}),g("online",function(){if(h.state==h.states.disconnected||h.state==h.states.suspended)b.logAction(b.LOG_MINOR,"ConnectionManager caught browser \u2018online\u2019 event","reattempting connection"),h.requestState({state:"connecting"})}),g("offline",
  function(){h.state==h.states.connected&&(b.logAction(b.LOG_MINOR,"ConnectionManager caught browser \u2018offline\u2019 event","disconnecting active transport"),h.disconnectAllTransports())})}function c(a,b,c){var g;if(a.channel!==b.channel||(g=a.action)!==m.PRESENCE&&g!==m.MESSAGE||g!==b.action)return!1;g=g===m.PRESENCE?"presence":"messages";b=a[g].concat(b[g]);if(B.getMessagesSize(b)>c||!k.allSame(b,"clientId")||!k.arrEvery(b,function(a){return!a.id}))return!1;a[g]=b;return!0}var n=!("undefined"===
  typeof J||!J.get),e=!("undefined"===typeof J||!J.getSession),m=y.Action,t=ha.PendingMessage,h=q.transportPreferenceOrder,u=h[h.length-1];d.prototype.getConnectParams=function(a){a=a?k.copy(a):{};var b=this.options;switch(this.mode){case "upgrade":a.upgrade=this.connectionKey;break;case "resume":a.resume=this.connectionKey;void 0!==this.timeSerial?a.timeSerial=this.timeSerial:void 0!==this.connectionSerial&&(a.connectionSerial=this.connectionSerial);break;case "recover":var c=b.recover.split(":");
  c&&(a.recover=c[0],c=c[1],isNaN(c)?a.timeSerial=c:a.connectionSerial=c)}void 0!==b.clientId&&(a.clientId=b.clientId);!1===b.echoMessages&&(a.echo="false");void 0!==this.format&&(a.format=this.format);void 0!==this.stream&&(a.stream=this.stream);void 0!==this.heartbeats&&(a.heartbeats=this.heartbeats);a.v=q.apiVersion;a.lib=q.libstring;void 0!==b.transportParams&&k.mixin(a,b.transportParams);return a};d.prototype.toString=function(){var a="[mode="+this.mode;this.host&&(a+=",host="+this.host);this.connectionKey&&
  (a+=",connectionKey="+this.connectionKey);void 0!==this.connectionSerial&&(a+=",connectionSerial="+this.connectionSerial);this.timeSerial&&(a+=",timeSerial="+this.timeSerial);this.format&&(a+=",format="+this.format);return a+"]"};k.inherits(a,z);a.supportedTransports={};a.prototype.createTransportParams=function(a,b){var c=new d(this.options,a,b,this.connectionKey);this.timeSerial?c.timeSerial=this.timeSerial:void 0!==this.connectionSerial&&(c.connectionSerial=this.connectionSerial);return c};a.prototype.getTransportParams=
  function(a){var c=this;(function(a){if(c.connectionKey)a("resume");else if("string"===typeof c.options.recover)a("recover");else{var g=c.options.recover,d=e&&J.getSession("ably-connection-recovery");d&&"function"===typeof g?(b.logAction(b.LOG_MINOR,"ConnectionManager.getTransportParams()","Calling clientOptions-provided recover function with last session data"),g(d,function(b){b?(c.options.recover=d.recoveryKey,a("recover")):a("clean")})):a("clean")}})(function(g){var e=c.createTransportParams(null,
  g);"recover"===g?(b.logAction(b.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport recovery mode = recover; recoveryKey = "+c.options.recover),(g=c.options.recover.split(":"))&&g[2]&&(c.msgSerial=g[2])):b.logAction(b.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport params = "+e.toString());a(e)})};a.prototype.tryATransport=function(c,e,d){var g=this;b.logAction(b.LOG_MICRO,"ConnectionManager.tryATransport()","trying "+e);a.supportedTransports[e].tryConnect(this,this.realtime.auth,
  c,function(a,h){var f=g.state;f==g.states.closing||f==g.states.closed||f==g.states.failed?(h&&(b.logAction(b.LOG_MINOR,"ConnectionManager.tryATransport()","connection "+f.state+" while we were attempting the transport; closing "+h),h.close()),d(!0)):a?(b.logAction(b.LOG_MINOR,"ConnectionManager.tryATransport()","transport "+e+" "+a.event+", err: "+a.error.toString()),M.isTokenErr(a.error)?g.realtime.auth._forceNewToken(null,null,function(a){a?g.actOnErrorFromAuthorize(a):g.tryATransport(c,e,d)}):
  "failed"===a.event?(g.notifyState({state:"failed",error:a.error}),d(!0)):"disconnected"===a.event&&d(!1)):(b.logAction(b.LOG_MICRO,"ConnectionManager.tryATransport()","viable transport "+e+"; setting pending"),g.setTransportPending(h,c),d(null,h))})};a.prototype.setTransportPending=function(a,c){var g=c.mode;b.logAction(b.LOG_MINOR,"ConnectionManager.setTransportPending()","transport = "+a+"; mode = "+g);k.arrDeleteValue(this.proposedTransports,a);this.pendingTransports.push(a);var e=this;a.once("connected",
  function(b,d,h,f){"upgrade"==g&&e.activeProtocol?a.shortName!==u&&k.arrIn(e.getUpgradePossibilities(),u)?setTimeout(function(){e.scheduleTransportActivation(b,a,d,h,f)},e.options.timeouts.parallelUpgradeDelay):e.scheduleTransportActivation(b,a,d,h,f):(e.activateTransport(b,a,d,h,f),k.nextTick(function(){e.connectImpl(c)}));"recover"===g&&e.options.recover&&(e.options.recover=null,e.unpersistConnection())});a.on(["disconnected","closed","failed"],function(b){e.deactivateTransport(a,this.event,b)});
  this.emit("transport.pending",a)};a.prototype.scheduleTransportActivation=function(a,c,e,d,h){function g(){c.disconnect();k.arrDeleteValue(f.pendingTransports,c)}var f=this,m=this.activeProtocol&&this.activeProtocol.getTransport();this.state!==this.states.connected&&this.state!==this.states.connecting?(b.logAction(b.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Current connection state ("+this.state.state+(this.state===this.states.synchronizing?", but with an upgrade already in progress":
  "")+") is not valid to upgrade in; abandoning upgrade to "+c.shortName),g()):m&&!l(c,m)?(b.logAction(b.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Proposed transport "+c.shortName+" is no better than current active transport "+m.shortName+" - abandoning upgrade"),g()):(b.logAction(b.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Scheduling transport upgrade; transport = "+c),this.realtime.channels.onceNopending(function(m){if(m)b.logAction(b.LOG_ERROR,"ConnectionManager.scheduleTransportActivation()",
  "Unable to activate transport; transport = "+c+"; err = "+m);else if(c.isConnected){if(f.state===f.states.connected){b.logAction(b.LOG_MICRO,"ConnectionManager.scheduleTransportActivation()","Currently connected, so temporarily pausing events until the upgrade is complete");f.state=f.states.synchronizing;var n=f.activeProtocol}else if(f.state!==f.states.connecting){b.logAction(b.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Current connection state ("+f.state.state+(f.state===f.states.synchronizing?
  ", but with an upgrade already in progress":"")+") is not valid to upgrade in; abandoning upgrade to "+c.shortName);g();return}var u=(m=e!==f.connectionId)?h:f;m&&b.logAction(b.LOG_ERROR,"ConnectionManager.scheduleTransportActivation()","Upgrade resulted in new connectionId; resetting library connection position from "+(f.timeSerial||f.connectionSerial)+" to "+(u.timeSerial||u.connectionSerial)+"; upgrade error was "+a);b.logAction(b.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Syncing transport; transport = "+
  c);f.sync(c,u,function(g,e,h){if(g)f.state===f.states.synchronizing&&(b.logAction(b.LOG_ERROR,"ConnectionManager.scheduleTransportActivation()","Unexpected error attempting to sync transport; transport = "+c+"; err = "+g),f.disconnectAllTransports());else if(g=function(){b.logAction(b.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Activating transport; transport = "+c);f.activateTransport(a,c,e,d,h);f.state===f.states.synchronizing?(b.logAction(b.LOG_MICRO,"ConnectionManager.scheduleTransportActivation()",
  "Pre-upgrade protocol idle, sending queued messages on upgraded transport; transport = "+c),f.state=f.states.connected):b.logAction(b.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Pre-upgrade protocol idle, but state is now "+f.state.state+", so leaving unchanged");f.state.sendEvents&&f.sendQueuedMessages()},n)n.onceIdle(g);else g()})}else b.logAction(b.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Proposed transport "+c.shortName+"is no longer connected; abandoning upgrade"),
  g()}))};a.prototype.activateTransport=function(a,c,e,d,h){b.logAction(b.LOG_MINOR,"ConnectionManager.activateTransport()","transport = "+c);a&&b.logAction(b.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+a);e&&b.logAction(b.LOG_MICRO,"ConnectionManager.activateTransport()","connectionId =  "+e);d&&b.logAction(b.LOG_MICRO,"ConnectionManager.activateTransport()","connectionDetails =  "+JSON.stringify(d));h&&b.logAction(b.LOG_MICRO,"ConnectionManager.activateTransport()","serial =  "+(h.timeSerial||
  h.connectionSerial));this.persistTransportPreference(c);var g=this.state,f=this.states.connected.state;b.logAction(b.LOG_MINOR,"ConnectionManager.activateTransport()","current state = "+g.state);if(g.state==this.states.closing.state||g.state==this.states.closed.state||g.state==this.states.failed.state)return b.logAction(b.LOG_MINOR,"ConnectionManager.activateTransport()","Disconnecting transport and abandoning"),c.disconnect(),!1;k.arrDeleteValue(this.pendingTransports,c);if(!c.isConnected)return b.logAction(b.LOG_MINOR,
  "ConnectionManager.activateTransport()","Declining to activate transport "+c+" since it appears to no longer be connected"),!1;var m=this.activeProtocol;this.activeProtocol=new ha(c);this.host=c.params.host;var n=d.connectionKey;n&&this.connectionKey!=n&&this.setConnection(e,d,h,!!a);this.onConnectionDetailsUpdate(d,c);var u=this;k.nextTick(function(){c.on("connected",function(a,b,e){u.onConnectionDetailsUpdate(e,c);u.emit("update",new R(f,f,null,a))})});g.state===this.states.connected.state?a&&(this.errorReason=
  this.realtime.connection.errorReason=a,this.emit("update",new R(f,f,null,a))):(this.notifyState({state:"connected",error:a}),this.errorReason=this.realtime.connection.errorReason=a||null);this.emit("transport.active",c);m&&(0<m.messageQueue.count()&&b.logAction(b.LOG_ERROR,"ConnectionManager.activateTransport()","Previous active protocol (for transport "+m.transport.shortName+", new one is "+c.shortName+") finishing with "+m.messageQueue.count()+" messages still pending"),m.transport===c?(a="Assumption violated: activating a transport that was also the transport for the previous active protocol; transport = "+
  c.shortName+"; stack = "+Error().stack,b.logAction(b.LOG_ERROR,"ConnectionManager.activateTransport()",a),S.report("error",a,"transport-previously-active")):m.finish());k.safeArrForEach(this.pendingTransports,function(a){a===c?(a="Assumption violated: activating a transport that is still marked as a pending transport; transport = "+c.shortName+"; stack = "+Error().stack,b.logAction(b.LOG_ERROR,"ConnectionManager.activateTransport()",a),S.report("error",a,"transport-activating-pending"),k.arrDeleteValue(u.pendingTransports,
  c)):a.disconnect()});k.safeArrForEach(this.proposedTransports,function(a){a===c?(a="Assumption violated: activating a transport that is still marked as a proposed transport; transport = "+c.shortName+"; stack = "+Error().stack,b.logAction(b.LOG_ERROR,"ConnectionManager.activateTransport()",a),S.report("error",a,"transport-activating-proposed"),k.arrDeleteValue(u.proposedTransports,c)):a.dispose()});return!0};a.prototype.deactivateTransport=function(a,c,e){var g=this.activeProtocol,d=g&&g.getTransport()===
  a,h=k.arrDeleteValue(this.pendingTransports,a),f=k.arrDeleteValue(this.proposedTransports,a),m=this.noTransportsScheduledForActivation();b.logAction(b.LOG_MINOR,"ConnectionManager.deactivateTransport()","transport = "+a);b.logAction(b.LOG_MINOR,"ConnectionManager.deactivateTransport()","state = "+c+(d?"; was active":h?"; was pending":f?"; was proposed":"")+(m?"":"; another transport is scheduled for activation"));e&&e.message&&b.logAction(b.LOG_MICRO,"ConnectionManager.deactivateTransport()","reason =  "+
  e.message);d&&(b.logAction(b.LOG_MICRO,"ConnectionManager.deactivateTransport()","Getting, clearing, and requeuing "+this.activeProtocol.messageQueue.count()+" pending messages"),this.queuePendingMessages(g.getPendingMessages()),k.nextTick(function(){g.clearPendingMessages()}),this.activeProtocol=this.host=null,clearTimeout(this.channelResumeCheckTimer));this.emit("transport.inactive",a);d&&m||d&&"failed"===c||"closed"===c||null===g&&h&&0===this.pendingTransports.length?"disconnected"===c&&e&&500<
  e.statusCode&&1<this.httpHosts.length?(this.unpersistTransportPreference(),this.forceFallbackHost=!0,this.notifyState({state:c,error:e,retryImmediately:!0})):(a="failed"===c&&M.isTokenErr(e)?"disconnected":c,this.notifyState({state:a,error:e})):d&&"disconnected"===c&&this.state!==this.states.synchronizing&&(b.logAction(b.LOG_MICRO,"ConnectionManager.deactivateTransport()","wasActive but another transport is connected and scheduled for activation, so going into the connecting state until it activates"),
  this.startSuspendTimer(),this.startTransitionTimer(this.states.connecting),this.notifyState({state:"connecting",error:e}))};a.prototype.noTransportsScheduledForActivation=function(){return k.isEmpty(this.pendingTransports)||this.pendingTransports.every(function(a){return!a.isConnected})};a.prototype.sync=function(a,b,c){var e=setTimeout(function(){a.off("sync");c(new p("Timeout waiting for sync response",5E4,500))},this.options.timeouts.realtimeRequestTimeout),g=y.fromValues({action:m.SYNC,connectionKey:this.connectionKey});
  b.timeSerial?g.timeSerial=b.timeSerial:void 0!==b.connectionSerial&&(g.connectionSerial=b.connectionSerial);a.send(g);a.once("sync",function(a,b){clearTimeout(e);c(null,a,b)})};a.prototype.setConnection=function(a,c,e,d){var g=this,h=this.connectionid,f=h&&h!==a;if(f||!h&&d)b.logAction(b.LOG_MINOR,"ConnectionManager.setConnection()","Resetting msgSerial"),this.msgSerial=0;this.connectionId!==a?(b.logAction(b.LOG_MINOR,"ConnectionManager.setConnection()","New connectionId; reattaching any attached channels"),
  k.nextTick(function(){g.realtime.channels.reattach()})):this.options.checkChannelsOnResume&&(b.logAction(b.LOG_MINOR,"ConnectionManager.setConnection()","Same connectionId; checkChannelsOnResume is enabled"),clearTimeout(this.channelResumeCheckTimer),this.realtime.channels.resetAttachedMsgIndicators(),this.channelResumeCheckTimer=setTimeout(function(){g.realtime.channels.checkAttachedMsgIndicators(a)},3E4));this.realtime.connection.id=this.connectionId=a;this.realtime.connection.key=this.connectionKey=
  c.connectionKey;this.setConnectionSerial(e,f||!h)};a.prototype.clearConnection=function(){this.realtime.connection.id=this.connectionId=void 0;this.realtime.connection.key=this.connectionKey=void 0;this.clearConnectionSerial();this.msgSerial=0;this.unpersistConnection()};a.prototype.setConnectionSerial=function(a,c){var e=a.timeSerial,g=a.connectionSerial;b.logAction(b.LOG_MICRO,"ConnectionManager.setConnectionSerial()","Updating connection serial; serial = "+g+"; timeSerial = "+e+"; force = "+c+
  "; previous = "+this.connectionSerial);if(void 0!==e){if(e<=this.timeSerial&&!c)return b.logAction(b.LOG_ERROR,"ConnectionManager.setConnectionSerial()","received message with timeSerial "+e+", but current timeSerial is "+this.timeSerial+"; assuming message is a duplicate and discarding it"),!0;this.realtime.connection.timeSerial=this.timeSerial=e;this.setRecoveryKey()}else if(void 0!==g){if(g<=this.connectionSerial&&!c)return b.logAction(b.LOG_ERROR,"ConnectionManager.setConnectionSerial()","received message with connectionSerial "+
  g+", but current connectionSerial is "+this.connectionSerial+"; assuming message is a duplicate and discarding it"),!0;this.realtime.connection.serial=this.connectionSerial=g;this.setRecoveryKey()}};a.prototype.clearConnectionSerial=function(){this.realtime.connection.serial=this.connectionSerial=void 0;this.realtime.connection.timeSerial=this.timeSerial=void 0;this.clearRecoveryKey()};a.prototype.setRecoveryKey=function(){this.realtime.connection.recoveryKey=this.connectionKey+":"+(this.timeSerial||
  this.connectionSerial)+":"+this.msgSerial};a.prototype.clearRecoveryKey=function(){this.realtime.connection.recoveryKey=null};a.prototype.checkConnectionStateFreshness=function(){if(this.lastActivity&&this.connectionId){var a=k.now()-this.lastActivity;a>this.connectionStateTtl+this.maxIdleInterval&&(b.logAction(b.LOG_MINOR,"ConnectionManager.checkConnectionStateFreshness()","Last known activity from realtime was "+a+"ms ago; discarding connection state"),this.clearConnection(),this.states.connecting.failState=
  "suspended",this.states.connecting.queueEvents=!1)}};a.prototype.persistConnection=function(){if(e){var a=this.realtime.connection.recoveryKey;a&&(a={recoveryKey:a,disconnectedAt:k.now(),location:r.location,clientId:this.realtime.auth.clientId},e&&J.setSession("ably-connection-recovery",a))}};a.prototype.unpersistConnection=function(){e&&J.removeSession("ably-connection-recovery")};a.prototype.getError=function(){return this.errorReason||this.getStateError()};a.prototype.getStateError=function(){return K[this.state.state]};
  a.prototype.activeState=function(){return this.state.queueEvents||this.state.sendEvents};a.prototype.enactStateChange=function(a){b.logAction("failed"===a.current?b.LOG_ERROR:b.LOG_MAJOR,"Connection state",a.current+(a.reason?"; reason: "+a.reason:""));b.logAction(b.LOG_MINOR,"ConnectionManager.enactStateChange","setting new state: "+a.current+"; reason = "+(a.reason&&a.reason.message));var c=this.state=this.states[a.current];a.reason&&(this.errorReason=a.reason,this.realtime.connection.errorReason=
  a.reason);(c.terminal||"suspended"===c.state)&&this.clearConnection();this.emit("connectionstate",a)};a.prototype.startTransitionTimer=function(a){b.logAction(b.LOG_MINOR,"ConnectionManager.startTransitionTimer()","transitionState: "+a.state);this.transitionTimer&&(b.logAction(b.LOG_MINOR,"ConnectionManager.startTransitionTimer()","clearing already-running timer"),clearTimeout(this.transitionTimer));var c=this;this.transitionTimer=setTimeout(function(){c.transitionTimer&&(c.transitionTimer=null,b.logAction(b.LOG_MINOR,
  "ConnectionManager "+a.state+" timer expired","requesting new state: "+a.failState),c.notifyState({state:a.failState}))},a.retryDelay)};a.prototype.cancelTransitionTimer=function(){b.logAction(b.LOG_MINOR,"ConnectionManager.cancelTransitionTimer()","");this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)};a.prototype.startSuspendTimer=function(){var a=this;this.suspendTimer||(this.suspendTimer=setTimeout(function(){a.suspendTimer&&(a.suspendTimer=null,b.logAction(b.LOG_MINOR,
  "ConnectionManager suspend timer expired","requesting new state: suspended"),a.states.connecting.failState="suspended",a.states.connecting.queueEvents=!1,a.notifyState({state:"suspended"}))},this.connectionStateTtl))};a.prototype.checkSuspendTimer=function(a){"disconnected"!==a&&"suspended"!==a&&"connecting"!==a&&this.cancelSuspendTimer()};a.prototype.cancelSuspendTimer=function(){this.states.connecting.failState="disconnected";this.states.connecting.queueEvents=!0;this.suspendTimer&&(clearTimeout(this.suspendTimer),
  this.suspendTimer=null)};a.prototype.startRetryTimer=function(a){var c=this;this.retryTimer=setTimeout(function(){b.logAction(b.LOG_MINOR,"ConnectionManager retry timer expired","retrying");c.retryTimer=null;c.requestState({state:"connecting"})},a)};a.prototype.cancelRetryTimer=function(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)};a.prototype.notifyState=function(a){var c=a.state,e=this,g="disconnected"===c&&(this.state===this.states.connected||this.state===this.states.synchronizing||
  a.retryImmediately||this.state===this.states.connecting&&a.error&&M.isTokenErr(a.error)&&!(this.errorReason&&M.isTokenErr(this.errorReason)));b.logAction(b.LOG_MINOR,"ConnectionManager.notifyState()","new state: "+c+(g?"; will retry connection immediately":""));if(c!=this.state.state&&(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(a.state),!this.state.terminal)){var d=this.states[a.state];a=new R(this.state.state,d.state,d.retryDelay,a.error||K[d.state]);if(g){var h=
  function(){e.state===e.states.disconnected&&(e.lastAutoReconnectAttempt=k.now(),e.requestState({state:"connecting"}))},f=this.lastAutoReconnectAttempt&&k.now()-this.lastAutoReconnectAttempt+1;f&&1E3>f?(b.logAction(b.LOG_MICRO,"ConnectionManager.notifyState()","Last reconnect attempt was only "+f+"ms ago, waiting another "+(1E3-f)+"ms before trying again"),setTimeout(h,1E3-f)):k.nextTick(h)}else"disconnected"!==c&&"suspended"!==c||this.startRetryTimer(d.retryDelay);("disconnected"===c&&!g||"suspended"===
  c||d.terminal)&&k.nextTick(function(){e.disconnectAllTransports()});"connected"!=c||this.activeProtocol||b.logAction(b.LOG_ERROR,"ConnectionManager.notifyState()","Broken invariant: attempted to go into connected state, but there is no active protocol");this.enactStateChange(a);this.state.sendEvents?this.sendQueuedMessages():this.state.queueEvents||(this.realtime.channels.propogateConnectionInterruption(c,a.reason),this.failQueuedMessages(a.reason))}};a.prototype.requestState=function(a){var c=a.state,
  e=this;b.logAction(b.LOG_MINOR,"ConnectionManager.requestState()","requested state: "+c+"; current state: "+this.state.state);if(c!=this.state.state&&(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(c),"connecting"!=c||"connected"!=this.state.state)&&("closing"!=c||"closed"!=this.state.state)){var g=this.states[c];a=new R(this.state.state,g.state,null,a.error||K[g.state]);this.enactStateChange(a);"connecting"==c&&k.nextTick(function(){e.startConnect()});"closing"==c&&this.closeImpl()}};
  a.prototype.startConnect=function(){if(this.state!==this.states.connecting)b.logAction(b.LOG_MINOR,"ConnectionManager.startConnect()","Must be in connecting state to connect, but was "+this.state.state);else{var a=this.realtime.auth,c=this,e=++this.connectCounter,d=function(){c.checkConnectionStateFreshness();c.getTransportParams(function(a){e===c.connectCounter&&c.connectImpl(a,e)})};b.logAction(b.LOG_MINOR,"ConnectionManager.startConnect()","starting connection");this.startSuspendTimer();this.startTransitionTimer(this.states.connecting);
  if("basic"===a.method)d();else{var h=function(a){e===c.connectCounter&&(a?c.actOnErrorFromAuthorize(a):d())};this.errorReason&&M.isTokenErr(this.errorReason)?a._forceNewToken(null,null,h):a._ensureValidAuthCredentials(!1,h)}}};a.prototype.connectImpl=function(a,c){var e=this.state.state;e!==this.states.connecting.state&&e!==this.states.connected.state?b.logAction(b.LOG_MINOR,"ConnectionManager.connectImpl()","Must be in connecting state to connect (or connected to upgrade), but was "+e):this.pendingTransports.length?
  b.logAction(b.LOG_MINOR,"ConnectionManager.connectImpl()","Transports "+this.pendingTransports[0].toString()+" currently pending; taking no action"):e==this.states.connected.state?this.upgradeIfNeeded(a):1<this.transports.length&&this.getTransportPreference()?this.connectPreference(a):this.connectBase(a,c)};a.prototype.connectPreference=function(a){var c=this.getTransportPreference(),e=this,g=!1;k.arrIn(this.transports,c)||(this.unpersistTransportPreference(),this.connectImpl(a));b.logAction(b.LOG_MINOR,
  "ConnectionManager.connectPreference()","Trying to connect with stored transport preference "+c);var d=setTimeout(function(){g=!0;e.state.state!==e.states.connected.state&&(b.logAction(b.LOG_MINOR,"ConnectionManager.connectPreference()","Shortcircuit connection attempt with "+c+" failed; clearing preference and trying from scratch"),e.disconnectAllTransports(),e.unpersistTransportPreference());e.connectImpl(a)},this.options.timeouts.preferenceConnectTimeout);a.host=e.httpHosts[0];e.tryATransport(a,
  c,function(b,c){clearTimeout(d);g&&c?(c.off(),c.disconnect(),k.arrDeleteValue(this.pendingTransports,c)):c||b||(e.unpersistTransportPreference(),e.connectImpl(a))})};a.prototype.connectBase=function(a,c){function e(a,b){c===h.connectCounter&&(b||a||d())}function g(a){h.notifyState({state:h.states.connecting.failState,error:a})}function d(){f.length?x.checkConnectivity(function(b,d){c===h.connectCounter&&(b?g(b):d?(a.host=k.arrPopRandomElement(f),h.tryATransport(a,h.baseTransport,e)):g(new p("Unable to connect (network unreachable)",
  80003,404)))}):g(new p("Unable to connect (and no more fallback hosts to try)",80003,404))}var h=this,f=this.httpHosts.slice();b.logAction(b.LOG_MINOR,"ConnectionManager.connectBase()","Trying to connect with base transport "+this.baseTransport);var m=f.shift();m?(a.host=m,this.forceFallbackHost&&f.length?(this.forceFallbackHost=!1,d()):this.tryATransport(a,this.baseTransport,e)):g(new p("Unable to connect (no available host)",80003,404))};a.prototype.getUpgradePossibilities=function(){var a=this.activeProtocol.getTransport().shortName;
  a=k.arrIndexOf(this.upgradeTransports,a);return this.upgradeTransports.slice(a+1)};a.prototype.upgradeIfNeeded=function(a){var c=this.getUpgradePossibilities(),e=this;b.logAction(b.LOG_MINOR,"ConnectionManager.upgradeIfNeeded()","upgrade possibilities: "+k.inspect(c));c.length&&k.arrForEach(c,function(b){var c=e.createTransportParams(a.host,"upgrade");e.tryATransport(c,b,f)})};a.prototype.closeImpl=function(){b.logAction(b.LOG_MINOR,"ConnectionManager.closeImpl()","closing connection");this.cancelSuspendTimer();
  this.startTransitionTimer(this.states.closing);k.safeArrForEach(this.pendingTransports,function(a){b.logAction(b.LOG_MICRO,"ConnectionManager.closeImpl()","Closing pending transport: "+a);a&&a.close()});k.safeArrForEach(this.proposedTransports,function(a){b.logAction(b.LOG_MICRO,"ConnectionManager.closeImpl()","Disposing of proposed transport: "+a);a&&a.dispose()});this.activeProtocol&&(b.logAction(b.LOG_MICRO,"ConnectionManager.closeImpl()","Closing active transport: "+this.activeProtocol.getTransport()),
  this.activeProtocol.getTransport().close());this.notifyState({state:"closed"})};a.prototype.onAuthUpdated=function(a,c){var e=this;switch(this.state.state){case "connected":b.logAction(b.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Sending AUTH message on active transport");if((this.pendingTransports.length||this.proposedTransports.length)&&e.state!==e.states.synchronizing){this.disconnectAllTransports(!0);var g=this.activeProtocol.getTransport().params;k.nextTick(function(){"connected"===e.state.state&&
  e.upgradeIfNeeded(g)})}this.activeProtocol.getTransport().onAuthUpdated(a);var d=y.fromValues({action:m.AUTH,auth:{accessToken:a.token}});this.send(d);var h=function(){e.off(f);c(null,a)},f=function(a){"failed"===a.current&&(e.off(h),e.off(f),c(a.reason||e.getStateError()))};this.once("connectiondetails",h);this.on("connectionstate",f);break;case "connecting":b.logAction(b.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Aborting current connection attempts in order to start again with the new auth details"),
  this.disconnectAllTransports();default:b.logAction(b.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Connection state is "+this.state.state+"; waiting until either connected or failed");var n=function(b){switch(b.current){case "connected":e.off(n);c(null,a);break;case "failed":case "closed":case "suspended":e.off(n),c(b.reason||e.getStateError())}};e.on("connectionstate",n);"connecting"===this.state.state?e.startConnect():e.requestState({state:"connecting"})}};a.prototype.disconnectAllTransports=function(a){b.logAction(b.LOG_MINOR,
  "ConnectionManager.disconnectAllTransports()","Disconnecting all transports"+(a?" except the active transport":""));this.connectCounter++;k.safeArrForEach(this.pendingTransports,function(a){b.logAction(b.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting pending transport: "+a);a&&a.disconnect()});this.pendingTransports=[];k.safeArrForEach(this.proposedTransports,function(a){b.logAction(b.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disposing of proposed transport: "+
  a);a&&a.dispose()});this.proposedTransports=[];this.activeProtocol&&!a&&(b.logAction(b.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().disconnect())};a.prototype.send=function(a,c,e){e=e||f;var g=this.state;g.sendEvents?(b.logAction(b.LOG_MICRO,"ConnectionManager.send()","sending event"),this.sendImpl(new t(a,e))):c&&g.queueEvents||g.forceQueueEvents?(b.shouldLog(b.LOG_MICRO)&&b.logAction(b.LOG_MICRO,
  "ConnectionManager.send()","queueing msg; "+y.stringify(a)),this.queue(a,e)):(a="rejecting event, queueEvent was "+c+", state was "+g.state,b.logAction(b.LOG_MICRO,"ConnectionManager.send()",a),e(this.errorReason||new p(a,9E4,400)))};a.prototype.sendImpl=function(a){var c=a.message;a.ackRequired&&!a.sendAttempted&&(c.msgSerial=this.msgSerial++,this.setRecoveryKey());try{this.activeProtocol.send(a)}catch(H){b.logAction(b.LOG_ERROR,"ConnectionManager.sendImpl()","Unexpected exception in transport.send(): "+
  H.stack)}};a.prototype.queue=function(a,e){b.logAction(b.LOG_MICRO,"ConnectionManager.queue()","queueing event");var g=this.queuedMessages.last(),d=this.options.maxMessageSize;g&&!g.sendAttempted&&c(g.message,a,d)?(g.merged||(g.callback=Y([g.callback]),g.merged=!0),g.callback.push(e)):this.queuedMessages.push(new t(a,e))};a.prototype.sendQueuedMessages=function(){b.logAction(b.LOG_MICRO,"ConnectionManager.sendQueuedMessages()","sending "+this.queuedMessages.count()+" queued messages");for(var a;a=
  this.queuedMessages.shift();)this.sendImpl(a)};a.prototype.queuePendingMessages=function(a){a&&a.length&&(b.logAction(b.LOG_MICRO,"ConnectionManager.queuePendingMessages()","queueing "+a.length+" pending messages"),this.queuedMessages.prepend(a))};a.prototype.failQueuedMessages=function(a){var c=this.queuedMessages.count();0<c&&(b.logAction(b.LOG_ERROR,"ConnectionManager.failQueuedMessages()","failing "+c+" queued messages, err = "+k.inspectError(a)),this.queuedMessages.completeAllMessages(a))};a.prototype.onChannelMessage=
  function(a,c){var e=this.activeProtocol&&c===this.activeProtocol.getTransport(),g=k.arrIn(this.pendingTransports,c)&&this.state==this.states.synchronizing,d=a.action===m.MESSAGE||a.action===m.PRESENCE;if(e||g){if(d){if(this.setConnectionSerial(a))return;if(y.isDuplicate(a,this.mostRecentMsg)){b.logAction(b.LOG_ERROR,"ConnectionManager.onChannelMessage()","received message with different connectionSerial, but same message id as a previous; discarding; id = "+a.id);return}this.mostRecentMsg=a}this.realtime.channels.onChannelMessage(a)}else if(-1<
  k.arrIndexOf([m.ACK,m.NACK,m.ERROR],a.action))this.realtime.channels.onChannelMessage(a);else b.logAction(b.LOG_MICRO,"ConnectionManager.onChannelMessage()","received message "+JSON.stringify(a)+"on defunct transport; discarding")};a.prototype.ping=function(a,c){if(a){b.logAction(b.LOG_MINOR,"ConnectionManager.ping()","transport = "+a);var e=k.now(),d=k.cheapRandStr(),g=function(b){b===d&&(a.off("heartbeat",g),clearTimeout(h),b=k.now()-e,c(null,b))},h=setTimeout(function(){a.off("heartbeat",g);c(new p("Timeout waiting for heartbeat response",
  5E4,500))},this.options.timeouts.realtimeRequestTimeout);a.on("heartbeat",g);a.ping(d)}else if("connected"!==this.state.state)c(new p("Unable to ping service; not connected",4E4,400));else{var f=!1,m=this,n=function(){f||(f=!0,k.nextTick(function(){m.ping(null,c)}))};this.on("transport.active",n);this.ping(this.activeProtocol.getTransport(),function(a,b){m.off("transport.active",n);f||(f=!0,c(a,b))})}};a.prototype.abort=function(a){this.activeProtocol.getTransport().fail(a)};a.prototype.registerProposedTransport=
  function(a){this.proposedTransports.push(a)};a.prototype.getTransportPreference=function(){return this.transportPreference||n&&J.get("ably-transport-preference")};a.prototype.persistTransportPreference=function(a){k.arrIn(q.upgradeTransports,a.shortName)&&(this.transportPreference=a.shortName,n&&J.set("ably-transport-preference",a.shortName))};a.prototype.unpersistTransportPreference=function(){this.transportPreference=null;n&&J.remove("ably-transport-preference")};a.prototype.actOnErrorFromAuthorize=
  function(a){if(40171===a.code)this.notifyState({state:"failed",error:a});else if(403===a.statusCode){var c="Client configured authentication provider returned 403; failing the connection";b.logAction(b.LOG_ERROR,"ConnectionManager.actOnErrorFromAuthorize()",c);this.notifyState({state:"failed",error:new p(c,80019,403,a)})}else c="Client configured authentication provider request failed",b.logAction(b.LOG_MINOR,"ConnectionManager.actOnErrorFromAuthorize",c),this.notifyState({state:this.state.failState,
  error:new p(c,80019,401,a)})};a.prototype.onConnectionDetailsUpdate=function(a,c){if(a){this.connectionDetails=a;a.maxMessageSize&&(this.options.maxMessageSize=a.maxMessageSize);var e=a.clientId;if(e&&(e=this.realtime.auth._uncheckedSetClientId(e))){b.logAction(b.LOG_ERROR,"ConnectionManager.onConnectionDetailsUpdate()",e.message);c.fail(e);return}if(e=a.connectionStateTtl)this.connectionStateTtl=e;this.maxIdleInterval=a.maxIdleInterval;this.emit("connectiondetails",a)}};return a}(),P=function(){function f(a,
  b,e){z.call(this);this.connectionManager=a;a.registerProposedTransport(this);this.auth=b;this.params=e;this.timeouts=e.options.timeouts;this.format=e.format;this.isDisposed=this.isFinished=this.isConnected=!1;this.lastActivity=this.idleTimer=this.maxIdleInterval=null}var l=y.Action,d=y.fromValues({action:l.CLOSE}),a=y.fromValues({action:l.DISCONNECT});k.inherits(f,z);f.prototype.connect=function(){};f.prototype.close=function(){this.isConnected&&this.requestClose();this.finish("closed",K.closed)};
  f.prototype.disconnect=function(a){this.isConnected&&this.requestDisconnect();this.finish("disconnected",a||K.disconnected)};f.prototype.fail=function(a){this.isConnected&&this.requestDisconnect();this.finish("failed",a||K.failed)};f.prototype.finish=function(a,b){this.isFinished||(this.isFinished=!0,this.isConnected=!1,this.maxIdleInterval=null,clearTimeout(this.idleTimer),this.idleTimer=null,this.emit(a,b),this.dispose())};f.prototype.onProtocolMessage=function(a){b.shouldLog(b.LOG_MICRO)&&b.logAction(b.LOG_MICRO,
  "Transport.onProtocolMessage()","received on "+this.shortName+": "+y.stringify(a)+"; connectionId = "+this.connectionManager.connectionId);this.onActivity();switch(a.action){case l.HEARTBEAT:b.logAction(b.LOG_MICRO,"Transport.onProtocolMessage()",this.shortName+" heartbeat; connectionId = "+this.connectionManager.connectionId);this.emit("heartbeat",a.id);break;case l.CONNECTED:this.onConnect(a);this.emit("connected",a.error,a.connectionId,a.connectionDetails,a);break;case l.CLOSED:this.onClose(a);
  break;case l.DISCONNECTED:this.onDisconnect(a);break;case l.ACK:this.emit("ack",a.msgSerial,a.count);break;case l.NACK:this.emit("nack",a.msgSerial,a.count,a.error);break;case l.SYNC:if(void 0!==a.connectionId){this.emit("sync",a.connectionId,a);break}this.connectionManager.onChannelMessage(a,this);break;case l.AUTH:this.auth.authorize(function(a){a&&b.logAction(b.LOG_ERROR,"Transport.onProtocolMessage()","Ably requested re-authentication, but unable to obtain a new token: "+k.inspectError(a))});
  break;case l.ERROR:b.logAction(b.LOG_MINOR,"Transport.onProtocolMessage()","received error action; connectionId = "+this.connectionManager.connectionId+"; err = "+k.inspect(a.error)+(a.channel?", channel: "+a.channel:""));if(void 0===a.channel){this.onFatalError(a);break}this.connectionManager.onChannelMessage(a,this);break;default:this.connectionManager.onChannelMessage(a,this)}};f.prototype.onConnect=function(a){this.isConnected=!0;if(a=a.connectionDetails.maxIdleInterval)this.maxIdleInterval=a+
  this.timeouts.realtimeRequestTimeout,this.onActivity()};f.prototype.onDisconnect=function(a){a=a&&a.error;b.logAction(b.LOG_MINOR,"Transport.onDisconnect()","err = "+k.inspectError(a));this.finish("disconnected",a)};f.prototype.onFatalError=function(a){a=a&&a.error;b.logAction(b.LOG_MINOR,"Transport.onFatalError()","err = "+k.inspectError(a));this.finish("failed",a)};f.prototype.onClose=function(a){a=a&&a.error;b.logAction(b.LOG_MINOR,"Transport.onClose()","err = "+k.inspectError(a));this.finish("closed",
  a)};f.prototype.requestClose=function(){b.logAction(b.LOG_MINOR,"Transport.requestClose()","");this.send(d)};f.prototype.requestDisconnect=function(){b.logAction(b.LOG_MINOR,"Transport.requestDisconnect()","");this.send(a)};f.prototype.ping=function(a){var b={action:y.Action.HEARTBEAT};a&&(b.id=a);this.send(y.fromValues(b))};f.prototype.dispose=function(){b.logAction(b.LOG_MINOR,"Transport.dispose()","");this.isDisposed=!0;this.off()};f.prototype.onActivity=function(){this.maxIdleInterval&&(this.lastActivity=
  this.connectionManager.lastActivity=k.now(),this.setIdleTimer(this.maxIdleInterval+100))};f.prototype.setIdleTimer=function(a){var b=this;this.idleTimer||(this.idleTimer=setTimeout(function(){b.onIdleTimerExpire()},a))};f.prototype.onIdleTimerExpire=function(){this.idleTimer=null;var a=k.now()-this.lastActivity,d=this.maxIdleInterval-a;0>=d?(a="No activity seen from realtime in "+a+"ms; assuming connection has dropped",b.logAction(b.LOG_ERROR,"Transport.onIdleTimerExpire()",a),this.disconnect(new p(a,
  80003,408))):this.setIdleTimer(d+100)};f.prototype.onAuthUpdated=function(){};return f}();(function(){function f(b,a,c){this.shortName="web_socket";c.heartbeats=v.useProtocolHeartbeats;P.call(this,b,a,c);this.wsHost=q.getHost(c.options,c.host,!0)}var l=v.WebSocket;k.inherits(f,P);f.isAvailable=function(){return!!l};f.isAvailable()&&(N.supportedTransports.web_socket=f);f.tryConnect=function(d,a,c,n){function e(a){n({event:this.event,error:a})}var m=new f(d,a,c);m.on(["failed","disconnected"],e);m.on("wsopen",
  function(){b.logAction(b.LOG_MINOR,"WebSocketTransport.tryConnect()","viable transport "+m);m.off(["failed","disconnected"],e);n(null,m)});m.connect()};f.prototype.createWebSocket=function(b,a){var c=0;if(a)for(var d in a)b+=(c++?"&":"?")+d+"="+a[d];this.uri=b;return new l(b)};f.prototype.toString=function(){return"WebSocketTransport; uri="+this.uri};f.prototype.connect=function(){b.logAction(b.LOG_MINOR,"WebSocketTransport.connect()","starting");P.prototype.connect.call(this);var d=this,a=this.params,
  c=a.options,f=(c.tls?"wss://":"ws://")+this.wsHost+":"+q.getPort(c)+"/";b.logAction(b.LOG_MINOR,"WebSocketTransport.connect()","uri: "+f);this.auth.getAuthParams(function(c,m){if(!d.isDisposed){var e="",h;for(h in m)e+=" "+h+": "+m[h]+";";b.logAction(b.LOG_MINOR,"WebSocketTransport.connect()","authParams:"+e+" err: "+c);if(c)d.disconnect(c);else{e=a.getConnectParams(m);try{var n=d.wsConnection=d.createWebSocket(f,e);n.binaryType=v.binaryType;n.onopen=function(){d.onWsOpen()};n.onclose=function(a){d.onWsClose(a)};
  n.onmessage=function(a){d.onWsData(a.data)};n.onerror=function(a){d.onWsError(a)};if(n.on)n.on("ping",function(){d.onActivity()})}catch(g){b.logAction(b.LOG_ERROR,"WebSocketTransport.connect()","Unexpected exception creating websocket: err = "+(g.stack||g.message)),d.disconnect(g)}}}})};f.prototype.send=function(d){var a=this.wsConnection;if(a)try{a.send(y.serialize(d,this.params.format))}catch(c){d="Exception from ws connection when trying to send: "+k.inspectError(c),b.logAction(b.LOG_ERROR,"WebSocketTransport.send()",
  d),this.finish("disconnected",new p(d,5E4,500))}else b.logAction(b.LOG_ERROR,"WebSocketTransport.send()","No socket connection")};f.prototype.onWsData=function(d){b.logAction(b.LOG_MICRO,"WebSocketTransport.onWsData()","data received; length = "+d.length+"; type = "+typeof d);try{this.onProtocolMessage(y.deserialize(d,this.format))}catch(a){b.logAction(b.LOG_ERROR,"WebSocketTransport.onWsData()","Unexpected exception handing channel message: "+a.stack)}};f.prototype.onWsOpen=function(){b.logAction(b.LOG_MINOR,
  "WebSocketTransport.onWsOpen()","opened WebSocket");this.emit("wsopen")};f.prototype.onWsClose=function(d){if("object"==typeof d){var a=d.wasClean;d=d.code}else a=1E3==d;delete this.wsConnection;a?(b.logAction(b.LOG_MINOR,"WebSocketTransport.onWsClose()","Cleanly closed WebSocket"),a=new p("Websocket closed",80003,400)):(d="Unclean disconnection of WebSocket ; code = "+d,a=new p(d,80003,400),b.logAction(b.LOG_MINOR,"WebSocketTransport.onWsClose()",d));this.finish("disconnected",a);this.emit("disposed")};
  f.prototype.onWsError=function(d){b.logAction(b.LOG_MINOR,"WebSocketTransport.onError()","Error from WebSocket: "+d.message);var a=this;k.nextTick(function(){a.disconnect(d)})};f.prototype.dispose=function(){b.logAction(b.LOG_MINOR,"WebSocketTransport.dispose()","");this.isDisposed=!0;var d=this.wsConnection;d&&(d.onmessage=function(){},delete this.wsConnection,k.nextTick(function(){b.logAction(b.LOG_MICRO,"WebSocketTransport.dispose()","closing websocket");d.close()}))};return f})();var L=function(){function f(b){var a=
  [80015,80017,80030];return b.code&&(M.isTokenErr(b)?0:k.arrIn(a,b.code)||4E4<=b.code&&5E4>b.code)?[y.fromValues({action:y.Action.ERROR,error:b})]:[y.fromValues({action:y.Action.DISCONNECTED,error:b})]}function l(b,a,c){c.format=void 0;c.heartbeats=!0;P.call(this,b,a,c);this.stream="stream"in c?c.stream:!0;this.pendingItems=this.pendingCallback=this.recvRequest=this.sendRequest=null}k.inherits(l,P);l.REQ_SEND=0;l.REQ_RECV=1;l.REQ_RECV_POLL=2;l.REQ_RECV_STREAM=3;l.prototype.connect=function(){b.logAction(b.LOG_MINOR,
  "CometTransport.connect()","starting");P.prototype.connect.call(this);var d=this,a=this.params,c=a.options;a=q.getHost(c,a.host);var n=q.getPort(c);this.baseUri=(c.tls?"https://":"http://")+a+":"+n+"/comet/";var e=this.baseUri+"connect";b.logAction(b.LOG_MINOR,"CometTransport.connect()","uri: "+e);this.auth.getAuthParams(function(a,c){if(a)d.disconnect(a);else if(!d.isDisposed){d.authParams=c;var h=d.params.getConnectParams(c);"stream"in h&&(d.stream=h.stream);b.logAction(b.LOG_MINOR,"CometTransport.connect()",
  "connectParams:"+k.toQueryString(h));var m=!1;h=d.recvRequest=d.createRequest(e,null,h,null,d.stream?3:1);h.on("data",function(a){d.recvRequest&&(m||(m=!0,d.emit("preconnect")),d.onData(a))});h.on("complete",function(a){d.recvRequest||(a=a||new p("Request cancelled",80003,400));d.recvRequest=null;m||(m=!0,d.emit("preconnect"));d.onActivity();if(a)if(a.code)d.onData(f(a));else d.disconnect(a);else k.nextTick(function(){d.recv()})});h.exec()}})};l.prototype.requestClose=function(){b.logAction(b.LOG_MINOR,
  "CometTransport.requestClose()");this._requestCloseOrDisconnect(!0)};l.prototype.requestDisconnect=function(){b.logAction(b.LOG_MINOR,"CometTransport.requestDisconnect()");this._requestCloseOrDisconnect(!1)};l.prototype._requestCloseOrDisconnect=function(d){var a=d?this.closeUri:this.disconnectUri;if(a){var c=this;a=this.createRequest(a,null,this.authParams,null,0);a.on("complete",function(a){a&&(b.logAction(b.LOG_ERROR,"CometTransport.request"+(d?"Close()":"Disconnect()"),"request returned err = "+
  k.inspectError(a)),c.finish("disconnected",a))});a.exec()}};l.prototype.dispose=function(){b.logAction(b.LOG_MINOR,"CometTransport.dispose()","");if(!this.isDisposed){this.isDisposed=!0;this.recvRequest&&(b.logAction(b.LOG_MINOR,"CometTransport.dispose()","aborting recv request"),this.recvRequest.abort(),this.recvRequest=null);this.finish("disconnected",K.disconnected);var d=this;k.nextTick(function(){d.emit("disposed")})}};l.prototype.onConnect=function(d){if(!this.isDisposed){var a=d.connectionKey;
  P.prototype.onConnect.call(this,d);a=this.baseUri+a;b.logAction(b.LOG_MICRO,"CometTransport.onConnect()","baseUri = "+a+"; connectionKey = "+d.connectionKey);this.sendUri=a+"/send";this.recvUri=a+"/recv";this.closeUri=a+"/close";this.disconnectUri=a+"/disconnect"}};l.prototype.send=function(b){if(this.sendRequest)this.pendingItems=this.pendingItems||[],this.pendingItems.push(b);else{var a=this.pendingItems||[];a.push(b);this.pendingItems=null;this.sendItems(a)}};l.prototype.sendAnyPending=function(){var b=
  this.pendingItems;b&&(this.pendingItems=null,this.sendItems(b))};l.prototype.sendItems=function(d){var a=this;d=this.sendRequest=a.createRequest(a.sendUri,null,a.authParams,this.encodeRequest(d),0);d.on("complete",function(c,d){c&&b.logAction(b.LOG_ERROR,"CometTransport.sendItems()","on complete: err = "+k.inspectError(c));a.sendRequest=null;if(c)if(c.code)a.onData(f(c));else a.disconnect(c);else{if(d)a.onData(d);a.pendingItems&&k.nextTick(function(){a.sendRequest||a.sendAnyPending()})}});d.exec()};
  l.prototype.recv=function(){if(!this.recvRequest&&this.isConnected){var b=this,a=this.recvRequest=this.createRequest(this.recvUri,null,this.authParams,null,b.stream?3:2);a.on("data",function(a){b.onData(a)});a.on("complete",function(a){b.recvRequest=null;b.onActivity();if(a)if(a.code)b.onData(f(a));else b.disconnect(a);else k.nextTick(function(){b.recv()})});a.exec()}};l.prototype.onData=function(d){try{var a=this.decodeResponse(d);if(a&&a.length)for(d=0;d<a.length;d++)this.onProtocolMessage(y.fromDeserialized(a[d]))}catch(c){b.logAction(b.LOG_ERROR,
  "CometTransport.onData()","Unexpected exception handing channel event: "+c.stack)}};l.prototype.encodeRequest=function(b){return JSON.stringify(b)};l.prototype.decodeResponse=function(b){"string"==typeof b&&(b=JSON.parse(b));return b};l.prototype.onAuthUpdated=function(b){this.authParams={access_token:b.token}};return l}(),U=function(){function f(){}function l(b){this.channel=b;this.basePath=b.basePath+"/presence"}k.inherits(l,z);l.prototype.get=function(d,a){b.logAction(b.LOG_MICRO,"Presence.get()",
  "channel = "+this.channel.name);if(void 0===a)if("function"==typeof d)a=d,d=null;else{if(this.channel.rest.options.promises)return k.promisify(this,"get",arguments);a=f}var c=this.channel.rest,n=c.options.useBinaryProtocol?"msgpack":"json",e=x.supportsLinkHeaders?void 0:n,m=k.defaultGetHeaders(n);c.options.headers&&k.mixin(m,c.options.headers);var t=this.channel.channelOptions;(new O(c,this.basePath,m,e,function(a,b,c){return F.fromResponseBody(a,t,!c&&n)})).get(d,a)};l.prototype.history=function(d,
  a){b.logAction(b.LOG_MICRO,"Presence.history()","channel = "+this.channel.name);this._history(d,a)};l.prototype._history=function(b,a){if(void 0===a)if("function"==typeof b)a=b,b=null;else{if(this.channel.rest.options.promises)return k.promisify(this,"_history",arguments);a=f}var c=this.channel.rest,d=c.options.useBinaryProtocol?"msgpack":"json",e=x.supportsLinkHeaders?void 0:d,m=k.defaultGetHeaders(d);c.options.headers&&k.mixin(m,c.options.headers);var t=this.channel.channelOptions;(new O(c,this.basePath+
  "/history",m,e,function(a,b,c){return F.fromResponseBody(a,t,!c&&d)})).get(b,a)};return l}(),I=function(){function f(){}function l(a,b,c,d,f){x.supportsAuthHeaders?a.auth.getAuthHeaders(function(a,e){a?d(a):f(k.mixin(e,b),c)}):a.auth.getAuthParams(function(a,e){a?d(a):f(b,k.mixin(e,c))})}function d(a,b){return function(c,e,d,g,f){if(c&&!e)a(c);else{if(!g)try{e=k.decodeBody(e,b)}catch(H){a(H);return}void 0===e.statusCode?a(c,e,d,!0,f):(d=e.statusCode,g=e.response,f=e.headers,200>d||300<=d?(c=g&&g.error||
  c,c||(c=Error("Error in unenveloping "+e),c.statusCode=d),a(c,g,f,!0,d)):a(c,g,f,!0,d))}}}function a(a){var b=[];if(a)for(var c in a)b.push(c+"="+a[c]);return b.join("&")}function c(c,d,f,h){return function(e,g,m,n,l){e?b.logAction(b.LOG_MICRO,"Resource."+d+"()","Received Error; "+(f+(h?"?":"")+a(h))+"; Error: "+k.inspectError(e)):b.logAction(b.LOG_MICRO,"Resource."+d+"()","Received; "+(f+(h?"?":"")+a(h))+"; Headers: "+a(m)+"; StatusCode: "+l+"; Body: "+(A.isBuffer(g)?g.toString():g));c&&c(e,g,m,
  n,l)}}var n=v.msgpack;k.arrForEach(x.methodsWithoutBody,function(a){f[a]=function(b,c,e,d,g,n){f["do"](a,b,c,null,e,d,g,n)}});k.arrForEach(x.methodsWithBody,function(a){f[a]=function(b,c,e,d,g,n,k){f["do"](a,b,c,e,d,g,n,k)}});f["do"]=function(e,f,t,h,u,g,w,p){function m(c,d){b.shouldLog(b.LOG_MICRO)&&b.logAction(b.LOG_MICRO,"Resource."+e+"()","Sending; "+(t+(d?"?":"")+a(d)));var w=[f,t,c,h,d,function(a,b,c,e,d){a&&M.isTokenErr(a)?f.auth.authorize(null,null,function(a){a?p(a):l(f,u,g,p,m)}):p(a,b,
  c,e,d)}];h||w.splice(3,1);if(b.shouldLog(b.LOG_MICRO)){var H=h;if(0<(c["content-type"]||"").indexOf("msgpack"))try{H=n.decode(h)}catch(ka){b.logAction(b.LOG_MICRO,"Resource."+e+"()","Sending MsgPack Decoding Error: "+k.inspectError(ka))}b.logAction(b.LOG_MICRO,"Resource."+e+"()","Sending; "+(t+(d?"?":"")+a(d))+"; Body: "+H)}x[e].apply(this,w)}b.shouldLog(b.LOG_MICRO)&&(p=c(p,e,t,g));w&&(p=p&&d(p,w),(g=g||{}).envelope=w);l(f,u,g,p,m)};return f}(),O=function(){function f(a,b,d,e,f,k){this.rest=a;this.path=
  b;this.headers=d;this.envelope=e;this.bodyHandler=f;this.useHttpPaginatedResponse=k||!1}function l(a,b,d){this.resource=a;this.items=b;if(d){var c=this;"first"in d&&(this.first=function(a){if(!a&&c.resource.rest.options.promises)return k.promisify(c,"first",[]);c.get(d.first,a)});"current"in d&&(this.current=function(a){if(!a&&c.resource.rest.options.promises)return k.promisify(c,"current",[]);c.get(d.current,a)});this.next=function(a){if(!a&&c.resource.rest.options.promises)return k.promisify(c,
  "next",[]);"next"in d?c.get(d.next,a):a(null,null)};this.hasNext=function(){return"next"in d};this.isLast=function(){return!this.hasNext()}}}function d(a,b,d,e,f,k){l.call(this,a,b,f);this.statusCode=e;this.success=300>e&&200<=e;this.headers=d;this.errorCode=k&&k.code;this.errorMessage=k&&k.message}k.arrForEach(x.methodsWithoutBody,function(a){f.prototype[a]=function(b,d){var c=this;I[a](c.rest,c.path,c.headers,b,c.envelope,function(a,b,e,f,g){c.handlePage(a,b,e,f,g,d)})}});k.arrForEach(x.methodsWithBody,
  function(a){f.prototype[a]=function(b,d,e){var c=this;I[a](c.rest,c.path,d,c.headers,b,c.envelope,function(a,b,d,f,m){e&&c.handlePage(a,b,d,f,m,e)})}});f.prototype.handlePage=function(a,c,f,e,m,t){if(!a||this.useHttpPaginatedResponse&&(c||"number"===typeof a.code)){var h,n;try{var g=this.bodyHandler(c,f,e)}catch(H){t(a||H);return}if(f&&(h=f.Link||f.link)){c=h;"string"==typeof c&&(c=c.split(","));e={};for(h=0;h<c.length;h++)if(n=c[h].match(/^\s*<(.+)>;\s*rel="(\w+)"$/)){var w;(w=(w=n[1].match(/^\.\/(\w+)\?(.*)$/))&&
  k.parseQueryString(w[2]))&&(e[n[2]]=w)}n=e}this.useHttpPaginatedResponse?t(null,new d(this,g,f,m,n,a)):t(null,new l(this,g,n))}else b.logAction(b.LOG_ERROR,"PaginatedResource.handlePage()","Unexpected error getting resource: err = "+k.inspectError(a)),t(a)};l.prototype.get=function(a,b){var c=this.resource;I.get(c.rest,c.path,c.headers,a,c.envelope,function(a,d,f,h,k){c.handlePage(a,d,f,h,k,b)})};k.inherits(d,l);return f}(),M=function(){function f(){}function l(a){if(!k.isErrorInfo(a))return new p(k.inspectError(a),
  a.code||40170,a.statusCode||401);a.code||(403===a.statusCode?a.code=40300:(a.code=40170,a.statusCode=401));return a}function d(a){if(!a)return"";"string"==typeof a&&(a=JSON.parse(a));var b={},c=k.keysArray(a,!0);if(!c)return"";c.sort();for(var e=0;e<c.length;e++)b[c[e]]=a[c[e]].sort();return JSON.stringify(b)}function a(a){if(a.authCallback)b.logAction(b.LOG_MINOR,"Auth()","using token auth with authCallback");else if(a.authUrl)b.logAction(b.LOG_MINOR,"Auth()","using token auth with authUrl");else if(a.key)b.logAction(b.LOG_MINOR,
  "Auth()","using token auth with client-side signing");else if(a.tokenDetails)b.logAction(b.LOG_MINOR,"Auth()","using token auth with supplied token only");else throw b.logAction(b.LOG_ERROR,"Auth()","authOptions must include valid authentication parameters"),Error("authOptions must include valid authentication parameters");}function c(c,e){this.client=c;this.tokenParams=e.defaultTokenParams||{};this.waitingForTokenRequest=this.currentTokenRequestId=null;if(e.useTokenAuth||(!("useTokenAuth"in e)||
  e.useTokenAuth)&&(e.authCallback||e.authUrl||e.token||e.tokenDetails)){if(e.key&&!m){var d="client-side token request signing not supported";b.logAction(b.LOG_ERROR,"Auth()",d);throw Error(d);}e.key||e.authCallback||e.authUrl||b.logAction(b.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(e.defaultTokenParams,e);a(this.authOptions)}else{if(!e.key)throw d=
  "No authentication options provided; need one of: key, authUrl, or authCallback (or for testing only, token or tokenDetails)",b.logAction(b.LOG_ERROR,"Auth()",d),new p(d,40160,401);b.logAction(b.LOG_MINOR,"Auth()","anonymous, using basic auth");this._saveBasicOptions(e)}}var n=Math.pow(2,17);if(v.createHmac){var e=function(a){return(new Buffer(a,"ascii")).toString("base64")};var m=function(a,b){var c=v.createHmac("SHA256",b);c.update(a);return c.digest("base64")}}else e=la.encode,m=function(a,b){return G.HmacSHA256(a,
  b).toString(G.enc.Base64)};var t=0;c.prototype.authorize=function(a,c,e){"function"!=typeof a||e?"function"!=typeof c||e||(e=c,c=null):(e=a,c=a=null);if(!e){if(this.client.options.promises)return k.promisify(this,"authorize",arguments);e=f}var d=this;if(c&&c.key&&this.authOptions.key!==c.key)throw new p("Unable to update auth options with incompatible key",40102,401);c&&"force"in c&&(b.logAction(b.LOG_ERROR,"Auth.authorize","Deprecation warning: specifying {force: true} in authOptions is no longer necessary, authorize() now always gets a new token. Please remove this, as in version 1.0 and later, having a non-null authOptions will overwrite stored library authOptions, which may not be what you want"),
  k.isOnlyPropIn(c,"force")&&(c=null));this._forceNewToken(a,c,function(a,b){if(a)e(a);else if(d.client.connection)d.client.connection.connectionManager.onAuthUpdated(b,e);else e(null,b)})};c.prototype.authorise=function(){b.deprecated("Auth.authorise","Auth.authorize");this.authorize.apply(this,arguments)};c.prototype._forceNewToken=function(b,c,e){var d=this;this.tokenDetails=null;this._saveTokenOptions(b,c);a(this.authOptions);this._ensureValidAuthCredentials(!0,function(a,b){delete d.tokenParams.timestamp;
  delete d.authOptions.queryTime;e(a,b)})};c.prototype.requestToken=function(a,c,e){function g(a,e){var d="/keys/"+a.keyName+"/requestToken",f=k.defaultPostHeaders();c.requestHeaders&&k.mixin(f,c.requestHeaders);b.logAction(b.LOG_MICRO,"Auth.requestToken().requestToken","Sending POST to "+d+"; Token params: "+JSON.stringify(a));a=JSON.stringify(a);x.post(h,function(a){return h.baseUri(a)+d},f,a,null,e)}"function"!=typeof a||e?"function"!=typeof c||e||(e=c,c=null):(e=a,c=a=null);if(!e&&this.client.options.promises)return k.promisify(this,
  "requestToken",arguments);c=c||this.authOptions;a=a||k.copy(this.tokenParams);e=e||f;var h=this.client;if(c.authCallback){b.logAction(b.LOG_MINOR,"Auth.requestToken()","using token auth with authCallback");var m=c.authCallback}else if(c.authUrl)b.logAction(b.LOG_MINOR,"Auth.requestToken()","using token auth with authUrl"),m=function(a,e){function d(a,c,d,f){if(a)b.logAction(b.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received Error: "+k.inspectError(a));else{var g=d["content-type"];b.logAction(b.LOG_MICRO,
  "Auth.requestToken().tokenRequestCallback","Received; content-type: "+g+"; body: "+k.inspectBody(c))}if(a||f)return e(a,c);A.isBuffer(c)&&(c=c.toString());if(g)if(a=-1<g.indexOf("application/json"),d=-1<g.indexOf("text/plain")||-1<g.indexOf("application/jwt"),a||d){if(a){if(c.length>n){e(new p("authUrl response exceeded max permitted length",40170,401));return}try{c=JSON.parse(c)}catch(oa){e(new p("Unexpected error processing authURL response; err = "+oa.message,40170,401));return}}e(null,c,g)}else e(new p("authUrl responded with unacceptable content-type "+
  g+", should be either text/plain, application/jwt or application/json",40170,401));else e(new p("authUrl response is missing a content-type header",40170,401))}var f=k.mixin({accept:"application/json, text/plain"},c.authHeaders),g=c.authMethod&&"post"===c.authMethod.toLowerCase();if(!g){var m=c.authUrl.indexOf("?");if(-1<m){var l=k.parseQueryString(c.authUrl.slice(m));c.authUrl=c.authUrl.slice(0,m);c.authParams=k.mixin(l,c.authParams)}}m=k.mixin({},c.authParams||{},a);b.logAction(b.LOG_MICRO,"Auth.requestToken().tokenRequestCallback",
  "Requesting token from "+c.authUrl+"; Params: "+JSON.stringify(m)+"; method: "+(g?"POST":"GET"));g?(f=f||{},f["content-type"]="application/x-www-form-urlencoded",g=k.toQueryString(m).slice(1),x.postUri(h,c.authUrl,f,g,{},d)):x.getUri(h,c.authUrl,f||{},m,d)};else if(c.key){var t=this;b.logAction(b.LOG_MINOR,"Auth.requestToken()","using token auth with client-side signing");m=function(a,b){t.createTokenRequest(a,c,b)}}else{b.logAction(b.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");
  e(new p("Need a new token, but authOptions does not include any way to request one (no authUrl, authCallback, or key)",40171,403));return}"capability"in a&&(a.capability=d(a.capability));var u=!1,q=this.client.options.timeouts.realtimeRequestTimeout,r=setTimeout(function(){u=!0;var a="Token request callback timed out after "+q/1E3+" seconds";b.logAction(b.LOG_ERROR,"Auth.requestToken()",a);e(new p(a,40170,401))},q);m(a,function(a,d,f){u||(clearTimeout(r),a?(b.logAction(b.LOG_ERROR,"Auth.requestToken()",
  "token request signing call returned error; err = "+k.inspectError(a)),e(l(a))):"string"===typeof d?0===d.length?e(new p("Token string is empty",40170,401)):d.length>n?e(new p("Token string exceeded max permitted length (was "+d.length+" bytes)",40170,401)):"undefined"===d||"null"===d?e(new p("Token string was literal null/undefined",40170,401)):"{"!==d[0]||f&&-1<f.indexOf("application/jwt")?e(null,{token:d}):e(new p("Token was double-encoded; make sure you're not JSON-encoding an already encoded token request or details",
  40170,401)):"object"!==typeof d?(d="Expected token request callback to call back with a token string or token request/details object, but got a "+typeof d,b.logAction(b.LOG_ERROR,"Auth.requestToken()",d),e(new p(d,40170,401))):(a=JSON.stringify(d).length,a>n&&!c.suppressMaxLengthCheck?e(new p("Token request/details object exceeded max permitted stringified size (was "+a+" bytes)",40170,401)):"issued"in d?e(null,d):"keyName"in d?g(d,function(a,c,d,f){a?(b.logAction(b.LOG_ERROR,"Auth.requestToken()",
  "token request API call returned error; err = "+k.inspectError(a)),e(l(a))):(f||(c=JSON.parse(c)),b.logAction(b.LOG_MINOR,"Auth.getToken()","token received"),e(null,c))}):(d="Expected token request callback to call back with a token string, token request object, or token details object",b.logAction(b.LOG_ERROR,"Auth.requestToken()",d),e(new p(d,40170,401)))))})};c.prototype.createTokenRequest=function(a,c,e){"function"!=typeof a||e?"function"!=typeof c||e||(e=c,c=null):(e=a,c=a=null);if(!e&&this.client.options.promises)return k.promisify(this,
  "createTokenRequest",arguments);c=c||this.authOptions;a=a||k.copy(this.tokenParams);var f=c.key;if(f){f=f.split(":");var g=f[0],h=f[1];if(h)if(""===a.clientId)e(new p("clientId can\u2019t be an empty string",40012,400));else{"capability"in a&&(a.capability=d(a.capability));var n=k.mixin({keyName:g},a),l=a.clientId||"",t=a.ttl||"",u=a.capability||"",q=this;(function(a){n.timestamp?a():q.getTimestamp(c&&c.queryTime,function(b,c){b?e(b):(n.timestamp=c,a())})})(function(){var a=n.nonce||(n.nonce=("000000"+
  Math.floor(1E16*Math.random())).slice(-16));a=n.keyName+"\n"+t+"\n"+u+"\n"+l+"\n"+n.timestamp+"\n"+a+"\n";n.mac=n.mac||m(a,h);b.logAction(b.LOG_MINOR,"Auth.getTokenRequest()","generated signed request");e(null,n)})}else e(new p("Invalid key specified",40101,403))}else e(new p("No key specified",40101,403))};c.prototype.getAuthParams=function(a){"basic"==this.method?a(null,{key:this.key}):this._ensureValidAuthCredentials(!1,function(b,c){b?a(b):a(null,{access_token:c.token})})};c.prototype.getAuthHeaders=
  function(a){"basic"==this.method?a(null,{authorization:"Basic "+this.basicKey}):this._ensureValidAuthCredentials(!1,function(b,c){b?a(b):a(null,{authorization:"Bearer "+e(c.token)})})};c.prototype.getTimestamp=function(a,b){this.isTimeOffsetSet()||!a&&!this.authOptions.queryTime?b(null,this.getTimestampUsingOffset()):this.client.time(b)};c.prototype.getTimestampUsingOffset=function(){return k.now()+(this.client.serverTimeOffset||0)};c.prototype.isTimeOffsetSet=function(){return null!==this.client.serverTimeOffset};
  c.prototype._saveBasicOptions=function(a){this.method="basic";this.key=a.key;this.basicKey=e(a.key);this.authOptions=a||{};"clientId"in a&&this._userSetClientId(a.clientId)};c.prototype._saveTokenOptions=function(a,b){this.method="token";a&&(this.tokenParams=a);b&&(b.token&&(b.tokenDetails="string"===typeof b.token?{token:b.token}:b.token),b.tokenDetails&&(this.tokenDetails=b.tokenDetails),"clientId"in b&&this._userSetClientId(b.clientId),this.authOptions=b)};c.prototype._ensureValidAuthCredentials=
  function(a,c){var e=this,d=this.tokenDetails;if(d){if(this._tokenClientIdMismatch(d.clientId)){c(new p("Mismatch between clientId in token ("+d.clientId+") and current clientId ("+this.clientId+")",40102,403));return}if(!this.isTimeOffsetSet()||!d.expires||d.expires>=this.getTimestampUsingOffset()){b.logAction(b.LOG_MINOR,"Auth.getToken()","using cached token; expires = "+d.expires);c(null,d);return}b.logAction(b.LOG_MINOR,"Auth.getToken()","deleting expired token");this.tokenDetails=null}(this.waitingForTokenRequest||
  (this.waitingForTokenRequest=Y())).push(c);if(null===this.currentTokenRequestId||a){var h=this.currentTokenRequestId=t++;this.requestToken(this.tokenParams,this.authOptions,function(a,c){if(e.currentTokenRequestId>h)b.logAction(b.LOG_MINOR,"Auth._ensureValidAuthCredentials()","Discarding token request response; overtaken by newer one");else{e.currentTokenRequestId=null;var d=e.waitingForTokenRequest||f;e.waitingForTokenRequest=null;a?d(a):d(null,e.tokenDetails=c)}})}};c.prototype._userSetClientId=
  function(a){if("string"!==typeof a&&null!==a)throw new p("clientId must be either a string or null",40012,400);if("*"===a)throw new p('Can\u2019t 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);if(a=this._uncheckedSetClientId(a))throw a;};c.prototype._uncheckedSetClientId=
  function(a){if(this._tokenClientIdMismatch(a)){a="Unexpected clientId mismatch: client has "+this.clientId+", requested "+a;var c=new p(a,40102,401);b.logAction(b.LOG_ERROR,"Auth._uncheckedSetClientId()",a);return c}this.clientId=this.tokenParams.clientId=a;return null};c.prototype._tokenClientIdMismatch=function(a){return this.clientId&&"*"!==this.clientId&&a&&"*"!==a&&this.clientId!==a};c.isTokenErr=function(a){return a.code&&40140<=a.code&&40150>a.code};return c}(),D=function(){function f(){}function l(a){if(!(this instanceof
  l))return new l(a);if(!a){var c="no options provided";b.logAction(b.LOG_ERROR,"Rest()",c);throw Error(c);}a=q.objectifyOptions(a);a.log&&b.setLog(a.log.level,a.log.handler);b.logAction(b.LOG_MICRO,"Rest()","initialized with clientOptions "+k.inspect(a));this.options=q.normaliseOptions(a);if(a.key){c=a.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!c)throw c="invalid key parameter",b.logAction(b.LOG_ERROR,"Rest()",c),Error(c);a.keyName=c[1];a.keySecret=c[2]}if("clientId"in a){if("string"!==typeof a.clientId&&
  null!==a.clientId)throw new p("clientId must be either a string or null",40012,400);if("*"===a.clientId)throw new p('Can\u2019t 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);}b.logAction(b.LOG_MINOR,"Rest()","started; version = "+q.libstring);this.baseUri=this.authority=function(b){return q.getHttpScheme(a)+b+":"+q.getPort(a,!1)};this.serverTimeOffset=this._currentFallback=
  null;this.auth=new M(this,a);this.channels=new d(this);this.push=new pa(this)}function d(a){this.rest=a;this.attached={}}var a=v.msgpack;l.prototype.stats=function(a,b){if(void 0===b)if("function"==typeof a)b=a,a=null;else{if(this.options.promises)return k.promisify(this,"stats",arguments);b=f}var c=k.defaultGetHeaders(),d=this.options.useBinaryProtocol?"msgpack":"json";d=x.supportsLinkHeaders?void 0:d;this.options.headers&&k.mixin(c,this.options.headers);(new O(this,"/stats",c,d,function(a,b,c){a=
  c?a:JSON.parse(a);for(b=0;b<a.length;b++)a[b]=ma.fromValues(a[b]);return a})).get(a,b)};l.prototype.time=function(a,b){if(void 0===b)if("function"==typeof a)b=a,a=null;else{if(this.options.promises)return k.promisify(this,"time",arguments);b=f}var c=k.defaultGetHeaders();this.options.headers&&k.mixin(c,this.options.headers);var d=this;x.get(this,function(a){return d.authority(a)+"/time"},c,a,function(a,c,e,f){a?b(a):(f||(c=JSON.parse(c)),(a=c[0])?(d.serverTimeOffset=a-k.now(),b(null,a)):(a=Error("Internal error (unexpected result type from GET /time)"),
  a.statusCode=500,b(a)))})};l.prototype.request=function(b,d,e,m,l,h){var c=this.options.useBinaryProtocol,g=c?a.encode:JSON.stringify,n=c?a.decode:JSON.parse,t=c?"msgpack":"json";c=x.supportsLinkHeaders?void 0:t;e=e||{};b=b.toLowerCase();t="get"==b?k.defaultGetHeaders(t):k.defaultPostHeaders(t);if(void 0===h){if(this.options.promises)return k.promisify(this,"request",[b,d,e,m,l]);h=f}"string"!==typeof m&&(m=g(m));this.options.headers&&k.mixin(t,this.options.headers);l&&k.mixin(t,l);d=new O(this,d,
  t,c,function(a,b,c){return k.ensureArray(c?a:n(a))},!0);if(!k.arrIn(x.methods,b))throw new p("Unsupported method "+b,40500,405);if(k.arrIn(x.methodsWithBody,b))d[b](e,m,h);else d[b](e,h)};l.prototype.setLog=function(a){b.setLog(a.level,a.handler)};d.prototype.get=function(a,b){a=String(a);var c=this.attached[a];c?b&&c.setOptions(b):this.attached[a]=c=new V(this.rest,a,b);return c};d.prototype.release=function(a){delete this.attached[String(a)]};return l}();D.Promise=function(b){b=q.objectifyOptions(b);
  b.promises=!0;return new D(b)};D.Callbacks=D;var E=function(){function f(d){if(!(this instanceof f))return new f(d);b.logAction(b.LOG_MINOR,"Realtime()","");D.call(this,d);this.connection=new qa(this,this.options);this.channels=new l(this);!1!==d.autoConnect&&this.connect()}function l(b){z.call(this);this.realtime=b;this.all={};this.inProgress={};var a=this;b.connection.connectionManager.on("transport.active",function(){a.onTransportActive()})}k.inherits(f,D);f.prototype.connect=function(){b.logAction(b.LOG_MINOR,
  "Realtime.connect()","");this.connection.connect()};f.prototype.close=function(){b.logAction(b.LOG_MINOR,"Realtime.close()","");this.connection.close()};k.inherits(l,z);l.prototype.onChannelMessage=function(d){var a=d.channel;if(void 0===a)b.logAction(b.LOG_ERROR,"Channels.onChannelMessage()","received event unspecified channel, action = "+d.action);else{var c=this.all[a];if(c)c.onMessage(d);else b.logAction(b.LOG_ERROR,"Channels.onChannelMessage()","received event for non-existent channel: "+a)}};
  l.prototype.onTransportActive=function(){for(var b in this.all){var a=this.all[b];"attaching"===a.state||"detaching"===a.state?a.checkPendingState():"suspended"===a.state&&a.attach()}};l.prototype.reattach=function(b){for(var a in this.all){var c=this.all[a];"attached"===c.state&&c.requestState("attaching",b)}};l.prototype.resetAttachedMsgIndicators=function(){for(var b in this.all){var a=this.all[b];"attached"===a.state&&(a._attachedMsgIndicator=!1)}};l.prototype.checkAttachedMsgIndicators=function(d){for(var a in this.all){var c=
  this.all[a];if("attached"===c.state&&!1===c._attachedMsgIndicator){var f="30s after a resume, found channel which has not received an attached; channelId = "+a+"; connectionId = "+d;b.logAction(b.LOG_ERROR,"Channels.checkAttachedMsgIndicators()",f);S.report("error",f,"channel-no-attached-after-resume");c.requestState("attaching")}}};l.prototype.propogateConnectionInterruption=function(b,a){var c=["attaching","attached","detaching","suspended"],d={closing:"detached",closed:"detached",failed:"failed",
  suspended:"suspended"}[b],e;for(e in this.all){var f=this.all[e];k.arrIn(c,f.state)&&f.notifyState(d,a)}};l.prototype.get=function(b,a){b=String(b);var c=this.all[b];c?a&&c.setOptions(a):c=this.all[b]=new Q(this.realtime,b,a);return c};l.prototype.release=function(b){this.all[b]&&delete this.all[b]};l.prototype.setInProgress=function(b,a,c){this.inProgress[b.name]=this.inProgress[b.name]||{};this.inProgress[b.name][a]=c;!c&&this.hasNopending()&&this.emit("nopending")};l.prototype.onceNopending=function(b){if(this.hasNopending())b();
  else this.once("nopending",b)};l.prototype.hasNopending=function(){return k.arrEvery(k.valuesArray(this.inProgress,!0),function(b){return!k.containsValue(b,!0)})};return f}();E.Promise=function(b){b=q.objectifyOptions(b);b.promises=!0;return new E(b)};E.Callbacks=E;var R=function(){return function(b,k,d,a){this.previous=b;this.current=k;d&&(this.retryIn=d);a&&(this.reason=a)}}(),aa=function(){return function(b,k,d,a){this.previous=b;this.current=k;"attached"===k&&(this.resumed=d);a&&(this.reason=
  a)}}(),qa=function(){function f(){}function l(b,a){z.call(this);this.ably=b;this.connectionManager=new N(b,a);this.state=this.connectionManager.state.state;this.recoveryKey=this.timeSerial=this.serial=this.id=this.key=void 0;this.errorReason=null;var c=this;this.connectionManager.on("connectionstate",function(a){var b=c.state=a.current;k.nextTick(function(){c.emit(b,a)})});this.connectionManager.on("update",function(a){k.nextTick(function(){c.emit("update",a)})})}k.inherits(l,z);l.prototype.whenState=
  function(b,a){return z.prototype.whenState.call(this,b,this.state,a,new R(void 0,b))};l.prototype.connect=function(){b.logAction(b.LOG_MINOR,"Connection.connect()","");this.connectionManager.requestState({state:"connecting"})};l.prototype.ping=function(d){b.logAction(b.LOG_MINOR,"Connection.ping()","");if(!d){if(this.ably.options.promises)return k.promisify(this,"ping",arguments);d=f}this.connectionManager.ping(null,d)};l.prototype.close=function(){b.logAction(b.LOG_MINOR,"Connection.close()","connectionKey = "+
  this.key);this.connectionManager.requestState({state:"closing"})};return l}(),pa=function(){function b(){}function l(b){this.rest=b;this.deviceRegistrations=new d(b);this.channelSubscriptions=new a(b)}function d(a){this.rest=a}function a(a){this.rest=a}l.prototype.publish=function(a,d,e){var c=this.rest,f=c.options.useBinaryProtocol?"msgpack":"json",h=k.mixin({recipient:a},d),n=k.defaultPostHeaders(f),g={};if("function"!==typeof e){if(this.rest.options.promises)return k.promisify(this,"publish",arguments);
  e=b}c.options.headers&&k.mixin(n,c.options.headers);c.options.pushFullWait&&k.mixin(g,{fullWait:"true"});h=k.encodeBody(h,f);I.post(c,"/push/publish",h,n,g,!1,function(a){e(a)})};d.prototype.save=function(a,d){var c=this.rest,f=c.options.useBinaryProtocol?"msgpack":"json",n=T.fromValues(a),h=k.defaultPostHeaders(f),l={};if("function"!==typeof d){if(this.rest.options.promises)return k.promisify(this,"save",arguments);d=b}c.options.headers&&k.mixin(h,c.options.headers);c.options.pushFullWait&&k.mixin(l,
  {fullWait:"true"});n=k.encodeBody(n,f);I.put(c,"/push/deviceRegistrations/"+encodeURIComponent(a.id),n,h,l,!1,function(a,b,c,e){d(a,!a&&T.fromResponseBody(b,!e&&f))})};d.prototype.get=function(a,d){var c=this.rest,f=c.options.useBinaryProtocol?"msgpack":"json",n=k.defaultGetHeaders(f),h=a.id||a;if("function"!==typeof d){if(this.rest.options.promises)return k.promisify(this,"get",arguments);d=b}"string"===typeof h&&h.length?(c.options.headers&&k.mixin(n,c.options.headers),I.get(c,"/push/deviceRegistrations/"+
  encodeURIComponent(h),n,{},!1,function(a,b,c,e){d(a,!a&&T.fromResponseBody(b,!e&&f))})):d(new p("First argument to DeviceRegistrations#get must be a deviceId string or DeviceDetails",4E4,400))};d.prototype.list=function(a,d){var c=this.rest,f=c.options.useBinaryProtocol?"msgpack":"json",n=x.supportsLinkHeaders?void 0:f,h=k.defaultGetHeaders(f);if("function"!==typeof d){if(this.rest.options.promises)return k.promisify(this,"list",arguments);d=b}c.options.headers&&k.mixin(h,c.options.headers);(new O(c,
  "/push/deviceRegistrations",h,n,function(a,b,c){return T.fromResponseBody(a,!c&&f)})).get(a,d)};d.prototype.remove=function(a,d){var c=this.rest,f=k.defaultGetHeaders(c.options.useBinaryProtocol?"msgpack":"json"),n={},h=a.id||a;if("function"!==typeof d){if(this.rest.options.promises)return k.promisify(this,"remove",arguments);d=b}"string"===typeof h&&h.length?(c.options.headers&&k.mixin(f,c.options.headers),c.options.pushFullWait&&k.mixin(n,{fullWait:"true"}),I["delete"](c,"/push/deviceRegistrations/"+
  encodeURIComponent(h),f,n,!1,function(a){d(a)})):d(new p("First argument to DeviceRegistrations#remove must be a deviceId string or DeviceDetails",4E4,400))};d.prototype.removeWhere=function(a,d){var c=this.rest,f=k.defaultGetHeaders(c.options.useBinaryProtocol?"msgpack":"json");if("function"!==typeof d){if(this.rest.options.promises)return k.promisify(this,"removeWhere",arguments);d=b}c.options.headers&&k.mixin(f,c.options.headers);c.options.pushFullWait&&k.mixin(a,{fullWait:"true"});I["delete"](c,
  "/push/deviceRegistrations",f,a,!1,function(a){d(a)})};a.prototype.save=function(a,d){var c=this.rest,f=c.options.useBinaryProtocol?"msgpack":"json",l=Z.fromValues(a),h=k.defaultPostHeaders(f),n={};if("function"!==typeof d){if(this.rest.options.promises)return k.promisify(this,"save",arguments);d=b}c.options.headers&&k.mixin(h,c.options.headers);c.options.pushFullWait&&k.mixin(n,{fullWait:"true"});l=k.encodeBody(l,f);I.post(c,"/push/channelSubscriptions",l,h,n,!1,function(a,b,c,e){d(a,!a&&Z.fromResponseBody(b,
  !e&&f))})};a.prototype.list=function(a,d){var c=this.rest,f=c.options.useBinaryProtocol?"msgpack":"json",l=x.supportsLinkHeaders?void 0:f,h=k.defaultGetHeaders(f);if("function"!==typeof d){if(this.rest.options.promises)return k.promisify(this,"list",arguments);d=b}c.options.headers&&k.mixin(h,c.options.headers);(new O(c,"/push/channelSubscriptions",h,l,function(a,b,c){return Z.fromResponseBody(a,!c&&f)})).get(a,d)};a.prototype.removeWhere=function(a,d){var c=this.rest,f=k.defaultGetHeaders(c.options.useBinaryProtocol?
  "msgpack":"json");if("function"!==typeof d){if(this.rest.options.promises)return k.promisify(this,"removeWhere",arguments);d=b}c.options.headers&&k.mixin(f,c.options.headers);c.options.pushFullWait&&k.mixin(a,{fullWait:"true"});I["delete"](c,"/push/channelSubscriptions",f,a,!1,function(a){d(a)})};a.prototype.remove=a.prototype.removeWhere;a.prototype.listChannels=function(a,d){var c=this.rest,f=c.options.useBinaryProtocol?"msgpack":"json",l=x.supportsLinkHeaders?void 0:f,h=k.defaultGetHeaders(f);
  if("function"!==typeof d){if(this.rest.options.promises)return k.promisify(this,"listChannels",arguments);d=b}c.options.headers&&k.mixin(h,c.options.headers);c.options.pushFullWait&&k.mixin(a,{fullWait:"true"});(new O(c,"/push/channels",h,l,function(a,b,c){!c&&f&&(a=k.decodeBody(a,f));for(b=0;b<a.length;b++)a[b]=String(a[b]);return a})).get(a,d)};return function(a){this.rest=a;this.admin=new l(a)}}(),V=function(){function f(){}function l(a,c,d){b.logAction(b.LOG_MINOR,"Channel()","started; name = "+
  c);z.call(this);this.rest=a;this.name=c;this.basePath="/channels/"+encodeURIComponent(c);this.presence=new U(this);this.setOptions(d)}function d(a){return k.arrEvery(a,function(a){return!a.id})}k.inherits(l,z);l.prototype.setOptions=function(a){this.channelOptions=a=a||{};if(a.cipher){if(!Crypto)throw Error("Encryption not enabled; use ably.encryption.js instead");var b=Crypto.getCipher(a.cipher);a.cipher=b.cipherParams;a.channelCipher=b.cipher}else"cipher"in a&&(a.cipher=null,a.channelCipher=null)};
  l.prototype.history=function(a,c){b.logAction(b.LOG_MICRO,"Channel.history()","channel = "+this.name);if(void 0===c)if("function"==typeof a)c=a,a=null;else{if(this.rest.options.promises)return k.promisify(this,"history",arguments);c=f}this._history(a,c)};l.prototype._history=function(a,b){var c=this.rest,e=c.options.useBinaryProtocol?"msgpack":"json",d=x.supportsLinkHeaders?void 0:e,f=k.defaultGetHeaders(e);c.options.headers&&k.mixin(f,c.options.headers);var h=this.channelOptions;(new O(c,this.basePath+
  "/messages",f,d,function(a,b,c){return B.fromResponseBody(a,h,!c&&e)})).get(a,b)};l.prototype.publish=function(){var a=arguments[0],b=arguments[1],l=arguments[arguments.length-1],e=this;if("function"!==typeof l){if(this.rest.options.promises)return k.promisify(this,"publish",arguments);l=f}if("string"===typeof a||null===a){var m=[B.fromValues({name:a,data:b})];var t=arguments[2]}else if(k.isObject(a))m=[B.fromValues(a)],t=arguments[1];else if(k.isArray(a))m=B.fromValuesArray(a),t=arguments[1];else throw new p("The single-argument form of publish() expects a message object or an array of message objects",
  40013,400);"object"===typeof t&&t||(t={});a=this.rest;var h=a.options,u=h.useBinaryProtocol?"msgpack":"json";a=a.options.idempotentRestPublishing;var g=k.defaultPostHeaders(u);h.headers&&k.mixin(g,h.headers);if(a&&d(m)){var w=k.randomString(9);k.arrForEach(m,function(a,b){a.id=w+":"+b.toString()})}B.encodeArray(m,this.channelOptions,function(a){if(a)l(a);else{a=B.getMessagesSize(m);var b=h.maxMessageSize;a>b?l(new p("Maximum size of messages that can be published at once exceeded ( was "+a+" bytes; limit is "+
  b+" bytes)",40009,400)):e._publish(B.serialize(m,u),g,t,l)}})};l.prototype._publish=function(a,b,d,e){I.post(this.rest,this.basePath+"/messages",a,b,d,!1,e)};return l}(),Q=function(){function f(){}function l(a,c,d){b.logAction(b.LOG_MINOR,"RealtimeChannel()","started; name = "+c);V.call(this,a,c,d);this.realtime=a;this.presence=new ra(this,a.options);this.connectionManager=a.connection.connectionManager;this.state="initialized";this.subscriptions=new z;this.syncChannelSerial=void 0;this.properties=
  {attachSerial:void 0};this.setOptions(d);this._mode=this._requestedFlags=this.errorReason=null;this._attachedMsgIndicator=!1}var d=y.Action;k.inherits(l,V);l.invalidStateError=function(a){return{statusCode:400,code:90001,message:"Channel operation failed as channel state is "+a}};l.progressOps={statechange:"statechange",sync:"sync"};l.processListenerArgs=function(a){a=Array.prototype.slice.call(a);"function"===typeof a[0]&&a.unshift(null);void 0==a[a.length-1]&&a.pop();return a};l.prototype.publish=
  function(){var a=arguments.length,b=arguments[0],d=arguments[a-1];if("function"!==typeof d){if(this.realtime.options.promises)return k.promisify(this,"publish",arguments);d=f;++a}if(this.connectionManager.activeState()){if(2==a)if(k.isObject(b))b=[B.fromValues(b)];else if(k.isArray(b))b=B.fromValuesArray(b);else throw new p("The single-argument form of publish() expects a message object or an array of message objects",40013,400);else b=[B.fromValues({name:arguments[0],data:arguments[1]})];var e=this,
  m=this.realtime.options.maxMessageSize;B.encodeArray(b,this.channelOptions,function(a){a?d(a):(a=B.getMessagesSize(b),a>m?d(new p("Maximum size of messages that can be published at once exceeded ( was "+a+" bytes; limit is "+m+" bytes)",40009,400)):e._publish(b,d))})}else d(this.connectionManager.getError())};l.prototype._publish=function(a,c){b.logAction(b.LOG_MICRO,"RealtimeChannel.publish()","message count = "+a.length);var f=this.state;switch(f){case "failed":case "suspended":c(p.fromValues(l.invalidStateError(f)));
  break;default:b.logAction(b.LOG_MICRO,"RealtimeChannel.publish()","sending message; channel state is "+f),f=new y,f.action=d.MESSAGE,f.channel=this.name,f.messages=a,this.sendMessage(f,c)}};l.prototype.onEvent=function(a){b.logAction(b.LOG_MICRO,"RealtimeChannel.onEvent()","received message");for(var c=this.subscriptions,d=0;d<a.length;d++){var e=a[d];c.emit(e.name,e)}};l.prototype.attach=function(a,c){"function"===typeof a&&(c=a,a=null);if(!c){if(this.realtime.options.promises)return k.promisify(this,
  "attach",arguments);c=function(a){a&&b.logAction(b.LOG_MAJOR,"RealtimeChannel.attach()","Channel attach failed: "+a.toString())}}a&&(this._requestedFlags=a);var d=this.connectionManager;if(d.activeState())switch(this.state){case "attached":if(!a){c();break}default:this.requestState("attaching");case "attaching":this.once(function(a){switch(this.event){case "attached":c();break;case "detached":case "suspended":case "failed":c(a.reason||d.getError());break;case "detaching":c(new p("Attach request superseded by a subsequent detach request",
  9E4,409))}})}else c(d.getError())};l.prototype.attachImpl=function(){b.logAction(b.LOG_MICRO,"RealtimeChannel.attachImpl()","sending ATTACH message");this.setInProgress("statechange",!0);var a=y.fromValues({action:d.ATTACH,channel:this.name});this._requestedFlags&&k.arrForEach(this._requestedFlags,function(b){a.setFlag(b)});this.sendMessage(a,f)};l.prototype.detach=function(a){if(!a){if(this.realtime.options.promises)return k.promisify(this,"detach",arguments);a=f}var b=this.connectionManager;if(b.activeState())switch(this.state){case "detached":case "failed":a();
  break;default:this.requestState("detaching");case "detaching":this.once(function(c){switch(this.event){case "detached":a();break;case "attached":case "suspended":case "failed":a(c.reason||b.getError());break;case "attaching":a(new p("Detach request superseded by a subsequent attach request",9E4,409))}})}else a(b.getError())};l.prototype.detachImpl=function(a){b.logAction(b.LOG_MICRO,"RealtimeChannel.detach()","sending DETACH message");this.setInProgress("statechange",!0);var c=y.fromValues({action:d.DETACH,
  channel:this.name});this.sendMessage(c,a||f)};l.prototype.subscribe=function(){var a=l.processListenerArgs(arguments),b=a[0],d=a[1];a=a[2];if(!a){if(this.realtime.options.promises)return k.promisify(this,"subscribe",[b,d]);a=f}if("failed"===this.state)a(p.fromValues(l.invalidStateError("failed")));else return this.subscriptions.on(b,d),this.attach(a)};l.prototype.unsubscribe=function(){var a=l.processListenerArgs(arguments);this.subscriptions.off(a[0],a[1])};l.prototype.sync=function(){switch(this.state){case "initialized":case "detaching":case "detached":throw new p("Unable to sync to channel; not attached",
  4E4);}var a=this.connectionManager;if(!a.activeState())throw a.getError();var b=y.fromValues({action:d.SYNC,channel:this.name});this.syncChannelSerial&&(b.channelSerial=this.syncChannelSerial);a.send(b)};l.prototype.sendMessage=function(a,b){this.connectionManager.send(a,this.realtime.options.queueMessages,b)};l.prototype.sendPresence=function(a,b){var c=y.fromValues({action:d.PRESENCE,channel:this.name,presence:k.isArray(a)?F.fromValuesArray(a):[F.fromValues(a)]});this.sendMessage(c,b)};l.prototype.onMessage=
  function(a){var c=!1;switch(a.action){case d.ATTACHED:this._attachedMsgIndicator=!0;this.properties.attachSerial=a.channelSerial;this._mode=a.getMode();if("attached"===this.state){var f=a.hasFlag("RESUMED");if(!f||this.channelOptions.updateOnAttached)this.presence.onAttached(a.hasFlag("HAS_PRESENCE")),f=new aa(this.state,this.state,f,a.error),this.emit("update",f)}else this.notifyState("attached",a.error,a.hasFlag("RESUMED"),a.hasFlag("HAS_PRESENCE"));break;case d.DETACHED:f=a.error?p.fromValues(a.error):
  new p("Channel detached",90001,404);"detaching"===this.state?this.notifyState("detached",f):"attaching"===this.state?this.notifyState("suspended",f):this.requestState("attaching",f);break;case d.SYNC:c=!0;var e=this.syncChannelSerial=a.channelSerial;if(!a.presence)break;case d.PRESENCE:var k=a.presence;f=a.id;var l=a.connectionId;a=a.timestamp;for(var h=this.channelOptions,u=0;u<k.length;u++){try{var g=k[u];F.decode(g,h)}catch(w){b.logAction(b.LOG_ERROR,"RealtimeChannel.onMessage()",w.toString())}g.connectionId||
  (g.connectionId=l);g.timestamp||(g.timestamp=a);g.id||(g.id=f+":"+u)}this.presence.setPresence(k,c,e);break;case d.MESSAGE:e=a.messages;f=a.id;l=a.connectionId;a=a.timestamp;h=this.channelOptions;for(u=0;u<e.length;u++){try{k=e[u],B.decode(k,h)}catch(w){b.logAction(b.LOG_MINOR,"RealtimeChannel.onMessage()",w.toString())}k.connectionId||(k.connectionId=l);k.timestamp||(k.timestamp=a);k.id||(k.id=f+":"+u)}this.onEvent(e);break;case d.ERROR:(f=a.error)&&80016==f.code?this.checkPendingState():this.notifyState("failed",
  p.fromValues(f));break;default:b.logAction(b.LOG_ERROR,"RealtimeChannel.onMessage()","Fatal protocol error: unrecognised action ("+a.action+")"),this.connectionManager.abort(K.unknownChannelErr)}};l.prototype.onAttached=function(){b.logAction(b.LOG_MINOR,"RealtimeChannel.onAttached","activating channel; name = "+this.name)};l.prototype.notifyState=function(a,c,d,e){b.logAction(b.LOG_MICRO,"RealtimeChannel.notifyState","name = "+this.name+", current state = "+this.state+", notifying state "+a);this.clearStateTimer();
  if(a!==this.state){this.presence.actOnChannelState(a,e,c);"suspended"===a&&this.connectionManager.state.sendEvents?this.startRetryTimer():this.cancelRetryTimer();c&&(this.errorReason=c);d=new aa(this.state,a,d,c);b.logAction("failed"===a?b.LOG_ERROR:b.LOG_MAJOR,'Channel state for channel "'+this.name+'"',a+(c?"; reason: "+c:""));if("attached"===a)this.onAttached(),this.setInProgress("sync",e),this.setInProgress("statechange",!1);else if("detached"===a||"failed"===a||"suspended"===a)this.setInProgress("statechange",
  !1),this.setInProgress("sync",!1);this.state=a;this.emit(a,d)}};l.prototype.requestState=function(a,c){b.logAction(b.LOG_MINOR,"RealtimeChannel.requestState","name = "+this.name+", state = "+a);this.notifyState(a,c);this.checkPendingState()};l.prototype.checkPendingState=function(){var a=this.connectionManager.state;if(a.sendEvents||a.forceQueueEvents)switch(b.logAction(b.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()}else b.logAction(b.LOG_MINOR,"RealtimeChannel.checkPendingState","sendEvents is false; state is "+this.connectionManager.state.state)};l.prototype.timeoutPendingState=function(){switch(this.state){case "attaching":var a=new p("Channel attach timed out",90007,408);this.notifyState("suspended",a);break;case "detaching":a=new p("Channel detach timed out",90007,408);this.notifyState("attached",
  a);break;default:this.checkPendingState()}};l.prototype.startStateTimerIfNotRunning=function(){var a=this;this.stateTimer||(this.stateTimer=setTimeout(function(){b.logAction(b.LOG_MINOR,"RealtimeChannel.startStateTimerIfNotRunning","timer expired");a.stateTimer=null;a.timeoutPendingState()},this.realtime.options.timeouts.realtimeRequestTimeout))};l.prototype.clearStateTimer=function(){var a=this.stateTimer;a&&(clearTimeout(a),this.stateTimer=null)};l.prototype.startRetryTimer=function(){var a=this;
  this.retryTimer||(this.retryTimer=setTimeout(function(){"suspended"===a.state&&a.connectionManager.state.sendEvents&&(a.retryTimer=null,b.logAction(b.LOG_MINOR,"RealtimeChannel retry timer expired","attempting a new attach"),a.requestState("attaching"))},this.realtime.options.timeouts.channelRetryTimeout))};l.prototype.cancelRetryTimer=function(){this.retryTimer&&(clearTimeout(this.retryTimer),this.suspendTimer=null)};l.prototype.setInProgress=function(a,b){this.rest.channels.setInProgress(this,a,
  b)};l.prototype.history=function(a,c){b.logAction(b.LOG_MICRO,"RealtimeChannel.history()","channel = "+this.name);if(void 0===c)if("function"==typeof a)c=a,a=null;else{if(this.rest.options.promises)return k.promisify(this,"history",arguments);c=f}if(a&&a.untilAttach){if("attached"!==this.state){c(new p("option untilAttach requires the channel to be attached",4E4,400));return}if(!this.properties.attachSerial){c(new p("untilAttach was specified and channel is attached, but attachSerial is not defined",
  4E4,400));return}delete a.untilAttach;a.from_serial=this.properties.attachSerial}V.prototype._history.call(this,a,c)};l.prototype.whenState=function(a,b){return z.prototype.whenState.call(this,a,this.state,b)};return l}(),ra=function(){function f(){}function l(a){a=a.channel.realtime;var b=a.auth.clientId;return(!b||"*"===b)&&"connected"===a.connection.state}function d(a,b,c){switch(a.state){case "attached":case "suspended":c();break;case "initialized":case "detached":case "detaching":case "attaching":a.attach(function(a){a?
  b(a):c()});break;default:b(p.fromValues(Q.invalidStateError(a.state)))}}function a(a){U.call(this,a);this.syncComplete=!1;this.members=new c(this);this._myMembers=new c(this);this.subscriptions=new z;this.pendingPresence=[]}function c(a){z.call(this);this.presence=a;this.map={};this.syncInProgress=!1;this.residualMembers=null}function n(a,b){if(a.isSynthesized()||b.isSynthesized())return a.timestamp>b.timestamp;var c=a.parseId(),e=b.parseId();return c.msgSerial===e.msgSerial?c.index>e.index:c.msgSerial>
  e.msgSerial}k.inherits(a,U);a.prototype.enter=function(a,b){if(l(this))throw new p("clientId must be specified to enter a presence channel",40012,400);return this._enterOrUpdateClient(void 0,a,"enter",b)};a.prototype.update=function(a,b){if(l(this))throw new p("clientId must be specified to update presence data",40012,400);return this._enterOrUpdateClient(void 0,a,"update",b)};a.prototype.enterClient=function(a,b,c){return this._enterOrUpdateClient(a,b,"enter",c)};a.prototype.updateClient=function(a,
  b,c){return this._enterOrUpdateClient(a,b,"update",c)};a.prototype._enterOrUpdateClient=function(a,c,d,h){if(!h)if("function"===typeof c)h=c,c=null;else{if(this.channel.realtime.options.promises)return k.promisify(this,"_enterOrUpdateClient",[a,c,d]);h=f}var e=this.channel;if(e.connectionManager.activeState()){b.logAction(b.LOG_MICRO,"RealtimePresence."+d+"Client()","channel = "+e.name+", client = "+(a||"(implicit) "+this.channel.realtime.auth.clientId));var g=F.fromValues({action:d,data:c});a&&(g.clientId=
  a);var l=this;F.encode(g,e.channelOptions,function(a){if(a)h(a);else switch(e.state){case "attached":e.sendPresence(g,h);break;case "initialized":case "detached":e.attach();case "attaching":l.pendingPresence.push({presence:g,callback:h});break;default:a=new p("Unable to "+d+" presence channel (incompatible state)",90001),a.code=90001,h(a)}})}else h(e.connectionManager.getError())};a.prototype.leave=function(a,b){if(l(this))throw new p("clientId must have been specified to enter or leave a presence channel",
  40012,400);return this.leaveClient(void 0,a,b)};a.prototype.leaveClient=function(a,c,d){if(!d)if("function"===typeof c)d=c,c=null;else{if(this.channel.realtime.options.promises)return k.promisify(this,"leaveClient",[a,c]);d=f}var e=this.channel;if(e.connectionManager.activeState())switch(b.logAction(b.LOG_MICRO,"RealtimePresence.leaveClient()","leaving; channel = "+this.channel.name+", client = "+a),c=F.fromValues({action:"leave",data:c}),a&&(c.clientId=a),e.state){case "attached":e.sendPresence(c,
  d);break;case "attaching":this.pendingPresence.push({presence:c,callback:d});break;case "initialized":case "failed":a=new p("Unable to leave presence channel (incompatible state)",90001);d(a);break;default:d(K.failed)}else d(e.connectionManager.getError())};a.prototype.get=function(){function a(a){h(null,c?a.list(c):a.values())}var b=Array.prototype.slice.call(arguments);1==b.length&&"function"==typeof b[0]&&b.unshift(null);var c=b[0],h=b[1],l=!c||("waitForSync"in c?c.waitForSync:!0);if(!h){if(this.channel.realtime.options.promises)return k.promisify(this,
  "get",b);h=f}if("suspended"===this.channel.state)l?h(p.fromValues({statusCode:400,code:91005,message:"Presence state is out of sync due to channel being in the SUSPENDED state"})):a(this.members);else{var g=this;d(this.channel,h,function(){var b=g.members;l?b.waitSync(function(){a(b)}):a(b)})}};a.prototype.history=function(a,c){b.logAction(b.LOG_MICRO,"RealtimePresence.history()","channel = "+this.name);if(void 0===c)if("function"==typeof a)c=a,a=null;else{if(this.channel.realtime.options.promises)return k.promisify(this,
  "history",arguments);c=f}a&&a.untilAttach&&("attached"===this.channel.state?(delete a.untilAttach,a.from_serial=this.channel.properties.attachSerial):c(new p("option untilAttach requires the channel to be attached, was: "+this.channel.state,4E4,400)));U.prototype._history.call(this,a,c)};a.prototype.setPresence=function(a,c,d){b.logAction(b.LOG_MICRO,"RealtimePresence.setPresence()","received presence for "+a.length+" participants; syncChannelSerial = "+d);var e,f,g=this.members,k=this._myMembers,
  l=[],m=this.channel.connectionManager.connectionId;c&&(this.members.startSync(),d&&(f=d.match(/^[\w\-]+:(.*)$/))&&(e=f[1]));for(d=0;d<a.length;d++)switch(f=F.fromValues(a[d]),f.action){case "leave":g.remove(f)&&l.push(f);f.connectionId!==m||f.isSynthesized()||k.remove(f);break;case "enter":case "present":case "update":g.put(f)&&l.push(f),f.connectionId===m&&k.put(f)}c&&!e&&(g.endSync(),this._ensureMyMembersPresent(),this.channel.setInProgress(Q.progressOps.sync,!1),this.channel.syncChannelSerial=
  null);for(d=0;d<l.length;d++)f=l[d],this.subscriptions.emit(f.action,f)};a.prototype.onAttached=function(a){b.logAction(b.LOG_MINOR,"RealtimePresence.onAttached()","channel = "+this.channel.name+", hasPresence = "+a);a?this.members.startSync():(this._synthesizeLeaves(this.members.values()),this.members.clear(),this._ensureMyMembersPresent());a=this.pendingPresence;var c=a.length;if(c){this.pendingPresence=[];var e=[],d=Y();b.logAction(b.LOG_MICRO,"RealtimePresence.onAttached","sending "+c+" queued presence messages");
  for(var f=0;f<c;f++){var g=a[f];e.push(g.presence);d.push(g.callback)}this.channel.sendPresence(e,d)}};a.prototype.actOnChannelState=function(a,b,c){switch(a){case "attached":this.onAttached(b);break;case "detached":case "failed":this._clearMyMembers(),this.members.clear();case "suspended":this.failPendingPresence(c)}};a.prototype.failPendingPresence=function(a){if(this.pendingPresence.length){b.logAction(b.LOG_MINOR,"RealtimeChannel.failPendingPresence","channel; name = "+this.channel.name+", err = "+
  k.inspectError(a));for(var c=0;c<this.pendingPresence.length;c++)try{this.pendingPresence[c].callback(a)}catch(t){}this.pendingPresence=[]}};a.prototype._clearMyMembers=function(){this._myMembers.clear()};a.prototype._ensureMyMembersPresent=function(){function a(a){if(a){a="Presence auto-re-enter failed: "+a.toString();var e=new p(a,91004,400);b.logAction(b.LOG_ERROR,"RealtimePresence._ensureMyMembersPresent()",a);a=new aa(c.channel.state,c.channel.state,!0,e);c.channel.emit("update",a)}}var c=this,
  d=this.members,f=this._myMembers,k;for(k in f.map)if(!(k in d.map)){var g=f.map[k];b.logAction(b.LOG_MICRO,"RealtimePresence._ensureMyMembersPresent()",'Auto-reentering clientId "'+g.clientId+'" into the presence set');this._enterOrUpdateClient(g.clientId,g.data,"enter",a);delete f.map[k]}};a.prototype._synthesizeLeaves=function(a){var b=this.subscriptions;k.arrForEach(a,function(a){a=F.fromValues({action:"leave",connectionId:a.connectionId,clientId:a.clientId,data:a.data,encoding:a.encoding,timestamp:k.now()});
  b.emit("leave",a)})};a.prototype.on=function(){b.deprecated("presence.on","presence.subscribe");this.subscribe.apply(this,arguments)};a.prototype.off=function(){b.deprecated("presence.off","presence.unsubscribe");this.unsubscribe.apply(this,arguments)};a.prototype.subscribe=function(){var a=Q.processListenerArgs(arguments),b=a[0],c=a[1];a=a[2];var d=this.channel;if(!a){if(this.channel.realtime.options.promises)return k.promisify(this,"subscribe",[b,c]);a=f}"failed"===d.state?a(p.fromValues(Q.invalidStateError("failed"))):
  (this.subscriptions.on(b,c),d.attach(a))};a.prototype.unsubscribe=function(){var a=Q.processListenerArgs(arguments);this.subscriptions.off(a[0],a[1])};k.inherits(c,z);c.prototype.get=function(a){return this.map[a]};c.prototype.getClient=function(a){var b=this.map,c=[],d;for(d in b){var e=b[d];e.clientId==a&&"absent"!=e.action&&c.push(e)}return c};c.prototype.list=function(a){var b=this.map,c=a&&a.clientId;a=a&&a.connectionId;var d=[],e;for(e in b){var f=b[e];"absent"!==f.action&&(c&&c!=f.clientId||
  a&&a!=f.connectionId||d.push(f))}return d};c.prototype.put=function(a){if("enter"===a.action||"update"===a.action)a=F.fromValues(a),a.action="present";var b=this.map,c=a.clientId+":"+a.connectionId;this.residualMembers&&delete this.residualMembers[c];var d=b[c];if(d&&!n(a,d))return!1;b[c]=a;return!0};c.prototype.values=function(){var a=this.map,b=[],c;for(c in a){var d=a[c];"absent"!=d.action&&b.push(d)}return b};c.prototype.remove=function(a){var b=this.map,c=a.clientId+":"+a.connectionId,d=b[c];
  if(d&&!n(a,d))return!1;this.syncInProgress?(a=F.fromValues(a),a.action="absent",b[c]=a):delete b[c];return!0};c.prototype.startSync=function(){var a=this.map;b.logAction(b.LOG_MINOR,"PresenceMap.startSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+this.syncInProgress);this.syncInProgress||(this.residualMembers=k.copy(a),this.setInProgress(!0))};c.prototype.endSync=function(){var a=this.map,c=this.syncInProgress;b.logAction(b.LOG_MINOR,"PresenceMap.endSync()","channel = "+this.presence.channel.name+
  "; syncInProgress = "+c);if(c){for(var d in a)"absent"===a[d].action&&delete a[d];this.presence._synthesizeLeaves(k.valuesArray(this.residualMembers));for(d in this.residualMembers)delete a[d];this.residualMembers=null;this.setInProgress(!1)}this.emit("sync")};c.prototype.waitSync=function(a){var c=this.syncInProgress;b.logAction(b.LOG_MINOR,"PresenceMap.waitSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+c);if(c)this.once("sync",a);else a()};c.prototype.clear=function(){this.map=
  {};this.setInProgress(!1);this.residualMembers=null};c.prototype.setInProgress=function(a){b.logAction(b.LOG_MICRO,"PresenceMap.setInProgress()","inProgress = "+a);this.syncInProgress=a;this.presence.syncComplete=!a};return a}(),ia=function(){function f(){}function l(){for(var a in c)c[a].dispose()}function d(b,d,e,f,g,l,p){z.call(this);e=e||{};e.rnd=k.cheapRandStr();var h,m;if(m=n)m=h=(h=navigator.userAgent.toString().match(/MSIE\s([\d.]+)/))&&Number(h[1]);m&&10===h&&!e.envelope&&(e.envelope="json");
  this.uri=b+k.toQueryString(e);this.headers=d||{};this.body=f;this.method=p?p.toUpperCase():k.isEmptyArg(f)?"GET":"POST";this.requestMode=g;this.timeouts=l;this.requestComplete=this.timedOut=!1;c[this.id=String(++a)]=this}var a=0,c={},n="undefined"!==typeof r&&r.XDomainRequest;k.inherits(d,z);var e=d.createRequest=function(a,b,c,e,f,l,n){l=l||q.TIMEOUTS;return new d(a,b,k.copy(c),e,f,l,n)};d.prototype.complete=function(a,b,c,d,e){this.requestComplete||(this.requestComplete=!0,!a&&b&&this.emit("data",
  b),this.emit("complete",a,b,c,d,e),this.dispose())};d.prototype.abort=function(){this.dispose()};d.prototype.exec=function(){function a(a,c,d,f){c=c+" (event type: "+a.type+")"+(e.xhr.statusText?", current statusText is "+e.xhr.statusText:"");b.logAction(b.LOG_ERROR,"Request.on"+a.type+"()",c);e.complete(new p(c,d,f))}function c(){B=r.responseText;for(var a=B.length-1,b,c;E<a&&-1<(b=B.indexOf("\n",E));){c=B.slice(E,b);E=b+1;a:{try{c=JSON.parse(c)}catch(na){e.complete(new p("Malformed response body from server: "+
  na.message,null,400));break a}e.emit("data",c)}}}function d(){c();e.streamComplete=!0;k.nextTick(function(){e.complete()})}var e=this,f=this.timer=setTimeout(function(){e.timedOut=!0;r.abort()},0==this.requestMode?this.timeouts.httpRequestTimeout:this.timeouts.recvTimeout),l=this.body,n=this.method,q=this.headers,r=this.xhr=new XMLHttpRequest,v=q.accept,x="text";v?0===v.indexOf("application/x-msgpack")&&(x="arraybuffer"):q.accept="application/json";l&&-1<(q["content-type"]||(q["content-type"]="application/json")).indexOf("application/json")&&
  "string"!=typeof l&&(l=JSON.stringify(l));r.open(n,this.uri,!0);r.responseType=x;"authorization"in q&&(r.withCredentials=!0);for(var y in q)r.setRequestHeader(y,q[y]);r.onerror=function(b){a(b,"XHR error occurred",null,400)};r.onabort=function(b){e.timedOut?a(b,"Request aborted due to request timeout expiring",null,408):a(b,"Request cancelled",null,400)};r.ontimeout=function(b){a(b,"Request timed out",null,408)};var z,C,B,D,E=0,F=!1;r.onreadystatechange=function(){var a=r.readyState;if(!(3>a)&&0!==
  r.status){if(void 0===C)if(C=r.status,1223===C&&(C=204),clearTimeout(f),D=400>C,204==C)e.complete(null,null,null,null,C);else{var b;if(b=3==e.requestMode&&D)b=r,b=b.getResponseHeader&&(b.getResponseHeader("transfer-encoding")||!b.getResponseHeader("content-length"));z=b}if(3==a&&z)c();else if(4==a)if(z)d();else a:{try{var g=r.getResponseHeader&&r.getResponseHeader("content-type");if(g?0<=g.indexOf("application/json"):"text"==r.responseType){var h="arraybuffer"===r.responseType?A.utf8Decode(r.response):
  String(r.responseText);h.length&&(h=JSON.parse(h));F=!0}else h=r.response;if(void 0!==h.response){C=h.statusCode;D=400>C;var l=h.headers;h=h.response}else{var m=k.trim(r.getAllResponseHeaders()).split("\r\n");a={};for(g=0;g<m.length;g++){var n=k.arrMap(m[g].split(":"),k.trim);a[n[0].toLowerCase()]=n[1]}l=a}}catch(sa){e.complete(new p("Malformed response body from server: "+sa.message,null,400));break a}D||k.isArray(h)?e.complete(null,h,l,F,C):((m=h.error)||(m=new p("Error response received from server: "+
  C+" body was: "+k.inspect(h),null,C)),e.complete(m,h,l,F,C))}}};r.send(l)};d.prototype.dispose=function(){var a=this.xhr;if(a){a.onreadystatechange=a.onerror=a.onabort=a.ontimeout=f;this.xhr=null;var b=this.timer;b&&(clearTimeout(b),this.timer=null);this.requestComplete||a.abort()}delete c[this.id]};v.xhrSupported&&("object"===typeof da&&da.addUnloadListener(l),"undefined"!==typeof x&&(x.supportsAuthHeaders=!0,x.Request=function(a,b,c,d,f,k,l){a=e(c,d,f,k,0,b&&b.options.timeouts,a);a.once("complete",
  l);a.exec();return a},x.checkConnectivity=function(a){var c=q.internetUpUrl;b.logAction(b.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Sending; "+c);x.getUri(null,c,null,null,function(c,d){var e=!c&&"yes"==d.replace(/\n/,"");b.logAction(b.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Result: "+e);a(null,e)})}));return d}();(function(){function f(b,d,a){L.call(this,b,d,a);this.shortName="xhr_streaming"}k.inherits(f,L);f.isAvailable=function(){return v.xhrSupported&&v.streamingSupported&&v.allowComet};
  f.tryConnect=function(k,d,a,c){function l(a){c({event:this.event,error:a})}var e=new f(k,d,a);e.on(["failed","disconnected"],l);e.on("preconnect",function(){b.logAction(b.LOG_MINOR,"XHRStreamingTransport.tryConnect()","viable transport "+e);e.off(["failed","disconnected"],l);c(null,e)});e.connect()};f.prototype.toString=function(){return"XHRStreamingTransport; uri="+this.baseUri+"; isConnected="+this.isConnected};f.prototype.createRequest=function(b,d,a,c,f){return ia.createRequest(b,d,a,c,f,this.timeouts)};
  "undefined"!==typeof N&&f.isAvailable()&&(N.supportedTransports.xhr_streaming=f);return f})();(function(){function f(b,d,a){a.stream=!1;L.call(this,b,d,a);this.shortName="xhr_polling"}k.inherits(f,L);f.isAvailable=function(){return v.xhrSupported&&v.allowComet};f.tryConnect=function(k,d,a,c){function l(a){c({event:this.event,error:a})}var e=new f(k,d,a);e.on(["failed","disconnected"],l);e.on("preconnect",function(){b.logAction(b.LOG_MINOR,"XHRPollingTransport.tryConnect()","viable transport "+e);
  e.off(["failed","disconnected"],l);c(null,e)});e.connect()};f.prototype.toString=function(){return"XHRPollingTransport; uri="+this.baseUri+"; isConnected="+this.isConnected};f.prototype.createRequest=function(b,d,a,c,f){return ia.createRequest(b,d,a,c,f,this.timeouts)};"undefined"!==typeof N&&f.isAvailable()&&(N.supportedTransports.xhr_polling=f);return f})();(function(){function f(){}function l(a,b,c){c.stream=!1;L.call(this,a,b,c);this.shortName="jsonp"}function d(a,b,d,e,f,l,m,n){z.call(this);
  void 0===a&&(a=c++);this.id=a;this.uri=b;this.params=e||{};this.params.rnd=k.cheapRandStr();d&&(d["X-Ably-Version"]&&(this.params.v=d["X-Ably-Version"]),d["X-Ably-Lib"]&&(this.params.lib=d["X-Ably-Lib"]));this.body=f;this.method=n;this.requestMode=l;this.timeouts=m;this.requestComplete=!1}var a=r._ablyjs_jsonp={};a._=function(b){return a["_"+b]||f};var c=1,n=null;k.inherits(l,L);l.isAvailable=function(){return v.jsonpSupported&&v.allowComet};l.isAvailable()&&(N.supportedTransports.jsonp=l);v.jsonpSupported&&
  (n=document.getElementsByTagName("head")[0]);var e=null;r.JSONPTransport=l;l.tryConnect=function(a,c,d,e){function f(a){e({event:this.event,error:a})}var g=new l(a,c,d);g.on(["failed","disconnected"],f);g.on("preconnect",function(){b.logAction(b.LOG_MINOR,"JSONPTransport.tryConnect()","viable transport "+g);g.off(["failed","disconnected"],f);e(null,g)});g.connect()};l.prototype.toString=function(){return"JSONPTransport; uri="+this.baseUri+"; isConnected="+this.isConnected};var m=l.prototype.createRequest=
  function(a,b,c,e,f,l,m){l=this&&this.timeouts||l||q.TIMEOUTS;return new d(void 0,a,b,k.copy(c),e,f,l,m)};k.inherits(d,z);d.prototype.exec=function(){var c=this.id,d=this.body,e=this.method,f=this.uri,l=this.params,m=this;l.callback="_ablyjs_jsonp._("+c+")";l.envelope="jsonp";d&&(l.body=d);e&&"get"!==e&&(l.method=e);d=this.script=document.createElement("script");f+=k.toQueryString(l);d.src=f;d.src.split("/").slice(-1)[0]!==f.split("/").slice(-1)[0]&&b.logAction(b.LOG_ERROR,"JSONP Request.exec()","Warning: the browser appears to have truncated the script URI. This will likely result in the request failing due to an unparseable body param");
  d.async=!0;d.type="text/javascript";d.charset="UTF-8";d.onerror=function(a){m.complete(new p("JSONP script error (event: "+k.inspect(a)+")",null,400))};a["_"+c]=function(a){if(a.statusCode){var b=a.response;204==a.statusCode?m.complete(null,null,null,a.statusCode):b?400>a.statusCode||k.isArray(b)?m.complete(null,b,a.headers,a.statusCode):(a=b.error||new p("Error response received from server",null,a.statusCode),m.complete(a)):m.complete(new p("Invalid server response: no envelope detected",null,500))}else m.complete(null,
  a)};this.timer=setTimeout(function(){m.abort()},this.requestMode==L.REQ_SEND?this.timeouts.httpRequestTimeout:this.timeouts.recvTimeout);n.insertBefore(d,n.firstChild)};d.prototype.complete=function(a,b,c,d){c=c||{};this.requestComplete||(this.requestComplete=!0,b&&(c["content-type"]="string"==typeof b?"text/plain":"application/json",this.emit("data",b)),this.emit("complete",a,b,c,!0,d),this.dispose())};d.prototype.abort=function(){this.dispose()};d.prototype.dispose=function(){var b=this.timer;b&&
  (clearTimeout(b),this.timer=null);b=this.script;b.parentNode&&b.parentNode.removeChild(b);delete a[this.id];this.emit("disposed")};v.jsonpSupported&&!x.Request&&(x.Request=function(a,b,c,d,e,f,l){var g=m(c,d,e,f,L.REQ_SEND,b&&b.options.timeouts,a);g.once("complete",l);k.nextTick(function(){g.exec()});return g},x.checkConnectivity=function(a){var c=q.jsonpInternetUpUrl;if(e)e.push(a);else{e=[a];b.logAction(b.LOG_MICRO,"(JSONP)Http.checkConnectivity()","Sending; "+c);var f=new d("isTheInternetUp",c,
  null,null,null,L.REQ_SEND,q.TIMEOUTS);f.once("complete",function(a,c){var d=!a&&c;b.logAction(b.LOG_MICRO,"(JSONP)Http.checkConnectivity()","Result: "+d);for(var f=0;f<e.length;f++)e[f](null,d);e=null});k.nextTick(function(){f.exec()})}});return l})();"undefined"!==typeof E&&(W.msgpack=ea,W.Rest=D,W.Realtime=E,E.ConnectionManager=N,E.BufferUtils=D.BufferUtils=A,"undefined"!==typeof Crypto&&(E.Crypto=D.Crypto=Crypto),E.Defaults=D.Defaults=q,E.Http=D.Http=x,E.Utils=D.Utils=k,E.Http=D.Http=x,E.Message=
  D.Message=B,E.PresenceMessage=D.PresenceMessage=F,E.ProtocolMessage=D.ProtocolMessage=y);if("object"===typeof r.exports){for(var ba in r.Ably)r.Ably.hasOwnProperty(ba)&&(r.exports[ba]=r.Ably[ba]);r.exports.__esModule=!0}"function"===typeof r.define&&r.define.amd&&r.define("ably",[],function(){return r.Ably})}).call({});
  
  