diff --git a/CHANGELOG.md b/CHANGELOG.md index dc46e231d2..2e838dcbca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ This contains only the most important and/or user-facing changes; for a full changelog, see the commit history. +## [1.0.19](https://github.com/ably/ably-js/tree/1.0.19) (2018-11-22) + +- Expose rest#setLog method to change log level or handler at runtime +- Allow jsonp for REST requests even if allowComet is false +- Expose Rest.Message for node, for consistency with Realtime.Message +- Add updateOnAttached channel option to force 'update' event even if `resumed` is true +- Stop a clientId from forcing token auth (https://github.com/ably/ably-js/issues/542) +- Fix package bloat through mistaken node_modules_node6 includes (due to npm not correctly parsing .gitignore) + ## [1.0.18](https://github.com/ably/ably-js/tree/1.0.18) (2018-09-27) - Fix bug where connectionSerial was not getting reset after a resume failure (https://github.com/ably/ably-js/pull/540) diff --git a/README.md b/README.md index bf7c5945c7..23d4cf69e4 100644 --- a/README.md +++ b/README.md @@ -25,9 +25,9 @@ However, we aim to be compatible with a much wider set of platforms and browsers Ably-js has fallback mechanisms in order to be able to support older browsers; specifically it supports comet-based connections for browsers that do not support websockets, and this includes JSONP for browsers that do not support cross-origin XHR. Each of these fallback transport mechanisms is supported and tested on all the browsers we test against, even when those browsers do not themselves require those fallbacks. These mean that the library should be compatible with nearly any browser on most platforms. Any known browser incompatibilities can be found [here](https://github.com/ably/ably-js/issues?q=is%3Aissue+is%3Aopen+label%3A%22compatibility%22). -#### Version: 1.0.18 +#### Version: 1.0.19 -The latest stable version of the Ably Javascript client library is version: 1.0.18 . +The latest stable version of the Ably Javascript client library is version: 1.0.19 . For complete API documentation, see the [Ably documentation](https://www.ably.io/documentation). diff --git a/bower.json b/bower.json index fd0441f69e..9fd850e8f5 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "Ably", - "version": "1.0.18", + "version": "1.0.19", "homepage": "https://www.ably.io/", "authors": [ "Paddy Byers ", diff --git a/browser/fragments/license.js b/browser/fragments/license.js index 9cba3f608a..ae008ac618 100644 --- a/browser/fragments/license.js +++ b/browser/fragments/license.js @@ -1,7 +1,7 @@ /** * @license Copyright 2018, Ably * - * Ably JavaScript Library v1.0.18 + * Ably JavaScript Library v1.0.19 * https://github.com/ably/ably-js * * Ably Realtime Messaging diff --git a/browser/static/ably-commonjs.js b/browser/static/ably-commonjs.js index 2cc07dd9f9..95a9506dc2 100644 --- a/browser/static/ably-commonjs.js +++ b/browser/static/ably-commonjs.js @@ -1,7 +1,7 @@ /** * @license Copyright 2018, Ably * - * Ably JavaScript Library v1.0.18 + * Ably JavaScript Library v1.0.19 * https://github.com/ably/ably-js * * Ably Realtime Messaging @@ -4091,7 +4091,7 @@ Defaults.TIMEOUTS = { }; Defaults.httpMaxRetryCount = 3; -Defaults.version = '1.0.18'; +Defaults.version = '1.0.19'; Defaults.libstring = Platform.libver + Defaults.version; Defaults.apiVersion = '1.0'; @@ -4189,6 +4189,11 @@ Defaults.normaliseOptions = function(options) { options.useBinaryProtocol = Platform.preferBinary; } + if(options.clientId) { + var headers = options.headers = options.headers || {}; + headers['X-Ably-ClientId'] = options.clientId; + } + return options; }; @@ -8514,8 +8519,7 @@ var Auth = (function() { function useTokenAuth(options) { return options.useTokenAuth || (!basicAuthForced(options) && - (options.clientId || - options.authCallback || + (options.authCallback || options.authUrl || options.token || options.tokenDetails)) @@ -8536,12 +8540,10 @@ var Auth = (function() { logAndValidateTokenAuthMethod(this.authOptions); } else { /* Basic auth */ - if(options.clientId || !options.key) { - var msg = 'Cannot authenticate with basic auth' + - (options.clientId ? ' as a clientId implies token auth' : - (!options.key ? ' as no key was given' : '')); - Logger.logAction(Logger.LOG_ERROR, 'Auth()', msg); - throw new Error(msg); + if(!options.key) { + var msg = 'Cannot authenticate with basic auth as no key was given'; + Logger.logAction(Logger.LOG_ERROR, 'Auth()', msg); + throw new Error(msg); } Logger.logAction(Logger.LOG_MINOR, 'Auth()', 'anonymous, using basic auth'); this._saveBasicOptions(options); @@ -9341,6 +9343,10 @@ var Rest = (function() { } }; + Rest.prototype.setLog = function(logOptions) { + Logger.setLog(logOptions.level, logOptions.handler); + }; + function Channels(rest) { this.rest = rest; this.attached = {}; @@ -9396,7 +9402,10 @@ var Realtime = (function() { this.realtime = realtime; this.all = {}; this.inProgress = {}; - realtime.connection.connectionManager.on('transport.active', this.onTransportActive.bind(this)); + var self = this; + realtime.connection.connectionManager.on('transport.active', function() { + self.onTransportActive(); + }); } Utils.inherits(Channels, EventEmitter); @@ -9973,10 +9982,11 @@ var RealtimeChannel = (function() { this.attachSerial = message.channelSerial; this._mode = message.getMode(); if(this.state === 'attached') { - if(!message.hasFlag('RESUMED')) { + var resumed = message.hasFlag('RESUMED'); + if(!resumed || this.channelOptions.updateOnAttached) { /* On a loss of continuity, the presence set needs to be re-synced */ this.presence.onAttached(message.hasFlag('HAS_PRESENCE')) - var change = new ChannelStateChange(this.state, this.state, false, message.error); + var change = new ChannelStateChange(this.state, this.state, resumed, message.error); this.emit('update', change); } } else { @@ -10346,7 +10356,7 @@ var RealtimePresence = (function() { } Logger.logAction(Logger.LOG_MICRO, 'RealtimePresence.' + action + 'Client()', - action + 'ing; channel = ' + channel.name + ', client = ' + clientId || '(implicit) ' + getClientId(this)); + 'channel = ' + channel.name + ', client = ' + (clientId || '(implicit) ' + getClientId(this))); var presence = PresenceMessage.fromValues({ action : action, @@ -11272,6 +11282,8 @@ var JSONPTransport = (function() { }; if(JSONPTransport.isAvailable()) { ConnectionManager.supportedTransports[shortName] = JSONPTransport; + } + if(Platform.jsonpSupported) { head = document.getElementsByTagName('head')[0]; } @@ -11414,7 +11426,7 @@ var JSONPTransport = (function() { this.emit('disposed'); }; - if(!Http.Request) { + if(Platform.jsonpSupported && !Http.Request) { Http.Request = function(rest, uri, headers, params, body, callback) { var req = createRequest(uri, headers, params, body, CometTransport.REQ_SEND, rest && rest.options.timeouts); req.once('complete', callback); diff --git a/browser/static/ably-commonjs.noencryption.js b/browser/static/ably-commonjs.noencryption.js index 474a85c74c..8e083e3d52 100644 --- a/browser/static/ably-commonjs.noencryption.js +++ b/browser/static/ably-commonjs.noencryption.js @@ -1,7 +1,7 @@ /** * @license Copyright 2018, Ably * - * Ably JavaScript Library v1.0.18 + * Ably JavaScript Library v1.0.19 * https://github.com/ably/ably-js * * Ably Realtime Messaging @@ -2659,7 +2659,7 @@ Defaults.TIMEOUTS = { }; Defaults.httpMaxRetryCount = 3; -Defaults.version = '1.0.18'; +Defaults.version = '1.0.19'; Defaults.libstring = Platform.libver + Defaults.version; Defaults.apiVersion = '1.0'; @@ -2757,6 +2757,11 @@ Defaults.normaliseOptions = function(options) { options.useBinaryProtocol = Platform.preferBinary; } + if(options.clientId) { + var headers = options.headers = options.headers || {}; + headers['X-Ably-ClientId'] = options.clientId; + } + return options; }; @@ -4962,11 +4967,15 @@ var ConnectionManager = (function() { /* TODO remove below line once realtime sends token errors as DISCONNECTEDs */ if(state === 'failed' && Auth.isTokenErr(error)) { state = 'disconnected' } this.notifyState({state: state, error: error}); - } else if(wasActive && (state === 'disconnected')) { + } else if(wasActive && (state === 'disconnected') && (this.state !== this.states.synchronizing)) { /* If we were active but there is another transport scheduled for * activation, go into to the connecting state until that transport * activates and sets us back to connected. (manually starting the - * transition timers in case that never happens) */ + * transition timers in case that never happens). (If we were in the + * synchronizing state, then that's fine, the old transport just got its + * disconnected before the new one got the sync -- ignore it and keep + * waiting for the sync. If it fails we have a separate sync timer that + * will expire). */ Logger.logAction(Logger.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); @@ -7078,8 +7087,7 @@ var Auth = (function() { function useTokenAuth(options) { return options.useTokenAuth || (!basicAuthForced(options) && - (options.clientId || - options.authCallback || + (options.authCallback || options.authUrl || options.token || options.tokenDetails)) @@ -7100,12 +7108,10 @@ var Auth = (function() { logAndValidateTokenAuthMethod(this.authOptions); } else { /* Basic auth */ - if(options.clientId || !options.key) { - var msg = 'Cannot authenticate with basic auth' + - (options.clientId ? ' as a clientId implies token auth' : - (!options.key ? ' as no key was given' : '')); - Logger.logAction(Logger.LOG_ERROR, 'Auth()', msg); - throw new Error(msg); + if(!options.key) { + var msg = 'Cannot authenticate with basic auth as no key was given'; + Logger.logAction(Logger.LOG_ERROR, 'Auth()', msg); + throw new Error(msg); } Logger.logAction(Logger.LOG_MINOR, 'Auth()', 'anonymous, using basic auth'); this._saveBasicOptions(options); @@ -7905,6 +7911,10 @@ var Rest = (function() { } }; + Rest.prototype.setLog = function(logOptions) { + Logger.setLog(logOptions.level, logOptions.handler); + }; + function Channels(rest) { this.rest = rest; this.attached = {}; @@ -7960,7 +7970,10 @@ var Realtime = (function() { this.realtime = realtime; this.all = {}; this.inProgress = {}; - realtime.connection.connectionManager.on('transport.active', this.onTransportActive.bind(this)); + var self = this; + realtime.connection.connectionManager.on('transport.active', function() { + self.onTransportActive(); + }); } Utils.inherits(Channels, EventEmitter); @@ -8537,10 +8550,11 @@ var RealtimeChannel = (function() { this.attachSerial = message.channelSerial; this._mode = message.getMode(); if(this.state === 'attached') { - if(!message.hasFlag('RESUMED')) { + var resumed = message.hasFlag('RESUMED'); + if(!resumed || this.channelOptions.updateOnAttached) { /* On a loss of continuity, the presence set needs to be re-synced */ this.presence.onAttached(message.hasFlag('HAS_PRESENCE')) - var change = new ChannelStateChange(this.state, this.state, false, message.error); + var change = new ChannelStateChange(this.state, this.state, resumed, message.error); this.emit('update', change); } } else { @@ -8910,7 +8924,7 @@ var RealtimePresence = (function() { } Logger.logAction(Logger.LOG_MICRO, 'RealtimePresence.' + action + 'Client()', - action + 'ing; channel = ' + channel.name + ', client = ' + clientId || '(implicit) ' + getClientId(this)); + 'channel = ' + channel.name + ', client = ' + (clientId || '(implicit) ' + getClientId(this))); var presence = PresenceMessage.fromValues({ action : action, @@ -9836,6 +9850,8 @@ var JSONPTransport = (function() { }; if(JSONPTransport.isAvailable()) { ConnectionManager.supportedTransports[shortName] = JSONPTransport; + } + if(Platform.jsonpSupported) { head = document.getElementsByTagName('head')[0]; } @@ -9978,7 +9994,7 @@ var JSONPTransport = (function() { this.emit('disposed'); }; - if(!Http.Request) { + if(Platform.jsonpSupported && !Http.Request) { Http.Request = function(rest, uri, headers, params, body, callback) { var req = createRequest(uri, headers, params, body, CometTransport.REQ_SEND, rest && rest.options.timeouts); req.once('complete', callback); diff --git a/browser/static/ably-nativescript.js b/browser/static/ably-nativescript.js index 60c17dad67..021babc733 100644 --- a/browser/static/ably-nativescript.js +++ b/browser/static/ably-nativescript.js @@ -1,7 +1,7 @@ /** * @license Copyright 2018, Ably * - * Ably JavaScript Library v1.0.18 + * Ably JavaScript Library v1.0.19 * https://github.com/ably/ably-js * * Ably Realtime Messaging @@ -4023,7 +4023,7 @@ Defaults.TIMEOUTS = { }; Defaults.httpMaxRetryCount = 3; -Defaults.version = '1.0.18'; +Defaults.version = '1.0.19'; Defaults.libstring = Platform.libver + Defaults.version; Defaults.apiVersion = '1.0'; @@ -4121,6 +4121,11 @@ Defaults.normaliseOptions = function(options) { options.useBinaryProtocol = Platform.preferBinary; } + if(options.clientId) { + var headers = options.headers = options.headers || {}; + headers['X-Ably-ClientId'] = options.clientId; + } + return options; }; @@ -6326,11 +6331,15 @@ var ConnectionManager = (function() { /* TODO remove below line once realtime sends token errors as DISCONNECTEDs */ if(state === 'failed' && Auth.isTokenErr(error)) { state = 'disconnected' } this.notifyState({state: state, error: error}); - } else if(wasActive && (state === 'disconnected')) { + } else if(wasActive && (state === 'disconnected') && (this.state !== this.states.synchronizing)) { /* If we were active but there is another transport scheduled for * activation, go into to the connecting state until that transport * activates and sets us back to connected. (manually starting the - * transition timers in case that never happens) */ + * transition timers in case that never happens). (If we were in the + * synchronizing state, then that's fine, the old transport just got its + * disconnected before the new one got the sync -- ignore it and keep + * waiting for the sync. If it fails we have a separate sync timer that + * will expire). */ Logger.logAction(Logger.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); @@ -8442,8 +8451,7 @@ var Auth = (function() { function useTokenAuth(options) { return options.useTokenAuth || (!basicAuthForced(options) && - (options.clientId || - options.authCallback || + (options.authCallback || options.authUrl || options.token || options.tokenDetails)) @@ -8464,12 +8472,10 @@ var Auth = (function() { logAndValidateTokenAuthMethod(this.authOptions); } else { /* Basic auth */ - if(options.clientId || !options.key) { - var msg = 'Cannot authenticate with basic auth' + - (options.clientId ? ' as a clientId implies token auth' : - (!options.key ? ' as no key was given' : '')); - Logger.logAction(Logger.LOG_ERROR, 'Auth()', msg); - throw new Error(msg); + if(!options.key) { + var msg = 'Cannot authenticate with basic auth as no key was given'; + Logger.logAction(Logger.LOG_ERROR, 'Auth()', msg); + throw new Error(msg); } Logger.logAction(Logger.LOG_MINOR, 'Auth()', 'anonymous, using basic auth'); this._saveBasicOptions(options); @@ -9269,6 +9275,10 @@ var Rest = (function() { } }; + Rest.prototype.setLog = function(logOptions) { + Logger.setLog(logOptions.level, logOptions.handler); + }; + function Channels(rest) { this.rest = rest; this.attached = {}; @@ -9324,7 +9334,10 @@ var Realtime = (function() { this.realtime = realtime; this.all = {}; this.inProgress = {}; - realtime.connection.connectionManager.on('transport.active', this.onTransportActive.bind(this)); + var self = this; + realtime.connection.connectionManager.on('transport.active', function() { + self.onTransportActive(); + }); } Utils.inherits(Channels, EventEmitter); @@ -9901,10 +9914,11 @@ var RealtimeChannel = (function() { this.attachSerial = message.channelSerial; this._mode = message.getMode(); if(this.state === 'attached') { - if(!message.hasFlag('RESUMED')) { + var resumed = message.hasFlag('RESUMED'); + if(!resumed || this.channelOptions.updateOnAttached) { /* On a loss of continuity, the presence set needs to be re-synced */ this.presence.onAttached(message.hasFlag('HAS_PRESENCE')) - var change = new ChannelStateChange(this.state, this.state, false, message.error); + var change = new ChannelStateChange(this.state, this.state, resumed, message.error); this.emit('update', change); } } else { @@ -10274,7 +10288,7 @@ var RealtimePresence = (function() { } Logger.logAction(Logger.LOG_MICRO, 'RealtimePresence.' + action + 'Client()', - action + 'ing; channel = ' + channel.name + ', client = ' + clientId || '(implicit) ' + getClientId(this)); + 'channel = ' + channel.name + ', client = ' + (clientId || '(implicit) ' + getClientId(this))); var presence = PresenceMessage.fromValues({ action : action, diff --git a/browser/static/ably-reactnative.js b/browser/static/ably-reactnative.js index e6b04da64e..084906f391 100644 --- a/browser/static/ably-reactnative.js +++ b/browser/static/ably-reactnative.js @@ -1,7 +1,7 @@ /** * @license Copyright 2018, Ably * - * Ably JavaScript Library v1.0.18 + * Ably JavaScript Library v1.0.19 * https://github.com/ably/ably-js * * Ably Realtime Messaging @@ -4052,7 +4052,7 @@ Defaults.TIMEOUTS = { }; Defaults.httpMaxRetryCount = 3; -Defaults.version = '1.0.18'; +Defaults.version = '1.0.19'; Defaults.libstring = Platform.libver + Defaults.version; Defaults.apiVersion = '1.0'; @@ -4150,6 +4150,11 @@ Defaults.normaliseOptions = function(options) { options.useBinaryProtocol = Platform.preferBinary; } + if(options.clientId) { + var headers = options.headers = options.headers || {}; + headers['X-Ably-ClientId'] = options.clientId; + } + return options; }; @@ -6355,11 +6360,15 @@ var ConnectionManager = (function() { /* TODO remove below line once realtime sends token errors as DISCONNECTEDs */ if(state === 'failed' && Auth.isTokenErr(error)) { state = 'disconnected' } this.notifyState({state: state, error: error}); - } else if(wasActive && (state === 'disconnected')) { + } else if(wasActive && (state === 'disconnected') && (this.state !== this.states.synchronizing)) { /* If we were active but there is another transport scheduled for * activation, go into to the connecting state until that transport * activates and sets us back to connected. (manually starting the - * transition timers in case that never happens) */ + * transition timers in case that never happens). (If we were in the + * synchronizing state, then that's fine, the old transport just got its + * disconnected before the new one got the sync -- ignore it and keep + * waiting for the sync. If it fails we have a separate sync timer that + * will expire). */ Logger.logAction(Logger.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); @@ -8471,8 +8480,7 @@ var Auth = (function() { function useTokenAuth(options) { return options.useTokenAuth || (!basicAuthForced(options) && - (options.clientId || - options.authCallback || + (options.authCallback || options.authUrl || options.token || options.tokenDetails)) @@ -8493,12 +8501,10 @@ var Auth = (function() { logAndValidateTokenAuthMethod(this.authOptions); } else { /* Basic auth */ - if(options.clientId || !options.key) { - var msg = 'Cannot authenticate with basic auth' + - (options.clientId ? ' as a clientId implies token auth' : - (!options.key ? ' as no key was given' : '')); - Logger.logAction(Logger.LOG_ERROR, 'Auth()', msg); - throw new Error(msg); + if(!options.key) { + var msg = 'Cannot authenticate with basic auth as no key was given'; + Logger.logAction(Logger.LOG_ERROR, 'Auth()', msg); + throw new Error(msg); } Logger.logAction(Logger.LOG_MINOR, 'Auth()', 'anonymous, using basic auth'); this._saveBasicOptions(options); @@ -9298,6 +9304,10 @@ var Rest = (function() { } }; + Rest.prototype.setLog = function(logOptions) { + Logger.setLog(logOptions.level, logOptions.handler); + }; + function Channels(rest) { this.rest = rest; this.attached = {}; @@ -9353,7 +9363,10 @@ var Realtime = (function() { this.realtime = realtime; this.all = {}; this.inProgress = {}; - realtime.connection.connectionManager.on('transport.active', this.onTransportActive.bind(this)); + var self = this; + realtime.connection.connectionManager.on('transport.active', function() { + self.onTransportActive(); + }); } Utils.inherits(Channels, EventEmitter); @@ -9930,10 +9943,11 @@ var RealtimeChannel = (function() { this.attachSerial = message.channelSerial; this._mode = message.getMode(); if(this.state === 'attached') { - if(!message.hasFlag('RESUMED')) { + var resumed = message.hasFlag('RESUMED'); + if(!resumed || this.channelOptions.updateOnAttached) { /* On a loss of continuity, the presence set needs to be re-synced */ this.presence.onAttached(message.hasFlag('HAS_PRESENCE')) - var change = new ChannelStateChange(this.state, this.state, false, message.error); + var change = new ChannelStateChange(this.state, this.state, resumed, message.error); this.emit('update', change); } } else { @@ -10303,7 +10317,7 @@ var RealtimePresence = (function() { } Logger.logAction(Logger.LOG_MICRO, 'RealtimePresence.' + action + 'Client()', - action + 'ing; channel = ' + channel.name + ', client = ' + clientId || '(implicit) ' + getClientId(this)); + 'channel = ' + channel.name + ', client = ' + (clientId || '(implicit) ' + getClientId(this))); var presence = PresenceMessage.fromValues({ action : action, diff --git a/browser/static/ably.d.ts b/browser/static/ably.d.ts index 5c8ee34e1e..98ad0390ad 100644 --- a/browser/static/ably.d.ts +++ b/browser/static/ably.d.ts @@ -332,7 +332,7 @@ declare namespace Types { syncComplete: boolean; get: (Params: realtimePresenceGetCallback | RealtimePresenceParams, callback?: realtimePresenceGetCallback) => void; history: (ParamsOrCallback: RealtimePresenceHistoryParams | paginatedResultCallback, callback?: paginatedResultCallback) => void; - subscribe: (presenceOrCallback: PresenceAction | messageCallback, listener?: messageCallback) => void; + subscribe: (presenceOrCallback: PresenceAction | messageCallback | Array, listener?: messageCallback) => void; unsubscribe: (presence?: PresenceAction, listener?: messageCallback) => void; enter: (data?: errorCallback | any, callback?: errorCallback) => void; update: (data?: errorCallback | any, callback?: errorCallback) => void; @@ -357,7 +357,7 @@ declare namespace Types { attach: (callback?: standardCallback) => void; detach: (callback?: standardCallback) => void; history: (paramsOrCallback?: RealtimePresenceHistoryParams | paginatedResultCallback, callback?: paginatedResultCallback) => void; - subscribe: (eventOrCallback: messageCallback | string, listener?: messageCallback) => void; + subscribe: (eventOrCallback: messageCallback | string | Array, listener?: messageCallback) => void; unsubscribe: (eventOrCallback?: messageCallback | string, listener?: messageCallback) => void; publish: (messagesOrName: any, messageDataOrCallback?: errorCallback | any, callback?: errorCallback) => void; setOptions: (options: any, callback?: errorCallback) => void; diff --git a/browser/static/ably.js b/browser/static/ably.js index 54872b2b5d..b8c96b9cc3 100644 --- a/browser/static/ably.js +++ b/browser/static/ably.js @@ -1,7 +1,7 @@ /** * @license Copyright 2018, Ably * - * Ably JavaScript Library v1.0.18 + * Ably JavaScript Library v1.0.19 * https://github.com/ably/ably-js * * Ably Realtime Messaging @@ -4102,7 +4102,7 @@ Defaults.TIMEOUTS = { }; Defaults.httpMaxRetryCount = 3; -Defaults.version = '1.0.18'; +Defaults.version = '1.0.19'; Defaults.libstring = Platform.libver + Defaults.version; Defaults.apiVersion = '1.0'; @@ -4200,6 +4200,11 @@ Defaults.normaliseOptions = function(options) { options.useBinaryProtocol = Platform.preferBinary; } + if(options.clientId) { + var headers = options.headers = options.headers || {}; + headers['X-Ably-ClientId'] = options.clientId; + } + return options; }; @@ -6405,11 +6410,15 @@ var ConnectionManager = (function() { /* TODO remove below line once realtime sends token errors as DISCONNECTEDs */ if(state === 'failed' && Auth.isTokenErr(error)) { state = 'disconnected' } this.notifyState({state: state, error: error}); - } else if(wasActive && (state === 'disconnected')) { + } else if(wasActive && (state === 'disconnected') && (this.state !== this.states.synchronizing)) { /* If we were active but there is another transport scheduled for * activation, go into to the connecting state until that transport * activates and sets us back to connected. (manually starting the - * transition timers in case that never happens) */ + * transition timers in case that never happens). (If we were in the + * synchronizing state, then that's fine, the old transport just got its + * disconnected before the new one got the sync -- ignore it and keep + * waiting for the sync. If it fails we have a separate sync timer that + * will expire). */ Logger.logAction(Logger.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); @@ -8521,8 +8530,7 @@ var Auth = (function() { function useTokenAuth(options) { return options.useTokenAuth || (!basicAuthForced(options) && - (options.clientId || - options.authCallback || + (options.authCallback || options.authUrl || options.token || options.tokenDetails)) @@ -8543,12 +8551,10 @@ var Auth = (function() { logAndValidateTokenAuthMethod(this.authOptions); } else { /* Basic auth */ - if(options.clientId || !options.key) { - var msg = 'Cannot authenticate with basic auth' + - (options.clientId ? ' as a clientId implies token auth' : - (!options.key ? ' as no key was given' : '')); - Logger.logAction(Logger.LOG_ERROR, 'Auth()', msg); - throw new Error(msg); + if(!options.key) { + var msg = 'Cannot authenticate with basic auth as no key was given'; + Logger.logAction(Logger.LOG_ERROR, 'Auth()', msg); + throw new Error(msg); } Logger.logAction(Logger.LOG_MINOR, 'Auth()', 'anonymous, using basic auth'); this._saveBasicOptions(options); @@ -9348,6 +9354,10 @@ var Rest = (function() { } }; + Rest.prototype.setLog = function(logOptions) { + Logger.setLog(logOptions.level, logOptions.handler); + }; + function Channels(rest) { this.rest = rest; this.attached = {}; @@ -9403,7 +9413,10 @@ var Realtime = (function() { this.realtime = realtime; this.all = {}; this.inProgress = {}; - realtime.connection.connectionManager.on('transport.active', this.onTransportActive.bind(this)); + var self = this; + realtime.connection.connectionManager.on('transport.active', function() { + self.onTransportActive(); + }); } Utils.inherits(Channels, EventEmitter); @@ -9980,10 +9993,11 @@ var RealtimeChannel = (function() { this.attachSerial = message.channelSerial; this._mode = message.getMode(); if(this.state === 'attached') { - if(!message.hasFlag('RESUMED')) { + var resumed = message.hasFlag('RESUMED'); + if(!resumed || this.channelOptions.updateOnAttached) { /* On a loss of continuity, the presence set needs to be re-synced */ this.presence.onAttached(message.hasFlag('HAS_PRESENCE')) - var change = new ChannelStateChange(this.state, this.state, false, message.error); + var change = new ChannelStateChange(this.state, this.state, resumed, message.error); this.emit('update', change); } } else { @@ -10353,7 +10367,7 @@ var RealtimePresence = (function() { } Logger.logAction(Logger.LOG_MICRO, 'RealtimePresence.' + action + 'Client()', - action + 'ing; channel = ' + channel.name + ', client = ' + clientId || '(implicit) ' + getClientId(this)); + 'channel = ' + channel.name + ', client = ' + (clientId || '(implicit) ' + getClientId(this))); var presence = PresenceMessage.fromValues({ action : action, @@ -11279,6 +11293,8 @@ var JSONPTransport = (function() { }; if(JSONPTransport.isAvailable()) { ConnectionManager.supportedTransports[shortName] = JSONPTransport; + } + if(Platform.jsonpSupported) { head = document.getElementsByTagName('head')[0]; } @@ -11421,7 +11437,7 @@ var JSONPTransport = (function() { this.emit('disposed'); }; - if(!Http.Request) { + if(Platform.jsonpSupported && !Http.Request) { Http.Request = function(rest, uri, headers, params, body, callback) { var req = createRequest(uri, headers, params, body, CometTransport.REQ_SEND, rest && rest.options.timeouts); req.once('complete', callback); diff --git a/browser/static/ably.min.js b/browser/static/ably.min.js index 3266969fef..1cc4e9bfd0 100644 --- a/browser/static/ably.min.js +++ b/browser/static/ably.min.js @@ -1,7 +1,7 @@ /* Copyright 2018, Ably - Ably JavaScript Library v1.0.18 + Ably JavaScript Library v1.0.19 https://github.com/ably/ably-js Ably Realtime Messaging @@ -15,303 +15,304 @@ $jscomp.Symbol=function(){var r=0;return function(x){return $jscomp.SYMBOL_PREFI $jscomp.arrayIterator=function(r){var x=0;return $jscomp.iteratorPrototype(function(){return x>>2]|=(d[h>>>2]>>>24-h%4*8&255)<<24-(b+h)%4*8;else if(65535>>2]=d[h>>>2];else f.push.apply(f,d);this.sigBytes+=a;return this}, +a.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),p=a.WordArray=d.extend({init:function(a,f){a=this.words=a||[];this.sigBytes=f!=c?f:4*a.length},toString:function(a){return(a||m).stringify(this)},concat:function(a){var f=this.words,d=a.words,b=this.sigBytes;a=a.sigBytes;this.clamp();if(b%4)for(var h=0;h>>2]|=(d[h>>>2]>>>24-h%4*8&255)<<24-(b+h)%4*8;else if(65535>>2]=d[h>>>2];else f.push.apply(f,d);this.sigBytes+=a;return this}, clamp:function(){var a=this.words,f=this.sigBytes;a[f>>>2]&=4294967295<<32-f%4*8;a.length=e.ceil(f/4)},clone:function(){var a=d.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var f=[],d=function(a){var f=987654321;return function(){f=36969*(f&65535)+(f>>16)&4294967295;a=18E3*(a&65535)+(a>>16)&4294967295;return(((f<<16)+a&4294967295)/4294967296+.5)*(.5>>2]>>>24-b%4*8&255;d.push((h>>>4).toString(16));d.push((h&15).toString(16))}return d.join("")},parse:function(a){for(var f=a.length,d=[],b=0;b>>3]|=parseInt(a.substr(b,2),16)<<24-b%8*4;return new p.init(d,f/2)}},n=g.Latin1={stringify:function(a){var f=a.words;a=a.sigBytes;for(var d=[],b=0;b>>2]>>>24-b%4*8&255));return d.join("")},parse:function(a){for(var f= +a)}}),g=b.enc={},m=g.Hex={stringify:function(a){var f=a.words;a=a.sigBytes;for(var d=[],b=0;b>>2]>>>24-b%4*8&255;d.push((h>>>4).toString(16));d.push((h&15).toString(16))}return d.join("")},parse:function(a){for(var f=a.length,d=[],b=0;b>>3]|=parseInt(a.substr(b,2),16)<<24-b%8*4;return new p.init(d,f/2)}},n=g.Latin1={stringify:function(a){var f=a.words;a=a.sigBytes;for(var d=[],b=0;b>>2]>>>24-b%4*8&255));return d.join("")},parse:function(a){for(var f= a.length,d=[],b=0;b>>2]|=(a.charCodeAt(b)&255)<<24-b%4*8;return new p.init(d,f)}},h=g.Utf8={stringify:function(a){try{return decodeURIComponent(escape(n.stringify(a)))}catch(B){throw Error("Malformed UTF-8 data");}},parse:function(a){return n.parse(unescape(encodeURIComponent(a)))}},f=a.BufferedBlockAlgorithm=d.extend({reset:function(){this._data=new p.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 f= this._data,d=f.words,b=f.sigBytes,h=this.blockSize,g=b/(4*h);g=a?e.ceil(g):e.max((g|0)-this._minBufferSize,0);a=g*h;b=e.min(4*a,b);if(a){for(var u=0;ub;)a(f)&&(8>b&&(p[b]=d(c.pow(f,.5))),g[b]=d(c.pow(f,1/3)),b++),f++})();var l=[];b=b.SHA256=d.extend({_doReset:function(){this._hash=new a.init(p.slice(0))},_doProcessBlock:function(a,d){for(var f=this._hash.words,b=f[0],h=f[1],c=f[2],n=f[3],e=f[4],p=f[5],m=f[6],k=f[7],H=0;64>H;H++){if(16>H)l[H]=a[d+H]|0;else{var q=l[H-15],Q=l[H-2];l[H]=((q<<25|q>>>7)^(q<<14|q>>>18)^q>>>3)+l[H-7]+((Q<<15|Q>>>17)^(Q<<13|Q>>>19)^Q>>>10)+l[H-16]}q=k+((e<<26|e>>>6)^(e<<21|e>>>11)^(e<<7|e>>> -25))+(e&p^~e&m)+g[H]+l[H];Q=((b<<30|b>>>2)^(b<<19|b>>>13)^(b<<10|b>>>22))+(b&h^b&c^h&c);k=m;m=p;p=e;e=n+q|0;n=c;c=h;h=b;b=q+Q|0}f[0]=f[0]+b|0;f[1]=f[1]+h|0;f[2]=f[2]+c|0;f[3]=f[3]+n|0;f[4]=f[4]+e|0;f[5]=f[5]+p|0;f[6]=f[6]+m|0;f[7]=f[7]+k|0},_doFinalize:function(){var a=this._data,d=a.words,f=8*this._nDataBytes,b=8*a.sigBytes;d[b>>>5]|=128<<24-b%32;d[(b+64>>>9<<4)+14]=c.floor(f/4294967296);d[(b+64>>>9<<4)+15]=f;a.sigBytes=4*d.length;this._process();return this._hash},clone:function(){var a=d.clone.call(this); -a._hash=this._hash.clone();return a}});e.SHA256=d._createHelper(b);e.HmacSHA256=d._createHmacHelper(b)})(Math);(function(){var c=x,m=c.enc.Utf8;c.algo.HMAC=c.lib.Base.extend({init:function(b,a){b=this._hasher=new b.init;"string"==typeof a&&(a=m.parse(a));var d=b.blockSize,c=4*d;a.sigBytes>c&&(a=b.finalize(a));a.clamp();b=this._oKey=a.clone();a=this._iKey=a.clone();for(var g=b.words,l=a.words,e=0;e>>2]>>>24-g%4*8&255)<<16|(a[g+1>>>2]>>>24-(g+1)%4*8&255)<<8|a[g+2>>>2]>>>24-(g+2)%4*8&255,n=0;4>n&&g+.75*n>> -6*(3-n)&63));if(a=c.charAt(64))for(;b.length%4;)b.push(a);return b.join("")},parse:function(b){var a=b.length,d=this._map,c=d.charAt(64);c&&(c=b.indexOf(c),-1!=c&&(a=c));c=[];for(var g=0,e=0;e>>6-e%4*2;c[g>>>2]|=(n|h)<<24-g%4*8;g++}return m.create(c,g)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})();x.lib.Cipher||function(c){var e=x,b=e.lib,a=b.Base,d=b.WordArray,p=b.BufferedBlockAlgorithm, -g=e.enc.Base64,l=e.algo.EvpKDF,n=b.Cipher=p.extend({cfg:a.extend(),createEncryptor:function(a,f){return this.create(this._ENC_XFORM_MODE,a,f)},createDecryptor:function(a,f){return this.create(this._DEC_XFORM_MODE,a,f)},init:function(a,f,d){this.cfg=this.cfg.extend(d);this._xformMode=a;this._key=f;this.reset()},reset:function(){p.reset.call(this);this._doReset()},process:function(a){this._append(a);return this._process()},finalize:function(a){a&&this._append(a);return this._doFinalize()},keySize:4, -ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){return function(a){return{encrypt:function(f,d,b){return("string"==typeof d?S:B).encrypt(a,f,d,b)},decrypt:function(f,d,b){return("string"==typeof d?S:B).decrypt(a,f,d,b)}}}}()});b.StreamCipher=n.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var h=e.mode={},f=b.BlockCipherMode=a.extend({createEncryptor:function(a,f){return this.Encryptor.create(a,f)},createDecryptor:function(a,f){return this.Decryptor.create(a, +this._process();return this},finalize:function(a){a&&this._append(a);return this._doFinalize()},blockSize:16,_createHelper:function(a){return function(f,d){return(new a.init(d)).finalize(f)}},_createHmacHelper:function(a){return function(f,d){return(new u.HMAC.init(a,d)).finalize(f)}}});var u=b.algo={};return b}(Math);(function(e){var c=x,b=c.lib,a=b.WordArray,d=b.Hasher;b=c.algo;var p=[],g=[];(function(){function a(a){for(var f=e.sqrt(a),d=2;d<=f;d++)if(!(a%d))return!1;return!0}function d(a){return 4294967296* +(a-(a|0))|0}for(var f=2,b=0;64>b;)a(f)&&(8>b&&(p[b]=d(e.pow(f,.5))),g[b]=d(e.pow(f,1/3)),b++),f++})();var m=[];b=b.SHA256=d.extend({_doReset:function(){this._hash=new a.init(p.slice(0))},_doProcessBlock:function(a,d){for(var f=this._hash.words,b=f[0],h=f[1],c=f[2],e=f[3],n=f[4],p=f[5],k=f[6],l=f[7],I=0;64>I;I++){if(16>I)m[I]=a[d+I]|0;else{var q=m[I-15],R=m[I-2];m[I]=((q<<25|q>>>7)^(q<<14|q>>>18)^q>>>3)+m[I-7]+((R<<15|R>>>17)^(R<<13|R>>>19)^R>>>10)+m[I-16]}q=l+((n<<26|n>>>6)^(n<<21|n>>>11)^(n<<7|n>>> +25))+(n&p^~n&k)+g[I]+m[I];R=((b<<30|b>>>2)^(b<<19|b>>>13)^(b<<10|b>>>22))+(b&h^b&c^h&c);l=k;k=p;p=n;n=e+q|0;e=c;c=h;h=b;b=q+R|0}f[0]=f[0]+b|0;f[1]=f[1]+h|0;f[2]=f[2]+c|0;f[3]=f[3]+e|0;f[4]=f[4]+n|0;f[5]=f[5]+p|0;f[6]=f[6]+k|0;f[7]=f[7]+l|0},_doFinalize:function(){var a=this._data,d=a.words,f=8*this._nDataBytes,b=8*a.sigBytes;d[b>>>5]|=128<<24-b%32;d[(b+64>>>9<<4)+14]=e.floor(f/4294967296);d[(b+64>>>9<<4)+15]=f;a.sigBytes=4*d.length;this._process();return this._hash},clone:function(){var a=d.clone.call(this); +a._hash=this._hash.clone();return a}});c.SHA256=d._createHelper(b);c.HmacSHA256=d._createHmacHelper(b)})(Math);(function(){var c=x,k=c.enc.Utf8;c.algo.HMAC=c.lib.Base.extend({init:function(b,a){b=this._hasher=new b.init;"string"==typeof a&&(a=k.parse(a));var d=b.blockSize,c=4*d;a.sigBytes>c&&(a=b.finalize(a));a.clamp();b=this._oKey=a.clone();a=this._iKey=a.clone();for(var g=b.words,m=a.words,n=0;n>>2]>>>24-g%4*8&255)<<16|(a[g+1>>>2]>>>24-(g+1)%4*8&255)<<8|a[g+2>>>2]>>>24-(g+2)%4*8&255,n=0;4>n&&g+.75*n>> +6*(3-n)&63));if(a=c.charAt(64))for(;b.length%4;)b.push(a);return b.join("")},parse:function(b){var a=b.length,d=this._map,c=d.charAt(64);c&&(c=b.indexOf(c),-1!=c&&(a=c));c=[];for(var g=0,m=0;m>>6-m%4*2;c[g>>>2]|=(n|h)<<24-g%4*8;g++}return k.create(c,g)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})();x.lib.Cipher||function(c){var e=x,b=e.lib,a=b.Base,d=b.WordArray,p=b.BufferedBlockAlgorithm, +g=e.enc.Base64,m=e.algo.EvpKDF,n=b.Cipher=p.extend({cfg:a.extend(),createEncryptor:function(a,f){return this.create(this._ENC_XFORM_MODE,a,f)},createDecryptor:function(a,f){return this.create(this._DEC_XFORM_MODE,a,f)},init:function(a,f,d){this.cfg=this.cfg.extend(d);this._xformMode=a;this._key=f;this.reset()},reset:function(){p.reset.call(this);this._doReset()},process:function(a){this._append(a);return this._process()},finalize:function(a){a&&this._append(a);return this._doFinalize()},keySize:4, +ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){return function(a){return{encrypt:function(f,d,b){return("string"==typeof d?H:B).encrypt(a,f,d,b)},decrypt:function(f,d,b){return("string"==typeof d?H:B).decrypt(a,f,d,b)}}}}()});b.StreamCipher=n.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var h=e.mode={},f=b.BlockCipherMode=a.extend({createEncryptor:function(a,f){return this.Encryptor.create(a,f)},createDecryptor:function(a,f){return this.Decryptor.create(a, f)},init:function(a,f){this._cipher=a;this._iv=f}});h=h.CBC=function(){function a(a,f,d){var b=this._iv;b?this._iv=c:b=this._prevBlock;for(var h=0;h>>2]&255}};b.BlockCipher=n.extend({cfg:n.cfg.extend({mode:h,padding:u}),reset:function(){n.reset.call(this);var a=this.cfg,f=a.iv;a=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var d=a.createEncryptor;else d=a.createDecryptor,this._minBufferSize=1;this._mode=d.call(a,this,f&&f.words)},_doProcessBlock:function(a, f){this._mode.processBlock(a,f)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var f=this._process(!0)}else f=this._process(!0),a.unpad(f);return f},blockSize:4});var v=b.CipherParams=a.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}});h=(e.format={}).OpenSSL={stringify:function(a){var f=a.ciphertext;a=a.salt;return(a?d.create([1398893684,1701076831]).concat(a).concat(f): f).toString(g)},parse:function(a){a=g.parse(a);var f=a.words;if(1398893684==f[0]&&1701076831==f[1]){var b=d.create(f.slice(2,4));f.splice(0,4);a.sigBytes-=16}return v.create({ciphertext:a,salt:b})}};var B=b.SerializableCipher=a.extend({cfg:a.extend({format:h}),encrypt:function(a,f,d,b){b=this.cfg.extend(b);var h=a.createEncryptor(d,b);f=h.finalize(f);h=h.cfg;return v.create({ciphertext:f,key:d,iv:h.iv,algorithm:a,mode:h.mode,padding:h.padding,blockSize:a.blockSize,formatter:b.format})},decrypt:function(a, -f,d,b){b=this.cfg.extend(b);f=this._parse(f,b.format);return a.createDecryptor(d,b).finalize(f.ciphertext)},_parse:function(a,f){return"string"==typeof a?f.parse(a,this):a}});e=(e.kdf={}).OpenSSL={execute:function(a,f,b,h){h||(h=d.random(8));a=l.create({keySize:f+b}).compute(a,h);b=d.create(a.words.slice(f),4*b);a.sigBytes=4*f;return v.create({key:a,iv:b,salt:h})}};var S=b.PasswordBasedCipher=B.extend({cfg:B.cfg.extend({kdf:e}),encrypt:function(a,f,d,b){b=this.cfg.extend(b);d=b.kdf.execute(d,a.keySize, -a.ivSize);b.iv=d.iv;a=B.encrypt.call(this,a,f,d.key,b);a.mixIn(d);return a},decrypt:function(a,f,d,b){b=this.cfg.extend(b);f=this._parse(f,b.format);d=b.kdf.execute(d,a.keySize,a.ivSize,f.salt);b.iv=d.iv;return B.decrypt.call(this,a,f,d.key,b)}})}();(function(){var c=x,m=c.lib.BlockCipher,b=c.algo,a=[],d=[],p=[],g=[],l=[],n=[],h=[],f=[],u=[],v=[];(function(){for(var b=[],c=0;256>c;c++)b[c]=128>c?c<<1:c<<1^283;var e=0,m=0;for(c=0;256>c;c++){var B=m^m<<1^m<<2^m<<3^m<<4;B=B>>>8^B&255^99;a[e]=B;d[B]= -e;var k=b[e],q=b[k],t=b[q],r=257*b[B]^16843008*B;p[e]=r<<24|r>>>8;g[e]=r<<16|r>>>16;l[e]=r<<8|r>>>24;n[e]=r;r=16843009*t^65537*q^257*k^16843008*e;h[B]=r<<24|r>>>8;f[B]=r<<16|r>>>16;u[B]=r<<8|r>>>24;v[B]=r;e?(e=k^b[b[b[t^k]]],m^=b[b[m]]):e=m=1}})();var B=[0,1,2,4,8,16,32,64,128,27,54];b=b.AES=m.extend({_doReset:function(){var b=this._key,d=b.words,g=b.sigBytes/4;b=4*((this._nRounds=g+6)+1);for(var c=this._keySchedule=[],e=0;e>>24]<< -24|a[l>>>16&255]<<16|a[l>>>8&255]<<8|a[l&255]):(l=l<<8|l>>>24,l=a[l>>>24]<<24|a[l>>>16&255]<<16|a[l>>>8&255]<<8|a[l&255],l^=B[e/g|0]<<24);c[e]=c[e-g]^l}d=this._invKeySchedule=[];for(g=0;gg||4>=e?l:h[a[l>>>24]]^f[a[l>>>16&255]]^u[a[l>>>8&255]]^v[a[l&255]]},encryptBlock:function(f,b){this._doCryptBlock(f,b,this._keySchedule,p,g,l,n,a)},decryptBlock:function(a,b){var g=a[b+1];a[b+1]=a[b+3];a[b+3]=g;this._doCryptBlock(a,b,this._invKeySchedule,h,f,u,v,d);g=a[b+1]; -a[b+1]=a[b+3];a[b+3]=g},_doCryptBlock:function(a,f,b,d,h,g,c,e){for(var l=this._nRounds,u=a[f]^b[0],n=a[f+1]^b[1],p=a[f+2]^b[2],v=a[f+3]^b[3],m=4,B=1;B>>24]^h[n>>>16&255]^g[p>>>8&255]^c[v&255]^b[m++],S=d[n>>>24]^h[p>>>16&255]^g[v>>>8&255]^c[u&255]^b[m++],Z=d[p>>>24]^h[v>>>16&255]^g[u>>>8&255]^c[n&255]^b[m++];v=d[v>>>24]^h[u>>>16&255]^g[n>>>8&255]^c[p&255]^b[m++];u=k;n=S;p=Z}k=(e[u>>>24]<<24|e[n>>>16&255]<<16|e[p>>>8&255]<<8|e[v&255])^b[m++];S=(e[n>>>24]<<24|e[p>>>16&255]<<16|e[v>>> -8&255]<<8|e[u&255])^b[m++];Z=(e[p>>>24]<<24|e[v>>>16&255]<<16|e[u>>>8&255]<<8|e[n&255])^b[m++];v=(e[v>>>24]<<24|e[u>>>16&255]<<16|e[n>>>8&255]<<8|e[p&255])^b[m++];a[f]=k;a[f+1]=S;a[f+2]=Z;a[f+3]=v},keySize:8});c.AES=m._createHelper(b)})();(function(){if("undefined"!==typeof ArrayBuffer){var e=x.lib.WordArray,c=e.init;(e.init=function(b){if(b instanceof ArrayBuffer)b=new Uint8Array(b);else if(b instanceof Int8Array||"undefined"!==typeof Uint8ClampedArray&&b instanceof Uint8ClampedArray||b instanceof -Int16Array||b instanceof Uint16Array||b instanceof Int32Array||b instanceof Uint32Array||"undefined"!==typeof Float32Array&&b instanceof Float32Array||"undefined"!==typeof Float64Array&&b instanceof Float64Array)b=new Uint8Array(b.buffer,b.byteOffset,b.byteLength);if(b instanceof Uint8Array){for(var a=b.byteLength,d=[],e=0;e>>2]|=b[e]<<24-e%4*8;c.call(this,d,a)}else c.apply(this,arguments)}).prototype=e}})();var D=function(){function e(){}e.addListener=function(e,b,a){e.addEventListener? -e.addEventListener(b,a,!1):e.attachEvent("on"+b,function(){a.apply(e,arguments)})};e.removeListener=function(e,b,a){e.removeEventListener?e.removeEventListener(b,a,!1):e.detachEvent("on"+b,function(){a.apply(e,arguments)})};e.addMessageListener=function(c,b){e.addListener(c,"message",b)};e.removeMessageListener=function(c,b){e.removeListener(c,"message",b)};e.addUnloadListener=function(c){e.addListener(window,"unload",c)};return e}(),E=function(){function e(a,f,b){for(var d=0,h=b.length;dg)a.setUint8(f++,g>>>0&127|0);else if(2048>g)a.setUint8(f++,g>>>6&31|192),a.setUint8(f++,g>>>0&63|128);else if(65536>g)a.setUint8(f++,g>>>12&15|224),a.setUint8(f++,g>>>6&63|128),a.setUint8(f++,g>>>0&63|128);else if(1114112>g)a.setUint8(f++,g>>>18&7|240),a.setUint8(f++,g>>>12&63|128),a.setUint8(f++,g>>>6&63|128),a.setUint8(f++,g>>>0&63|128);else throw Error("bad codepoint "+g);}}function c(a,f,b){var d="",h=f;for(f+=b;hc;c++)b[c]=128>c?c<<1:c<<1^283;var e=0,k=0;for(c=0;256>c;c++){var B=k^k<<1^k<<2^k<<3^k<<4;B=B>>>8^B&255^99;a[e]=B;d[B]= +e;var l=b[e],q=b[l],t=b[q],r=257*b[B]^16843008*B;p[e]=r<<24|r>>>8;g[e]=r<<16|r>>>16;m[e]=r<<8|r>>>24;n[e]=r;r=16843009*t^65537*q^257*l^16843008*e;h[B]=r<<24|r>>>8;f[B]=r<<16|r>>>16;u[B]=r<<8|r>>>24;v[B]=r;e?(e=l^b[b[b[t^l]]],k^=b[b[k]]):e=k=1}})();var B=[0,1,2,4,8,16,32,64,128,27,54];b=b.AES=k.extend({_doReset:function(){var b=this._key,d=b.words,g=b.sigBytes/4;b=4*((this._nRounds=g+6)+1);for(var c=this._keySchedule=[],e=0;e>>24]<< +24|a[m>>>16&255]<<16|a[m>>>8&255]<<8|a[m&255]):(m=m<<8|m>>>24,m=a[m>>>24]<<24|a[m>>>16&255]<<16|a[m>>>8&255]<<8|a[m&255],m^=B[e/g|0]<<24);c[e]=c[e-g]^m}d=this._invKeySchedule=[];for(g=0;gg||4>=e?m:h[a[m>>>24]]^f[a[m>>>16&255]]^u[a[m>>>8&255]]^v[a[m&255]]},encryptBlock:function(f,b){this._doCryptBlock(f,b,this._keySchedule,p,g,m,n,a)},decryptBlock:function(a,b){var g=a[b+1];a[b+1]=a[b+3];a[b+3]=g;this._doCryptBlock(a,b,this._invKeySchedule,h,f,u,v,d);g=a[b+1]; +a[b+1]=a[b+3];a[b+3]=g},_doCryptBlock:function(a,f,b,d,h,g,c,e){for(var m=this._nRounds,n=a[f]^b[0],u=a[f+1]^b[1],p=a[f+2]^b[2],v=a[f+3]^b[3],k=4,B=1;B>>24]^h[u>>>16&255]^g[p>>>8&255]^c[v&255]^b[k++],H=d[u>>>24]^h[p>>>16&255]^g[v>>>8&255]^c[n&255]^b[k++],Z=d[p>>>24]^h[v>>>16&255]^g[n>>>8&255]^c[u&255]^b[k++];v=d[v>>>24]^h[n>>>16&255]^g[u>>>8&255]^c[p&255]^b[k++];n=l;u=H;p=Z}l=(e[n>>>24]<<24|e[u>>>16&255]<<16|e[p>>>8&255]<<8|e[v&255])^b[k++];H=(e[u>>>24]<<24|e[p>>>16&255]<<16|e[v>>> +8&255]<<8|e[n&255])^b[k++];Z=(e[p>>>24]<<24|e[v>>>16&255]<<16|e[n>>>8&255]<<8|e[u&255])^b[k++];v=(e[v>>>24]<<24|e[n>>>16&255]<<16|e[u>>>8&255]<<8|e[p&255])^b[k++];a[f]=l;a[f+1]=H;a[f+2]=Z;a[f+3]=v},keySize:8});c.AES=k._createHelper(b)})();(function(){if("undefined"!==typeof ArrayBuffer){var c=x.lib.WordArray,k=c.init;(c.init=function(b){if(b instanceof ArrayBuffer)b=new Uint8Array(b);else if(b instanceof Int8Array||"undefined"!==typeof Uint8ClampedArray&&b instanceof Uint8ClampedArray||b instanceof +Int16Array||b instanceof Uint16Array||b instanceof Int32Array||b instanceof Uint32Array||"undefined"!==typeof Float32Array&&b instanceof Float32Array||"undefined"!==typeof Float64Array&&b instanceof Float64Array)b=new Uint8Array(b.buffer,b.byteOffset,b.byteLength);if(b instanceof Uint8Array){for(var a=b.byteLength,d=[],c=0;c>>2]|=b[c]<<24-c%4*8;k.call(this,d,a)}else k.apply(this,arguments)}).prototype=c}})();var D=function(){function c(){}c.addListener=function(c,b,a){c.addEventListener? +c.addEventListener(b,a,!1):c.attachEvent("on"+b,function(){a.apply(c,arguments)})};c.removeListener=function(c,b,a){c.removeEventListener?c.removeEventListener(b,a,!1):c.detachEvent("on"+b,function(){a.apply(c,arguments)})};c.addMessageListener=function(e,b){c.addListener(e,"message",b)};c.removeMessageListener=function(e,b){c.removeListener(e,"message",b)};c.addUnloadListener=function(e){c.addListener(window,"unload",e)};return c}(),E=function(){function c(a,f,b){for(var d=0,h=b.length;dg)a.setUint8(f++,g>>>0&127|0);else if(2048>g)a.setUint8(f++,g>>>6&31|192),a.setUint8(f++,g>>>0&63|128);else if(65536>g)a.setUint8(f++,g>>>12&15|224),a.setUint8(f++,g>>>6&63|128),a.setUint8(f++,g>>>0&63|128);else if(1114112>g)a.setUint8(f++,g>>>18&7|240),a.setUint8(f++,g>>>12&63|128),a.setUint8(f++,g>>>6&63|128),a.setUint8(f++,g>>>0&63|128);else throw Error("bad codepoint "+g);}}function k(a,f,b){var d="",h=f;for(f+=b;hh)f+=1;else if(2048>h)f+=2;else if(65536>h)f+=3;else if(1114112> -h)f+=4;else throw Error("bad codepoint "+h);}return f}function a(a,f){this.offset=f||0;this.view=a}function d(a,f){return k.keysArray(a,!0).filter(function(b){b=a[b];return(!f||void 0!==b&&null!==b)&&("function"!==typeof b||!!b.toJSON)})}function p(a,f,g,c){var h=typeof a;if("string"===h){var l=b(a);if(32>l)return f.setUint8(g,l|160),e(f,g+1,a),1+l;if(256>l)return f.setUint8(g,217),f.setUint8(g+1,l),e(f,g+2,a),2+l;if(65536>l)return f.setUint8(g,218),f.setUint16(g+1,l),e(f,g+3,a),3+l;if(4294967296> -l)return f.setUint8(g,219),f.setUint32(g+1,l),e(f,g+5,a),5+l}if(a instanceof ArrayBuffer){l=a.byteLength;if(256>l)return f.setUint8(g,196),f.setUint8(g+1,l),(new Uint8Array(f.buffer)).set(new Uint8Array(a),g+2),2+l;if(65536>l)return f.setUint8(g,197),f.setUint16(g+1,l),(new Uint8Array(f.buffer)).set(new Uint8Array(a),g+3),3+l;if(4294967296>l)return f.setUint8(g,198),f.setUint32(g+1,l),(new Uint8Array(f.buffer)).set(new Uint8Array(a),g+5),5+l}if("number"===h){if(Math.floor(a)!==a)return f.setUint8(g, +h)f+=4;else throw Error("bad codepoint "+h);}return f}function a(a,f){this.offset=f||0;this.view=a}function d(a,f){return l.keysArray(a,!0).filter(function(b){b=a[b];return(!f||void 0!==b&&null!==b)&&("function"!==typeof b||!!b.toJSON)})}function p(a,f,g,e){var h=typeof a;if("string"===h){var m=b(a);if(32>m)return f.setUint8(g,m|160),c(f,g+1,a),1+m;if(256>m)return f.setUint8(g,217),f.setUint8(g+1,m),c(f,g+2,a),2+m;if(65536>m)return f.setUint8(g,218),f.setUint16(g+1,m),c(f,g+3,a),3+m;if(4294967296> +m)return f.setUint8(g,219),f.setUint32(g+1,m),c(f,g+5,a),5+m}if(a instanceof ArrayBuffer){m=a.byteLength;if(256>m)return f.setUint8(g,196),f.setUint8(g+1,m),(new Uint8Array(f.buffer)).set(new Uint8Array(a),g+2),2+m;if(65536>m)return f.setUint8(g,197),f.setUint16(g+1,m),(new Uint8Array(f.buffer)).set(new Uint8Array(a),g+3),3+m;if(4294967296>m)return f.setUint8(g,198),f.setUint32(g+1,m),(new Uint8Array(f.buffer)).set(new Uint8Array(a),g+5),5+m}if("number"===h){if(Math.floor(a)!==a)return f.setUint8(g, 203),f.setFloat64(g+1,a),9;if(0<=a){if(128>a)return f.setUint8(g,a),1;if(256>a)return f.setUint8(g,204),f.setUint8(g+1,a),2;if(65536>a)return f.setUint8(g,205),f.setUint16(g+1,a),3;if(4294967296>a)return f.setUint8(g,206),f.setUint32(g+1,a),5;if(1.8446744073709552E19>a)return f.setUint8(g,207),g+=1,1.8446744073709552E19>a?(f.setUint32(g,Math.floor(a*n)),f.setInt32(g+4,a&-1)):(f.setUint32(g,4294967295),f.setUint32(g+4,4294967295)),9;throw Error("Number too big 0x"+a.toString(16));}if(-32<=a)return f.setInt8(g, -a),1;if(-128<=a)return f.setUint8(g,208),f.setInt8(g+1,a),2;if(-32768<=a)return f.setUint8(g,209),f.setInt16(g+1,a),3;if(-2147483648<=a)return f.setUint8(g,210),f.setInt32(g+1,a),5;if(-9223372036854775808<=a)return f.setUint8(g,211),g+=1,0x7fffffffffffffff>a?(f.setInt32(g,Math.floor(a*n)),f.setInt32(g+4,a&-1)):(f.setUint32(g,2147483647),f.setUint32(g+4,2147483647)),9;throw Error("Number too small -0x"+(-a).toString(16).substr(1));}if("undefined"===h){if(c)return 0;f.setUint8(g,212);f.setUint8(g+1, -0);f.setUint8(g+2,0);return 3}if(null===a){if(c)return 0;f.setUint8(g,192);return 1}if("boolean"===h)return f.setUint8(g,a?195:194),1;if("function"===typeof a.toJSON)return p(a.toJSON(),f,g,c);if("object"===h){h=0;var u=Array.isArray(a);if(u)l=a.length;else{var v=d(a,c);l=v.length}16>l?(f.setUint8(g,l|(u?144:128)),h=1):65536>l?(f.setUint8(g,u?220:222),f.setUint16(g+1,l),h=3):4294967296>l&&(f.setUint8(g,u?221:223),f.setUint32(g+1,l),h=5);if(u)for(u=0;ue)return 1+e;if(256>e)return 2+e;if(65536>e)return 3+e;if(4294967296>e)return 5+e}if(a instanceof ArrayBuffer){e=a.byteLength;if(256>e)return 2+e;if(65536>e)return 3+e;if(4294967296>e)return 5+e}if("number"===h){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"===h)return 1;if(null===a)return f?0:1;if(void 0===a)return f?0:3;if("function"===typeof a.toJSON)return g(a.toJSON(),f);if("object"===h){h=0;if(Array.isArray(a)){e=a.length;for(var c=0;ce)return 1+h;if(65536>e)return 3+h;if(4294967296>e)return 5+h;throw Error("Array or object too long 0x"+e.toString(16));}if("function"===h)return 0;throw Error("Unknown type "+h);}var l={inspect:function(a){if(void 0===a)return"undefined";if(a instanceof ArrayBuffer){var f="ArrayBuffer";var b=new DataView(a)}else a instanceof DataView&&(f="DataView",b=a);if(!b)return JSON.stringify(a);for(var d=[],g=0;g"}};l.utf8Write=e;l.utf8Read=c;l.utf8ByteCount=b;l.encode=function(a,f){var b=g(a,f);if(0!=b){b=new ArrayBuffer(b);var d=new DataView(b);p(a,d,0,f);return b}};l.decode=function(b){var f=new DataView(b);f=new a(f);var d=f.parse();if(f.offset!==b.byteLength)throw Error(b.byteLength-f.offset+" trailing bytes");return d};var n=1/4294967296;a.prototype.map=function(a){for(var b={},d= -0;da?(f.setInt32(g,Math.floor(a*n)),f.setInt32(g+4,a&-1)):(f.setUint32(g,2147483647),f.setUint32(g+4,2147483647)),9;throw Error("Number too small -0x"+(-a).toString(16).substr(1));}if("undefined"===h){if(e)return 0;f.setUint8(g,212);f.setUint8(g+1, +0);f.setUint8(g+2,0);return 3}if(null===a){if(e)return 0;f.setUint8(g,192);return 1}if("boolean"===h)return f.setUint8(g,a?195:194),1;if("function"===typeof a.toJSON)return p(a.toJSON(),f,g,e);if("object"===h){h=0;var u=Array.isArray(a);if(u)m=a.length;else{var v=d(a,e);m=v.length}16>m?(f.setUint8(g,m|(u?144:128)),h=1):65536>m?(f.setUint8(g,u?220:222),f.setUint16(g+1,m),h=3):4294967296>m&&(f.setUint8(g,u?221:223),f.setUint32(g+1,m),h=5);if(u)for(u=0;uh)return 1+h;if(256>h)return 2+h;if(65536>h)return 3+h;if(4294967296>h)return 5+h}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"===c){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"===c)return 1;if(null===a)return f?0:1;if(void 0===a)return f?0:3;if("function"===typeof a.toJSON)return g(a.toJSON(),f);if("object"===c){c=0;if(Array.isArray(a)){h=a.length;for(var m=0;mh)return 1+c;if(65536>h)return 3+c;if(4294967296>h)return 5+c;throw Error("Array or object too long 0x"+h.toString(16));}if("function"===c)return 0;throw Error("Unknown type "+c);}var m={inspect:function(a){if(void 0===a)return"undefined";if(a instanceof ArrayBuffer){var f="ArrayBuffer";var b=new DataView(a)}else a instanceof DataView&&(f="DataView",b=a);if(!b)return JSON.stringify(a);for(var d=[],g=0;g"}};m.utf8Write=c;m.utf8Read=k;m.utf8ByteCount=b;m.encode=function(a,f){var b=g(a,f);if(0!=b){b=new ArrayBuffer(b);var d=new DataView(b);p(a,d,0,f);return b}};m.decode=function(b){var f=new DataView(b);f=new a(f);var d=f.parse();if(f.offset!==b.byteLength)throw Error(b.byteLength-f.offset+" trailing bytes");return d};var n=1/4294967296;a.prototype.map=function(a){for(var b={},d= +0;d>>2]>>>24-h%4*8&255;return b}throw Error("BufferUtils.toArrayBuffer expected a buffer");};b.toWordArray=function(b){return e(b)?b:a.create(b)};b.base64Encode=function(a){if(c(a)){var b="";a=new Uint8Array(a);var d=a.byteLength,g=d%3;d-=g;for(var f,p,v,m,k=0;k>18,p=(m&258048)>>12,v=(m&4032)>>6,m&=63,b+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[f]+ -"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[p]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[v]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[m];1==g?(m=a[d],b+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(m&252)>>2]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(m&3)<<4]+"=="):2==g&&(m=a[d]<<8|a[d+1],b+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(m&64512)>>10]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(m& -1008)>>4]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(m&15)<<2]+"=");return b}if(e(a))return x.enc.Base64.stringify(a)};b.base64Decode=function(a){if(d&&p){a=p(a);for(var b=a.length,g=new Uint8Array(b),e=0;e=b}var b=function(){};e.get=function(a,d,p, -g,l){l=l||b;var n="function"==typeof d?d:function(b){return a.baseUri(b)+d};var h=(h=a.connection)&&"connected"==h.state?[h.connectionManager.host]:t.getHosts(a.options);if(1==h.length)e.getUri(a,n(h[0]),p,g,l);else{var f=function(b){e.getUri(a,n(b.shift()),p,g,function(a){a&&c(a)&&b.length?f(b):l.apply(null,arguments)})};f(h)}};e.getUri=function(a,d,c,g,l){e.Request(a,d,c,g,null,l||b)};e.post=function(a,d,p,g,l,n){n=n||b;var h="function"==typeof d?d:function(b){return a.baseUri(b)+d};var f=(f=a.connection)&& -"connected"==f.state?[f.connectionManager.host]:t.getHosts(a.options);if(1==f.length)e.postUri(a,h(f[0]),p,g,l,n);else{var u=function(b){e.postUri(a,h(b.shift()),p,g,l,function(a){a&&c(a)&&b.length?u(b):n.apply(null,arguments)})};u(f)}};e.postUri=function(a,d,c,g,l,n){e.Request(a,d,c,l,g,n||b)};e.supportsAuthHeaders=!1;e.supportsLinkHeaders=!1;return e}(),ia=function(){function e(){this.buffer=[]}function c(a){this._input=a;this._index=-1;this._buffer=[]}function b(a){this._input=a;this._index=-1; -this._buffer=[]}e.prototype.append=function(a){this.buffer.push(a);return this};e.prototype.toString=function(){return this.buffer.join("")};var a={codex:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(b){var d=new e,g=a.codex;for(b=new c(b);b.moveNext();){var l=b.current;b.moveNext();var n=b.current;b.moveNext();var h=b.current,f=l>>2;l=(l&3)<<4|n>>4;var u=(n&15)<<2|h>>6,v=h&63;isNaN(n)?u=v=64:isNaN(h)&&(v=64);d.append(g.charAt(f)+g.charAt(l)+g.charAt(u)+g.charAt(v))}return d.toString()}, -decode:function(a){var d=new e;for(a=new b(a);a.moveNext();){var g=a.current;if(128>g)d.append(String.fromCharCode(g));else if(191g){a.moveNext();var c=a.current;d.append(String.fromCharCode((g&31)<<6|c&63))}else a.moveNext(),c=a.current,a.moveNext(),d.append(String.fromCharCode((g&15)<<12|(c&63)<<6|a.current&63))}return d.toString()}};c.prototype={current:Number.NaN,moveNext:function(){if(0=this._input.length- +269488144,269488144],16)];e.CipherParams=k;e.getDefaultParams=function(a){if("function"===typeof a||"string"===typeof a)if(c.deprecated("Crypto.getDefaultParams(key, callback)","Crypto.getDefaultParams({key: key})"),"function"===typeof a)e.generateRandomKey(function(b){a(null,e.getDefaultParams({key:b}))});else if("function"===typeof arguments[1])arguments[1](null,e.getDefaultParams({key:a}));else throw Error("Invalid arguments for Crypto.getDefaultParams");else{if(!a.key)throw Error("Crypto.getDefaultParams: a key is required"); +var b="string"===typeof a.key?x.enc.Base64.parse(a.key.replace("_","/").replace("-","+")):C.toWordArray(a.key);var d=new k;d.key=b;d.algorithm=a.algorithm||"aes";d.keyLength=32*b.words.length;d.mode=a.mode||"cbc";if(a.keyLength&&a.keyLength!==d.keyLength)throw Error("Crypto.getDefaultParams: a keyLength of "+a.keyLength+" was specified, but the key actually has length "+d.keyLength);if("aes"===d.algorithm&&"cbc"===d.mode&&128!==d.keyLength&&256!==d.keyLength)throw Error("Unsupported key length "+ +d.keyLength+" for aes-cbc encryption. Encryption key must be 128 or 256 bits (16 or 32 ASCII characters)");return d}};e.generateRandomKey=function(a,b){1==arguments.length&&"function"==typeof a&&(b=a,a=void 0);p((a||256)/8,b)};e.getCipher=function(a){var d=a instanceof k?a:e.getDefaultParams(a);return{cipherParams:d,cipher:new b(d,4,a.iv)}};b.prototype.encrypt=function(a,b){c.logAction(c.LOG_MICRO,"CBCCipher.encrypt()","");a=C.toWordArray(a);var d=a.sigBytes,f=d+16&-16,e=this,m=function(){e.getIv(function(c, +m){c?b(c):(c=e.encryptCipher.process(a.concat(g[f-d])),m=m.concat(c),b(null,m))})};this.encryptCipher?m():this.iv?(this.encryptCipher=x.algo[this.cjsAlgorithm].createEncryptor(this.key,{iv:this.iv}),m()):p(16,function(a,d){a?b(a):(e.encryptCipher=x.algo[e.cjsAlgorithm].createEncryptor(e.key,{iv:d}),e.iv=d,m())})};b.prototype.decrypt=function(b){c.logAction(c.LOG_MICRO,"CBCCipher.decrypt()","");b=C.toWordArray(b);var d=this.blockLengthWords,g=b.words;b=a.create(g.slice(0,d));g=a.create(g.slice(d)); +d=x.algo[this.cjsAlgorithm].createDecryptor(this.key,{iv:b});b=d.process(g);g=d.finalize();d.reset();g&&g.sigBytes&&b.concat(g);return b};b.prototype.getIv=function(a){if(this.iv){var b=this.iv;this.iv=null;a(null,b)}else{var d=this;p(16,function(b,g){b?a(b):a(null,d.encryptCipher.process(g))})}};return e}(),L=function(){function c(){}function k(a){return a?window.sessionStorage:window.localStorage}function b(a,b,d,c){b={value:b};d&&(b.expires=l.now()+d);return k(c).setItem(a,JSON.stringify(b))}function a(a, +b){var d=k(b).getItem(a);if(!d)return null;d=JSON.parse(d);return d.expires&&d.expires>>2]>>>24-e%4*8&255;return b}throw Error("BufferUtils.toArrayBuffer expected a buffer");};b.toWordArray=function(b){return c(b)?b:a.create(b)};b.base64Encode=function(a){if(k(a)){var b="";a=new Uint8Array(a);var d=a.byteLength,g=d%3;d-=g;for(var f,e,p,l,H=0;H>18,e=(l&258048)>>12,p=(l&4032)>>6,l&=63,b+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[f]+ +"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[e]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[p]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[l];1==g?(l=a[d],b+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(l&252)>>2]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(l&3)<<4]+"=="):2==g&&(l=a[d]<<8|a[d+1],b+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(l&64512)>>10]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(l& +1008)>>4]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(l&15)<<2]+"=");return b}if(c(a))return x.enc.Base64.stringify(a)};b.base64Decode=function(a){if(d&&p){a=p(a);for(var b=a.length,g=new Uint8Array(b),c=0;c=b}var b=function(){};c.get=function(a,d,e, +g,m){m=m||b;var n="function"==typeof d?d:function(b){return a.baseUri(b)+d};var h=(h=a.connection)&&"connected"==h.state?[h.connectionManager.host]:t.getHosts(a.options);if(1==h.length)c.getUri(a,n(h[0]),e,g,m);else{var f=function(b){c.getUri(a,n(b.shift()),e,g,function(a){a&&k(a)&&b.length?f(b):m.apply(null,arguments)})};f(h)}};c.getUri=function(a,d,e,g,m){c.Request(a,d,e,g,null,m||b)};c.post=function(a,d,e,g,m,n){n=n||b;var h="function"==typeof d?d:function(b){return a.baseUri(b)+d};var f=(f=a.connection)&& +"connected"==f.state?[f.connectionManager.host]:t.getHosts(a.options);if(1==f.length)c.postUri(a,h(f[0]),e,g,m,n);else{var p=function(b){c.postUri(a,h(b.shift()),e,g,m,function(a){a&&k(a)&&b.length?p(b):n.apply(null,arguments)})};p(f)}};c.postUri=function(a,d,e,g,m,n){c.Request(a,d,e,m,g,n||b)};c.supportsAuthHeaders=!1;c.supportsLinkHeaders=!1;return c}(),ia=function(){function c(){this.buffer=[]}function k(a){this._input=a;this._index=-1;this._buffer=[]}function b(a){this._input=a;this._index=-1; +this._buffer=[]}c.prototype.append=function(a){this.buffer.push(a);return this};c.prototype.toString=function(){return this.buffer.join("")};var a={codex:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(b){var d=new c,g=a.codex;for(b=new k(b);b.moveNext();){var e=b.current;b.moveNext();var n=b.current;b.moveNext();var h=b.current,f=e>>2;e=(e&3)<<4|n>>4;var u=(n&15)<<2|h>>6,v=h&63;isNaN(n)?u=v=64:isNaN(h)&&(v=64);d.append(g.charAt(f)+g.charAt(e)+g.charAt(u)+g.charAt(v))}return d.toString()}, +decode:function(a){var d=new c;for(a=new b(a);a.moveNext();){var g=a.current;if(128>g)d.append(String.fromCharCode(g));else if(191g){a.moveNext();var e=a.current;d.append(String.fromCharCode((g&31)<<6|e&63))}else a.moveNext(),e=a.current,a.moveNext(),d.append(String.fromCharCode((g&15)<<12|(e&63)<<6|a.current&63))}return d.toString()}};k.prototype={current:Number.NaN,moveNext:function(){if(0=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:(127a?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}};b.prototype={current:64,moveNext:function(){if(0=this._input.length-1)return this.current=64,!1;var b=a.codex.indexOf(this._input.charAt(++this._index)), -e=a.codex.indexOf(this._input.charAt(++this._index)),g=a.codex.indexOf(this._input.charAt(++this._index)),c=a.codex.indexOf(this._input.charAt(++this._index)),n=(g&3)<<6|c;this.current=b<<2|e>>4;64!=g&&this._buffer.push((e&15)<<4|g>>2);64!=c&&this._buffer.push(n);return!0}};return a}();t.ENVIRONMENT="";t.REST_HOST="rest.ably.io";t.REALTIME_HOST="realtime.ably.io";t.FALLBACK_HOSTS=["A.ably-realtime.com","B.ably-realtime.com","C.ably-realtime.com","D.ably-realtime.com","E.ably-realtime.com"];t.PORT= -80;t.TLS_PORT=443;t.TIMEOUTS={disconnectedRetryTimeout:15E3,suspendedRetryTimeout:3E4,httpRequestTimeout:15E3,channelRetryTimeout:15E3,connectionStateTtl:12E4,realtimeRequestTimeout:1E4,recvTimeout:9E4,preferenceConnectTimeout:6E3,parallelUpgradeDelay:6E3};t.httpMaxRetryCount=3;t.version="1.0.18";t.libstring=w.libver+t.version;t.apiVersion="1.0";t.getHost=function(e,c,b){return c=b?c==e.restHost&&e.realtimeHost||c||e.realtimeHost:c||e.restHost};t.getPort=function(e,c){return c||e.tls?e.tlsPort:e.port}; -t.getHttpScheme=function(e){return e.tls?"https://":"http://"};t.getHosts=function(e){var c=[e.restHost],b=e.fallbackHosts;e="undefined"!==typeof e.httpMaxRetryCount?e.httpMaxRetryCount:t.httpMaxRetryCount;b&&(c=c.concat(k.arrChooseN(b,e)));return c};t.normaliseOptions=function(e){e.host&&(c.deprecated("host","restHost"),e.restHost=e.host);e.wsHost&&(c.deprecated("wsHost","realtimeHost"),e.realtimeHost=e.wsHost);e.queueEvents&&(c.deprecated("queueEvents","queueMessages"),e.queueMessages=e.queueEvents); -!0===e.recover&&(c.deprecated("{recover: true}","{recover: function(lastConnectionDetails, cb) { cb(true); }}"),e.recover=function(a,b){b(!0)});"function"===typeof e.recover&&!0===e.closeOnUnload&&(c.logAction(c.LOG_ERROR,"Defaults.normaliseOptions","closeOnUnload was true and a session recovery function was set - these are mutually exclusive, so unsetting the latter"),e.recover=null);"closeOnUnload"in e||(e.closeOnUnload=!e.recover);e.transports&&k.arrIn(e.transports,"xhr")&&(c.deprecated('transports: ["xhr"]', -'transports: ["xhr_streaming"]'),k.arrDeleteValue(e.transports,"xhr"),e.transports.push("xhr_streaming"));"queueMessages"in e||(e.queueMessages=!0);var m=!1;if(e.restHost)e.realtimeHost=e.realtimeHost||e.restHost;else{var b=e.environment&&String(e.environment).toLowerCase()||t.ENVIRONMENT;m=!b||"production"===b;e.restHost=m?t.REST_HOST:b+"-"+t.REST_HOST;e.realtimeHost=m?t.REALTIME_HOST:b+"-"+t.REALTIME_HOST}e.fallbackHosts=m||e.fallbackHostsUseDefault?t.FALLBACK_HOSTS:e.fallbackHosts;e.port=e.port|| -t.PORT;e.tlsPort=e.tlsPort||t.TLS_PORT;"tls"in e||(e.tls=!0);e.timeouts={};for(var a in t.TIMEOUTS)e.timeouts[a]=e[a]||t.TIMEOUTS[a];e.useBinaryProtocol="useBinaryProtocol"in e?w.supportsBinary&&e.useBinaryProtocol:w.preferBinary;return e};var A=function(){function e(){this.any=[];this.events={};this.anyOnce=[];this.eventsOnce={}}function m(a,b,e){try{b.apply(a,e)}catch(g){c.logAction(c.LOG_ERROR,"EventEmitter.emit()","Unexpected listener exception: "+g+"; stack = "+(g&&g.stack))}}function b(a,d, -e){var g,c,n;for(n=0;n>4;64!=g&&this._buffer.push((c&15)<<4|g>>2);64!=e&&this._buffer.push(n);return!0}};return a}();t.ENVIRONMENT="";t.REST_HOST="rest.ably.io";t.REALTIME_HOST="realtime.ably.io";t.FALLBACK_HOSTS=["A.ably-realtime.com","B.ably-realtime.com","C.ably-realtime.com","D.ably-realtime.com","E.ably-realtime.com"];t.PORT= +80;t.TLS_PORT=443;t.TIMEOUTS={disconnectedRetryTimeout:15E3,suspendedRetryTimeout:3E4,httpRequestTimeout:15E3,channelRetryTimeout:15E3,connectionStateTtl:12E4,realtimeRequestTimeout:1E4,recvTimeout:9E4,preferenceConnectTimeout:6E3,parallelUpgradeDelay:6E3};t.httpMaxRetryCount=3;t.version="1.0.19";t.libstring=w.libver+t.version;t.apiVersion="1.0";t.getHost=function(c,k,b){return k=b?k==c.restHost&&c.realtimeHost||k||c.realtimeHost:k||c.restHost};t.getPort=function(c,k){return k||c.tls?c.tlsPort:c.port}; +t.getHttpScheme=function(c){return c.tls?"https://":"http://"};t.getHosts=function(c){var e=[c.restHost],b=c.fallbackHosts;c="undefined"!==typeof c.httpMaxRetryCount?c.httpMaxRetryCount:t.httpMaxRetryCount;b&&(e=e.concat(l.arrChooseN(b,c)));return e};t.normaliseOptions=function(e){e.host&&(c.deprecated("host","restHost"),e.restHost=e.host);e.wsHost&&(c.deprecated("wsHost","realtimeHost"),e.realtimeHost=e.wsHost);e.queueEvents&&(c.deprecated("queueEvents","queueMessages"),e.queueMessages=e.queueEvents); +!0===e.recover&&(c.deprecated("{recover: true}","{recover: function(lastConnectionDetails, cb) { cb(true); }}"),e.recover=function(a,b){b(!0)});"function"===typeof e.recover&&!0===e.closeOnUnload&&(c.logAction(c.LOG_ERROR,"Defaults.normaliseOptions","closeOnUnload was true and a session recovery function was set - these are mutually exclusive, so unsetting the latter"),e.recover=null);"closeOnUnload"in e||(e.closeOnUnload=!e.recover);e.transports&&l.arrIn(e.transports,"xhr")&&(c.deprecated('transports: ["xhr"]', +'transports: ["xhr_streaming"]'),l.arrDeleteValue(e.transports,"xhr"),e.transports.push("xhr_streaming"));"queueMessages"in e||(e.queueMessages=!0);var k=!1;if(e.restHost)e.realtimeHost=e.realtimeHost||e.restHost;else{var b=e.environment&&String(e.environment).toLowerCase()||t.ENVIRONMENT;k=!b||"production"===b;e.restHost=k?t.REST_HOST:b+"-"+t.REST_HOST;e.realtimeHost=k?t.REALTIME_HOST:b+"-"+t.REALTIME_HOST}e.fallbackHosts=k||e.fallbackHostsUseDefault?t.FALLBACK_HOSTS:e.fallbackHosts;e.port=e.port|| +t.PORT;e.tlsPort=e.tlsPort||t.TLS_PORT;"tls"in e||(e.tls=!0);e.timeouts={};for(var a in t.TIMEOUTS)e.timeouts[a]=e[a]||t.TIMEOUTS[a];e.useBinaryProtocol="useBinaryProtocol"in e?w.supportsBinary&&e.useBinaryProtocol:w.preferBinary;e.clientId&&((e.headers=e.headers||{})["X-Ably-ClientId"]=e.clientId);return e};var A=function(){function e(){this.any=[];this.events={};this.anyOnce=[];this.eventsOnce={}}function k(a,b,e){try{b.apply(a,e)}catch(g){c.logAction(c.LOG_ERROR,"EventEmitter.emit()","Unexpected listener exception: "+ +g+"; stack = "+(g&&g.stack))}}function b(a,d,c){var g,e,n;for(n=0;n=c?null:d.slice(0,c).join("/"),a.data=n}}};e.fromResponseBody=function(a,d,p){p&&(a="msgpack"==p?b.decode(a):JSON.parse(String(a)));for(p=0;p=d?null:c.slice(0,d).join("/"),a.data=n}}};e.fromResponseBody=function(a,d,p){p&&(a="msgpack"==p?b.decode(a):JSON.parse(String(a)));for(p=0;pk.arrIndexOf(n,b.shortName)}function m(a,b,c,d){this.options=a;this.host=b;this.mode=c;this.connectionKey=d;this.format=a.useBinaryProtocol?"msgpack":"json";this.timeSerial=this.connectionSerial= -void 0}function b(a,e){A.call(this);this.realtime=a;this.options=e;a=e.timeouts;var f=this;this.states={initialized:{state:"initialized",terminal:!1,queueEvents:!0,sendEvents:!1,failState:"disconnected"},connecting:{state:"connecting",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:a.preferenceConnectTimeout+a.realtimeRequestTimeout,failState:"disconnected"},connected:{state:"connected",terminal:!1,queueEvents:!1,sendEvents:!0,failState:"disconnected"},synchronizing:{state:"connected",terminal:!1, +e.prototype.finish=function(){var b=this.transport;this.onceIdle(function(){b.disconnect()})};e.PendingMessage=function(b,a){this.message=b;this.callback=a;this.merged=!1;b=b.action;this.sendAttempted=!1;this.ackRequired=b==k.MESSAGE||b==k.PRESENCE};return e}(),Q=function(){function e(a,b){return l.arrIndexOf(n,a.shortName)>l.arrIndexOf(n,b.shortName)}function k(a,b,c,d){this.options=a;this.host=b;this.mode=c;this.connectionKey=d;this.format=a.useBinaryProtocol?"msgpack":"json";this.timeSerial=this.connectionSerial= +void 0}function b(a,g){A.call(this);this.realtime=a;this.options=g;a=g.timeouts;var f=this;this.states={initialized:{state:"initialized",terminal:!1,queueEvents:!0,sendEvents:!1,failState:"disconnected"},connecting:{state:"connecting",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:a.preferenceConnectTimeout+a.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:a.disconnectedRetryTimeout,failState:"disconnected"},suspended:{state:"suspended",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:a.suspendedRetryTimeout,failState:"suspended"},closing:{state:"closing",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:a.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 da;this.msgSerial=0;this.connectionSerial=this.timeSerial=this.connectionKey=this.connectionId=this.connectionDetails=void 0;this.connectionStateTtl=a.connectionStateTtl;this.maxIdleInterval=null;this.transports=k.intersect(e.transports||t.defaultTransports,b.supportedTransports);this.baseTransport=k.intersect(t.baseTransportOrder, -this.transports)[0];this.upgradeTransports=k.intersect(this.transports,t.upgradeTransports);this.transportHostBlacklist={};this.transportPreference=null;this.httpHosts=t.getHosts(e);this.activeProtocol=null;this.proposedTransports=[];this.pendingTransports=[];this.mostRecentMsgId=this.lastActivity=this.lastAutoReconnectAttempt=this.host=null;c.logAction(c.LOG_MINOR,"Realtime.ConnectionManager()","started");c.logAction(c.LOG_MICRO,"Realtime.ConnectionManager()","requested transports = ["+(e.transports|| -t.defaultTransports)+"]");c.logAction(c.LOG_MICRO,"Realtime.ConnectionManager()","available transports = ["+this.transports+"]");c.logAction(c.LOG_MICRO,"Realtime.ConnectionManager()","http hosts = ["+this.httpHosts+"]");if(!this.transports.length)throw c.logAction(c.LOG_ERROR,"realtime.ConnectionManager()","no requested transports available"),Error("no requested transports available");if(a=w.addEventListener)d&&"function"===typeof e.recover&&a("beforeunload",this.persistConnection.bind(this)),!0=== -e.closeOnUnload&&a("beforeunload",function(){c.logAction(c.LOG_MAJOR,"Realtime.ConnectionManager()","beforeunload event has triggered the connection to close as closeOnUnload is true");f.requestState({state:"closing"})}),a("online",function(){if(f.state==f.states.disconnected||f.state==f.states.suspended)c.logAction(c.LOG_MINOR,"ConnectionManager caught browser \u2018online\u2019 event","reattempting connection"),f.requestState({state:"connecting"})}),a("offline",function(){f.state==f.states.connected&& -(c.logAction(c.LOG_MINOR,"ConnectionManager caught browser \u2018offline\u2019 event","disconnecting active transport"),f.disconnectAllTransports())})}var a=!("undefined"===typeof K||!K.get),d=!("undefined"===typeof K||!K.getSession),p=z.Action,g=ea.PendingMessage,l=function(){},n=t.transportPreferenceOrder,h=n[n.length-1];m.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; +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 da;this.msgSerial=0;this.connectionSerial=this.timeSerial=this.connectionKey=this.connectionId=this.connectionDetails=void 0;this.connectionStateTtl=a.connectionStateTtl;this.maxIdleInterval=null;this.transports=l.intersect(g.transports||t.defaultTransports,b.supportedTransports);this.baseTransport=l.intersect(t.baseTransportOrder, +this.transports)[0];this.upgradeTransports=l.intersect(this.transports,t.upgradeTransports);this.transportHostBlacklist={};this.transportPreference=null;this.httpHosts=t.getHosts(g);this.activeProtocol=null;this.proposedTransports=[];this.pendingTransports=[];this.mostRecentMsgId=this.lastActivity=this.lastAutoReconnectAttempt=this.host=null;c.logAction(c.LOG_MINOR,"Realtime.ConnectionManager()","started");c.logAction(c.LOG_MICRO,"Realtime.ConnectionManager()","requested transports = ["+(g.transports|| +t.defaultTransports)+"]");c.logAction(c.LOG_MICRO,"Realtime.ConnectionManager()","available transports = ["+this.transports+"]");c.logAction(c.LOG_MICRO,"Realtime.ConnectionManager()","http hosts = ["+this.httpHosts+"]");if(!this.transports.length)throw c.logAction(c.LOG_ERROR,"realtime.ConnectionManager()","no requested transports available"),Error("no requested transports available");if(a=w.addEventListener)d&&"function"===typeof g.recover&&a("beforeunload",this.persistConnection.bind(this)),!0=== +g.closeOnUnload&&a("beforeunload",function(){c.logAction(c.LOG_MAJOR,"Realtime.ConnectionManager()","beforeunload event has triggered the connection to close as closeOnUnload is true");f.requestState({state:"closing"})}),a("online",function(){if(f.state==f.states.disconnected||f.state==f.states.suspended)c.logAction(c.LOG_MINOR,"ConnectionManager caught browser \u2018online\u2019 event","reattempting connection"),f.requestState({state:"connecting"})}),a("offline",function(){f.state==f.states.connected&& +(c.logAction(c.LOG_MINOR,"ConnectionManager caught browser \u2018offline\u2019 event","disconnecting active transport"),f.disconnectAllTransports())})}var a=!("undefined"===typeof L||!L.get),d=!("undefined"===typeof L||!L.getSession),p=z.Action,g=ea.PendingMessage,m=function(){},n=t.transportPreferenceOrder,h=n[n.length-1];k.prototype.getConnectParams=function(a){a=a?l.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=t.apiVersion;a.lib= -t.libstring;void 0!==b.transportParams&&k.mixin(a,b.transportParams);return a};m.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(b,A);b.supportedTransports={};b.prototype.createTransportParams=function(a, -b){a=new m(this.options,a,b,this.connectionKey);this.timeSerial?a.timeSerial=this.timeSerial:void 0!==this.connectionSerial&&(a.connectionSerial=this.connectionSerial);return a};b.prototype.getTransportParams=function(a){var b=this;(function(a){if(b.connectionKey)a("resume");else if("string"===typeof b.options.recover)a("recover");else{var f=b.options.recover,e=d&&K.getSession("ably-connection-recovery");e&&"function"===typeof f?(c.logAction(c.LOG_MINOR,"ConnectionManager.getTransportParams()","Calling clientOptions-provided recover function with last session data"), -f(e,function(c){c?(b.options.recover=e.recoveryKey,a("recover")):a("clean")})):a("clean")}})(function(d){var f=b.createTransportParams(null,d);"recover"===d?(c.logAction(c.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport recovery mode = recover; recoveryKey = "+b.options.recover),(d=b.options.recover.split(":"))&&d[2]&&(b.msgSerial=d[2])):c.logAction(c.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport params = "+f.toString());a(f)})};b.prototype.tryATransport=function(a,d, -e){var f=this,g=a.host;c.logAction(c.LOG_MICRO,"ConnectionManager.tryATransport()","trying "+d);g in this.transportHostBlacklist&&k.arrIn(this.transportHostBlacklist[g],d)?c.logAction(c.LOG_MINOR,"ConnectionManager.tryATransport()",d+" transport is blacklisted for host "+a.host):b.supportedTransports[d].tryConnect(this,this.realtime.auth,a,function(b,g){var h=f.state;h==f.states.closing||h==f.states.closed||h==f.states.failed?(g&&(c.logAction(c.LOG_MINOR,"ConnectionManager.tryATransport()","connection "+ -h.state+" while we were attempting the transport; closing "+g),g.close()),e(!0)):b?(c.logAction(c.LOG_MINOR,"ConnectionManager.tryATransport()","transport "+d+" "+b.event+", err: "+b.error.toString()),N.isTokenErr(b.error)?f.realtime.auth._forceNewToken(null,null,function(b){b?f.actOnErrorFromAuthorize(b):f.tryATransport(a,d,e)}):"failed"===b.event?(f.notifyState({state:"failed",error:b.error}),e(!0)):"disconnected"===b.event&&e(!1)):(c.logAction(c.LOG_MICRO,"ConnectionManager.chooseTransportForHost()", -"viable transport "+d+"; setting pending"),f.setTransportPending(g,a),e(null,g))})};b.prototype.setTransportPending=function(a,b){var d=b.mode;c.logAction(c.LOG_MINOR,"ConnectionManager.setTransportPending()","transport = "+a+"; mode = "+d);k.arrDeleteValue(this.proposedTransports,a);this.pendingTransports.push(a);var f=this;a.once("connected",function(c,e,g,n){"upgrade"==d&&f.activeProtocol?a.shortName!==h&&k.arrIn(f.getUpgradePossibilities(),h)?setTimeout(function(){f.scheduleTransportActivation(c, -a,e,g,n)},f.options.timeouts.parallelUpgradeDelay):f.scheduleTransportActivation(c,a,e,g,n):(f.activateTransport(c,a,e,g,n),k.nextTick(function(){f.connectImpl(b)}));"recover"===d&&f.options.recover&&(f.options.recover=null,f.unpersistConnection())});a.on(["disconnected","closed","failed"],function(b){f.deactivateTransport(a,this.event,b)});this.emit("transport.pending",a)};b.prototype.scheduleTransportActivation=function(a,b,d,g,h){var f=this,n=this.activeProtocol&&this.activeProtocol.getTransport(), -l=function(){b.disconnect();k.arrDeleteValue(f.pendingTransports,b)};this.state!==this.states.connected&&this.state!==this.states.connecting?(c.logAction(c.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 "+b.shortName),l()):n&&!e(b,n)?(c.logAction(c.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()", -"Proposed transport "+b.shortName+" is no better than current active transport "+n.shortName+" - abandoning upgrade"),l()):(c.logAction(c.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Scheduling transport upgrade; transport = "+b),this.realtime.channels.onceNopending(function(e){if(e)c.logAction(c.LOG_ERROR,"ConnectionManager.scheduleTransportActivation()","Unable to activate transport; transport = "+b+"; err = "+e);else if(b.isConnected){if(f.state===f.states.connected){c.logAction(c.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){c.logAction(c.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 "+b.shortName);l();return}var u= +t.libstring;void 0!==b.transportParams&&l.mixin(a,b.transportParams);return a};k.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+"]"};l.inherits(b,A);b.supportedTransports={};b.prototype.createTransportParams=function(a, +b){a=new k(this.options,a,b,this.connectionKey);this.timeSerial?a.timeSerial=this.timeSerial:void 0!==this.connectionSerial&&(a.connectionSerial=this.connectionSerial);return a};b.prototype.getTransportParams=function(a){var b=this;(function(a){if(b.connectionKey)a("resume");else if("string"===typeof b.options.recover)a("recover");else{var f=b.options.recover,g=d&&L.getSession("ably-connection-recovery");g&&"function"===typeof f?(c.logAction(c.LOG_MINOR,"ConnectionManager.getTransportParams()","Calling clientOptions-provided recover function with last session data"), +f(g,function(c){c?(b.options.recover=g.recoveryKey,a("recover")):a("clean")})):a("clean")}})(function(d){var f=b.createTransportParams(null,d);"recover"===d?(c.logAction(c.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport recovery mode = recover; recoveryKey = "+b.options.recover),(d=b.options.recover.split(":"))&&d[2]&&(b.msgSerial=d[2])):c.logAction(c.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport params = "+f.toString());a(f)})};b.prototype.tryATransport=function(a,d, +g){var f=this,e=a.host;c.logAction(c.LOG_MICRO,"ConnectionManager.tryATransport()","trying "+d);e in this.transportHostBlacklist&&l.arrIn(this.transportHostBlacklist[e],d)?c.logAction(c.LOG_MINOR,"ConnectionManager.tryATransport()",d+" transport is blacklisted for host "+a.host):b.supportedTransports[d].tryConnect(this,this.realtime.auth,a,function(b,e){var h=f.state;h==f.states.closing||h==f.states.closed||h==f.states.failed?(e&&(c.logAction(c.LOG_MINOR,"ConnectionManager.tryATransport()","connection "+ +h.state+" while we were attempting the transport; closing "+e),e.close()),g(!0)):b?(c.logAction(c.LOG_MINOR,"ConnectionManager.tryATransport()","transport "+d+" "+b.event+", err: "+b.error.toString()),O.isTokenErr(b.error)?f.realtime.auth._forceNewToken(null,null,function(b){b?f.actOnErrorFromAuthorize(b):f.tryATransport(a,d,g)}):"failed"===b.event?(f.notifyState({state:"failed",error:b.error}),g(!0)):"disconnected"===b.event&&g(!1)):(c.logAction(c.LOG_MICRO,"ConnectionManager.chooseTransportForHost()", +"viable transport "+d+"; setting pending"),f.setTransportPending(e,a),g(null,e))})};b.prototype.setTransportPending=function(a,b){var d=b.mode;c.logAction(c.LOG_MINOR,"ConnectionManager.setTransportPending()","transport = "+a+"; mode = "+d);l.arrDeleteValue(this.proposedTransports,a);this.pendingTransports.push(a);var f=this;a.once("connected",function(c,g,e,n){"upgrade"==d&&f.activeProtocol?a.shortName!==h&&l.arrIn(f.getUpgradePossibilities(),h)?setTimeout(function(){f.scheduleTransportActivation(c, +a,g,e,n)},f.options.timeouts.parallelUpgradeDelay):f.scheduleTransportActivation(c,a,g,e,n):(f.activateTransport(c,a,g,e,n),l.nextTick(function(){f.connectImpl(b)}));"recover"===d&&f.options.recover&&(f.options.recover=null,f.unpersistConnection())});a.on(["disconnected","closed","failed"],function(b){f.deactivateTransport(a,this.event,b)});this.emit("transport.pending",a)};b.prototype.scheduleTransportActivation=function(a,b,d,g,h){var f=this,n=this.activeProtocol&&this.activeProtocol.getTransport(), +m=function(){b.disconnect();l.arrDeleteValue(f.pendingTransports,b)};this.state!==this.states.connected&&this.state!==this.states.connecting?(c.logAction(c.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 "+b.shortName),m()):n&&!e(b,n)?(c.logAction(c.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()", +"Proposed transport "+b.shortName+" is no better than current active transport "+n.shortName+" - abandoning upgrade"),m()):(c.logAction(c.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Scheduling transport upgrade; transport = "+b),this.realtime.channels.onceNopending(function(e){if(e)c.logAction(c.LOG_ERROR,"ConnectionManager.scheduleTransportActivation()","Unable to activate transport; transport = "+b+"; err = "+e);else if(b.isConnected){if(f.state===f.states.connected){c.logAction(c.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){c.logAction(c.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 "+b.shortName);m();return}var u= (e=d!==f.connectionId)?h:f;e&&c.logAction(c.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);c.logAction(c.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Syncing transport; transport = "+b);f.sync(b,u,function(d,e,h){if(d)f.state===f.states.synchronizing&&(c.logAction(c.LOG_ERROR,"ConnectionManager.scheduleTransportActivation()", "Unexpected error attempting to sync transport; transport = "+b+"; err = "+d),f.disconnectAllTransports());else if(d=function(){c.logAction(c.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Activating transport; transport = "+b);f.activateTransport(a,b,e,g,h);f.state===f.states.synchronizing?(c.logAction(c.LOG_MICRO,"ConnectionManager.scheduleTransportActivation()","Pre-upgrade protocol idle, sending queued messages on upgraded transport; transport = "+b),f.state=f.states.connected): -c.logAction(c.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(d);else d()})}else c.logAction(c.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Proposed transport "+b.shortName+"is no longer connected; abandoning upgrade"),l()}))};b.prototype.activateTransport=function(a,b,d,e,g){c.logAction(c.LOG_MINOR,"ConnectionManager.activateTransport()", -"transport = "+b);a&&c.logAction(c.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+a);d&&c.logAction(c.LOG_MICRO,"ConnectionManager.activateTransport()","connectionId = "+d);e&&c.logAction(c.LOG_MICRO,"ConnectionManager.activateTransport()","connectionDetails = "+JSON.stringify(e));g&&c.logAction(c.LOG_MICRO,"ConnectionManager.activateTransport()","serial = "+(g.timeSerial||g.connectionSerial));this.persistTransportPreference(b);var f=this.state,h=this.states.connected.state;c.logAction(c.LOG_MINOR, -"ConnectionManager.activateTransport()","current state = "+f.state);if(f.state==this.states.closing.state||f.state==this.states.closed.state||f.state==this.states.failed.state)return c.logAction(c.LOG_MINOR,"ConnectionManager.activateTransport()","Disconnecting transport and abandoning"),b.disconnect(),!1;k.arrDeleteValue(this.pendingTransports,b);if(!b.isConnected)return c.logAction(c.LOG_MINOR,"ConnectionManager.activateTransport()","Declining to activate transport "+b+" since it appears to no longer be connected"), -!1;var n=this.activeProtocol;this.activeProtocol=new ea(b);this.host=b.params.host;var l=e.connectionKey;l&&this.connectionKey!=l&&this.setConnection(d,e,g,!0);this.onConnectionDetailsUpdate(e,b);var u=this;k.nextTick(function(){b.on("connected",function(a,c,d){u.onConnectionDetailsUpdate(d,b);u.emit("update",new U(h,h,null,a))})});f.state===this.states.connected.state?a&&(this.errorReason=this.realtime.connection.errorReason=a,this.emit("update",new U(h,h,null,a))):(this.notifyState({state:"connected", -error:a}),this.errorReason=this.realtime.connection.errorReason=a||null);this.emit("transport.active",b);n&&(0this.connectionStateTtl+ -this.maxIdleInterval&&(c.logAction(c.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)}};b.prototype.persistConnection=function(){if(d){var a=this.realtime.connection.recoveryKey;a&&(a={recoveryKey:a,disconnectedAt:k.now(),location:window.location,clientId:this.realtime.auth.clientId},d&&K.setSession("ably-connection-recovery", -a))}};b.prototype.unpersistConnection=function(){d&&K.removeSession("ably-connection-recovery")};b.prototype.getStateError=function(){return L[this.state.state]};b.prototype.activeState=function(){return this.state.queueEvents||this.state.sendEvents};b.prototype.enactStateChange=function(a){c.logAction("failed"===a.current?c.LOG_ERROR:c.LOG_MAJOR,"Connection state",a.current+(a.reason?"; reason: "+a.reason:""));c.logAction(c.LOG_MINOR,"ConnectionManager.enactStateChange","setting new state: "+a.current+ -"; reason = "+(a.reason&&a.reason.message));var b=this.state=this.states[a.current];a.reason&&(this.errorReason=a.reason,this.realtime.connection.errorReason=a.reason);(b.terminal||"suspended"===b.state)&&this.clearConnection();this.emit("connectionstate",a)};b.prototype.startTransitionTimer=function(a){c.logAction(c.LOG_MINOR,"ConnectionManager.startTransitionTimer()","transitionState: "+a.state);this.transitionTimer&&(c.logAction(c.LOG_MINOR,"ConnectionManager.startTransitionTimer()","clearing already-running timer"), -clearTimeout(this.transitionTimer));var b=this;this.transitionTimer=setTimeout(function(){b.transitionTimer&&(b.transitionTimer=null,c.logAction(c.LOG_MINOR,"ConnectionManager "+a.state+" timer expired","requesting new state: "+a.failState),b.notifyState({state:a.failState}))},a.retryDelay)};b.prototype.cancelTransitionTimer=function(){c.logAction(c.LOG_MINOR,"ConnectionManager.cancelTransitionTimer()","");this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)};b.prototype.startSuspendTimer= -function(){var a=this;this.suspendTimer||(this.suspendTimer=setTimeout(function(){a.suspendTimer&&(a.suspendTimer=null,c.logAction(c.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))};b.prototype.checkSuspendTimer=function(a){"disconnected"!==a&&"suspended"!==a&&"connecting"!==a&&this.cancelSuspendTimer()};b.prototype.cancelSuspendTimer= -function(){this.states.connecting.failState="disconnected";this.states.connecting.queueEvents=!0;this.suspendTimer&&(clearTimeout(this.suspendTimer),this.suspendTimer=null)};b.prototype.startRetryTimer=function(a){var b=this;this.retryTimer=setTimeout(function(){c.logAction(c.LOG_MINOR,"ConnectionManager retry timer expired","retrying");b.retryTimer=null;b.requestState({state:"connecting"})},a)};b.prototype.cancelRetryTimer=function(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer= -null)};b.prototype.notifyState=function(a){var b=a.state,d=this,f="disconnected"===b&&(this.state===this.states.connected||this.state===this.states.synchronizing||this.state===this.states.connecting&&a.error&&N.isTokenErr(a.error));c.logAction(c.LOG_MINOR,"ConnectionManager.notifyState()","new state: "+b+(f?"; will retry connection immediately":""));if(b!=this.state.state&&(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(a.state),!this.state.terminal)){var e=this.states[a.state]; -a=new U(this.state.state,e.state,e.retryDelay,a.error||L[e.state]);if(f){var g=function(){d.state===d.states.disconnected&&(d.lastAutoReconnectAttempt=k.now(),d.requestState({state:"connecting"}))},h=this.lastAutoReconnectAttempt&&k.now()-this.lastAutoReconnectAttempt+1;h&&1E3>h?(c.logAction(c.LOG_MICRO,"ConnectionManager.notifyState()","Last reconnect attempt was only "+h+"ms ago, waiting another "+(1E3-h)+"ms before trying again"),setTimeout(g,1E3-h)):k.nextTick(g)}else"disconnected"!==b&&"suspended"!== -b||this.startRetryTimer(e.retryDelay);("disconnected"===b&&!f||"suspended"===b||e.terminal)&&k.nextTick(function(){d.disconnectAllTransports()});"connected"!=b||this.activeProtocol||c.logAction(c.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(b,a.reason),this.failQueuedMessages(a.reason))}}; -b.prototype.requestState=function(a){var b=a.state,d=this;c.logAction(c.LOG_MINOR,"ConnectionManager.requestState()","requested state: "+b+"; current state: "+this.state.state);if(b!=this.state.state&&(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(b),"connecting"!=b||"connected"!=this.state.state)&&("closing"!=b||"closed"!=this.state.state)){var f=this.states[b];a=new U(this.state.state,f.state,null,a.error||L[f.state]);this.enactStateChange(a);"connecting"==b&&k.nextTick(function(){d.startConnect()}); -"closing"==b&&this.closeImpl()}};b.prototype.startConnect=function(){if(this.state!==this.states.connecting)c.logAction(c.LOG_MINOR,"ConnectionManager.startConnect()","Must be in connecting state to connect, but was "+this.state.state);else{var a=this.realtime.auth,b=this,d=function(){b.checkConnectionStateFreshness();b.getTransportParams(function(a){b.connectImpl(a)})};c.logAction(c.LOG_MINOR,"ConnectionManager.startConnect()","starting connection");this.startSuspendTimer();this.startTransitionTimer(this.states.connecting); -if("basic"===a.method)d();else{var e=function(a){a?b.actOnErrorFromAuthorize(a):d()};this.errorReason&&N.isTokenErr(this.errorReason)?a._forceNewToken(null,null,e):a._ensureValidAuthCredentials(e)}}};b.prototype.connectImpl=function(a){var b=this.state.state;b!==this.states.connecting.state&&b!==this.states.connected.state?c.logAction(c.LOG_MINOR,"ConnectionManager.connectImpl()","Must be in connecting state to connect (or connected to upgrade), but was "+b):this.pendingTransports.length?c.logAction(c.LOG_MINOR, -"ConnectionManager.connectImpl()","Transports "+this.pendingTransports[0].toString()+" currently pending; taking no action"):b==this.states.connected.state?this.upgradeIfNeeded(a):1=b?(a="No activity seen from realtime in "+a+"ms; assuming connection has dropped", -c.logAction(c.LOG_ERROR,"Transport.onIdleTimerExpire()",a),this.disconnect(new q(a,80003,408))):this.setIdleTimer(b+100)};e.prototype.onAuthUpdated=function(){};return e}();(function(){function e(b,a,c){this.shortName="web_socket";c.heartbeats=w.useProtocolHeartbeats;R.call(this,b,a,c);this.wsHost=t.getHost(c.options,c.host,!0)}var m=w.WebSocket;k.inherits(e,R);e.isAvailable=function(){return!!m};e.isAvailable()&&(P.supportedTransports.web_socket=e);e.tryConnect=function(b,a,d,p){var g=new e(b,a, -d),l=function(a){p({event:this.event,error:a})};g.on(["failed","disconnected"],l);g.on("wsopen",function(){c.logAction(c.LOG_MINOR,"WebSocketTransport.tryConnect()","viable transport "+g);g.off(["failed","disconnected"],l);p(null,g)});g.connect()};e.prototype.createWebSocket=function(b,a){var c=0;if(a)for(var e in a)b+=(c++?"&":"?")+e+"="+a[e];this.uri=b;return new m(b)};e.prototype.toString=function(){return"WebSocketTransport; uri="+this.uri};e.prototype.connect=function(){c.logAction(c.LOG_MINOR, -"WebSocketTransport.connect()","starting");R.prototype.connect.call(this);var b=this,a=this.params,d=a.options,e=(d.tls?"wss://":"ws://")+this.wsHost+":"+t.getPort(d)+"/";c.logAction(c.LOG_MINOR,"WebSocketTransport.connect()","uri: "+e);this.auth.getAuthParams(function(d,l){var g="",h;for(h in l)g+=" "+h+": "+l[h]+";";c.logAction(c.LOG_MINOR,"WebSocketTransport.connect()","authParams:"+g+" err: "+d);if(d)b.disconnect(d);else{d=a.getConnectParams(l);try{var f=b.wsConnection=b.createWebSocket(e,d); -f.binaryType=w.binaryType;f.onopen=function(){b.onWsOpen()};f.onclose=function(a){b.onWsClose(a)};f.onmessage=function(a){b.onWsData(a.data)};f.onerror=function(a){b.onWsError(a)};if(f.on)f.on("ping",function(){b.onActivity()})}catch(u){c.logAction(c.LOG_ERROR,"WebSocketTransport.connect()","Unexpected exception creating websocket: err = "+(u.stack||u.message)),b.disconnect(u)}}})};e.prototype.send=function(b){var a=this.wsConnection;if(a)try{a.send(z.serialize(b,this.params.format))}catch(d){b="Exception from ws connection when trying to send: "+ -k.inspectError(d),c.logAction(c.LOG_ERROR,"WebSocketTransport.send()",b),this.finish("disconnected",new q(b,5E4,500))}else c.logAction(c.LOG_ERROR,"WebSocketTransport.send()","No socket connection")};e.prototype.onWsData=function(b){c.logAction(c.LOG_MICRO,"WebSocketTransport.onWsData()","data received; length = "+b.length+"; type = "+typeof b);try{this.onProtocolMessage(z.deserialize(b,this.format))}catch(a){c.logAction(c.LOG_ERROR,"WebSocketTransport.onWsData()","Unexpected exception handing channel message: "+ -a.stack)}};e.prototype.onWsOpen=function(){c.logAction(c.LOG_MINOR,"WebSocketTransport.onWsOpen()","opened WebSocket");this.emit("wsopen")};e.prototype.onWsClose=function(b){if("object"==typeof b){var a=b.wasClean;b=b.code}else a=1E3==b;delete this.wsConnection;a?(c.logAction(c.LOG_MINOR,"WebSocketTransport.onWsClose()","Cleanly closed WebSocket"),a=new q("Websocket closed",80003,400)):(b="Unclean disconnection of WebSocket ; code = "+b,a=new q(b,80003,400),c.logAction(c.LOG_MINOR,"WebSocketTransport.onWsClose()", -b));this.finish("disconnected",a);this.emit("disposed")};e.prototype.onWsError=function(b){c.logAction(c.LOG_MINOR,"WebSocketTransport.onError()","Error from WebSocket: "+b.message);var a=this;k.nextTick(function(){a.disconnect(b)})};e.prototype.dispose=function(){c.logAction(c.LOG_MINOR,"WebSocketTransport.dispose()","");var b=this.wsConnection;b&&(b.onmessage=function(){},delete this.wsConnection,k.nextTick(function(){c.logAction(c.LOG_MICRO,"WebSocketTransport.dispose()","closing websocket");b.close()}))}; -return e})();var M=function(){function e(a,b,c){a&&a.server&&-1a.code)?[z.fromValues({action:z.Action.ERROR,error:a})]:[z.fromValues({action:z.Action.DISCONNECTED,error:a})]}function b(a,b,c){c.format=void 0;c.heartbeats=!0;R.call(this, -a,b,c);this.stream="stream"in c?c.stream:!0;this.pendingItems=this.pendingCallback=this.recvRequest=this.sendRequest=null;this.disposed=!1}k.inherits(b,R);b.REQ_SEND=0;b.REQ_RECV=1;b.REQ_RECV_POLL=2;b.REQ_RECV_STREAM=3;b.prototype.connect=function(){c.logAction(c.LOG_MINOR,"CometTransport.connect()","starting");R.prototype.connect.call(this);var a=this,b=this.params,p=b.options,g=t.getHost(p,b.host);b=t.getPort(p);this.baseUri=(p.tls?"https://":"http://")+g+":"+b+"/comet/";var l=this.baseUri+"connect"; -c.logAction(c.LOG_MINOR,"CometTransport.connect()","uri: "+l);this.auth.getAuthParams(function(b,d){if(b)a.disconnect(b);else{a.authParams=d;b=a.params.getConnectParams(d);"stream"in b&&(a.stream=b.stream);c.logAction(c.LOG_MINOR,"CometTransport.connect()","connectParams:"+k.toQueryString(b));var f=!1;b=a.recvRequest=a.createRequest(l,null,b,null,a.stream?3:1);b.on("data",function(b){a.recvRequest&&(f||(f=!0,a.emit("preconnect")),a.onData(b))});b.on("complete",function(b,c,d){e(d,g,a.connectionManager); -a.recvRequest||(b=b||new q("Request cancelled",8E4,400));a.recvRequest=null;a.onActivity();if(b)if(b.code)a.onData(m(b));else a.disconnect(b);else k.nextTick(function(){a.recv()})});b.exec()}})};b.prototype.requestClose=function(){c.logAction(c.LOG_MINOR,"CometTransport.requestClose()");this._requestCloseOrDisconnect(!0)};b.prototype.requestDisconnect=function(){c.logAction(c.LOG_MINOR,"CometTransport.requestDisconnect()");this._requestCloseOrDisconnect(!1)};b.prototype._requestCloseOrDisconnect= -function(a){var b=a?this.closeUri:this.disconnectUri;if(b){var e=this;b=this.createRequest(b,null,this.authParams,null,0);b.on("complete",function(b){b&&(c.logAction(c.LOG_ERROR,"CometTransport.request"+(a?"Close()":"Disconnect()"),"request returned err = "+b),e.finish("disconnected",b))});b.exec()}};b.prototype.dispose=function(){c.logAction(c.LOG_MINOR,"CometTransport.dispose()","");if(!this.disposed){this.disposed=!0;this.recvRequest&&(c.logAction(c.LOG_MINOR,"CometTransport.dispose()","aborting recv request"), -this.recvRequest.abort(),this.recvRequest=null);this.finish("disconnected",L.disconnected);var a=this;k.nextTick(function(){a.emit("disposed")})}};b.prototype.onConnect=function(a){if(!this.disposed){var b=a.connectionKey;R.prototype.onConnect.call(this,a);b=this.baseUri+b;c.logAction(c.LOG_MICRO,"CometTransport.onConnect()","baseUri = "+b+"; connectionKey = "+a.connectionKey);this.sendUri=b+"/send";this.recvUri=b+"/recv";this.closeUri=b+"/close";this.disconnectUri=b+"/disconnect"}};b.prototype.send= -function(a){if(this.sendRequest)this.pendingItems=this.pendingItems||[],this.pendingItems.push(a);else{var b=this.pendingItems||[];b.push(a);this.pendingItems=null;this.sendItems(b)}};b.prototype.sendAnyPending=function(){var a=this.pendingItems;a&&(this.pendingItems=null,this.sendItems(a))};b.prototype.sendItems=function(a){var b=this;a=this.sendRequest=b.createRequest(b.sendUri,null,b.authParams,this.encodeRequest(a),0);a.on("complete",function(a,d){a&&c.logAction(c.LOG_ERROR,"CometTransport.sendItems()", -"on complete: err = "+k.inspectError(a));b.sendRequest=null;if(d)b.onData(d);else if(a&&a.code)b.onData(m(a));else b.disconnect(a);b.pendingItems&&k.nextTick(function(){b.sendRequest||b.sendAnyPending()})});a.exec()};b.prototype.recv=function(){if(!this.recvRequest&&this.isConnected){var a=this,b=this.recvRequest=this.createRequest(this.recvUri,null,this.authParams,null,a.stream?3:2);b.on("data",function(b){a.onData(b)});b.on("complete",function(b){a.recvRequest=null;a.onActivity();if(b)if(b.code)a.onData(m(b)); -else a.disconnect(b);else k.nextTick(function(){a.recv()})});b.exec()}};b.prototype.onData=function(a){try{var b=this.decodeResponse(a);if(b&&b.length)for(a=0;al||300<=l?(c=g&&g.error||c,c||(c=Error("Error in unenveloping "+d),c.statusCode=l),a(c,g,e,!0,l)):a(c,g,e,!0,l))}}}function a(a){var b=[];if(a)for(var c in a)b.push(c+"="+a[c]);return b.join("&")}function d(b,d,e,h){return function(f,g,n,l,p){f?c.logAction(c.LOG_MICRO,"Resource."+d+"()","Received Error; "+(e+(h?"?":"")+a(h))+"; Error: "+k.inspectError(f)):c.logAction(c.LOG_MICRO,"Resource."+d+"()","Received; "+ -(e+(h?"?":"")+a(h))+"; Headers: "+a(n)+"; StatusCode: "+p+"; Body: "+(C.isBuffer(g)?g.toString():g));b&&b(f,g,n,l,p)}}var p=w.msgpack;e.get=function(e,l,n,h,f,p){function g(b,d){c.shouldLog(c.LOG_MICRO)&&c.logAction(c.LOG_MICRO,"Resource.get()","Sending; "+(l+(d?"?":"")+a(d)));y.get(e,l,b,d,function(a,b,c,d,f){a&&N.isTokenErr(a)?e.auth.authorize(null,null,function(a){a?p(a):m(e,n,h,p,g)}):p(a,b,c,d,f)})}c.shouldLog(c.LOG_MICRO)&&(p=d(p,"get",l,h));f&&(p=p&&b(p,f),(h=h||{}).envelope=f);m(e,n,h,p,g)}; -e.post=function(e,l,n,h,f,u,v){function g(b,d){if(c.shouldLog(c.LOG_MICRO)){var u=n;if(0<(b["content-type"]||"").indexOf("msgpack"))try{u=p.decode(n)}catch(ha){c.logAction(c.LOG_MICRO,"Resource.post()","Sending MsgPack Decoding Error: "+k.inspectError(ha))}c.logAction(c.LOG_MICRO,"Resource.post()","Sending; "+(l+(d?"?":"")+a(d))+"; Body: "+u)}y.post(e,l,b,n,d,function(a,b,c,d,n){a&&N.isTokenErr(a)?e.auth.authorize(null,null,function(a){a?v(a):m(e,h,f,v,g)}):v(a,b,c,d,n)})}c.shouldLog(c.LOG_MICRO)&& -(v=d(v,"post",l,f));u&&(v=b(v,u),f.envelope=u);m(e,h,f,v,g)};return e}(),V=function(){function e(a,b,c,e,l,n){this.rest=a;this.path=b;this.headers=c;this.envelope=e;this.bodyHandler=l;this.useHttpPaginatedResponse=n||!1}function m(a,b,c){this.resource=a;this.items=b;if(c){var d=this;"first"in c&&(this.first=function(a){d.get(c.first,a)});"current"in c&&(this.current=function(a){d.get(c.current,a)});this.next=function(a){"next"in c?d.get(c.next,a):a(null,null)};this.hasNext=function(){return"next"in -c};this.isLast=function(){return!this.hasNext()}}}function b(a,b,c,e,l,n){m.call(this,a,b,l);this.statusCode=e;this.success=300>e&&200<=e;this.headers=c;this.errorCode=n&&n.code;this.errorMessage=n&&n.message}e.prototype.get=function(a,b){var c=this;X.get(c.rest,c.path,c.headers,a,c.envelope,function(a,d,e,h,f){c.handlePage(a,d,e,h,f,b)})};e.prototype.post=function(a,b,c){var d=this;X.post(d.rest,d.path,b,d.headers,a,d.envelope,function(a,b,e,f,g){c&&d.handlePage(a,b,e,f,g,c)})};e.prototype.handlePage= -function(a,d,e,g,l,n){if(!a||this.useHttpPaginatedResponse&&(d||"number"===typeof a.code)){var h,f;try{var p=this.bodyHandler(d,e,g)}catch(B){n(a||B);return}if(e&&(h=e.Link||e.link)){d=h;"string"==typeof d&&(d=d.split(","));g={};for(h=0;h;\s*rel="(\w+)"$/)){var v;(v=(v=f[1].match(/^\.\/(\w+)\?(.*)$/))&&k.parseQueryString(v[2]))&&(g[f[2]]=v)}f=g}this.useHttpPaginatedResponse?n(null,new b(this,p,e,l,f,a)):n(null,new m(this,p,f))}else c.logAction(c.LOG_ERROR, -"PaginatedResource.handlePage()","Unexpected error getting resource: err = "+k.inspectError(a)),n(a)};m.prototype.get=function(a,b){var c=this.resource;X.get(c.rest,c.path,c.headers,a,c.envelope,function(a,d,e,h,f){c.handlePage(a,d,e,h,f,b)})};k.inherits(b,m);return e}(),N=function(){function e(){}function m(a){if(!k.isErrorInfo(a))return new q(k.inspectError(a),a.code||40170,a.statusCode||401);a.code||(a.code=403===a.statusCode?40300:40170);return a}function b(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 d=0;dp){b(new q("authUrl response exceeded max permitted length",40170,401));return}try{d=JSON.parse(d)}catch(aa){b(new q("Unexpected error processing authURL response; err = "+aa.message,40170,401));return}}b(null,d)}else b(new q("authUrl responded with unacceptable content-type "+a+", should be either text/plain, application/jwt or application/json", -40170,401));else b(new q("authUrl response is missing a content-type header",40170,401))};c.logAction(c.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Requesting token from "+d.authUrl+"; Params: "+JSON.stringify(h)+"; method: "+(f?"POST":"GET"));f?(e=e||{},e["content-type"]="application/x-www-form-urlencoded",f=k.toQueryString(h).slice(1),y.postUri(g,d.authUrl,e,f,{},a)):y.getUri(g,d.authUrl,e||{},h,a)};else if(d.key){var n=this;c.logAction(c.LOG_MINOR,"Auth.requestToken()","using token auth with client-side signing"); -h=function(a,b){n.createTokenRequest(a,d,b)}}else{c.logAction(c.LOG_ERROR,"Auth.requestToken()","Need a new token, but authOptions does not include any way to request one");f(new q("Need a new token, but authOptions does not include any way to request one",40101,403));return}"capability"in a&&(a.capability=b(a.capability));g=this.client;var l=function(a,b){var e=a.keyName,f=function(a){return g.baseUri(a)+"/keys/"+e+"/requestToken"},h=k.defaultPostHeaders();d.requestHeaders&&k.mixin(h,d.requestHeaders); -c.logAction(c.LOG_MICRO,"Auth.requestToken().requestToken","Sending POST; "+f+"; Token params: "+JSON.stringify(a));a=JSON.stringify(a);y.post(g,f,h,a,null,b)},r=!1,t=this.client.options.timeouts.realtimeRequestTimeout,w=setTimeout(function(){r=!0;var a="Token request callback timed out after "+t/1E3+" seconds";c.logAction(c.LOG_ERROR,"Auth.requestToken()",a);f(new q(a,40170,401))},t);h(a,function(a,b){r||(clearTimeout(w),a?(c.logAction(c.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+ -k.inspectError(a)),f(m(a))):"string"===typeof b?0===b.length?f(new q("Token string is empty",40170,401)):384p&&!d.suppressMaxLengthCheck?f(new q("Token request/details object exceeded max permitted stringified size (was "+ -a+" bytes)",40170,401)):"issued"in b?f(null,b):"keyName"in b?l(b,function(a,b,d,e){a?(c.logAction(c.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+k.inspectError(a)),f(m(a))):(e||(b=JSON.parse(b)),c.logAction(c.LOG_MINOR,"Auth.getToken()","token received"),f(null,b))}):(b="Expected token request callback to call back with a token string, token request object, or token details object",c.logAction(c.LOG_ERROR,"Auth.requestToken()",b),f(new q(b,40170,401)))))})};d.prototype.createTokenRequest= -function(a,d,e){"function"!=typeof a||e?"function"!=typeof d||e||(e=d,d=null):(e=a,d=a=null);d=d||this.authOptions;a=a||k.copy(this.tokenParams);var f=d.key;if(f){f=f.split(":");var g=f[0],h=f[1];if(h)if(""===a.clientId)e(new q("clientId can\u2019t be an empty string",40012,400));else{"capability"in a&&(a.capability=b(a.capability));var n=k.mixin({keyName:g},a),p=a.clientId||"",m=a.ttl||"",r=a.capability||"",t=this;(function(a){n.timestamp?a():t.getTimestamp(d&&d.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"+m+"\n"+r+"\n"+p+"\n"+n.timestamp+"\n"+a+"\n";n.mac=n.mac||l(a,h);c.logAction(c.LOG_MINOR,"Auth.getTokenRequest()","generated signed request");e(null,n)})}else e(new q("Invalid key specified",40101,403))}else e(new q("No key specified",40101,403))};d.prototype.getAuthParams=function(a){"basic"==this.method?a(null,{key:this.key}):this._ensureValidAuthCredentials(function(b,c){b?a(b): -a(null,{access_token:c.token})})};d.prototype.getAuthHeaders=function(a){"basic"==this.method?a(null,{authorization:"Basic "+this.basicKey}):this._ensureValidAuthCredentials(function(b,c){b?a(b):a(null,{authorization:"Bearer "+g(c.token)})})};d.prototype.getTimestamp=function(a,b){isNaN(parseInt(this.client.serverTimeOffset))&&(a||this.authOptions.queryTime)?this.client.time(function(a,c){a?b(a):b(null,c)}):b(null,k.now()+(this.client.serverTimeOffset||0))};d.prototype._saveBasicOptions=function(a){this.method= -"basic";this.key=a.key;this.basicKey=g(a.key);this.authOptions=a||{};"clientId"in a&&this._userSetClientId(a.clientId)};d.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)};d.prototype._ensureValidAuthCredentials=function(a){var b=this,d=this.tokenDetails,e=function(){b.requestToken(b.tokenParams, -b.authOptions,function(c,d){c?a(c):a(null,b.tokenDetails=d)})};d?this._tokenClientIdMismatch(d.clientId)?a(new q("Mismatch between clientId in token ("+d.clientId+") and current clientId ("+this.clientId+")",40102,403)):this.getTimestamp(b.authOptions&&b.authOptions.queryTime,function(f,g){f&&a(f);void 0===d.expires||d.expires>=g?(c.logAction(c.LOG_MINOR,"Auth.getToken()","using cached token; expires = "+d.expires),a(null,d)):(c.logAction(c.LOG_MINOR,"Auth.getToken()","deleting expired token"),b.tokenDetails= -null,e())}):e()};d.prototype._userSetClientId=function(a){if("string"!==typeof a&&null!==a)throw new q("clientId must be either a string or null",40012,400);if("*"===a)throw new q('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.logAction(c.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(d);else d()})}else c.logAction(c.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Proposed transport "+b.shortName+"is no longer connected; abandoning upgrade"),m()}))};b.prototype.activateTransport=function(a,b,d,g,e){c.logAction(c.LOG_MINOR,"ConnectionManager.activateTransport()", +"transport = "+b);a&&c.logAction(c.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+a);d&&c.logAction(c.LOG_MICRO,"ConnectionManager.activateTransport()","connectionId = "+d);g&&c.logAction(c.LOG_MICRO,"ConnectionManager.activateTransport()","connectionDetails = "+JSON.stringify(g));e&&c.logAction(c.LOG_MICRO,"ConnectionManager.activateTransport()","serial = "+(e.timeSerial||e.connectionSerial));this.persistTransportPreference(b);var f=this.state,h=this.states.connected.state;c.logAction(c.LOG_MINOR, +"ConnectionManager.activateTransport()","current state = "+f.state);if(f.state==this.states.closing.state||f.state==this.states.closed.state||f.state==this.states.failed.state)return c.logAction(c.LOG_MINOR,"ConnectionManager.activateTransport()","Disconnecting transport and abandoning"),b.disconnect(),!1;l.arrDeleteValue(this.pendingTransports,b);if(!b.isConnected)return c.logAction(c.LOG_MINOR,"ConnectionManager.activateTransport()","Declining to activate transport "+b+" since it appears to no longer be connected"), +!1;var n=this.activeProtocol;this.activeProtocol=new ea(b);this.host=b.params.host;var m=g.connectionKey;m&&this.connectionKey!=m&&this.setConnection(d,g,e,!0);this.onConnectionDetailsUpdate(g,b);var p=this;l.nextTick(function(){b.on("connected",function(a,c,d){p.onConnectionDetailsUpdate(d,b);p.emit("update",new U(h,h,null,a))})});f.state===this.states.connected.state?a&&(this.errorReason=this.realtime.connection.errorReason=a,this.emit("update",new U(h,h,null,a))):(this.notifyState({state:"connected", +error:a}),this.errorReason=this.realtime.connection.errorReason=a||null);this.emit("transport.active",b);n&&(0this.connectionStateTtl+this.maxIdleInterval&&(c.logAction(c.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)}};b.prototype.persistConnection=function(){if(d){var a=this.realtime.connection.recoveryKey;a&&(a={recoveryKey:a,disconnectedAt:l.now(), +location:window.location,clientId:this.realtime.auth.clientId},d&&L.setSession("ably-connection-recovery",a))}};b.prototype.unpersistConnection=function(){d&&L.removeSession("ably-connection-recovery")};b.prototype.getStateError=function(){return M[this.state.state]};b.prototype.activeState=function(){return this.state.queueEvents||this.state.sendEvents};b.prototype.enactStateChange=function(a){c.logAction("failed"===a.current?c.LOG_ERROR:c.LOG_MAJOR,"Connection state",a.current+(a.reason?"; reason: "+ +a.reason:""));c.logAction(c.LOG_MINOR,"ConnectionManager.enactStateChange","setting new state: "+a.current+"; reason = "+(a.reason&&a.reason.message));var b=this.state=this.states[a.current];a.reason&&(this.errorReason=a.reason,this.realtime.connection.errorReason=a.reason);(b.terminal||"suspended"===b.state)&&this.clearConnection();this.emit("connectionstate",a)};b.prototype.startTransitionTimer=function(a){c.logAction(c.LOG_MINOR,"ConnectionManager.startTransitionTimer()","transitionState: "+a.state); +this.transitionTimer&&(c.logAction(c.LOG_MINOR,"ConnectionManager.startTransitionTimer()","clearing already-running timer"),clearTimeout(this.transitionTimer));var b=this;this.transitionTimer=setTimeout(function(){b.transitionTimer&&(b.transitionTimer=null,c.logAction(c.LOG_MINOR,"ConnectionManager "+a.state+" timer expired","requesting new state: "+a.failState),b.notifyState({state:a.failState}))},a.retryDelay)};b.prototype.cancelTransitionTimer=function(){c.logAction(c.LOG_MINOR,"ConnectionManager.cancelTransitionTimer()", +"");this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)};b.prototype.startSuspendTimer=function(){var a=this;this.suspendTimer||(this.suspendTimer=setTimeout(function(){a.suspendTimer&&(a.suspendTimer=null,c.logAction(c.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))};b.prototype.checkSuspendTimer= +function(a){"disconnected"!==a&&"suspended"!==a&&"connecting"!==a&&this.cancelSuspendTimer()};b.prototype.cancelSuspendTimer=function(){this.states.connecting.failState="disconnected";this.states.connecting.queueEvents=!0;this.suspendTimer&&(clearTimeout(this.suspendTimer),this.suspendTimer=null)};b.prototype.startRetryTimer=function(a){var b=this;this.retryTimer=setTimeout(function(){c.logAction(c.LOG_MINOR,"ConnectionManager retry timer expired","retrying");b.retryTimer=null;b.requestState({state:"connecting"})}, +a)};b.prototype.cancelRetryTimer=function(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)};b.prototype.notifyState=function(a){var b=a.state,d=this,f="disconnected"===b&&(this.state===this.states.connected||this.state===this.states.synchronizing||this.state===this.states.connecting&&a.error&&O.isTokenErr(a.error));c.logAction(c.LOG_MINOR,"ConnectionManager.notifyState()","new state: "+b+(f?"; will retry connection immediately":""));if(b!=this.state.state&&(this.cancelTransitionTimer(), +this.cancelRetryTimer(),this.checkSuspendTimer(a.state),!this.state.terminal)){var g=this.states[a.state];a=new U(this.state.state,g.state,g.retryDelay,a.error||M[g.state]);if(f){var e=function(){d.state===d.states.disconnected&&(d.lastAutoReconnectAttempt=l.now(),d.requestState({state:"connecting"}))},h=this.lastAutoReconnectAttempt&&l.now()-this.lastAutoReconnectAttempt+1;h&&1E3>h?(c.logAction(c.LOG_MICRO,"ConnectionManager.notifyState()","Last reconnect attempt was only "+h+"ms ago, waiting another "+ +(1E3-h)+"ms before trying again"),setTimeout(e,1E3-h)):l.nextTick(e)}else"disconnected"!==b&&"suspended"!==b||this.startRetryTimer(g.retryDelay);("disconnected"===b&&!f||"suspended"===b||g.terminal)&&l.nextTick(function(){d.disconnectAllTransports()});"connected"!=b||this.activeProtocol||c.logAction(c.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(b,a.reason),this.failQueuedMessages(a.reason))}};b.prototype.requestState=function(a){var b=a.state,d=this;c.logAction(c.LOG_MINOR,"ConnectionManager.requestState()","requested state: "+b+"; current state: "+this.state.state);if(b!=this.state.state&&(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(b),"connecting"!=b||"connected"!=this.state.state)&&("closing"!=b||"closed"!=this.state.state)){var f= +this.states[b];a=new U(this.state.state,f.state,null,a.error||M[f.state]);this.enactStateChange(a);"connecting"==b&&l.nextTick(function(){d.startConnect()});"closing"==b&&this.closeImpl()}};b.prototype.startConnect=function(){if(this.state!==this.states.connecting)c.logAction(c.LOG_MINOR,"ConnectionManager.startConnect()","Must be in connecting state to connect, but was "+this.state.state);else{var a=this.realtime.auth,b=this,d=function(){b.checkConnectionStateFreshness();b.getTransportParams(function(a){b.connectImpl(a)})}; +c.logAction(c.LOG_MINOR,"ConnectionManager.startConnect()","starting connection");this.startSuspendTimer();this.startTransitionTimer(this.states.connecting);if("basic"===a.method)d();else{var g=function(a){a?b.actOnErrorFromAuthorize(a):d()};this.errorReason&&O.isTokenErr(this.errorReason)?a._forceNewToken(null,null,g):a._ensureValidAuthCredentials(g)}}};b.prototype.connectImpl=function(a){var b=this.state.state;b!==this.states.connecting.state&&b!==this.states.connected.state?c.logAction(c.LOG_MINOR, +"ConnectionManager.connectImpl()","Must be in connecting state to connect (or connected to upgrade), but was "+b):this.pendingTransports.length?c.logAction(c.LOG_MINOR,"ConnectionManager.connectImpl()","Transports "+this.pendingTransports[0].toString()+" currently pending; taking no action"):b==this.states.connected.state?this.upgradeIfNeeded(a):1=b?(a="No activity seen from realtime in "+a+"ms; assuming connection has dropped",c.logAction(c.LOG_ERROR,"Transport.onIdleTimerExpire()",a),this.disconnect(new q(a,80003,408))):this.setIdleTimer(b+100)};e.prototype.onAuthUpdated=function(){};return e}();(function(){function e(b,a,c){this.shortName="web_socket";c.heartbeats=w.useProtocolHeartbeats;S.call(this,b,a,c);this.wsHost=t.getHost(c.options,c.host,!0)}var k=w.WebSocket;l.inherits(e,S);e.isAvailable=function(){return!!k};e.isAvailable()&& +(Q.supportedTransports.web_socket=e);e.tryConnect=function(b,a,d,p){var g=new e(b,a,d),m=function(a){p({event:this.event,error:a})};g.on(["failed","disconnected"],m);g.on("wsopen",function(){c.logAction(c.LOG_MINOR,"WebSocketTransport.tryConnect()","viable transport "+g);g.off(["failed","disconnected"],m);p(null,g)});g.connect()};e.prototype.createWebSocket=function(b,a){var c=0;if(a)for(var e in a)b+=(c++?"&":"?")+e+"="+a[e];this.uri=b;return new k(b)};e.prototype.toString=function(){return"WebSocketTransport; uri="+ +this.uri};e.prototype.connect=function(){c.logAction(c.LOG_MINOR,"WebSocketTransport.connect()","starting");S.prototype.connect.call(this);var b=this,a=this.params,d=a.options,e=(d.tls?"wss://":"ws://")+this.wsHost+":"+t.getPort(d)+"/";c.logAction(c.LOG_MINOR,"WebSocketTransport.connect()","uri: "+e);this.auth.getAuthParams(function(d,m){var g="",h;for(h in m)g+=" "+h+": "+m[h]+";";c.logAction(c.LOG_MINOR,"WebSocketTransport.connect()","authParams:"+g+" err: "+d);if(d)b.disconnect(d);else{d=a.getConnectParams(m); +try{var f=b.wsConnection=b.createWebSocket(e,d);f.binaryType=w.binaryType;f.onopen=function(){b.onWsOpen()};f.onclose=function(a){b.onWsClose(a)};f.onmessage=function(a){b.onWsData(a.data)};f.onerror=function(a){b.onWsError(a)};if(f.on)f.on("ping",function(){b.onActivity()})}catch(u){c.logAction(c.LOG_ERROR,"WebSocketTransport.connect()","Unexpected exception creating websocket: err = "+(u.stack||u.message)),b.disconnect(u)}}})};e.prototype.send=function(b){var a=this.wsConnection;if(a)try{a.send(z.serialize(b, +this.params.format))}catch(d){b="Exception from ws connection when trying to send: "+l.inspectError(d),c.logAction(c.LOG_ERROR,"WebSocketTransport.send()",b),this.finish("disconnected",new q(b,5E4,500))}else c.logAction(c.LOG_ERROR,"WebSocketTransport.send()","No socket connection")};e.prototype.onWsData=function(b){c.logAction(c.LOG_MICRO,"WebSocketTransport.onWsData()","data received; length = "+b.length+"; type = "+typeof b);try{this.onProtocolMessage(z.deserialize(b,this.format))}catch(a){c.logAction(c.LOG_ERROR, +"WebSocketTransport.onWsData()","Unexpected exception handing channel message: "+a.stack)}};e.prototype.onWsOpen=function(){c.logAction(c.LOG_MINOR,"WebSocketTransport.onWsOpen()","opened WebSocket");this.emit("wsopen")};e.prototype.onWsClose=function(b){if("object"==typeof b){var a=b.wasClean;b=b.code}else a=1E3==b;delete this.wsConnection;a?(c.logAction(c.LOG_MINOR,"WebSocketTransport.onWsClose()","Cleanly closed WebSocket"),a=new q("Websocket closed",80003,400)):(b="Unclean disconnection of WebSocket ; code = "+ +b,a=new q(b,80003,400),c.logAction(c.LOG_MINOR,"WebSocketTransport.onWsClose()",b));this.finish("disconnected",a);this.emit("disposed")};e.prototype.onWsError=function(b){c.logAction(c.LOG_MINOR,"WebSocketTransport.onError()","Error from WebSocket: "+b.message);var a=this;l.nextTick(function(){a.disconnect(b)})};e.prototype.dispose=function(){c.logAction(c.LOG_MINOR,"WebSocketTransport.dispose()","");var b=this.wsConnection;b&&(b.onmessage=function(){},delete this.wsConnection,l.nextTick(function(){c.logAction(c.LOG_MICRO, +"WebSocketTransport.dispose()","closing websocket");b.close()}))};return e})();var N=function(){function e(a,b,c){a&&a.server&&-1a.code)?[z.fromValues({action:z.Action.ERROR,error:a})]:[z.fromValues({action:z.Action.DISCONNECTED, +error:a})]}function b(a,b,c){c.format=void 0;c.heartbeats=!0;S.call(this,a,b,c);this.stream="stream"in c?c.stream:!0;this.pendingItems=this.pendingCallback=this.recvRequest=this.sendRequest=null;this.disposed=!1}l.inherits(b,S);b.REQ_SEND=0;b.REQ_RECV=1;b.REQ_RECV_POLL=2;b.REQ_RECV_STREAM=3;b.prototype.connect=function(){c.logAction(c.LOG_MINOR,"CometTransport.connect()","starting");S.prototype.connect.call(this);var a=this,b=this.params,p=b.options,g=t.getHost(p,b.host);b=t.getPort(p);this.baseUri= +(p.tls?"https://":"http://")+g+":"+b+"/comet/";var m=this.baseUri+"connect";c.logAction(c.LOG_MINOR,"CometTransport.connect()","uri: "+m);this.auth.getAuthParams(function(b,d){if(b)a.disconnect(b);else{a.authParams=d;b=a.params.getConnectParams(d);"stream"in b&&(a.stream=b.stream);c.logAction(c.LOG_MINOR,"CometTransport.connect()","connectParams:"+l.toQueryString(b));var f=!1;b=a.recvRequest=a.createRequest(m,null,b,null,a.stream?3:1);b.on("data",function(b){a.recvRequest&&(f||(f=!0,a.emit("preconnect")), +a.onData(b))});b.on("complete",function(b,c,d){e(d,g,a.connectionManager);a.recvRequest||(b=b||new q("Request cancelled",8E4,400));a.recvRequest=null;a.onActivity();if(b)if(b.code)a.onData(k(b));else a.disconnect(b);else l.nextTick(function(){a.recv()})});b.exec()}})};b.prototype.requestClose=function(){c.logAction(c.LOG_MINOR,"CometTransport.requestClose()");this._requestCloseOrDisconnect(!0)};b.prototype.requestDisconnect=function(){c.logAction(c.LOG_MINOR,"CometTransport.requestDisconnect()"); +this._requestCloseOrDisconnect(!1)};b.prototype._requestCloseOrDisconnect=function(a){var b=a?this.closeUri:this.disconnectUri;if(b){var e=this;b=this.createRequest(b,null,this.authParams,null,0);b.on("complete",function(b){b&&(c.logAction(c.LOG_ERROR,"CometTransport.request"+(a?"Close()":"Disconnect()"),"request returned err = "+b),e.finish("disconnected",b))});b.exec()}};b.prototype.dispose=function(){c.logAction(c.LOG_MINOR,"CometTransport.dispose()","");if(!this.disposed){this.disposed=!0;this.recvRequest&& +(c.logAction(c.LOG_MINOR,"CometTransport.dispose()","aborting recv request"),this.recvRequest.abort(),this.recvRequest=null);this.finish("disconnected",M.disconnected);var a=this;l.nextTick(function(){a.emit("disposed")})}};b.prototype.onConnect=function(a){if(!this.disposed){var b=a.connectionKey;S.prototype.onConnect.call(this,a);b=this.baseUri+b;c.logAction(c.LOG_MICRO,"CometTransport.onConnect()","baseUri = "+b+"; connectionKey = "+a.connectionKey);this.sendUri=b+"/send";this.recvUri=b+"/recv"; +this.closeUri=b+"/close";this.disconnectUri=b+"/disconnect"}};b.prototype.send=function(a){if(this.sendRequest)this.pendingItems=this.pendingItems||[],this.pendingItems.push(a);else{var b=this.pendingItems||[];b.push(a);this.pendingItems=null;this.sendItems(b)}};b.prototype.sendAnyPending=function(){var a=this.pendingItems;a&&(this.pendingItems=null,this.sendItems(a))};b.prototype.sendItems=function(a){var b=this;a=this.sendRequest=b.createRequest(b.sendUri,null,b.authParams,this.encodeRequest(a), +0);a.on("complete",function(a,d){a&&c.logAction(c.LOG_ERROR,"CometTransport.sendItems()","on complete: err = "+l.inspectError(a));b.sendRequest=null;if(d)b.onData(d);else if(a&&a.code)b.onData(k(a));else b.disconnect(a);b.pendingItems&&l.nextTick(function(){b.sendRequest||b.sendAnyPending()})});a.exec()};b.prototype.recv=function(){if(!this.recvRequest&&this.isConnected){var a=this,b=this.recvRequest=this.createRequest(this.recvUri,null,this.authParams,null,a.stream?3:2);b.on("data",function(b){a.onData(b)}); +b.on("complete",function(b){a.recvRequest=null;a.onActivity();if(b)if(b.code)a.onData(k(b));else a.disconnect(b);else l.nextTick(function(){a.recv()})});b.exec()}};b.prototype.onData=function(a){try{var b=this.decodeResponse(a);if(b&&b.length)for(a=0;ae||300<=e?(c=g&&g.error||c,c||(c=Error("Error in unenveloping "+d),c.statusCode=e),a(c,g,f,!0,e)):a(c,g,f,!0,e))}}}function a(a){var b=[];if(a)for(var c in a)b.push(c+"="+a[c]);return b.join("&")}function d(b,d,e,h){return function(f,g,n,m,p){f?c.logAction(c.LOG_MICRO,"Resource."+d+"()","Received Error; "+(e+(h?"?":"")+a(h))+"; Error: "+ +l.inspectError(f)):c.logAction(c.LOG_MICRO,"Resource."+d+"()","Received; "+(e+(h?"?":"")+a(h))+"; Headers: "+a(n)+"; StatusCode: "+p+"; Body: "+(C.isBuffer(g)?g.toString():g));b&&b(f,g,n,m,p)}}var p=w.msgpack;e.get=function(g,e,n,h,f,p){function m(b,d){c.shouldLog(c.LOG_MICRO)&&c.logAction(c.LOG_MICRO,"Resource.get()","Sending; "+(e+(d?"?":"")+a(d)));y.get(g,e,b,d,function(a,b,c,d,f){a&&O.isTokenErr(a)?g.auth.authorize(null,null,function(a){a?p(a):k(g,n,h,p,m)}):p(a,b,c,d,f)})}c.shouldLog(c.LOG_MICRO)&& +(p=d(p,"get",e,h));f&&(p=p&&b(p,f),(h=h||{}).envelope=f);k(g,n,h,p,m)};e.post=function(g,e,n,h,f,u,v){function m(b,d){if(c.shouldLog(c.LOG_MICRO)){var u=n;if(0<(b["content-type"]||"").indexOf("msgpack"))try{u=p.decode(n)}catch(ha){c.logAction(c.LOG_MICRO,"Resource.post()","Sending MsgPack Decoding Error: "+l.inspectError(ha))}c.logAction(c.LOG_MICRO,"Resource.post()","Sending; "+(e+(d?"?":"")+a(d))+"; Body: "+u)}y.post(g,e,b,n,d,function(a,b,c,d,e){a&&O.isTokenErr(a)?g.auth.authorize(null,null,function(a){a? +v(a):k(g,h,f,v,m)}):v(a,b,c,d,e)})}c.shouldLog(c.LOG_MICRO)&&(v=d(v,"post",e,f));u&&(v=b(v,u),f.envelope=u);k(g,h,f,v,m)};return e}(),V=function(){function e(a,b,c,g,e,n){this.rest=a;this.path=b;this.headers=c;this.envelope=g;this.bodyHandler=e;this.useHttpPaginatedResponse=n||!1}function k(a,b,c){this.resource=a;this.items=b;if(c){var d=this;"first"in c&&(this.first=function(a){d.get(c.first,a)});"current"in c&&(this.current=function(a){d.get(c.current,a)});this.next=function(a){"next"in c?d.get(c.next, +a):a(null,null)};this.hasNext=function(){return"next"in c};this.isLast=function(){return!this.hasNext()}}}function b(a,b,c,g,e,n){k.call(this,a,b,e);this.statusCode=g;this.success=300>g&&200<=g;this.headers=c;this.errorCode=n&&n.code;this.errorMessage=n&&n.message}e.prototype.get=function(a,b){var c=this;X.get(c.rest,c.path,c.headers,a,c.envelope,function(a,d,e,h,f){c.handlePage(a,d,e,h,f,b)})};e.prototype.post=function(a,b,c){var d=this;X.post(d.rest,d.path,b,d.headers,a,d.envelope,function(a,b, +g,f,e){c&&d.handlePage(a,b,g,f,e,c)})};e.prototype.handlePage=function(a,d,e,g,m,n){if(!a||this.useHttpPaginatedResponse&&(d||"number"===typeof a.code)){var h,f;try{var p=this.bodyHandler(d,e,g)}catch(B){n(a||B);return}if(e&&(h=e.Link||e.link)){d=h;"string"==typeof d&&(d=d.split(","));g={};for(h=0;h;\s*rel="(\w+)"$/)){var v;(v=(v=f[1].match(/^\.\/(\w+)\?(.*)$/))&&l.parseQueryString(v[2]))&&(g[f[2]]=v)}f=g}this.useHttpPaginatedResponse?n(null,new b(this,p,e, +m,f,a)):n(null,new k(this,p,f))}else c.logAction(c.LOG_ERROR,"PaginatedResource.handlePage()","Unexpected error getting resource: err = "+l.inspectError(a)),n(a)};k.prototype.get=function(a,b){var c=this.resource;X.get(c.rest,c.path,c.headers,a,c.envelope,function(a,d,e,h,f){c.handlePage(a,d,e,h,f,b)})};l.inherits(b,k);return e}(),O=function(){function e(){}function k(a){if(!l.isErrorInfo(a))return new q(l.inspectError(a),a.code||40170,a.statusCode||401);a.code||(a.code=403===a.statusCode?40300:40170); +return a}function b(a){if(!a)return"";"string"==typeof a&&(a=JSON.parse(a));var b={},c=l.keysArray(a,!0);if(!c)return"";c.sort();for(var d=0;dp){b(new q("authUrl response exceeded max permitted length",40170,401));return}try{d=JSON.parse(d)}catch(aa){b(new q("Unexpected error processing authURL response; err = "+aa.message,40170,401));return}}b(null,d)}else b(new q("authUrl responded with unacceptable content-type "+a+", should be either text/plain, application/jwt or application/json", +40170,401));else b(new q("authUrl response is missing a content-type header",40170,401))};c.logAction(c.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Requesting token from "+d.authUrl+"; Params: "+JSON.stringify(h)+"; method: "+(e?"POST":"GET"));e?(f=f||{},f["content-type"]="application/x-www-form-urlencoded",e=l.toQueryString(h).slice(1),y.postUri(g,d.authUrl,f,e,{},a)):y.getUri(g,d.authUrl,f||{},h,a)};else if(d.key){var n=this;c.logAction(c.LOG_MINOR,"Auth.requestToken()","using token auth with client-side signing"); +h=function(a,b){n.createTokenRequest(a,d,b)}}else{c.logAction(c.LOG_ERROR,"Auth.requestToken()","Need a new token, but authOptions does not include any way to request one");f(new q("Need a new token, but authOptions does not include any way to request one",40101,403));return}"capability"in a&&(a.capability=b(a.capability));g=this.client;var m=function(a,b){var f=a.keyName,e=function(a){return g.baseUri(a)+"/keys/"+f+"/requestToken"},h=l.defaultPostHeaders();d.requestHeaders&&l.mixin(h,d.requestHeaders); +c.logAction(c.LOG_MICRO,"Auth.requestToken().requestToken","Sending POST; "+e+"; Token params: "+JSON.stringify(a));a=JSON.stringify(a);y.post(g,e,h,a,null,b)},r=!1,t=this.client.options.timeouts.realtimeRequestTimeout,w=setTimeout(function(){r=!0;var a="Token request callback timed out after "+t/1E3+" seconds";c.logAction(c.LOG_ERROR,"Auth.requestToken()",a);f(new q(a,40170,401))},t);h(a,function(a,b){r||(clearTimeout(w),a?(c.logAction(c.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+ +l.inspectError(a)),f(k(a))):"string"===typeof b?0===b.length?f(new q("Token string is empty",40170,401)):384p&&!d.suppressMaxLengthCheck?f(new q("Token request/details object exceeded max permitted stringified size (was "+ +a+" bytes)",40170,401)):"issued"in b?f(null,b):"keyName"in b?m(b,function(a,b,d,g){a?(c.logAction(c.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+l.inspectError(a)),f(k(a))):(g||(b=JSON.parse(b)),c.logAction(c.LOG_MINOR,"Auth.getToken()","token received"),f(null,b))}):(b="Expected token request callback to call back with a token string, token request object, or token details object",c.logAction(c.LOG_ERROR,"Auth.requestToken()",b),f(new q(b,40170,401)))))})};d.prototype.createTokenRequest= +function(a,d,f){"function"!=typeof a||f?"function"!=typeof d||f||(f=d,d=null):(f=a,d=a=null);d=d||this.authOptions;a=a||l.copy(this.tokenParams);var g=d.key;if(g){g=g.split(":");var e=g[0],h=g[1];if(h)if(""===a.clientId)f(new q("clientId can\u2019t be an empty string",40012,400));else{"capability"in a&&(a.capability=b(a.capability));var n=l.mixin({keyName:e},a),p=a.clientId||"",k=a.ttl||"",r=a.capability||"",t=this;(function(a){n.timestamp?a():t.getTimestamp(d&&d.queryTime,function(b,c){b?f(b):(n.timestamp= +c,a())})})(function(){var a=n.nonce||(n.nonce=("000000"+Math.floor(1E16*Math.random())).slice(-16));a=n.keyName+"\n"+k+"\n"+r+"\n"+p+"\n"+n.timestamp+"\n"+a+"\n";n.mac=n.mac||m(a,h);c.logAction(c.LOG_MINOR,"Auth.getTokenRequest()","generated signed request");f(null,n)})}else f(new q("Invalid key specified",40101,403))}else f(new q("No key specified",40101,403))};d.prototype.getAuthParams=function(a){"basic"==this.method?a(null,{key:this.key}):this._ensureValidAuthCredentials(function(b,c){b?a(b): +a(null,{access_token:c.token})})};d.prototype.getAuthHeaders=function(a){"basic"==this.method?a(null,{authorization:"Basic "+this.basicKey}):this._ensureValidAuthCredentials(function(b,c){b?a(b):a(null,{authorization:"Bearer "+g(c.token)})})};d.prototype.getTimestamp=function(a,b){isNaN(parseInt(this.client.serverTimeOffset))&&(a||this.authOptions.queryTime)?this.client.time(function(a,c){a?b(a):b(null,c)}):b(null,l.now()+(this.client.serverTimeOffset||0))};d.prototype._saveBasicOptions=function(a){this.method= +"basic";this.key=a.key;this.basicKey=g(a.key);this.authOptions=a||{};"clientId"in a&&this._userSetClientId(a.clientId)};d.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)};d.prototype._ensureValidAuthCredentials=function(a){var b=this,d=this.tokenDetails,g=function(){b.requestToken(b.tokenParams, +b.authOptions,function(c,d){c?a(c):a(null,b.tokenDetails=d)})};d?this._tokenClientIdMismatch(d.clientId)?a(new q("Mismatch between clientId in token ("+d.clientId+") and current clientId ("+this.clientId+")",40102,403)):this.getTimestamp(b.authOptions&&b.authOptions.queryTime,function(f,e){f&&a(f);void 0===d.expires||d.expires>=e?(c.logAction(c.LOG_MINOR,"Auth.getToken()","using cached token; expires = "+d.expires),a(null,d)):(c.logAction(c.LOG_MINOR,"Auth.getToken()","deleting expired token"),b.tokenDetails= +null,g())}):g()};d.prototype._userSetClientId=function(a){if("string"!==typeof a&&null!==a)throw new q("clientId must be either a string or null",40012,400);if("*"===a)throw new q('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; };d.prototype._uncheckedSetClientId=function(a){if(this._tokenClientIdMismatch(a)){a="Unexpected clientId mismatch: client has "+this.clientId+", requested "+a;var b=new q(a,40102,401);c.logAction(c.LOG_ERROR,"Auth._uncheckedSetClientId()",a);return b}if("*"===a)this.tokenParams.clientId=a;else return this.clientId=this.tokenParams.clientId=a,null};d.prototype._tokenClientIdMismatch=function(a){return this.clientId&&a&&"*"!==a&&this.clientId!==a};d.isTokenErr=function(a){return a.code&&40140<=a.code&& -40150>a.code};return d}(),I=function(){function e(a){if(!(this instanceof e))return new e(a);if(!a){var b="no options provided";c.logAction(c.LOG_ERROR,"Rest()",b);throw Error(b);}"string"==typeof a&&(a=-1==a.indexOf(":")?{token:a}:{key:a});a.log&&c.setLog(a.log.level,a.log.handler);c.logAction(c.LOG_MICRO,"Rest()","initialized with clientOptions "+k.inspect(a));this.options=t.normaliseOptions(a);if(a.key){b=a.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!b)throw b="invalid key parameter",c.logAction(c.LOG_ERROR, +40150>a.code};return d}(),J=function(){function e(a){if(!(this instanceof e))return new e(a);if(!a){var b="no options provided";c.logAction(c.LOG_ERROR,"Rest()",b);throw Error(b);}"string"==typeof a&&(a=-1==a.indexOf(":")?{token:a}:{key:a});a.log&&c.setLog(a.log.level,a.log.handler);c.logAction(c.LOG_MICRO,"Rest()","initialized with clientOptions "+l.inspect(a));this.options=t.normaliseOptions(a);if(a.key){b=a.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!b)throw b="invalid key parameter",c.logAction(c.LOG_ERROR, "Rest()",b),Error(b);a.keyName=b[1];a.keySecret=b[2]}if("clientId"in a){if("string"!==typeof a.clientId&&null!==a.clientId)throw new q("clientId must be either a string or null",40012,400);if("*"===a.clientId)throw new q('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);}c.logAction(c.LOG_MINOR,"Rest()","started; version = "+t.libstring);this.baseUri=this.authority= -function(b){return t.getHttpScheme(a)+b+":"+t.getPort(a,!1)};this.serverTimeOffset=null;this.auth=new N(this,a);this.channels=new m(this)}function m(a){this.rest=a;this.attached={}}var b=function(){},a=w.msgpack;e.prototype.stats=function(a,c){void 0===c&&("function"==typeof a?(c=a,a=null):c=b);var d=k.copy(k.defaultGetHeaders()),e=this.options.useBinaryProtocol?"msgpack":"json";e=y.supportsLinkHeaders?void 0:e;this.options.headers&&k.mixin(d,this.options.headers);(new V(this,"/stats",d,e,function(a, -b,c){a=c?a:JSON.parse(a);for(b=0;bb.timestamp;a=a.parseId();b=b.parseId();return a.msgSerial===b.msgSerial?a.index>b.index:a.msgSerial>b.msgSerial}var p=function(){};k.inherits(b,W);b.prototype.enter=function(a,b){if(e(this))throw new q("clientId must be specified to enter a presence channel",40012,400);this._enterOrUpdateClient(void 0,a,b,"enter")};b.prototype.update=function(a,b){if(e(this))throw new q("clientId must be specified to update presence data", -40012,400);this._enterOrUpdateClient(void 0,a,b,"update")};b.prototype.enterClient=function(a,b,c){this._enterOrUpdateClient(a,b,c,"enter")};b.prototype.updateClient=function(a,b,c){this._enterOrUpdateClient(a,b,c,"update")};b.prototype._enterOrUpdateClient=function(a,b,d,e){d||("function"===typeof b?(d=b,b=null):d=p);var f=this.channel;if(f.connectionManager.activeState()){c.logAction(c.LOG_MICRO,"RealtimePresence."+e+"Client()",e+"ing; channel = "+f.name+", client = "+a||"(implicit) "+this.channel.realtime.auth.clientId); -var g=G.fromValues({action:e,data:b});a&&(g.clientId=a);var h=this;G.encode(g,f.channelOptions,function(a){if(a)d(a);else switch(f.state){case "attached":f.sendPresence(g,d);break;case "initialized":case "detached":f.attach();case "attaching":h.pendingPresence.push({presence:g,callback:d});break;default:a=new q("Unable to "+e+" presence channel (incompatible state)",90001),a.code=90001,d(a)}})}else d(f.connectionManager.getStateError())};b.prototype.leave=function(a,b){if(e(this))throw new q("clientId must have been specified to enter or leave a presence channel", -40012,400);this.leaveClient(void 0,a,b)};b.prototype.leaveClient=function(a,b,d){d||("function"===typeof b?(d=b,b=null):d=p);var e=this.channel;if(e.connectionManager.activeState())switch(c.logAction(c.LOG_MICRO,"RealtimePresence.leaveClient()","leaving; channel = "+this.channel.name+", client = "+a),b=G.fromValues({action:"leave",data:b}),a&&(b.clientId=a),e.state){case "attached":e.sendPresence(b,d);break;case "attaching":this.pendingPresence.push({presence:b,callback:d});break;case "initialized":case "failed":a= -new q("Unable to leave presence channel (incompatible state)",90001);d(a);break;default:d(L.failed)}else d(e.connectionManager.getStateError())};b.prototype.get=function(){function a(a){d(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],d=b[1]||p,e=!c||("waitForSync"in c?c.waitForSync:!0);if("suspended"===this.channel.state)e?d(q.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 k=this;m(this.channel,d,function(){var b=k.members;e?b.waitSync(function(){a(b)}):a(b)})}};b.prototype.history=function(a,b){c.logAction(c.LOG_MICRO,"RealtimePresence.history()","channel = "+this.name);void 0===b&&("function"==typeof a?(b=a,a=null):b=p);a&&a.untilAttach&&("attached"===this.channel.state?(delete a.untilAttach,a.from_serial=this.channel.attachSerial):b(new q("option untilAttach requires the channel to be attached, was: "+this.channel.state,4E4,400)));W.prototype._history.call(this, -a,b)};b.prototype.setPresence=function(a,b,d){c.logAction(c.LOG_MICRO,"RealtimePresence.setPresence()","received presence for "+a.length+" participants; syncChannelSerial = "+d);var e,f,g=this.members,l=this._myMembers,n=[],k=this.channel.connectionManager.connectionId;b&&(this.members.startSync(),d&&(f=d.match(/^[\w\-]+:(.*)$/))&&(e=f[1]));for(d=0;dc)&&0!==r.status){if(void 0===y)if(y=r.status,1223===y&&(y=204),clearTimeout(e),E=400>y,204==y)d.complete(null,null,null,null,y);else{var f;if(f=3==d.requestMode&&E)f=r,f=f.getResponseHeader&&f.getResponseHeader("transfer-encoding")&&!f.getResponseHeader("content-length");A=f}if(3==c&&A)a();else if(4==c)if(A)b();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?C.utf8Decode(r.response):String(r.responseText);h.length&&(h=JSON.parse(h));G=!0}else h=r.response;if(void 0!==h.response){y=h.statusCode;E=400>y;var l=h.headers;h=h.response}else{var n=k.trim(r.getAllResponseHeaders()).split("\r\n");c={};for(g=0;ga.statusCode||k.isArray(b)?l.complete(null,b,a.headers,a.statusCode):(a=b.error||new q("Error response received from server",null,a.statusCode),l.complete(a)):l.complete(new q("Invalid server response: no envelope detected",null,500))}else l.complete(null, -a)};this.timer=setTimeout(function(){l.abort()},this.requestMode==M.REQ_SEND?this.timeouts.httpRequestTimeout:this.timeouts.recvTimeout);p.insertBefore(d,p.firstChild)};m.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())};m.prototype.abort=function(){this.dispose()};m.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")};y.Request||(y.Request=function(a,b,c,d,e,g){var f=l(b,c,d,e,M.REQ_SEND,a&&a.options.timeouts);f.once("complete",g);k.nextTick(function(){f.exec()});return f},y.checkConnectivity=function(a){var b=t.jsonpInternetUpUrl;if(g)g.push(a);else{g=[a];c.logAction(c.LOG_MICRO,"(JSONP)Http.checkConnectivity()","Sending; "+b);var d=new m("isTheInternetUp",b,null,null,null,M.REQ_SEND, -t.TIMEOUTS);d.once("complete",function(a,b){a=!a&&b;c.logAction(c.LOG_MICRO,"(JSONP)Http.checkConnectivity()","Result: "+a);for(b=0;bb.timestamp;a=a.parseId();b=b.parseId();return a.msgSerial===b.msgSerial?a.index>b.index:a.msgSerial>b.msgSerial}var p=function(){};l.inherits(b,W);b.prototype.enter=function(a,b){if(e(this))throw new q("clientId must be specified to enter a presence channel", +40012,400);this._enterOrUpdateClient(void 0,a,b,"enter")};b.prototype.update=function(a,b){if(e(this))throw new q("clientId must be specified to update presence data",40012,400);this._enterOrUpdateClient(void 0,a,b,"update")};b.prototype.enterClient=function(a,b,c){this._enterOrUpdateClient(a,b,c,"enter")};b.prototype.updateClient=function(a,b,c){this._enterOrUpdateClient(a,b,c,"update")};b.prototype._enterOrUpdateClient=function(a,b,d,e){d||("function"===typeof b?(d=b,b=null):d=p);var f=this.channel; +if(f.connectionManager.activeState()){c.logAction(c.LOG_MICRO,"RealtimePresence."+e+"Client()","channel = "+f.name+", client = "+(a||"(implicit) "+this.channel.realtime.auth.clientId));var g=G.fromValues({action:e,data:b});a&&(g.clientId=a);var h=this;G.encode(g,f.channelOptions,function(a){if(a)d(a);else switch(f.state){case "attached":f.sendPresence(g,d);break;case "initialized":case "detached":f.attach();case "attaching":h.pendingPresence.push({presence:g,callback:d});break;default:a=new q("Unable to "+ +e+" presence channel (incompatible state)",90001),a.code=90001,d(a)}})}else d(f.connectionManager.getStateError())};b.prototype.leave=function(a,b){if(e(this))throw new q("clientId must have been specified to enter or leave a presence channel",40012,400);this.leaveClient(void 0,a,b)};b.prototype.leaveClient=function(a,b,d){d||("function"===typeof b?(d=b,b=null):d=p);var e=this.channel;if(e.connectionManager.activeState())switch(c.logAction(c.LOG_MICRO,"RealtimePresence.leaveClient()","leaving; channel = "+ +this.channel.name+", client = "+a),b=G.fromValues({action:"leave",data:b}),a&&(b.clientId=a),e.state){case "attached":e.sendPresence(b,d);break;case "attaching":this.pendingPresence.push({presence:b,callback:d});break;case "initialized":case "failed":a=new q("Unable to leave presence channel (incompatible state)",90001);d(a);break;default:d(M.failed)}else d(e.connectionManager.getStateError())};b.prototype.get=function(){function a(a){d(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],d=b[1]||p,e=!c||("waitForSync"in c?c.waitForSync:!0);if("suspended"===this.channel.state)e?d(q.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 l=this;k(this.channel,d,function(){var b=l.members;e?b.waitSync(function(){a(b)}):a(b)})}};b.prototype.history=function(a,b){c.logAction(c.LOG_MICRO,"RealtimePresence.history()","channel = "+ +this.name);void 0===b&&("function"==typeof a?(b=a,a=null):b=p);a&&a.untilAttach&&("attached"===this.channel.state?(delete a.untilAttach,a.from_serial=this.channel.attachSerial):b(new q("option untilAttach requires the channel to be attached, was: "+this.channel.state,4E4,400)));W.prototype._history.call(this,a,b)};b.prototype.setPresence=function(a,b,d){c.logAction(c.LOG_MICRO,"RealtimePresence.setPresence()","received presence for "+a.length+" participants; syncChannelSerial = "+d);var e,f,g=this.members, +m=this._myMembers,n=[],l=this.channel.connectionManager.connectionId;b&&(this.members.startSync(),d&&(f=d.match(/^[\w\-]+:(.*)$/))&&(e=f[1]));for(d=0;dc)&&0!==r.status){if(void 0===y)if(y=r.status,1223===y&&(y=204),clearTimeout(e),E=400>y,204==y)d.complete(null,null,null,null,y);else{var f;if(f=3==d.requestMode&&E)f=r,f=f.getResponseHeader&&f.getResponseHeader("transfer-encoding")&&!f.getResponseHeader("content-length");A=f}if(3==c&&A)a();else if(4==c)if(A)b();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?C.utf8Decode(r.response): +String(r.responseText);h.length&&(h=JSON.parse(h));G=!0}else h=r.response;if(void 0!==h.response){y=h.statusCode;E=400>y;var k=h.headers;h=h.response}else{var m=l.trim(r.getAllResponseHeaders()).split("\r\n");c={};for(g=0;ga.statusCode||l.isArray(b)?k.complete(null,b,a.headers,a.statusCode):(a=b.error||new q("Error response received from server",null,a.statusCode),k.complete(a)):k.complete(new q("Invalid server response: no envelope detected",null,500))}else k.complete(null, +a)};this.timer=setTimeout(function(){k.abort()},this.requestMode==N.REQ_SEND?this.timeouts.httpRequestTimeout:this.timeouts.recvTimeout);p.insertBefore(d,p.firstChild)};k.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())};k.prototype.abort=function(){this.dispose()};k.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")};w.jsonpSupported&&!y.Request&&(y.Request=function(a,b,c,d,e,g){var f=m(b,c,d,e,N.REQ_SEND,a&&a.options.timeouts);f.once("complete",g);l.nextTick(function(){f.exec()});return f},y.checkConnectivity=function(a){var b=t.jsonpInternetUpUrl;if(g)g.push(a);else{g=[a];c.logAction(c.LOG_MICRO,"(JSONP)Http.checkConnectivity()","Sending; "+b);var d=new k("isTheInternetUp",b,null, +null,null,N.REQ_SEND,t.TIMEOUTS);d.once("complete",function(a,b){a=!a&&b;c.logAction(c.LOG_MICRO,"(JSONP)Http.checkConnectivity()","Result: "+a);for(b=0;b>>2]|=(c[m>>>2]>>>24-m%4*8&255)<<24-(d+m)%4*8;else if(65535>>2]=c[m>>>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=b.ceil(g/4)},clone:function(){var a=c.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var g=[],c=function(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>>2]>>>24-d%4*8&255;c.push((m>>>4).toString(16));c.push((m&15).toString(16))}return c.join("")},parse:function(a){for(var g=a.length,c=[],d=0;d>>3]|=parseInt(a.substr(d,2),16)<<24-d%8*4;return new e.init(c,g/2)}},l=f.Latin1={stringify:function(a){var g=a.words;a=a.sigBytes;for(var c=[],d=0;d>>2]>>>24-d%4*8&255));return c.join("")},parse:function(a){for(var g= -a.length,c=[],d=0;d>>2]|=(a.charCodeAt(d)&255)<<24-d%4*8;return new e.init(c,g)}},m=f.Utf8={stringify:function(a){try{return decodeURIComponent(escape(l.stringify(a)))}catch(S){throw Error("Malformed UTF-8 data");}},parse:function(a){return l.parse(unescape(encodeURIComponent(a)))}},g=a.BufferedBlockAlgorithm=c.extend({reset:function(){this._data=new e.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=m.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var g= -this._data,c=g.words,d=g.sigBytes,m=this.blockSize,f=d/(4*m);f=a?b.ceil(f):b.max((f|0)-this._minBufferSize,0);a=f*m;d=b.min(4*a,d);if(a){for(var u=0;ud;)a(g)&&(8>d&&(n[d]=c(b.pow(g,.5))),f[d]=c(b.pow(g,1/3)),d++),g++})();var p=[];d=d.SHA256=c.extend({_doReset:function(){this._hash=new a.init(n.slice(0))},_doProcessBlock:function(a,c){for(var g=this._hash.words,d=g[0],m=g[1],b=g[2],e=g[3],l=g[4],n=g[5],k=g[6],h=g[7],r=0;64>r;r++){if(16>r)p[r]=a[c+r]|0;else{var q=p[r-15],t=p[r-2];p[r]=((q<<25|q>>>7)^(q<<14|q>>>18)^q>>>3)+p[r-7]+((t<<15|t>>>17)^(t<<13|t>>>19)^t>>>10)+p[r-16]}q=h+((l<<26|l>>>6)^(l<<21|l>>>11)^(l<<7|l>>> -25))+(l&n^~l&k)+f[r]+p[r];t=((d<<30|d>>>2)^(d<<19|d>>>13)^(d<<10|d>>>22))+(d&m^d&b^m&b);h=k;k=n;n=l;l=e+q|0;e=b;b=m;m=d;d=q+t|0}g[0]=g[0]+d|0;g[1]=g[1]+m|0;g[2]=g[2]+b|0;g[3]=g[3]+e|0;g[4]=g[4]+l|0;g[5]=g[5]+n|0;g[6]=g[6]+k|0;g[7]=g[7]+h|0},_doFinalize:function(){var a=this._data,c=a.words,g=8*this._nDataBytes,d=8*a.sigBytes;c[d>>>5]|=128<<24-d%32;c[(d+64>>>9<<4)+14]=b.floor(g/4294967296);c[(d+64>>>9<<4)+15]=g;a.sigBytes=4*c.length;this._process();return this._hash},clone:function(){var a=c.clone.call(this); +a.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),e=a.WordArray=c.extend({init:function(a,g){a=this.words=a||[];this.sigBytes=g!=k?g:4*a.length},toString:function(a){return(a||p).stringify(this)},concat:function(a){var g=this.words,c=a.words,d=this.sigBytes;a=a.sigBytes;this.clamp();if(d%4)for(var f=0;f>>2]|=(c[f>>>2]>>>24-f%4*8&255)<<24-(d+f)%4*8;else if(65535>>2]=c[f>>>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=b.ceil(g/4)},clone:function(){var a=c.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var g=[],c=function(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>>2]>>>24-d%4*8&255;c.push((f>>>4).toString(16));c.push((f&15).toString(16))}return c.join("")},parse:function(a){for(var g=a.length,c=[],d=0;d>>3]|=parseInt(a.substr(d,2),16)<<24-d%8*4;return new e.init(c,g/2)}},l=f.Latin1={stringify:function(a){var g=a.words;a=a.sigBytes;for(var c=[],d=0;d>>2]>>>24-d%4*8&255));return c.join("")},parse:function(a){for(var g= +a.length,c=[],d=0;d>>2]|=(a.charCodeAt(d)&255)<<24-d%4*8;return new e.init(c,g)}},n=f.Utf8={stringify:function(a){try{return decodeURIComponent(escape(l.stringify(a)))}catch(S){throw Error("Malformed UTF-8 data");}},parse:function(a){return l.parse(unescape(encodeURIComponent(a)))}},g=a.BufferedBlockAlgorithm=c.extend({reset:function(){this._data=new e.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=n.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var g= +this._data,c=g.words,d=g.sigBytes,f=this.blockSize,n=d/(4*f);n=a?b.ceil(n):b.max((n|0)-this._minBufferSize,0);a=n*f;d=b.min(4*a,d);if(a){for(var u=0;ud;)a(g)&&(8>d&&(m[d]=c(b.pow(g,.5))),f[d]=c(b.pow(g,1/3)),d++),g++})();var p=[];d=d.SHA256=c.extend({_doReset:function(){this._hash=new a.init(m.slice(0))},_doProcessBlock:function(a,c){for(var g=this._hash.words,d=g[0],n=g[1],b=g[2],e=g[3],l=g[4],m=g[5],k=g[6],h=g[7],r=0;64>r;r++){if(16>r)p[r]=a[c+r]|0;else{var q=p[r-15],t=p[r-2];p[r]=((q<<25|q>>>7)^(q<<14|q>>>18)^q>>>3)+p[r-7]+((t<<15|t>>>17)^(t<<13|t>>>19)^t>>>10)+p[r-16]}q=h+((l<<26|l>>>6)^(l<<21|l>>>11)^(l<<7|l>>> +25))+(l&m^~l&k)+f[r]+p[r];t=((d<<30|d>>>2)^(d<<19|d>>>13)^(d<<10|d>>>22))+(d&n^d&b^n&b);h=k;k=m;m=l;l=e+q|0;e=b;b=n;n=d;d=q+t|0}g[0]=g[0]+d|0;g[1]=g[1]+n|0;g[2]=g[2]+b|0;g[3]=g[3]+e|0;g[4]=g[4]+l|0;g[5]=g[5]+m|0;g[6]=g[6]+k|0;g[7]=g[7]+h|0},_doFinalize:function(){var a=this._data,c=a.words,g=8*this._nDataBytes,d=8*a.sigBytes;c[d>>>5]|=128<<24-d%32;c[(d+64>>>9<<4)+14]=b.floor(g/4294967296);c[(d+64>>>9<<4)+15]=g;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}});e.SHA256=c._createHelper(d);e.HmacSHA256=c._createHmacHelper(d)})(Math);(function(){var b=x,k=b.enc.Utf8;b.algo.HMAC=b.lib.Base.extend({init:function(d,a){d=this._hasher=new d.init;"string"==typeof a&&(a=k.parse(a));var c=d.blockSize,b=4*c;a.sigBytes>b&&(a=d.finalize(a));a.clamp();d=this._oKey=a.clone();a=this._iKey=a.clone();for(var f=d.words,e=a.words,l=0;l>>2]>>>24-f%4*8&255)<<16|(a[f+1>>>2]>>>24-(f+1)%4*8&255)<<8|a[f+2>>>2]>>>24-(f+2)%4*8&255,l=0;4>l&&f+.75*l>> -6*(3-l)&63));if(a=b.charAt(64))for(;d.length%4;)d.push(a);return d.join("")},parse:function(d){var a=d.length,c=this._map,b=c.charAt(64);b&&(b=d.indexOf(b),-1!=b&&(a=b));b=[];for(var f=0,e=0;e>>6-e%4*2;b[f>>>2]|=(l|m)<<24-f%4*8;f++}return k.create(b,f)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})();var B=function(){function b(){}b.addListener=function(b,d,a){b.addEventListener?b.addEventListener(d, -a,!1):b.attachEvent("on"+d,function(){a.apply(b,arguments)})};b.removeListener=function(b,d,a){b.removeEventListener?b.removeEventListener(d,a,!1):b.detachEvent("on"+d,function(){a.apply(b,arguments)})};b.addMessageListener=function(e,d){b.addListener(e,"message",d)};b.removeMessageListener=function(e,d){b.removeListener(e,"message",d)};b.addUnloadListener=function(e){b.addListener(window,"unload",e)};return b}(),C=function(){function b(a,g,c){for(var d=0,m=c.length;df)a.setUint8(g++,f>>>0&127|0);else if(2048>f)a.setUint8(g++,f>>>6&31|192),a.setUint8(g++,f>>>0&63|128);else if(65536>f)a.setUint8(g++,f>>>12&15|224),a.setUint8(g++,f>>>6&63|128),a.setUint8(g++,f>>>0&63|128);else if(1114112>f)a.setUint8(g++,f>>>18&7|240),a.setUint8(g++,f>>>12&63|128),a.setUint8(g++,f>>>6&63|128),a.setUint8(g++,f>>>0&63|128);else throw Error("bad codepoint "+f);}}function k(a,g,c){var d="",f=g;for(g+=c;f>>6-e%4*2;b[f>>>2]|=(l|n)<<24-f%4*8;f++}return k.create(b,f)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})();var B=function(){function b(){}b.addListener=function(b,d,a){b.addEventListener?b.addEventListener(d, +a,!1):b.attachEvent("on"+d,function(){a.apply(b,arguments)})};b.removeListener=function(b,d,a){b.removeEventListener?b.removeEventListener(d,a,!1):b.detachEvent("on"+d,function(){a.apply(b,arguments)})};b.addMessageListener=function(e,d){b.addListener(e,"message",d)};b.removeMessageListener=function(e,d){b.removeListener(e,"message",d)};b.addUnloadListener=function(e){b.addListener(window,"unload",e)};return b}(),C=function(){function b(a,g,c){for(var d=0,f=c.length;db)a.setUint8(g++,b>>>0&127|0);else if(2048>b)a.setUint8(g++,b>>>6&31|192),a.setUint8(g++,b>>>0&63|128);else if(65536>b)a.setUint8(g++,b>>>12&15|224),a.setUint8(g++,b>>>6&63|128),a.setUint8(g++,b>>>0&63|128);else if(1114112>b)a.setUint8(g++,b>>>18&7|240),a.setUint8(g++,b>>>12&63|128),a.setUint8(g++,b>>>6&63|128),a.setUint8(g++,b>>>0&63|128);else throw Error("bad codepoint "+b);}}function k(a,g,c){var d="",f=g;for(g+=c;ff)g+=1;else if(2048>f)g+=2;else if(65536>f)g+=3;else if(1114112>f)g+= -4;else throw Error("bad codepoint "+f);}return g}function a(a,g){this.offset=g||0;this.view=a}function c(a,g){return h.keysArray(a,!0).filter(function(c){c=a[c];return(!g||void 0!==c&&null!==c)&&("function"!==typeof c||!!c.toJSON)})}function n(a,g,f,e){var m=typeof a;if("string"===m){var p=d(a);if(32>p)return g.setUint8(f,p|160),b(g,f+1,a),1+p;if(256>p)return g.setUint8(f,217),g.setUint8(f+1,p),b(g,f+2,a),2+p;if(65536>p)return g.setUint8(f,218),g.setUint16(f+1,p),b(g,f+3,a),3+p;if(4294967296>p)return g.setUint8(f, -219),g.setUint32(f+1,p),b(g,f+5,a),5+p}if(a instanceof ArrayBuffer){p=a.byteLength;if(256>p)return g.setUint8(f,196),g.setUint8(f+1,p),(new Uint8Array(g.buffer)).set(new Uint8Array(a),f+2),2+p;if(65536>p)return g.setUint8(f,197),g.setUint16(f+1,p),(new Uint8Array(g.buffer)).set(new Uint8Array(a),f+3),3+p;if(4294967296>p)return g.setUint8(f,198),g.setUint32(f+1,p),(new Uint8Array(g.buffer)).set(new Uint8Array(a),f+5),5+p}if("number"===m){if(Math.floor(a)!==a)return g.setUint8(f,203),g.setFloat64(f+ +4;else throw Error("bad codepoint "+f);}return g}function a(a,g){this.offset=g||0;this.view=a}function c(a,g){return h.keysArray(a,!0).filter(function(c){c=a[c];return(!g||void 0!==c&&null!==c)&&("function"!==typeof c||!!c.toJSON)})}function m(a,g,f,e){var n=typeof a;if("string"===n){var p=d(a);if(32>p)return g.setUint8(f,p|160),b(g,f+1,a),1+p;if(256>p)return g.setUint8(f,217),g.setUint8(f+1,p),b(g,f+2,a),2+p;if(65536>p)return g.setUint8(f,218),g.setUint16(f+1,p),b(g,f+3,a),3+p;if(4294967296>p)return g.setUint8(f, +219),g.setUint32(f+1,p),b(g,f+5,a),5+p}if(a instanceof ArrayBuffer){p=a.byteLength;if(256>p)return g.setUint8(f,196),g.setUint8(f+1,p),(new Uint8Array(g.buffer)).set(new Uint8Array(a),f+2),2+p;if(65536>p)return g.setUint8(f,197),g.setUint16(f+1,p),(new Uint8Array(g.buffer)).set(new Uint8Array(a),f+3),3+p;if(4294967296>p)return g.setUint8(f,198),g.setUint32(f+1,p),(new Uint8Array(g.buffer)).set(new Uint8Array(a),f+5),5+p}if("number"===n){if(Math.floor(a)!==a)return g.setUint8(f,203),g.setFloat64(f+ 1,a),9;if(0<=a){if(128>a)return g.setUint8(f,a),1;if(256>a)return g.setUint8(f,204),g.setUint8(f+1,a),2;if(65536>a)return g.setUint8(f,205),g.setUint16(f+1,a),3;if(4294967296>a)return g.setUint8(f,206),g.setUint32(f+1,a),5;if(1.8446744073709552E19>a)return g.setUint8(f,207),f+=1,1.8446744073709552E19>a?(g.setUint32(f,Math.floor(a*l)),g.setInt32(f+4,a&-1)):(g.setUint32(f,4294967295),g.setUint32(f+4,4294967295)),9;throw Error("Number too big 0x"+a.toString(16));}if(-32<=a)return g.setInt8(f,a),1;if(-128<= -a)return g.setUint8(f,208),g.setInt8(f+1,a),2;if(-32768<=a)return g.setUint8(f,209),g.setInt16(f+1,a),3;if(-2147483648<=a)return g.setUint8(f,210),g.setInt32(f+1,a),5;if(-9223372036854775808<=a)return g.setUint8(f,211),f+=1,0x7fffffffffffffff>a?(g.setInt32(f,Math.floor(a*l)),g.setInt32(f+4,a&-1)):(g.setUint32(f,2147483647),g.setUint32(f+4,2147483647)),9;throw Error("Number too small -0x"+(-a).toString(16).substr(1));}if("undefined"===m){if(e)return 0;g.setUint8(f,212);g.setUint8(f+1,0);g.setUint8(f+ -2,0);return 3}if(null===a){if(e)return 0;g.setUint8(f,192);return 1}if("boolean"===m)return g.setUint8(f,a?195:194),1;if("function"===typeof a.toJSON)return n(a.toJSON(),g,f,e);if("object"===m){m=0;var u=Array.isArray(a);if(u)p=a.length;else{var A=c(a,e);p=A.length}16>p?(g.setUint8(f,p|(u?144:128)),m=1):65536>p?(g.setUint8(f,u?220:222),g.setUint16(f+1,p),m=3):4294967296>p&&(g.setUint8(f,u?221:223),g.setUint32(f+1,p),m=5);if(u)for(u=0;um)return 1+m;if(256>m)return 2+m;if(65536>m)return 3+m;if(4294967296>m)return 5+m}if(a instanceof ArrayBuffer){m=a.byteLength;if(256>m)return 2+m;if(65536>m)return 3+m;if(4294967296>m)return 5+m}if("number"===b){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"===b)return 1;if(null===a)return g?0:1;if(void 0===a)return g?0:3;if("function"===typeof a.toJSON)return f(a.toJSON(),g);if("object"===b){b=0;if(Array.isArray(a)){m=a.length;for(var e=0;em)return 1+b;if(65536>m)return 3+b;if(4294967296>m)return 5+b;throw Error("Array or object too long 0x"+m.toString(16));}if("function"===b)return 0;throw Error("Unknown type "+b);}var p={inspect:function(a){if(void 0===a)return"undefined";if(a instanceof ArrayBuffer){var g="ArrayBuffer";var c=new DataView(a)}else a instanceof DataView&&(g="DataView",c=a);if(!c)return JSON.stringify(a);for(var f=[],d=0;d"}};p.utf8Write=b;p.utf8Read=k;p.utf8ByteCount=d;p.encode=function(a,c){var g=f(a,c);if(0!=g){g=new ArrayBuffer(g);var d=new DataView(g);n(a,d,0,c);return g}};p.decode=function(c){var g=new DataView(c);g=new a(g);var d=g.parse();if(g.offset!==c.byteLength)throw Error(c.byteLength-g.offset+" trailing bytes");return d};var l=1/4294967296;a.prototype.map=function(a){for(var c={},d=0;da?(g.setInt32(f,Math.floor(a*l)),g.setInt32(f+4,a&-1)):(g.setUint32(f,2147483647),g.setUint32(f+4,2147483647)),9;throw Error("Number too small -0x"+(-a).toString(16).substr(1));}if("undefined"===n){if(e)return 0;g.setUint8(f,212);g.setUint8(f+1,0);g.setUint8(f+ +2,0);return 3}if(null===a){if(e)return 0;g.setUint8(f,192);return 1}if("boolean"===n)return g.setUint8(f,a?195:194),1;if("function"===typeof a.toJSON)return m(a.toJSON(),g,f,e);if("object"===n){n=0;var u=Array.isArray(a);if(u)p=a.length;else{var A=c(a,e);p=A.length}16>p?(g.setUint8(f,p|(u?144:128)),n=1):65536>p?(g.setUint8(f,u?220:222),g.setUint16(f+1,p),n=3):4294967296>p&&(g.setUint8(f,u?221:223),g.setUint32(f+1,p),n=5);if(u)for(u=0;ue)return 1+e;if(256>e)return 2+e;if(65536>e)return 3+e;if(4294967296>e)return 5+e}if(a instanceof ArrayBuffer){e=a.byteLength;if(256>e)return 2+e;if(65536>e)return 3+e;if(4294967296>e)return 5+e}if("number"===b){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"===b)return 1;if(null===a)return g?0:1;if(void 0===a)return g?0:3;if("function"===typeof a.toJSON)return f(a.toJSON(),g);if("object"===b){b=0;if(Array.isArray(a)){e=a.length;for(var n=0;ne)return 1+b;if(65536>e)return 3+b;if(4294967296>e)return 5+b;throw Error("Array or object too long 0x"+e.toString(16));}if("function"===b)return 0;throw Error("Unknown type "+b);}var p={inspect:function(a){if(void 0===a)return"undefined";if(a instanceof ArrayBuffer){var g="ArrayBuffer";var c=new DataView(a)}else a instanceof DataView&&(g="DataView",c=a);if(!c)return JSON.stringify(a);for(var f=[],d=0;d"}};p.utf8Write=b;p.utf8Read=k;p.utf8ByteCount=d;p.encode=function(a,c){var g=f(a,c);if(0!=g){g=new ArrayBuffer(g);var d=new DataView(g);m(a,d,0,c);return g}};p.decode=function(c){var g=new DataView(c);g=new a(g);var f=g.parse();if(g.offset!==c.byteLength)throw Error(c.byteLength-g.offset+" trailing bytes");return f};var l=1/4294967296;a.prototype.map=function(a){for(var c={},f=0;f>>2]>>>24-e%4*8&255;return d}throw Error("BufferUtils.toArrayBuffer expected a buffer");};d.toWordArray=function(c){return b(c)?c:a.create(c)};d.base64Encode=function(a){if(k(a)){var c="";a=new Uint8Array(a);var d=a.byteLength,f=d%3;d-=f;for(var g, -e,n,h,P=0;P>18,e=(h&258048)>>12,n=(h&4032)>>6,h&=63,c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[g]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[e]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[n]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[h];1==f?(h=a[d],c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(h&252)>>2]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(h& -3)<<4]+"=="):2==f&&(h=a[d]<<8|a[d+1],c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(h&64512)>>10]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(h&1008)>>4]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(h&15)<<2]+"=");return c}if(b(a))return x.enc.Base64.stringify(a)};d.base64Decode=function(a){if(c&&n){a=n(a);for(var d=a.length,f=new Uint8Array(d),b=0;b>18,e=(h&258048)>>12,m=(h&4032)>>6,h&=63,c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[g]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[e]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[m]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[h];1==f?(h=a[d],c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(h&252)>>2]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(h& +3)<<4]+"=="):2==f&&(h=a[d]<<8|a[d+1],c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(h&64512)>>10]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(h&1008)>>4]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(h&15)<<2]+"=");return c}if(b(a))return x.enc.Base64.stringify(a)};d.base64Decode=function(a){if(c&&m){a=m(a);for(var d=a.length,f=new Uint8Array(d),b=0;b=c}var d=function(){};b.get=function(a,c,e,f,p){p=p||d;var l="function"==typeof c?c:function(d){return a.baseUri(d)+c};var n=(n=a.connection)&&"connected"==n.state?[n.connectionManager.host]:q.getHosts(a.options);if(1==n.length)b.getUri(a,l(n[0]),e,f,p);else{var g=function(c){b.getUri(a,l(c.shift()),e,f,function(a){a&&k(a)&& -c.length?g(c):p.apply(null,arguments)})};g(n)}};b.getUri=function(a,c,e,f,p){b.Request(a,c,e,f,null,p||d)};b.post=function(a,c,e,f,p,l){l=l||d;var n="function"==typeof c?c:function(d){return a.baseUri(d)+c};var g=(g=a.connection)&&"connected"==g.state?[g.connectionManager.host]:q.getHosts(a.options);if(1==g.length)b.postUri(a,n(g[0]),e,f,p,l);else{var u=function(c){b.postUri(a,n(c.shift()),e,f,p,function(a){a&&k(a)&&c.length?u(c):l.apply(null,arguments)})};u(g)}};b.postUri=function(a,c,e,f,p,l){b.Request(a, +a.length;f++)if(b=a[f]-c[f],0!=b)return b;return 0};return d}(),w=function(){function b(){}function k(a){var c=a.statusCode;return 408===c&&!a.code||400===c&&!a.code||500<=c&&504>=c}var d=function(){};b.get=function(a,c,e,f,p){p=p||d;var l="function"==typeof c?c:function(d){return a.baseUri(d)+c};var m=(m=a.connection)&&"connected"==m.state?[m.connectionManager.host]:q.getHosts(a.options);if(1==m.length)b.getUri(a,l(m[0]),e,f,p);else{var g=function(c){b.getUri(a,l(c.shift()),e,f,function(a){a&&k(a)&& +c.length?g(c):p.apply(null,arguments)})};g(m)}};b.getUri=function(a,c,e,f,p){b.Request(a,c,e,f,null,p||d)};b.post=function(a,c,e,f,p,l){l=l||d;var m="function"==typeof c?c:function(d){return a.baseUri(d)+c};var g=(g=a.connection)&&"connected"==g.state?[g.connectionManager.host]:q.getHosts(a.options);if(1==g.length)b.postUri(a,m(g[0]),e,f,p,l);else{var u=function(c){b.postUri(a,m(c.shift()),e,f,p,function(a){a&&k(a)&&c.length?u(c):l.apply(null,arguments)})};u(g)}};b.postUri=function(a,c,e,f,p,l){b.Request(a, c,e,p,f,l||d)};b.supportsAuthHeaders=!1;b.supportsLinkHeaders=!1;return b}(),da=function(){function b(){this.buffer=[]}function k(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,f=a.codex;for(c=new k(c);c.moveNext();){var e= -c.current;c.moveNext();var l=c.current;c.moveNext();var m=c.current,g=e>>2;e=(e&3)<<4|l>>4;var u=(l&15)<<2|m>>6,A=m&63;isNaN(l)?u=A=64:isNaN(m)&&(A=64);d.append(f.charAt(g)+f.charAt(e)+f.charAt(u)+f.charAt(A))}return d.toString()},decode:function(a){var c=new b;for(a=new d(a);a.moveNext();){var f=a.current;if(128>f)c.append(String.fromCharCode(f));else if(191f){a.moveNext();var e=a.current;c.append(String.fromCharCode((f&31)<<6|e&63))}else a.moveNext(),e=a.current,a.moveNext(),c.append(String.fromCharCode((f& +c.current;c.moveNext();var l=c.current;c.moveNext();var n=c.current,g=e>>2;e=(e&3)<<4|l>>4;var u=(l&15)<<2|n>>6,A=n&63;isNaN(l)?u=A=64:isNaN(n)&&(A=64);d.append(f.charAt(g)+f.charAt(e)+f.charAt(u)+f.charAt(A))}return d.toString()},decode:function(a){var c=new b;for(a=new d(a);a.moveNext();){var f=a.current;if(128>f)c.append(String.fromCharCode(f));else if(191f){a.moveNext();var e=a.current;c.append(String.fromCharCode((f&31)<<6|e&63))}else a.moveNext(),e=a.current,a.moveNext(),c.append(String.fromCharCode((f& 15)<<12|(e&63)<<6|a.current&63))}return c.toString()}};k.prototype={current:Number.NaN,moveNext:function(){if(0=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:(127a?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._input.length-1)return this.current=64,!1;var c=a.codex.indexOf(this._input.charAt(++this._index)),d=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)),l=(b&3)<<6|e;this.current=c<<2|d>>4;64!=b&&this._buffer.push((d&15)<<4|b>>2);64!=e&&this._buffer.push(l); 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,connectionStateTtl:12E4,realtimeRequestTimeout:1E4,recvTimeout:9E4,preferenceConnectTimeout:6E3,parallelUpgradeDelay:6E3};q.httpMaxRetryCount= -3;q.version="1.0.18";q.libstring=v.libver+q.version;q.apiVersion="1.0";q.getHost=function(b,k,d){return k=d?k==b.restHost&&b.realtimeHost||k||b.realtimeHost:k||b.restHost};q.getPort=function(b,k){return k||b.tls?b.tlsPort:b.port};q.getHttpScheme=function(b){return b.tls?"https://":"http://"};q.getHosts=function(b){var e=[b.restHost],d=b.fallbackHosts;b="undefined"!==typeof b.httpMaxRetryCount?b.httpMaxRetryCount:q.httpMaxRetryCount;d&&(e=e.concat(h.arrChooseN(d,b)));return e};q.normaliseOptions=function(e){e.host&& +3;q.version="1.0.19";q.libstring=v.libver+q.version;q.apiVersion="1.0";q.getHost=function(b,k,d){return k=d?k==b.restHost&&b.realtimeHost||k||b.realtimeHost:k||b.restHost};q.getPort=function(b,k){return k||b.tls?b.tlsPort:b.port};q.getHttpScheme=function(b){return b.tls?"https://":"http://"};q.getHosts=function(b){var e=[b.restHost],d=b.fallbackHosts;b="undefined"!==typeof b.httpMaxRetryCount?b.httpMaxRetryCount:q.httpMaxRetryCount;d&&(e=e.concat(h.arrChooseN(d,b)));return e};q.normaliseOptions=function(e){e.host&& (b.deprecated("host","restHost"),e.restHost=e.host);e.wsHost&&(b.deprecated("wsHost","realtimeHost"),e.realtimeHost=e.wsHost);e.queueEvents&&(b.deprecated("queueEvents","queueMessages"),e.queueMessages=e.queueEvents);!0===e.recover&&(b.deprecated("{recover: true}","{recover: function(lastConnectionDetails, cb) { cb(true); }}"),e.recover=function(a,d){d(!0)});"function"===typeof e.recover&&!0===e.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"), e.recover=null);"closeOnUnload"in e||(e.closeOnUnload=!e.recover);e.transports&&h.arrIn(e.transports,"xhr")&&(b.deprecated('transports: ["xhr"]','transports: ["xhr_streaming"]'),h.arrDeleteValue(e.transports,"xhr"),e.transports.push("xhr_streaming"));"queueMessages"in e||(e.queueMessages=!0);var k=!1;if(e.restHost)e.realtimeHost=e.realtimeHost||e.restHost;else{var d=e.environment&&String(e.environment).toLowerCase()||q.ENVIRONMENT;k=!d||"production"===d;e.restHost=k?q.REST_HOST:d+"-"+q.REST_HOST; -e.realtimeHost=k?q.REALTIME_HOST:d+"-"+q.REALTIME_HOST}e.fallbackHosts=k||e.fallbackHostsUseDefault?q.FALLBACK_HOSTS:e.fallbackHosts;e.port=e.port||q.PORT;e.tlsPort=e.tlsPort||q.TLS_PORT;"tls"in e||(e.tls=!0);e.timeouts={};for(var a in q.TIMEOUTS)e.timeouts[a]=e[a]||q.TIMEOUTS[a];e.useBinaryProtocol="useBinaryProtocol"in e?v.supportsBinary&&e.useBinaryProtocol:v.preferBinary;return e};var z=function(){function e(){this.any=[];this.events={};this.anyOnce=[];this.eventsOnce={}}function k(a,c,d){try{c.apply(a, -d)}catch(f){b.logAction(b.LOG_ERROR,"EventEmitter.emit()","Unexpected listener exception: "+f+"; stack = "+(f&&f.stack))}}function d(a,c,b){var f,e,l;for(l=0;l=d?null:c.slice(0,d).join("/"),a.data=l}}};e.fromResponseBody=function(a,c,n){n&&(a="msgpack"==n?d.decode(a):JSON.parse(String(a)));for(n=0;n=d?null:c.slice(0,d).join("/"),a.data=l}}};e.fromResponseBody=function(a,c,m){m&&(a="msgpack"==m?d.decode(a):JSON.parse(String(a)));for(m=0;mh.arrIndexOf(l,b.shortName)} @@ -110,7 +110,7 @@ closing:{state:"closing",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:a.r a.connectionStateTtl;this.maxIdleInterval=null;this.transports=h.intersect(f.transports||q.defaultTransports,d.supportedTransports);this.baseTransport=h.intersect(q.baseTransportOrder,this.transports)[0];this.upgradeTransports=h.intersect(this.transports,q.upgradeTransports);this.transportHostBlacklist={};this.transportPreference=null;this.httpHosts=q.getHosts(f);this.activeProtocol=null;this.proposedTransports=[];this.pendingTransports=[];this.mostRecentMsgId=this.lastActivity=this.lastAutoReconnectAttempt= this.host=null;b.logAction(b.LOG_MINOR,"Realtime.ConnectionManager()","started");b.logAction(b.LOG_MICRO,"Realtime.ConnectionManager()","requested transports = ["+(f.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(a=v.addEventListener)c&&"function"===typeof f.recover&&a("beforeunload",this.persistConnection.bind(this)),!0===f.closeOnUnload&&a("beforeunload",function(){b.logAction(b.LOG_MAJOR,"Realtime.ConnectionManager()","beforeunload event has triggered the connection to close as closeOnUnload is true");g.requestState({state:"closing"})}),a("online",function(){if(g.state==g.states.disconnected||g.state==g.states.suspended)b.logAction(b.LOG_MINOR,"ConnectionManager caught browser \u2018online\u2019 event", -"reattempting connection"),g.requestState({state:"connecting"})}),a("offline",function(){g.state==g.states.connected&&(b.logAction(b.LOG_MINOR,"ConnectionManager caught browser \u2018offline\u2019 event","disconnecting active transport"),g.disconnectAllTransports())})}var a=!("undefined"===typeof I||!I.get),c=!("undefined"===typeof I||!I.getSession),n=y.Action,f=aa.PendingMessage,p=function(){},l=q.transportPreferenceOrder,m=l[l.length-1];k.prototype.getConnectParams=function(a){a=a?h.copy(a):{}; +"reattempting connection"),g.requestState({state:"connecting"})}),a("offline",function(){g.state==g.states.connected&&(b.logAction(b.LOG_MINOR,"ConnectionManager caught browser \u2018offline\u2019 event","disconnecting active transport"),g.disconnectAllTransports())})}var a=!("undefined"===typeof I||!I.get),c=!("undefined"===typeof I||!I.getSession),m=y.Action,f=aa.PendingMessage,p=function(){},l=q.transportPreferenceOrder,n=l[l.length-1];k.prototype.getConnectParams=function(a){a=a?h.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&&h.mixin(a,b.transportParams);return a};k.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+"]"};h.inherits(d,z);d.supportedTransports={};d.prototype.createTransportParams=function(a,b){a=new k(this.options,a,b,this.connectionKey);this.timeSerial?a.timeSerial=this.timeSerial:void 0!==this.connectionSerial&&(a.connectionSerial=this.connectionSerial);return a};d.prototype.getTransportParams=function(a){var d=this;(function(a){if(d.connectionKey)a("resume");else if("string"===typeof d.options.recover)a("recover");else{var g=d.options.recover,f=c&&I.getSession("ably-connection-recovery"); @@ -118,54 +118,54 @@ f&&"function"===typeof g?(b.logAction(b.LOG_MINOR,"ConnectionManager.getTranspor c[2])):b.logAction(b.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport params = "+g.toString());a(g)})};d.prototype.tryATransport=function(a,c,f){var g=this,e=a.host;b.logAction(b.LOG_MICRO,"ConnectionManager.tryATransport()","trying "+c);e in this.transportHostBlacklist&&h.arrIn(this.transportHostBlacklist[e],c)?b.logAction(b.LOG_MINOR,"ConnectionManager.tryATransport()",c+" transport is blacklisted for host "+a.host):d.supportedTransports[c].tryConnect(this,this.realtime.auth,a,function(d, e){var l=g.state;l==g.states.closing||l==g.states.closed||l==g.states.failed?(e&&(b.logAction(b.LOG_MINOR,"ConnectionManager.tryATransport()","connection "+l.state+" while we were attempting the transport; closing "+e),e.close()),f(!0)):d?(b.logAction(b.LOG_MINOR,"ConnectionManager.tryATransport()","transport "+c+" "+d.event+", err: "+d.error.toString()),L.isTokenErr(d.error)?g.realtime.auth._forceNewToken(null,null,function(b){b?g.actOnErrorFromAuthorize(b):g.tryATransport(a,c,f)}):"failed"===d.event? (g.notifyState({state:"failed",error:d.error}),f(!0)):"disconnected"===d.event&&f(!1)):(b.logAction(b.LOG_MICRO,"ConnectionManager.chooseTransportForHost()","viable transport "+c+"; setting pending"),g.setTransportPending(e,a),f(null,e))})};d.prototype.setTransportPending=function(a,c){var d=c.mode;b.logAction(b.LOG_MINOR,"ConnectionManager.setTransportPending()","transport = "+a+"; mode = "+d);h.arrDeleteValue(this.proposedTransports,a);this.pendingTransports.push(a);var g=this;a.once("connected", -function(b,f,e,l){"upgrade"==d&&g.activeProtocol?a.shortName!==m&&h.arrIn(g.getUpgradePossibilities(),m)?setTimeout(function(){g.scheduleTransportActivation(b,a,f,e,l)},g.options.timeouts.parallelUpgradeDelay):g.scheduleTransportActivation(b,a,f,e,l):(g.activateTransport(b,a,f,e,l),h.nextTick(function(){g.connectImpl(c)}));"recover"===d&&g.options.recover&&(g.options.recover=null,g.unpersistConnection())});a.on(["disconnected","closed","failed"],function(b){g.deactivateTransport(a,this.event,b)}); -this.emit("transport.pending",a)};d.prototype.scheduleTransportActivation=function(a,c,d,f,l){var g=this,m=this.activeProtocol&&this.activeProtocol.getTransport(),u=function(){c.disconnect();h.arrDeleteValue(g.pendingTransports,c)};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),u()):m&&!e(c,m)?(b.logAction(b.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Proposed transport "+c.shortName+" is no better than current active transport "+m.shortName+" - abandoning upgrade"),u()):(b.logAction(b.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Scheduling transport upgrade; transport = "+c),this.realtime.channels.onceNopending(function(e){if(e)b.logAction(b.LOG_ERROR,"ConnectionManager.scheduleTransportActivation()", -"Unable to activate transport; transport = "+c+"; err = "+e);else if(c.isConnected){if(g.state===g.states.connected){b.logAction(b.LOG_MICRO,"ConnectionManager.scheduleTransportActivation()","Currently connected, so temporarily pausing events until the upgrade is complete");g.state=g.states.synchronizing;var m=g.activeProtocol}else if(g.state!==g.states.connecting){b.logAction(b.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Current connection state ("+g.state.state+(g.state===g.states.synchronizing? -", but with an upgrade already in progress":"")+") is not valid to upgrade in; abandoning upgrade to "+c.shortName);u();return}var n=(e=d!==g.connectionId)?l:g;e&&b.logAction(b.LOG_ERROR,"ConnectionManager.scheduleTransportActivation()","Upgrade resulted in new connectionId; resetting library connection position from "+(g.timeSerial||g.connectionSerial)+" to "+(n.timeSerial||n.connectionSerial)+"; upgrade error was "+a);b.logAction(b.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Syncing transport; transport = "+ -c);g.sync(c,n,function(d,e,l){if(d)g.state===g.states.synchronizing&&(b.logAction(b.LOG_ERROR,"ConnectionManager.scheduleTransportActivation()","Unexpected error attempting to sync transport; transport = "+c+"; err = "+d),g.disconnectAllTransports());else if(d=function(){b.logAction(b.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Activating transport; transport = "+c);g.activateTransport(a,c,e,f,l);g.state===g.states.synchronizing?(b.logAction(b.LOG_MICRO,"ConnectionManager.scheduleTransportActivation()", -"Pre-upgrade protocol idle, sending queued messages on upgraded transport; transport = "+c),g.state=g.states.connected):b.logAction(b.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Pre-upgrade protocol idle, but state is now "+g.state.state+", so leaving unchanged");g.state.sendEvents&&g.sendQueuedMessages()},m)m.onceIdle(d);else d()})}else b.logAction(b.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Proposed transport "+c.shortName+"is no longer connected; abandoning upgrade"), +function(b,f,e,l){"upgrade"==d&&g.activeProtocol?a.shortName!==n&&h.arrIn(g.getUpgradePossibilities(),n)?setTimeout(function(){g.scheduleTransportActivation(b,a,f,e,l)},g.options.timeouts.parallelUpgradeDelay):g.scheduleTransportActivation(b,a,f,e,l):(g.activateTransport(b,a,f,e,l),h.nextTick(function(){g.connectImpl(c)}));"recover"===d&&g.options.recover&&(g.options.recover=null,g.unpersistConnection())});a.on(["disconnected","closed","failed"],function(b){g.deactivateTransport(a,this.event,b)}); +this.emit("transport.pending",a)};d.prototype.scheduleTransportActivation=function(a,c,d,f,l){var g=this,n=this.activeProtocol&&this.activeProtocol.getTransport(),u=function(){c.disconnect();h.arrDeleteValue(g.pendingTransports,c)};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),u()):n&&!e(c,n)?(b.logAction(b.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Proposed transport "+c.shortName+" is no better than current active transport "+n.shortName+" - abandoning upgrade"),u()):(b.logAction(b.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Scheduling transport upgrade; transport = "+c),this.realtime.channels.onceNopending(function(e){if(e)b.logAction(b.LOG_ERROR,"ConnectionManager.scheduleTransportActivation()", +"Unable to activate transport; transport = "+c+"; err = "+e);else if(c.isConnected){if(g.state===g.states.connected){b.logAction(b.LOG_MICRO,"ConnectionManager.scheduleTransportActivation()","Currently connected, so temporarily pausing events until the upgrade is complete");g.state=g.states.synchronizing;var n=g.activeProtocol}else if(g.state!==g.states.connecting){b.logAction(b.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Current connection state ("+g.state.state+(g.state===g.states.synchronizing? +", but with an upgrade already in progress":"")+") is not valid to upgrade in; abandoning upgrade to "+c.shortName);u();return}var m=(e=d!==g.connectionId)?l:g;e&&b.logAction(b.LOG_ERROR,"ConnectionManager.scheduleTransportActivation()","Upgrade resulted in new connectionId; resetting library connection position from "+(g.timeSerial||g.connectionSerial)+" to "+(m.timeSerial||m.connectionSerial)+"; upgrade error was "+a);b.logAction(b.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Syncing transport; transport = "+ +c);g.sync(c,m,function(d,e,l){if(d)g.state===g.states.synchronizing&&(b.logAction(b.LOG_ERROR,"ConnectionManager.scheduleTransportActivation()","Unexpected error attempting to sync transport; transport = "+c+"; err = "+d),g.disconnectAllTransports());else if(d=function(){b.logAction(b.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Activating transport; transport = "+c);g.activateTransport(a,c,e,f,l);g.state===g.states.synchronizing?(b.logAction(b.LOG_MICRO,"ConnectionManager.scheduleTransportActivation()", +"Pre-upgrade protocol idle, sending queued messages on upgraded transport; transport = "+c),g.state=g.states.connected):b.logAction(b.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Pre-upgrade protocol idle, but state is now "+g.state.state+", so leaving unchanged");g.state.sendEvents&&g.sendQueuedMessages()},n)n.onceIdle(d);else d()})}else b.logAction(b.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Proposed transport "+c.shortName+"is no longer connected; abandoning upgrade"), u()}))};d.prototype.activateTransport=function(a,c,d,f,e){b.logAction(b.LOG_MINOR,"ConnectionManager.activateTransport()","transport = "+c);a&&b.logAction(b.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+a);d&&b.logAction(b.LOG_MICRO,"ConnectionManager.activateTransport()","connectionId = "+d);f&&b.logAction(b.LOG_MICRO,"ConnectionManager.activateTransport()","connectionDetails = "+JSON.stringify(f));e&&b.logAction(b.LOG_MICRO,"ConnectionManager.activateTransport()","serial = "+(e.timeSerial|| e.connectionSerial));this.persistTransportPreference(c);var g=this.state,l=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;h.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 aa(c);this.host=c.params.host;var u=f.connectionKey;u&&this.connectionKey!=u&&this.setConnection(d,f,e,!0);this.onConnectionDetailsUpdate(f,c);var n=this;h.nextTick(function(){c.on("connected",function(a,b,d){n.onConnectionDetailsUpdate(d,c);n.emit("update",new Q(l,l,null,a))})});g.state===this.states.connected.state?a&&(this.errorReason= -this.realtime.connection.errorReason=a,this.emit("update",new Q(l,l,null,a))):(this.notifyState({state:"connected",error:a}),this.errorReason=this.realtime.connection.errorReason=a||null);this.emit("transport.active",c);m&&(0this.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)}};d.prototype.persistConnection=function(){if(c){var a=this.realtime.connection.recoveryKey;a&&(a={recoveryKey:a, -disconnectedAt:h.now(),location:window.location,clientId:this.realtime.auth.clientId},c&&I.setSession("ably-connection-recovery",a))}};d.prototype.unpersistConnection=function(){c&&I.removeSession("ably-connection-recovery")};d.prototype.getStateError=function(){return J[this.state.state]};d.prototype.activeState=function(){return this.state.queueEvents||this.state.sendEvents};d.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)};d.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)};d.prototype.cancelTransitionTimer=function(){b.logAction(b.LOG_MINOR, -"ConnectionManager.cancelTransitionTimer()","");this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)};d.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))}; -d.prototype.checkSuspendTimer=function(a){"disconnected"!==a&&"suspended"!==a&&"connecting"!==a&&this.cancelSuspendTimer()};d.prototype.cancelSuspendTimer=function(){this.states.connecting.failState="disconnected";this.states.connecting.queueEvents=!0;this.suspendTimer&&(clearTimeout(this.suspendTimer),this.suspendTimer=null)};d.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)};d.prototype.cancelRetryTimer=function(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)};d.prototype.notifyState=function(a){var c=a.state,d=this,g="disconnected"===c&&(this.state===this.states.connected||this.state===this.states.synchronizing||this.state===this.states.connecting&&a.error&&L.isTokenErr(a.error));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 f=this.states[a.state];a=new Q(this.state.state,f.state,f.retryDelay,a.error||J[f.state]);if(g){var e=function(){d.state===d.states.disconnected&&(d.lastAutoReconnectAttempt=h.now(),d.requestState({state:"connecting"}))},l=this.lastAutoReconnectAttempt&&h.now()-this.lastAutoReconnectAttempt+1;l&&1E3>l?(b.logAction(b.LOG_MICRO,"ConnectionManager.notifyState()","Last reconnect attempt was only "+ -l+"ms ago, waiting another "+(1E3-l)+"ms before trying again"),setTimeout(e,1E3-l)):h.nextTick(e)}else"disconnected"!==c&&"suspended"!==c||this.startRetryTimer(f.retryDelay);("disconnected"===c&&!g||"suspended"===c||f.terminal)&&h.nextTick(function(){d.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))}};d.prototype.requestState=function(a){var c=a.state,d=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 Q(this.state.state,g.state,null,a.error||J[g.state]);this.enactStateChange(a);"connecting"==c&&h.nextTick(function(){d.startConnect()});"closing"==c&&this.closeImpl()}};d.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,d=function(){c.checkConnectionStateFreshness(); -c.getTransportParams(function(a){c.connectImpl(a)})};b.logAction(b.LOG_MINOR,"ConnectionManager.startConnect()","starting connection");this.startSuspendTimer();this.startTransitionTimer(this.states.connecting);if("basic"===a.method)d();else{var f=function(a){a?c.actOnErrorFromAuthorize(a):d()};this.errorReason&&L.isTokenErr(this.errorReason)?a._forceNewToken(null,null,f):a._ensureValidAuthCredentials(f)}}};d.prototype.connectImpl=function(a){var c=this.state.state;c!==this.states.connecting.state&& -c!==this.states.connected.state?b.logAction(b.LOG_MINOR,"ConnectionManager.connectImpl()","Must be in connecting state to connect (or connected to upgrade), but was "+c):this.pendingTransports.length?b.logAction(b.LOG_MINOR,"ConnectionManager.connectImpl()","Transports "+this.pendingTransports[0].toString()+" currently pending; taking no action"):c==this.states.connected.state?this.upgradeIfNeeded(a):1this.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)}};d.prototype.persistConnection= +function(){if(c){var a=this.realtime.connection.recoveryKey;a&&(a={recoveryKey:a,disconnectedAt:h.now(),location:window.location,clientId:this.realtime.auth.clientId},c&&I.setSession("ably-connection-recovery",a))}};d.prototype.unpersistConnection=function(){c&&I.removeSession("ably-connection-recovery")};d.prototype.getStateError=function(){return J[this.state.state]};d.prototype.activeState=function(){return this.state.queueEvents||this.state.sendEvents};d.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)};d.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)};d.prototype.cancelTransitionTimer= +function(){b.logAction(b.LOG_MINOR,"ConnectionManager.cancelTransitionTimer()","");this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)};d.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))};d.prototype.checkSuspendTimer=function(a){"disconnected"!==a&&"suspended"!==a&&"connecting"!==a&&this.cancelSuspendTimer()};d.prototype.cancelSuspendTimer=function(){this.states.connecting.failState="disconnected";this.states.connecting.queueEvents=!0;this.suspendTimer&&(clearTimeout(this.suspendTimer),this.suspendTimer=null)};d.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)};d.prototype.cancelRetryTimer=function(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)};d.prototype.notifyState=function(a){var c=a.state,d=this,g="disconnected"===c&&(this.state===this.states.connected||this.state===this.states.synchronizing||this.state===this.states.connecting&&a.error&&L.isTokenErr(a.error));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 f=this.states[a.state];a=new Q(this.state.state,f.state,f.retryDelay,a.error||J[f.state]);if(g){var e=function(){d.state===d.states.disconnected&&(d.lastAutoReconnectAttempt=h.now(),d.requestState({state:"connecting"}))},l=this.lastAutoReconnectAttempt&&h.now()-this.lastAutoReconnectAttempt+1;l&&1E3>l?(b.logAction(b.LOG_MICRO,"ConnectionManager.notifyState()", +"Last reconnect attempt was only "+l+"ms ago, waiting another "+(1E3-l)+"ms before trying again"),setTimeout(e,1E3-l)):h.nextTick(e)}else"disconnected"!==c&&"suspended"!==c||this.startRetryTimer(f.retryDelay);("disconnected"===c&&!g||"suspended"===c||f.terminal)&&h.nextTick(function(){d.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))}};d.prototype.requestState=function(a){var c=a.state,d=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 Q(this.state.state,g.state,null,a.error||J[g.state]);this.enactStateChange(a);"connecting"==c&&h.nextTick(function(){d.startConnect()});"closing"==c&&this.closeImpl()}};d.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,d= +function(){c.checkConnectionStateFreshness();c.getTransportParams(function(a){c.connectImpl(a)})};b.logAction(b.LOG_MINOR,"ConnectionManager.startConnect()","starting connection");this.startSuspendTimer();this.startTransitionTimer(this.states.connecting);if("basic"===a.method)d();else{var f=function(a){a?c.actOnErrorFromAuthorize(a):d()};this.errorReason&&L.isTokenErr(this.errorReason)?a._forceNewToken(null,null,f):a._ensureValidAuthCredentials(f)}}};d.prototype.connectImpl=function(a){var c=this.state.state; +c!==this.states.connecting.state&&c!==this.states.connected.state?b.logAction(b.LOG_MINOR,"ConnectionManager.connectImpl()","Must be in connecting state to connect (or connected to upgrade), but was "+c):this.pendingTransports.length?b.logAction(b.LOG_MINOR,"ConnectionManager.connectImpl()","Transports "+this.pendingTransports[0].toString()+" currently pending; taking no action"):c==this.states.connected.state?this.upgradeIfNeeded(a):1=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 r(a,80003,408))):this.setIdleTimer(d+100)};e.prototype.onAuthUpdated=function(){};return e}();(function(){function e(b,a,c){this.shortName="web_socket";c.heartbeats=v.useProtocolHeartbeats;O.call(this,b,a,c);this.wsHost= -q.getHost(c.options,c.host,!0)}var k=v.WebSocket;h.inherits(e,O);e.isAvailable=function(){return!!k};e.isAvailable()&&(N.supportedTransports.web_socket=e);e.tryConnect=function(d,a,c,n){var f=new e(d,a,c),p=function(a){n({event:this.event,error:a})};f.on(["failed","disconnected"],p);f.on("wsopen",function(){b.logAction(b.LOG_MINOR,"WebSocketTransport.tryConnect()","viable transport "+f);f.off(["failed","disconnected"],p);n(null,f)});f.connect()};e.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 k(b)};e.prototype.toString=function(){return"WebSocketTransport; uri="+this.uri};e.prototype.connect=function(){b.logAction(b.LOG_MINOR,"WebSocketTransport.connect()","starting");O.prototype.connect.call(this);var d=this,a=this.params,c=a.options,e=(c.tls?"wss://":"ws://")+this.wsHost+":"+q.getPort(c)+"/";b.logAction(b.LOG_MINOR,"WebSocketTransport.connect()","uri: "+e);this.auth.getAuthParams(function(c,p){var f="",m;for(m in p)f+=" "+m+": "+p[m]+";"; -b.logAction(b.LOG_MINOR,"WebSocketTransport.connect()","authParams:"+f+" err: "+c);if(c)d.disconnect(c);else{c=a.getConnectParams(p);try{var g=d.wsConnection=d.createWebSocket(e,c);g.binaryType=v.binaryType;g.onopen=function(){d.onWsOpen()};g.onclose=function(a){d.onWsClose(a)};g.onmessage=function(a){d.onWsData(a.data)};g.onerror=function(a){d.onWsError(a)};if(g.on)g.on("ping",function(){d.onActivity()})}catch(u){b.logAction(b.LOG_ERROR,"WebSocketTransport.connect()","Unexpected exception creating websocket: err = "+ +q.getHost(c.options,c.host,!0)}var k=v.WebSocket;h.inherits(e,O);e.isAvailable=function(){return!!k};e.isAvailable()&&(N.supportedTransports.web_socket=e);e.tryConnect=function(d,a,c,m){var f=new e(d,a,c),p=function(a){m({event:this.event,error:a})};f.on(["failed","disconnected"],p);f.on("wsopen",function(){b.logAction(b.LOG_MINOR,"WebSocketTransport.tryConnect()","viable transport "+f);f.off(["failed","disconnected"],p);m(null,f)});f.connect()};e.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 k(b)};e.prototype.toString=function(){return"WebSocketTransport; uri="+this.uri};e.prototype.connect=function(){b.logAction(b.LOG_MINOR,"WebSocketTransport.connect()","starting");O.prototype.connect.call(this);var d=this,a=this.params,c=a.options,e=(c.tls?"wss://":"ws://")+this.wsHost+":"+q.getPort(c)+"/";b.logAction(b.LOG_MINOR,"WebSocketTransport.connect()","uri: "+e);this.auth.getAuthParams(function(c,m){var f="",n;for(n in m)f+=" "+n+": "+m[n]+";"; +b.logAction(b.LOG_MINOR,"WebSocketTransport.connect()","authParams:"+f+" err: "+c);if(c)d.disconnect(c);else{c=a.getConnectParams(m);try{var g=d.wsConnection=d.createWebSocket(e,c);g.binaryType=v.binaryType;g.onopen=function(){d.onWsOpen()};g.onclose=function(a){d.onWsClose(a)};g.onmessage=function(a){d.onWsData(a.data)};g.onerror=function(a){d.onWsError(a)};if(g.on)g.on("ping",function(){d.onActivity()})}catch(u){b.logAction(b.LOG_ERROR,"WebSocketTransport.connect()","Unexpected exception creating websocket: err = "+ (u.stack||u.message)),d.disconnect(u)}}})};e.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: "+h.inspectError(c),b.logAction(b.LOG_ERROR,"WebSocketTransport.send()",d),this.finish("disconnected",new r(d,5E4,500))}else b.logAction(b.LOG_ERROR,"WebSocketTransport.send()","No socket connection")};e.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)}};e.prototype.onWsOpen=function(){b.logAction(b.LOG_MINOR,"WebSocketTransport.onWsOpen()","opened WebSocket");this.emit("wsopen")};e.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 r("Websocket closed",80003,400)):(d="Unclean disconnection of WebSocket ; code = "+d,a=new r(d,80003,400),b.logAction(b.LOG_MINOR,"WebSocketTransport.onWsClose()",d));this.finish("disconnected",a);this.emit("disposed")};e.prototype.onWsError=function(d){b.logAction(b.LOG_MINOR,"WebSocketTransport.onError()","Error from WebSocket: "+d.message);var a=this;h.nextTick(function(){a.disconnect(d)})};e.prototype.dispose=function(){b.logAction(b.LOG_MINOR,"WebSocketTransport.dispose()", @@ -191,107 +191,107 @@ d.prototype.requestDisconnect=function(){b.logAction(b.LOG_MINOR,"CometTransport "CometTransport.dispose()","");if(!this.disposed){this.disposed=!0;this.recvRequest&&(b.logAction(b.LOG_MINOR,"CometTransport.dispose()","aborting recv request"),this.recvRequest.abort(),this.recvRequest=null);this.finish("disconnected",J.disconnected);var a=this;h.nextTick(function(){a.emit("disposed")})}};d.prototype.onConnect=function(a){if(!this.disposed){var c=a.connectionKey;O.prototype.onConnect.call(this,a);c=this.baseUri+c;b.logAction(b.LOG_MICRO,"CometTransport.onConnect()","baseUri = "+ c+"; connectionKey = "+a.connectionKey);this.sendUri=c+"/send";this.recvUri=c+"/recv";this.closeUri=c+"/close";this.disconnectUri=c+"/disconnect"}};d.prototype.send=function(a){if(this.sendRequest)this.pendingItems=this.pendingItems||[],this.pendingItems.push(a);else{var b=this.pendingItems||[];b.push(a);this.pendingItems=null;this.sendItems(b)}};d.prototype.sendAnyPending=function(){var a=this.pendingItems;a&&(this.pendingItems=null,this.sendItems(a))};d.prototype.sendItems=function(a){var c=this; a=this.sendRequest=c.createRequest(c.sendUri,null,c.authParams,this.encodeRequest(a),0);a.on("complete",function(a,d){a&&b.logAction(b.LOG_ERROR,"CometTransport.sendItems()","on complete: err = "+h.inspectError(a));c.sendRequest=null;if(d)c.onData(d);else if(a&&a.code)c.onData(k(a));else c.disconnect(a);c.pendingItems&&h.nextTick(function(){c.sendRequest||c.sendAnyPending()})});a.exec()};d.prototype.recv=function(){if(!this.recvRequest&&this.isConnected){var a=this,b=this.recvRequest=this.createRequest(this.recvUri, -null,this.authParams,null,a.stream?3:2);b.on("data",function(b){a.onData(b)});b.on("complete",function(b){a.recvRequest=null;a.onActivity();if(b)if(b.code)a.onData(k(b));else a.disconnect(b);else h.nextTick(function(){a.recv()})});b.exec()}};d.prototype.onData=function(a){try{var c=this.decodeResponse(a);if(c&&c.length)for(a=0;ap||300<=p?(c=e&&e.error||c,c||(c=Error("Error in unenveloping "+d),c.statusCode=p),a(c,e,f,!0,p)):a(c,e,f,!0,p))}}}function a(a){var b=[];if(a)for(var c in a)b.push(c+"="+a[c]);return b.join("&")}function c(c,d,e,m){return function(f,l,p,n,k){f?b.logAction(b.LOG_MICRO, -"Resource."+d+"()","Received Error; "+(e+(m?"?":"")+a(m))+"; Error: "+h.inspectError(f)):b.logAction(b.LOG_MICRO,"Resource."+d+"()","Received; "+(e+(m?"?":"")+a(m))+"; Headers: "+a(p)+"; StatusCode: "+k+"; Body: "+(D.isBuffer(l)?l.toString():l));c&&c(f,l,p,n,k)}}var n=v.msgpack;e.get=function(f,e,l,m,g,n){function p(c,d){b.shouldLog(b.LOG_MICRO)&&b.logAction(b.LOG_MICRO,"Resource.get()","Sending; "+(e+(d?"?":"")+a(d)));w.get(f,e,c,d,function(a,b,c,d,g){a&&L.isTokenErr(a)?f.auth.authorize(null,null, -function(a){a?n(a):k(f,l,m,n,p)}):n(a,b,c,d,g)})}b.shouldLog(b.LOG_MICRO)&&(n=c(n,"get",e,m));g&&(n=n&&d(n,g),(m=m||{}).envelope=g);k(f,l,m,n,p)};e.post=function(f,e,l,m,g,u,A){function p(c,d){if(b.shouldLog(b.LOG_MICRO)){var u=l;if(0<(c["content-type"]||"").indexOf("msgpack"))try{u=n.decode(l)}catch(ca){b.logAction(b.LOG_MICRO,"Resource.post()","Sending MsgPack Decoding Error: "+h.inspectError(ca))}b.logAction(b.LOG_MICRO,"Resource.post()","Sending; "+(e+(d?"?":"")+a(d))+"; Body: "+u)}w.post(f,e, -c,l,d,function(a,b,c,d,e){a&&L.isTokenErr(a)?f.auth.authorize(null,null,function(a){a?A(a):k(f,m,g,A,p)}):A(a,b,c,d,e)})}b.shouldLog(b.LOG_MICRO)&&(A=c(A,"post",e,g));u&&(A=d(A,u),g.envelope=u);k(f,m,g,A,p)};return e}(),R=function(){function e(a,b,d,f,e,l){this.rest=a;this.path=b;this.headers=d;this.envelope=f;this.bodyHandler=e;this.useHttpPaginatedResponse=l||!1}function k(a,b,d){this.resource=a;this.items=b;if(d){var c=this;"first"in d&&(this.first=function(a){c.get(d.first,a)});"current"in d&& -(this.current=function(a){c.get(d.current,a)});this.next=function(a){"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,f,e,l){k.call(this,a,b,e);this.statusCode=f;this.success=300>f&&200<=f;this.headers=d;this.errorCode=l&&l.code;this.errorMessage=l&&l.message}e.prototype.get=function(a,b){var c=this;U.get(c.rest,c.path,c.headers,a,c.envelope,function(a,d,e,m,g){c.handlePage(a,d,e,m,g,b)})};e.prototype.post= -function(a,b,d){var c=this;U.post(c.rest,c.path,b,c.headers,a,c.envelope,function(a,b,f,g,e){d&&c.handlePage(a,b,f,g,e,d)})};e.prototype.handlePage=function(a,c,e,f,p,l){if(!a||this.useHttpPaginatedResponse&&(c||"number"===typeof a.code)){var m,g;try{var n=this.bodyHandler(c,e,f)}catch(S){l(a||S);return}if(e&&(m=e.Link||e.link)){c=m;"string"==typeof c&&(c=c.split(","));f={};for(m=0;m;\s*rel="(\w+)"$/)){var A;(A=(A=g[1].match(/^\.\/(\w+)\?(.*)$/))&&h.parseQueryString(A[2]))&& -(f[g[2]]=A)}g=f}this.useHttpPaginatedResponse?l(null,new d(this,n,e,p,g,a)):l(null,new k(this,n,g))}else b.logAction(b.LOG_ERROR,"PaginatedResource.handlePage()","Unexpected error getting resource: err = "+h.inspectError(a)),l(a)};k.prototype.get=function(a,b){var c=this.resource;U.get(c.rest,c.path,c.headers,a,c.envelope,function(a,d,e,m,g){c.handlePage(a,d,e,m,g,b)})};h.inherits(d,k);return e}(),L=function(){function e(){}function k(a){if(!h.isErrorInfo(a))return new r(h.inspectError(a),a.code|| +f){a?d(a):g(b,h.mixin(f,c))})}function d(a,b){return function(c,d,f,e,p){if(c&&!d)a(c);else{if(!e)try{d="msgpack"==b?m.decode(d):JSON.parse(d)}catch(S){a(S);return}void 0===d.statusCode?a(c,d,f,!0,p):(p=d.statusCode,e=d.response,f=d.headers,200>p||300<=p?(c=e&&e.error||c,c||(c=Error("Error in unenveloping "+d),c.statusCode=p),a(c,e,f,!0,p)):a(c,e,f,!0,p))}}}function a(a){var b=[];if(a)for(var c in a)b.push(c+"="+a[c]);return b.join("&")}function c(c,d,e,n){return function(f,l,p,m,k){f?b.logAction(b.LOG_MICRO, +"Resource."+d+"()","Received Error; "+(e+(n?"?":"")+a(n))+"; Error: "+h.inspectError(f)):b.logAction(b.LOG_MICRO,"Resource."+d+"()","Received; "+(e+(n?"?":"")+a(n))+"; Headers: "+a(p)+"; StatusCode: "+k+"; Body: "+(D.isBuffer(l)?l.toString():l));c&&c(f,l,p,m,k)}}var m=v.msgpack;e.get=function(f,e,l,n,g,m){function p(c,d){b.shouldLog(b.LOG_MICRO)&&b.logAction(b.LOG_MICRO,"Resource.get()","Sending; "+(e+(d?"?":"")+a(d)));w.get(f,e,c,d,function(a,b,c,d,g){a&&L.isTokenErr(a)?f.auth.authorize(null,null, +function(a){a?m(a):k(f,l,n,m,p)}):m(a,b,c,d,g)})}b.shouldLog(b.LOG_MICRO)&&(m=c(m,"get",e,n));g&&(m=m&&d(m,g),(n=n||{}).envelope=g);k(f,l,n,m,p)};e.post=function(f,e,l,n,g,u,A){function p(c,d){if(b.shouldLog(b.LOG_MICRO)){var u=l;if(0<(c["content-type"]||"").indexOf("msgpack"))try{u=m.decode(l)}catch(ca){b.logAction(b.LOG_MICRO,"Resource.post()","Sending MsgPack Decoding Error: "+h.inspectError(ca))}b.logAction(b.LOG_MICRO,"Resource.post()","Sending; "+(e+(d?"?":"")+a(d))+"; Body: "+u)}w.post(f,e, +c,l,d,function(a,b,c,d,e){a&&L.isTokenErr(a)?f.auth.authorize(null,null,function(a){a?A(a):k(f,n,g,A,p)}):A(a,b,c,d,e)})}b.shouldLog(b.LOG_MICRO)&&(A=c(A,"post",e,g));u&&(A=d(A,u),g.envelope=u);k(f,n,g,A,p)};return e}(),R=function(){function e(a,b,d,f,e,l){this.rest=a;this.path=b;this.headers=d;this.envelope=f;this.bodyHandler=e;this.useHttpPaginatedResponse=l||!1}function k(a,b,d){this.resource=a;this.items=b;if(d){var c=this;"first"in d&&(this.first=function(a){c.get(d.first,a)});"current"in d&& +(this.current=function(a){c.get(d.current,a)});this.next=function(a){"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,f,e,l){k.call(this,a,b,e);this.statusCode=f;this.success=300>f&&200<=f;this.headers=d;this.errorCode=l&&l.code;this.errorMessage=l&&l.message}e.prototype.get=function(a,b){var c=this;U.get(c.rest,c.path,c.headers,a,c.envelope,function(a,d,e,n,g){c.handlePage(a,d,e,n,g,b)})};e.prototype.post= +function(a,b,d){var c=this;U.post(c.rest,c.path,b,c.headers,a,c.envelope,function(a,b,f,g,e){d&&c.handlePage(a,b,f,g,e,d)})};e.prototype.handlePage=function(a,c,e,f,p,l){if(!a||this.useHttpPaginatedResponse&&(c||"number"===typeof a.code)){var n,g;try{var m=this.bodyHandler(c,e,f)}catch(S){l(a||S);return}if(e&&(n=e.Link||e.link)){c=n;"string"==typeof c&&(c=c.split(","));f={};for(n=0;n;\s*rel="(\w+)"$/)){var A;(A=(A=g[1].match(/^\.\/(\w+)\?(.*)$/))&&h.parseQueryString(A[2]))&& +(f[g[2]]=A)}g=f}this.useHttpPaginatedResponse?l(null,new d(this,m,e,p,g,a)):l(null,new k(this,m,g))}else b.logAction(b.LOG_ERROR,"PaginatedResource.handlePage()","Unexpected error getting resource: err = "+h.inspectError(a)),l(a)};k.prototype.get=function(a,b){var c=this.resource;U.get(c.rest,c.path,c.headers,a,c.envelope,function(a,d,e,n,g){c.handlePage(a,d,e,n,g,b)})};h.inherits(d,k);return e}(),L=function(){function e(){}function k(a){if(!h.isErrorInfo(a))return new r(h.inspectError(a),a.code|| 40170,a.statusCode||401);a.code||(a.code=403===a.statusCode?40300:40170);return a}function d(a){if(!a)return"";"string"==typeof a&&(a=JSON.parse(a));var b={},c=h.keysArray(a,!0);if(!c)return"";c.sort();for(var d=0;dn){d(new r("authUrl response exceeded max permitted length",40170,401));return}try{c=JSON.parse(c)}catch(W){d(new r("Unexpected error processing authURL response; err = "+W.message,40170,401));return}}d(null,c)}else d(new r("authUrl responded with unacceptable content-type "+a+", should be either text/plain, application/jwt or application/json",40170,401));else d(new r("authUrl response is missing a content-type header",40170,401))};b.logAction(b.LOG_MICRO,"Auth.requestToken().tokenRequestCallback", -"Requesting token from "+c.authUrl+"; Params: "+JSON.stringify(l)+"; method: "+(e?"POST":"GET"));e?(f=f||{},f["content-type"]="application/x-www-form-urlencoded",e=h.toQueryString(l).slice(1),w.postUri(g,c.authUrl,f,e,{},a)):w.getUri(g,c.authUrl,f||{},l,a)};else if(c.key){var m=this;b.logAction(b.LOG_MINOR,"Auth.requestToken()","using token auth with client-side signing");l=function(a,b){m.createTokenRequest(a,c,b)}}else{b.logAction(b.LOG_ERROR,"Auth.requestToken()","Need a new token, but authOptions does not include any way to request one"); -f(new r("Need a new token, but authOptions does not include any way to request one",40101,403));return}"capability"in a&&(a.capability=d(a.capability));g=this.client;var p=function(a,d){var f=a.keyName,e=function(a){return g.baseUri(a)+"/keys/"+f+"/requestToken"},l=h.defaultPostHeaders();c.requestHeaders&&h.mixin(l,c.requestHeaders);b.logAction(b.LOG_MICRO,"Auth.requestToken().requestToken","Sending POST; "+e+"; Token params: "+JSON.stringify(a));a=JSON.stringify(a);w.post(g,e,l,a,null,d)},q=!1,t= -this.client.options.timeouts.realtimeRequestTimeout,v=setTimeout(function(){q=!0;var a="Token request callback timed out after "+t/1E3+" seconds";b.logAction(b.LOG_ERROR,"Auth.requestToken()",a);f(new r(a,40170,401))},t);l(a,function(a,d){q||(clearTimeout(v),a?(b.logAction(b.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+h.inspectError(a)),f(k(a))):"string"===typeof d?0===d.length?f(new r("Token string is empty",40170,401)):384n&&!c.suppressMaxLengthCheck?f(new r("Token request/details object exceeded max permitted stringified size (was "+a+" bytes)",40170,401)):"issued"in d?f(null,d):"keyName"in d?p(d,function(a,c,d,e){a?(b.logAction(b.LOG_ERROR, -"Auth.requestToken()","token request API call returned error; err = "+h.inspectError(a)),f(k(a))):(e||(c=JSON.parse(c)),b.logAction(b.LOG_MINOR,"Auth.getToken()","token received"),f(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),f(new r(d,40170,401)))))})};c.prototype.createTokenRequest=function(a,c,f){"function"!=typeof a||f?"function"!=typeof c||f||(f=c,c=null):(f=a, -c=a=null);c=c||this.authOptions;a=a||h.copy(this.tokenParams);var e=c.key;if(e){e=e.split(":");var g=e[0],l=e[1];if(l)if(""===a.clientId)f(new r("clientId can\u2019t be an empty string",40012,400));else{"capability"in a&&(a.capability=d(a.capability));var m=h.mixin({keyName:g},a),n=a.clientId||"",k=a.ttl||"",q=a.capability||"",t=this;(function(a){m.timestamp?a():t.getTimestamp(c&&c.queryTime,function(b,c){b?f(b):(m.timestamp=c,a())})})(function(){var a=m.nonce||(m.nonce=("000000"+Math.floor(1E16* -Math.random())).slice(-16));a=m.keyName+"\n"+k+"\n"+q+"\n"+n+"\n"+m.timestamp+"\n"+a+"\n";m.mac=m.mac||p(a,l);b.logAction(b.LOG_MINOR,"Auth.getTokenRequest()","generated signed request");f(null,m)})}else f(new r("Invalid key specified",40101,403))}else f(new r("No key specified",40101,403))};c.prototype.getAuthParams=function(a){"basic"==this.method?a(null,{key:this.key}):this._ensureValidAuthCredentials(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(function(b,c){b?a(b):a(null,{authorization:"Bearer "+f(c.token)})})};c.prototype.getTimestamp=function(a,b){isNaN(parseInt(this.client.serverTimeOffset))&&(a||this.authOptions.queryTime)?this.client.time(function(a,c){a?b(a):b(null,c)}):b(null,h.now()+(this.client.serverTimeOffset||0))};c.prototype._saveBasicOptions=function(a){this.method="basic";this.key=a.key;this.basicKey=f(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){var c=this,d=this.tokenDetails,f=function(){c.requestToken(c.tokenParams,c.authOptions,function(b,d){b?a(b): -a(null,c.tokenDetails=d)})};d?this._tokenClientIdMismatch(d.clientId)?a(new r("Mismatch between clientId in token ("+d.clientId+") and current clientId ("+this.clientId+")",40102,403)):this.getTimestamp(c.authOptions&&c.authOptions.queryTime,function(e,g){e&&a(e);void 0===d.expires||d.expires>=g?(b.logAction(b.LOG_MINOR,"Auth.getToken()","using cached token; expires = "+d.expires),a(null,d)):(b.logAction(b.LOG_MINOR,"Auth.getToken()","deleting expired token"),c.tokenDetails=null,f())}):f()};c.prototype._userSetClientId= -function(a){if("string"!==typeof a&&null!==a)throw new r("clientId must be either a string or null",40012,400);if("*"===a)throw new r('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 r(a,40102,401);b.logAction(b.LOG_ERROR,"Auth._uncheckedSetClientId()",a);return c}if("*"===a)this.tokenParams.clientId=a;else return this.clientId=this.tokenParams.clientId=a,null};c.prototype._tokenClientIdMismatch=function(a){return this.clientId&&a&&"*"!==a&&this.clientId!==a};c.isTokenErr=function(a){return a.code&&40140<=a.code&&40150>a.code};return c}(),G=function(){function e(a){if(!(this instanceof -e))return new e(a);if(!a){var c="no options provided";b.logAction(b.LOG_ERROR,"Rest()",c);throw Error(c);}"string"==typeof a&&(a=-1==a.indexOf(":")?{token:a}:{key:a});a.log&&b.setLog(a.log.level,a.log.handler);b.logAction(b.LOG_MICRO,"Rest()","initialized with clientOptions "+h.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 r("clientId must be either a string or null",40012,400);if("*"===a.clientId)throw new r('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=null;this.auth=new L(this,a);this.channels=new k(this)}function k(a){this.rest=a;this.attached={}}var d=function(){},a=v.msgpack;e.prototype.stats=function(a,b){void 0===b&&("function"==typeof a?(b=a,a=null):b=d);var c=h.copy(h.defaultGetHeaders()),e=this.options.useBinaryProtocol?"msgpack":"json";e=w.supportsLinkHeaders?void 0:e;this.options.headers&&h.mixin(c,this.options.headers);(new R(this,"/stats",c,e,function(a,b,c){a=c?a:JSON.parse(a);for(b=0;b -b.timestamp;a=a.parseId();b=b.parseId();return a.msgSerial===b.msgSerial?a.index>b.index:a.msgSerial>b.msgSerial}var n=function(){};h.inherits(d,T);d.prototype.enter=function(a,b){if(e(this))throw new r("clientId must be specified to enter a presence channel",40012,400);this._enterOrUpdateClient(void 0,a,b,"enter")};d.prototype.update=function(a,b){if(e(this))throw new r("clientId must be specified to update presence data",40012,400);this._enterOrUpdateClient(void 0,a,b,"update")};d.prototype.enterClient= -function(a,b,c){this._enterOrUpdateClient(a,b,c,"enter")};d.prototype.updateClient=function(a,b,c){this._enterOrUpdateClient(a,b,c,"update")};d.prototype._enterOrUpdateClient=function(a,c,d,e){d||("function"===typeof c?(d=c,c=null):d=n);var f=this.channel;if(f.connectionManager.activeState()){b.logAction(b.LOG_MICRO,"RealtimePresence."+e+"Client()",e+"ing; channel = "+f.name+", client = "+a||"(implicit) "+this.channel.realtime.auth.clientId);var l=F.fromValues({action:e,data:c});a&&(l.clientId=a); -var m=this;F.encode(l,f.channelOptions,function(a){if(a)d(a);else switch(f.state){case "attached":f.sendPresence(l,d);break;case "initialized":case "detached":f.attach();case "attaching":m.pendingPresence.push({presence:l,callback:d});break;default:a=new r("Unable to "+e+" presence channel (incompatible state)",90001),a.code=90001,d(a)}})}else d(f.connectionManager.getStateError())};d.prototype.leave=function(a,b){if(e(this))throw new r("clientId must have been specified to enter or leave a presence channel", -40012,400);this.leaveClient(void 0,a,b)};d.prototype.leaveClient=function(a,c,d){d||("function"===typeof c?(d=c,c=null):d=n);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 r("Unable to leave presence channel (incompatible state)",90001);d(a);break;default:d(J.failed)}else d(e.connectionManager.getStateError())};d.prototype.get=function(){function a(a){d(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],d=b[1]||n,e=!c||("waitForSync"in c?c.waitForSync:!0);if("suspended"===this.channel.state)e?d(r.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 h=this;k(this.channel,d,function(){var b=h.members;e?b.waitSync(function(){a(b)}):a(b)})}};d.prototype.history=function(a,c){b.logAction(b.LOG_MICRO,"RealtimePresence.history()","channel = "+this.name);void 0===c&&("function"==typeof a?(c=a,a=null):c=n);a&&a.untilAttach&&("attached"===this.channel.state?(delete a.untilAttach,a.from_serial=this.channel.attachSerial):c(new r("option untilAttach requires the channel to be attached, was: "+this.channel.state,4E4,400)));T.prototype._history.call(this, -a,c)};d.prototype.setPresence=function(a,c,d){b.logAction(b.LOG_MICRO,"RealtimePresence.setPresence()","received presence for "+a.length+" participants; syncChannelSerial = "+d);var e,f,l=this.members,h=this._myMembers,k=[],p=this.channel.connectionManager.connectionId;c&&(this.members.startSync(),d&&(f=d.match(/^[\w\-]+:(.*)$/))&&(e=f[1]));for(d=0;db)&&0!==q.status){if(void 0===w)if(w=q.status,1223===w&&(w=204),clearTimeout(e),C=400>w,204==w)d.complete(null,null,null,null,w);else{var f;if(f=3==d.requestMode&&C)f=q,f=f.getResponseHeader&&f.getResponseHeader("transfer-encoding")&&!f.getResponseHeader("content-length");z=f}if(3==b&&z)a();else if(4==b)if(z)c();else a:{try{var g= -q.getResponseHeader&&q.getResponseHeader("content-type");if(g?0<=g.indexOf("application/json"):"text"==q.responseType){var l="arraybuffer"===q.responseType?D.utf8Decode(q.response):String(q.responseText);l.length&&(l=JSON.parse(l));F=!0}else l=q.response;if(void 0!==l.response){w=l.statusCode;C=400>w;var m=l.headers;l=l.response}else{var k=h.trim(q.getAllResponseHeaders()).split("\r\n");b={};for(g=0;gm){d(new r("authUrl response exceeded max permitted length",40170,401));return}try{c=JSON.parse(c)}catch(W){d(new r("Unexpected error processing authURL response; err = "+W.message,40170,401));return}}d(null,c)}else d(new r("authUrl responded with unacceptable content-type "+a+", should be either text/plain, application/jwt or application/json", +40170,401));else d(new r("authUrl response is missing a content-type header",40170,401))};b.logAction(b.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Requesting token from "+c.authUrl+"; Params: "+JSON.stringify(l)+"; method: "+(e?"POST":"GET"));e?(f=f||{},f["content-type"]="application/x-www-form-urlencoded",e=h.toQueryString(l).slice(1),w.postUri(g,c.authUrl,f,e,{},a)):w.getUri(g,c.authUrl,f||{},l,a)};else if(c.key){var n=this;b.logAction(b.LOG_MINOR,"Auth.requestToken()","using token auth with client-side signing"); +l=function(a,b){n.createTokenRequest(a,c,b)}}else{b.logAction(b.LOG_ERROR,"Auth.requestToken()","Need a new token, but authOptions does not include any way to request one");f(new r("Need a new token, but authOptions does not include any way to request one",40101,403));return}"capability"in a&&(a.capability=d(a.capability));g=this.client;var p=function(a,d){var f=a.keyName,e=function(a){return g.baseUri(a)+"/keys/"+f+"/requestToken"},l=h.defaultPostHeaders();c.requestHeaders&&h.mixin(l,c.requestHeaders); +b.logAction(b.LOG_MICRO,"Auth.requestToken().requestToken","Sending POST; "+e+"; Token params: "+JSON.stringify(a));a=JSON.stringify(a);w.post(g,e,l,a,null,d)},q=!1,t=this.client.options.timeouts.realtimeRequestTimeout,v=setTimeout(function(){q=!0;var a="Token request callback timed out after "+t/1E3+" seconds";b.logAction(b.LOG_ERROR,"Auth.requestToken()",a);f(new r(a,40170,401))},t);l(a,function(a,d){q||(clearTimeout(v),a?(b.logAction(b.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+ +h.inspectError(a)),f(k(a))):"string"===typeof d?0===d.length?f(new r("Token string is empty",40170,401)):384m&&!c.suppressMaxLengthCheck?f(new r("Token request/details object exceeded max permitted stringified size (was "+ +a+" bytes)",40170,401)):"issued"in d?f(null,d):"keyName"in d?p(d,function(a,c,d,e){a?(b.logAction(b.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+h.inspectError(a)),f(k(a))):(e||(c=JSON.parse(c)),b.logAction(b.LOG_MINOR,"Auth.getToken()","token received"),f(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),f(new r(d,40170,401)))))})};c.prototype.createTokenRequest= +function(a,c,f){"function"!=typeof a||f?"function"!=typeof c||f||(f=c,c=null):(f=a,c=a=null);c=c||this.authOptions;a=a||h.copy(this.tokenParams);var e=c.key;if(e){e=e.split(":");var g=e[0],l=e[1];if(l)if(""===a.clientId)f(new r("clientId can\u2019t be an empty string",40012,400));else{"capability"in a&&(a.capability=d(a.capability));var n=h.mixin({keyName:g},a),m=a.clientId||"",k=a.ttl||"",q=a.capability||"",t=this;(function(a){n.timestamp?a():t.getTimestamp(c&&c.queryTime,function(b,c){b?f(b):(n.timestamp= +c,a())})})(function(){var a=n.nonce||(n.nonce=("000000"+Math.floor(1E16*Math.random())).slice(-16));a=n.keyName+"\n"+k+"\n"+q+"\n"+m+"\n"+n.timestamp+"\n"+a+"\n";n.mac=n.mac||p(a,l);b.logAction(b.LOG_MINOR,"Auth.getTokenRequest()","generated signed request");f(null,n)})}else f(new r("Invalid key specified",40101,403))}else f(new r("No key specified",40101,403))};c.prototype.getAuthParams=function(a){"basic"==this.method?a(null,{key:this.key}):this._ensureValidAuthCredentials(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(function(b,c){b?a(b):a(null,{authorization:"Bearer "+f(c.token)})})};c.prototype.getTimestamp=function(a,b){isNaN(parseInt(this.client.serverTimeOffset))&&(a||this.authOptions.queryTime)?this.client.time(function(a,c){a?b(a):b(null,c)}):b(null,h.now()+(this.client.serverTimeOffset||0))};c.prototype._saveBasicOptions=function(a){this.method= +"basic";this.key=a.key;this.basicKey=f(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){var c=this,d=this.tokenDetails,f=function(){c.requestToken(c.tokenParams, +c.authOptions,function(b,d){b?a(b):a(null,c.tokenDetails=d)})};d?this._tokenClientIdMismatch(d.clientId)?a(new r("Mismatch between clientId in token ("+d.clientId+") and current clientId ("+this.clientId+")",40102,403)):this.getTimestamp(c.authOptions&&c.authOptions.queryTime,function(e,g){e&&a(e);void 0===d.expires||d.expires>=g?(b.logAction(b.LOG_MINOR,"Auth.getToken()","using cached token; expires = "+d.expires),a(null,d)):(b.logAction(b.LOG_MINOR,"Auth.getToken()","deleting expired token"),c.tokenDetails= +null,f())}):f()};c.prototype._userSetClientId=function(a){if("string"!==typeof a&&null!==a)throw new r("clientId must be either a string or null",40012,400);if("*"===a)throw new r('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 r(a,40102,401);b.logAction(b.LOG_ERROR,"Auth._uncheckedSetClientId()",a);return c}if("*"===a)this.tokenParams.clientId=a;else return this.clientId=this.tokenParams.clientId=a,null};c.prototype._tokenClientIdMismatch=function(a){return this.clientId&&a&&"*"!==a&&this.clientId!==a};c.isTokenErr=function(a){return a.code&&40140<=a.code&& +40150>a.code};return c}(),G=function(){function e(a){if(!(this instanceof e))return new e(a);if(!a){var c="no options provided";b.logAction(b.LOG_ERROR,"Rest()",c);throw Error(c);}"string"==typeof a&&(a=-1==a.indexOf(":")?{token:a}:{key:a});a.log&&b.setLog(a.log.level,a.log.handler);b.logAction(b.LOG_MICRO,"Rest()","initialized with clientOptions "+h.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 r("clientId must be either a string or null",40012,400);if("*"===a.clientId)throw new r('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=null;this.auth=new L(this,a);this.channels=new k(this)}function k(a){this.rest=a;this.attached={}}var d=function(){},a=v.msgpack;e.prototype.stats=function(a,b){void 0===b&&("function"==typeof a?(b=a,a=null):b=d);var c=h.copy(h.defaultGetHeaders()),e=this.options.useBinaryProtocol?"msgpack":"json";e=w.supportsLinkHeaders?void 0:e;this.options.headers&&h.mixin(c,this.options.headers);(new R(this,"/stats",c,e,function(a, +b,c){a=c?a:JSON.parse(a);for(b=0;bb.timestamp;a=a.parseId();b=b.parseId();return a.msgSerial===b.msgSerial?a.index>b.index:a.msgSerial>b.msgSerial}var m=function(){};h.inherits(d,T);d.prototype.enter=function(a,b){if(e(this))throw new r("clientId must be specified to enter a presence channel", +40012,400);this._enterOrUpdateClient(void 0,a,b,"enter")};d.prototype.update=function(a,b){if(e(this))throw new r("clientId must be specified to update presence data",40012,400);this._enterOrUpdateClient(void 0,a,b,"update")};d.prototype.enterClient=function(a,b,c){this._enterOrUpdateClient(a,b,c,"enter")};d.prototype.updateClient=function(a,b,c){this._enterOrUpdateClient(a,b,c,"update")};d.prototype._enterOrUpdateClient=function(a,c,d,e){d||("function"===typeof c?(d=c,c=null):d=m);var f=this.channel; +if(f.connectionManager.activeState()){b.logAction(b.LOG_MICRO,"RealtimePresence."+e+"Client()","channel = "+f.name+", client = "+(a||"(implicit) "+this.channel.realtime.auth.clientId));var l=F.fromValues({action:e,data:c});a&&(l.clientId=a);var h=this;F.encode(l,f.channelOptions,function(a){if(a)d(a);else switch(f.state){case "attached":f.sendPresence(l,d);break;case "initialized":case "detached":f.attach();case "attaching":h.pendingPresence.push({presence:l,callback:d});break;default:a=new r("Unable to "+ +e+" presence channel (incompatible state)",90001),a.code=90001,d(a)}})}else d(f.connectionManager.getStateError())};d.prototype.leave=function(a,b){if(e(this))throw new r("clientId must have been specified to enter or leave a presence channel",40012,400);this.leaveClient(void 0,a,b)};d.prototype.leaveClient=function(a,c,d){d||("function"===typeof c?(d=c,c=null):d=m);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 r("Unable to leave presence channel (incompatible state)",90001);d(a);break;default:d(J.failed)}else d(e.connectionManager.getStateError())};d.prototype.get=function(){function a(a){d(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],d=b[1]||m,e=!c||("waitForSync"in c?c.waitForSync:!0);if("suspended"===this.channel.state)e?d(r.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 h=this;k(this.channel,d,function(){var b=h.members;e?b.waitSync(function(){a(b)}):a(b)})}};d.prototype.history=function(a,c){b.logAction(b.LOG_MICRO,"RealtimePresence.history()","channel = "+ +this.name);void 0===c&&("function"==typeof a?(c=a,a=null):c=m);a&&a.untilAttach&&("attached"===this.channel.state?(delete a.untilAttach,a.from_serial=this.channel.attachSerial):c(new r("option untilAttach requires the channel to be attached, was: "+this.channel.state,4E4,400)));T.prototype._history.call(this,a,c)};d.prototype.setPresence=function(a,c,d){b.logAction(b.LOG_MICRO,"RealtimePresence.setPresence()","received presence for "+a.length+" participants; syncChannelSerial = "+d);var e,f,l=this.members, +h=this._myMembers,k=[],p=this.channel.connectionManager.connectionId;c&&(this.members.startSync(),d&&(f=d.match(/^[\w\-]+:(.*)$/))&&(e=f[1]));for(d=0;db)&&0!==q.status){if(void 0===w)if(w=q.status,1223===w&&(w=204),clearTimeout(e),C=400>w,204==w)d.complete(null,null,null,null,w);else{var f;if(f=3==d.requestMode&&C)f=q,f=f.getResponseHeader&&f.getResponseHeader("transfer-encoding")&&!f.getResponseHeader("content-length");z=f}if(3==b&&z)a();else if(4==b)if(z)c();else a:{try{var g=q.getResponseHeader&&q.getResponseHeader("content-type");if(g?0<=g.indexOf("application/json"):"text"==q.responseType){var l="arraybuffer"===q.responseType?D.utf8Decode(q.response): +String(q.responseText);l.length&&(l=JSON.parse(l));F=!0}else l=q.response;if(void 0!==l.response){w=l.statusCode;C=400>w;var k=l.headers;l=l.response}else{var n=h.trim(q.getAllResponseHeaders()).split("\r\n");b={};for(g=0;ga.statusCode||h.isArray(b)?k.complete(null,b,a.headers,a.statusCode):(a=b.error||new r("Error response received from server",null,a.statusCode),k.complete(a)):k.complete(new r("Invalid server response: no envelope detected",null,500))}else k.complete(null, -a)};this.timer=setTimeout(function(){k.abort()},this.requestMode==K.REQ_SEND?this.timeouts.httpRequestTimeout:this.timeouts.recvTimeout);n.insertBefore(d,n.firstChild)};k.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())};k.prototype.abort=function(){this.dispose()};k.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")};w.Request||(w.Request=function(a,b,c,d,e,f){var g=p(b,c,d,e,K.REQ_SEND,a&&a.options.timeouts);g.once("complete",f);h.nextTick(function(){g.exec()});return g},w.checkConnectivity=function(a){var c=q.jsonpInternetUpUrl;if(f)f.push(a);else{f=[a];b.logAction(b.LOG_MICRO,"(JSONP)Http.checkConnectivity()","Sending; "+c);var d=new k("isTheInternetUp",c,null,null,null,K.REQ_SEND, -q.TIMEOUTS);d.once("complete",function(a,c){a=!a&&c;b.logAction(b.LOG_MICRO,"(JSONP)Http.checkConnectivity()","Result: "+a);for(c=0;c