From 4e8a101bc49b2408a5c678c83303f6219a7626fe Mon Sep 17 00:00:00 2001 From: Jonathan Gros-Dubois Date: Tue, 31 May 2016 12:22:33 +1000 Subject: [PATCH] v4.3.18 --- bower.json | 2 +- index.js | 2 +- package.json | 2 +- socketcluster.js | 6 +++--- socketcluster.min.js | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/bower.json b/bower.json index 200b5b0..0b9745f 100644 --- a/bower.json +++ b/bower.json @@ -1,7 +1,7 @@ { "name": "socketcluster-client", "main": "socketcluster.js", - "version": "4.3.17", + "version": "4.3.18", "homepage": "https://github.com/SocketCluster/socketcluster-client", "description": "SocketCluster JavaScript client", "authors": [ diff --git a/index.js b/index.js index 57f2787..8c89da2 100644 --- a/index.js +++ b/index.js @@ -14,4 +14,4 @@ module.exports.destroy = function (options) { return SCSocketCreator.destroy(options); }; -module.exports.version = '4.3.17'; +module.exports.version = '4.3.18'; diff --git a/package.json b/package.json index c220e7a..457042d 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "socketcluster-client", "description": "SocketCluster JavaScript client", - "version": "4.3.17", + "version": "4.3.18", "homepage": "http://socketcluster.io", "contributors": [ { diff --git a/socketcluster.js b/socketcluster.js index da43ff0..bd9caff 100644 --- a/socketcluster.js +++ b/socketcluster.js @@ -15,7 +15,7 @@ module.exports.destroy = function (options) { return SCSocketCreator.destroy(options); }; -module.exports.version = '4.3.17'; +module.exports.version = '4.3.18'; },{"./lib/scsocket":4,"./lib/scsocketcreator":5,"sc-emitter":12}],2:[function(require,module,exports){ (function (global){ @@ -434,10 +434,10 @@ SCSocket.prototype.disconnect = function (code, data) { data: data }; this.transport.emit('#disconnect', packet); - this.transport.close(code); + this.transport.close(code, data); } else if (this.state == this.CONNECTING) { - this.transport.close(code); + this.transport.close(code, data); } else { this.pendingReconnect = false; this.pendingReconnectTimeout = null; diff --git a/socketcluster.min.js b/socketcluster.min.js index 15c7317..2edaa34 100644 --- a/socketcluster.min.js +++ b/socketcluster.min.js @@ -1,3 +1,3 @@ -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.socketCluster=f()}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;omaxTimeout){throw new InvalidArgumentsError("The "+propertyName+" value provided exceeded the maximum amount allowed")}};verifyDuration("connectTimeout");verifyDuration("ackTimeout");verifyDuration("pingTimeout");this._localEvents={connect:1,connectAbort:1,disconnect:1,message:1,error:1,raw:1,fail:1,kickOut:1,subscribe:1,unsubscribe:1,subscribeStateChange:1,authStateChange:1,authenticate:1,deauthenticate:1,removeAuthToken:1,subscribeRequest:1};this.connectAttempts=0;this._emitBuffer=new LinkedList;this._channels={};this.options=opts;this._cid=1;this.options.callIdGenerator=function(){return self._callIdGenerator()};if(this.options.autoReconnect){if(this.options.autoReconnectOptions==null){this.options.autoReconnectOptions={}}var reconnectOptions=this.options.autoReconnectOptions;if(reconnectOptions.initialDelay==null){reconnectOptions.initialDelay=1e4}if(reconnectOptions.randomness==null){reconnectOptions.randomness=1e4}if(reconnectOptions.multiplier==null){reconnectOptions.multiplier=1.5}if(reconnectOptions.maxDelay==null){reconnectOptions.maxDelay=6e4}}if(this.options.subscriptionRetryOptions==null){this.options.subscriptionRetryOptions={}}if(this.options.authEngine){this.auth=this.options.authEngine}else{this.auth=new AuthEngine}this.options.path=this.options.path.replace(/\/$/,"")+"/";this.options.query=opts.query||{};if(typeof this.options.query=="string"){this.options.query=querystring.parse(this.options.query)}this.connect();this._channelEmitter=new SCEmitter;if(isBrowser){var unloadHandler=function(){self.disconnect()};if(global.attachEvent){global.attachEvent("onunload",unloadHandler)}else if(global.addEventListener){global.addEventListener("beforeunload",unloadHandler,false)}}};SCSocket.prototype=Object.create(SCEmitter.prototype);SCSocket.CONNECTING=SCSocket.prototype.CONNECTING=SCTransport.prototype.CONNECTING;SCSocket.OPEN=SCSocket.prototype.OPEN=SCTransport.prototype.OPEN;SCSocket.CLOSED=SCSocket.prototype.CLOSED=SCTransport.prototype.CLOSED;SCSocket.AUTHENTICATED=SCSocket.prototype.AUTHENTICATED="authenticated";SCSocket.UNAUTHENTICATED=SCSocket.prototype.UNAUTHENTICATED="unauthenticated";SCSocket.PENDING=SCSocket.prototype.PENDING="pending";SCSocket.ignoreStatuses=scErrors.socketProtocolIgnoreStatuses;SCSocket.errorStatuses=scErrors.socketProtocolErrorStatuses;SCSocket.prototype._privateEventHandlerMap={"#publish":function(data){var undecoratedChannelName=this._undecorateChannelName(data.channel);var isSubscribed=this.isSubscribed(undecoratedChannelName,true);if(isSubscribed){this._channelEmitter.emit(undecoratedChannelName,data.data)}},"#kickOut":function(data){var undecoratedChannelName=this._undecorateChannelName(data.channel);var channel=this._channels[undecoratedChannelName];if(channel){SCEmitter.prototype.emit.call(this,"kickOut",data.message,undecoratedChannelName);channel.emit("kickOut",data.message,undecoratedChannelName);this._triggerChannelUnsubscribe(channel)}},"#setAuthToken":function(data,response){var self=this;if(data){var triggerAuthenticate=function(err){if(err){response.error(err);self._onSCError(err)}else{self._changeToAuthenticatedState(data.token);response.end()}};this.auth.saveToken(this.options.authTokenName,data.token,{},triggerAuthenticate)}else{response.error(new InvalidMessageError("No token data provided by #setAuthToken event"))}},"#removeAuthToken":function(data,response){var self=this;this.auth.removeToken(this.options.authTokenName,function(err,oldToken){if(err){response.error(err);self._onSCError(err)}else{SCEmitter.prototype.emit.call(self,"removeAuthToken",oldToken);self._changeToUnauthenticatedState();response.end()}})},"#disconnect":function(data){this.transport.close(data.code,data.data)}};SCSocket.prototype._callIdGenerator=function(){return this._cid++};SCSocket.prototype.getState=function(){return this.state};SCSocket.prototype.getBytesReceived=function(){return this.transport.getBytesReceived()};SCSocket.prototype.deauthenticate=function(callback){var self=this;this.auth.removeToken(this.options.authTokenName,function(err,oldToken){self.emit("#removeAuthToken");callback&&callback(err);if(err){self._onSCError(err)}else{SCEmitter.prototype.emit.call(self,"removeAuthToken",oldToken);self._changeToUnauthenticatedState()}})};SCSocket.prototype.connect=SCSocket.prototype.open=function(){var self=this;if(this.state==this.CLOSED){this.pendingReconnect=false;this.pendingReconnectTimeout=null;clearTimeout(this._reconnectTimeoutRef);this.state=this.CONNECTING;this._changeToPendingAuthState();if(this.transport){this.transport.off()}this.transport=new SCTransport(this.auth,this.options);this.transport.on("open",function(status){self.state=self.OPEN;self._onSCOpen(status)});this.transport.on("error",function(err){self._onSCError(err)});this.transport.on("close",function(code,data){self.state=self.CLOSED;self._onSCClose(code,data)});this.transport.on("openAbort",function(code,data){self.state=self.CLOSED;self._onSCClose(code,data,true)});this.transport.on("event",function(event,data,res){self._onSCEvent(event,data,res)})}};SCSocket.prototype.reconnect=function(){this.disconnect();this.connect()};SCSocket.prototype.disconnect=function(code,data){code=code||1e3;if(this.state==this.OPEN){var packet={code:code,data:data};this.transport.emit("#disconnect",packet);this.transport.close(code)}else if(this.state==this.CONNECTING){this.transport.close(code)}else{this.pendingReconnect=false;this.pendingReconnectTimeout=null;clearTimeout(this._reconnectTimeoutRef)}};SCSocket.prototype._changeToPendingAuthState=function(){if(this.authState!=this.PENDING){var oldState=this.authState;this.authState=this.PENDING;var stateChangeData={oldState:oldState,newState:this.authState};SCEmitter.prototype.emit.call(this,"authStateChange",stateChangeData)}};SCSocket.prototype._changeToUnauthenticatedState=function(){if(this.authState!=this.UNAUTHENTICATED){var oldState=this.authState;this.authState=this.UNAUTHENTICATED;this.signedAuthToken=null;this.authToken=null;var stateChangeData={oldState:oldState,newState:this.authState};SCEmitter.prototype.emit.call(this,"authStateChange",stateChangeData);if(oldState==this.AUTHENTICATED){SCEmitter.prototype.emit.call(this,"deauthenticate")}}};SCSocket.prototype._changeToAuthenticatedState=function(signedAuthToken){if(this.authState!=this.AUTHENTICATED){var oldState=this.authState;this.authState=this.AUTHENTICATED;this.signedAuthToken=signedAuthToken;this.authToken=this._extractAuthTokenData(signedAuthToken);var stateChangeData={oldState:oldState,newState:this.authState,signedAuthToken:signedAuthToken,authToken:this.authToken};this.processPendingSubscriptions();SCEmitter.prototype.emit.call(this,"authStateChange",stateChangeData);SCEmitter.prototype.emit.call(this,"authenticate",signedAuthToken)}};SCSocket.prototype.decodeBase64=function(encodedString){var decodedString;if(typeof Buffer=="undefined"){if(global.atob){decodedString=global.atob(encodedString)}else{decodedString=base64.decode(encodedString)}}else{var buffer=new Buffer(encodedString,"base64");decodedString=buffer.toString("utf8")}return decodedString};SCSocket.prototype.encodeBase64=function(decodedString){var encodedString;if(typeof Buffer=="undefined"){if(global.btoa){encodedString=global.btoa(decodedString)}else{encodedString=base64.encode(decodedString)}}else{var buffer=new Buffer(decodedString,"utf8");encodedString=buffer.toString("base64")}return encodedString};SCSocket.prototype._extractAuthTokenData=function(signedAuthToken){var tokenParts=(signedAuthToken||"").split(".");var encodedTokenData=tokenParts[1];if(encodedTokenData!=null){var tokenData=encodedTokenData;try{tokenData=this.decodeBase64(tokenData);return JSON.parse(tokenData)}catch(e){return tokenData}}return null};SCSocket.prototype.getAuthToken=function(){return this.authToken};SCSocket.prototype.getSignedAuthToken=function(){return this.signedAuthToken};SCSocket.prototype.authenticate=function(signedAuthToken,callback){var self=this;this._changeToPendingAuthState();this.emit("#authenticate",signedAuthToken,function(err,authStatus){if(authStatus&&authStatus.authError){authStatus.authError=scErrors.hydrateError(authStatus.authError)}if(err){self._changeToUnauthenticatedState();callback&&callback(err,authStatus)}else{self.auth.saveToken(self.options.authTokenName,signedAuthToken,{},function(err){callback&&callback(err,authStatus);if(err){self._changeToUnauthenticatedState();self._onSCError(err)}else{if(authStatus.isAuthenticated){self._changeToAuthenticatedState(signedAuthToken)}else{self._changeToUnauthenticatedState()}}})}})};SCSocket.prototype._tryReconnect=function(initialDelay){var self=this;var exponent=this.connectAttempts++;var reconnectOptions=this.options.autoReconnectOptions;var timeout;if(initialDelay==null||exponent>0){var initialTimeout=Math.round(reconnectOptions.initialDelay+(reconnectOptions.randomness||0)*Math.random());timeout=Math.round(initialTimeout*Math.pow(reconnectOptions.multiplier,exponent))}else{timeout=initialDelay}if(timeout>reconnectOptions.maxDelay){timeout=reconnectOptions.maxDelay}clearTimeout(this._reconnectTimeoutRef);this.pendingReconnect=true;this.pendingReconnectTimeout=timeout;this._reconnectTimeoutRef=setTimeout(function(){self.connect()},timeout)};SCSocket.prototype._onSCOpen=function(status){var self=this;if(status){this.id=status.id;this.pingTimeout=status.pingTimeout;this.transport.pingTimeout=this.pingTimeout;if(status.isAuthenticated){this._changeToAuthenticatedState(status.authToken)}else{this._changeToUnauthenticatedState()}}else{this._changeToUnauthenticatedState()}this.connectAttempts=0;if(this.options.autoProcessSubscriptions){this.processPendingSubscriptions()}else{this.pendingConnectCallback=true}SCEmitter.prototype.emit.call(this,"connect",status,function(){self.processPendingSubscriptions()});this._flushEmitBuffer()};SCSocket.prototype._onSCError=function(err){var self=this;setTimeout(function(){if(self.listeners("error").length<1){throw err}else{SCEmitter.prototype.emit.call(self,"error",err)}},0)};SCSocket.prototype._suspendSubscriptions=function(){var channel,newState;for(var channelName in this._channels){if(this._channels.hasOwnProperty(channelName)){channel=this._channels[channelName];if(channel.state==channel.SUBSCRIBED||channel.state==channel.PENDING){newState=channel.PENDING}else{newState=channel.UNSUBSCRIBED}this._triggerChannelUnsubscribe(channel,newState)}}};SCSocket.prototype._onSCClose=function(code,data,openAbort){var self=this;this.id=null;if(this.transport){this.transport.off()}this.pendingReconnect=false;this.pendingReconnectTimeout=null;clearTimeout(this._reconnectTimeoutRef);this._changeToPendingAuthState();this._suspendSubscriptions();if(this.options.autoReconnect){if(code==4e3||code==4001||code==1005){this._tryReconnect(0)}else if(code!=1e3&&code<4500){this._tryReconnect()}}if(openAbort){SCEmitter.prototype.emit.call(self,"connectAbort",code,data)}else{SCEmitter.prototype.emit.call(self,"disconnect",code,data)}if(!SCSocket.ignoreStatuses[code]){var failureMessage;if(data){failureMessage="Socket connection failed: "+data}else{failureMessage="Socket connection failed for unknown reasons"}var err=new SocketProtocolError(SCSocket.errorStatuses[code]||failureMessage,code);this._onSCError(err)}};SCSocket.prototype._onSCEvent=function(event,data,res){var handler=this._privateEventHandlerMap[event];if(handler){handler.call(this,data,res)}else{SCEmitter.prototype.emit.call(this,event,data,function(){res&&res.callback.apply(res,arguments)})}};SCSocket.prototype.parse=function(message){return this.transport.parse(message)};SCSocket.prototype.stringify=function(object){return this.transport.stringify(object)};SCSocket.prototype._flushEmitBuffer=function(){var currentNode=this._emitBuffer.head;var nextNode;while(currentNode){nextNode=currentNode.next;var eventObject=currentNode.data;currentNode.detach();this.transport.emitRaw(eventObject);currentNode=nextNode}};SCSocket.prototype._handleEventAckTimeout=function(eventObject,eventNode){if(eventNode){eventNode.detach()}var error=new TimeoutError("Event response for '"+eventObject.event+"' timed out");var callback=eventObject.callback;if(callback){delete eventObject.callback;callback.call(eventObject,error,eventObject)}};SCSocket.prototype._emit=function(event,data,callback){var self=this;if(this.state==this.CLOSED){this.connect()}var eventObject={event:event,data:data,callback:callback};var eventNode=new LinkedList.Item;eventNode.data=eventObject;eventObject.timeout=setTimeout(function(){self._handleEventAckTimeout(eventObject,eventNode)},this.ackTimeout);this._emitBuffer.append(eventNode);if(this.state==this.OPEN){this._flushEmitBuffer()}};SCSocket.prototype.send=function(data){this.transport.send(data)};SCSocket.prototype.emit=function(event,data,callback){if(this._localEvents[event]==null){this._emit(event,data,callback)}else{SCEmitter.prototype.emit.call(this,event,data)}};SCSocket.prototype.publish=function(channelName,data,callback){var pubData={channel:this._decorateChannelName(channelName),data:data};this.emit("#publish",pubData,callback)};SCSocket.prototype._triggerChannelSubscribe=function(channel,subscriptionOptions){var channelName=channel.name;if(channel.state!=channel.SUBSCRIBED){var oldState=channel.state;channel.state=channel.SUBSCRIBED;var stateChangeData={channel:channelName,oldState:oldState,newState:channel.state,subscriptionOptions:subscriptionOptions};channel.emit("subscribeStateChange",stateChangeData);channel.emit("subscribe",channelName,subscriptionOptions);SCEmitter.prototype.emit.call(this,"subscribeStateChange",stateChangeData);SCEmitter.prototype.emit.call(this,"subscribe",channelName,subscriptionOptions)}};SCSocket.prototype._triggerChannelSubscribeFail=function(err,channel,subscriptionOptions){var channelName=channel.name;var meetsAuthRequirements=!channel.waitForAuth||this.authState==this.AUTHENTICATED;if(channel.state!=channel.UNSUBSCRIBED&&meetsAuthRequirements){channel.state=channel.UNSUBSCRIBED;channel.emit("subscribeFail",err,channelName,subscriptionOptions);SCEmitter.prototype.emit.call(this,"subscribeFail",err,channelName,subscriptionOptions)}};SCSocket.prototype._cancelPendingSubscribeCallback=function(channel){if(channel._pendingSubscriptionCid!=null){this.transport.cancelPendingResponse(channel._pendingSubscriptionCid);delete channel._pendingSubscriptionCid}};SCSocket.prototype._decorateChannelName=function(channelName){if(this.channelPrefix){channelName=this.channelPrefix+channelName}return channelName};SCSocket.prototype._undecorateChannelName=function(decoratedChannelName){if(this.channelPrefix&&decoratedChannelName.indexOf(this.channelPrefix)==0){return decoratedChannelName.replace(this.channelPrefix,"")}return decoratedChannelName};SCSocket.prototype._trySubscribe=function(channel){var self=this;var meetsAuthRequirements=!channel.waitForAuth||this.authState==this.AUTHENTICATED;if(this.state==this.OPEN&&!this.pendingConnectCallback&&channel._pendingSubscriptionCid==null&&meetsAuthRequirements){var options={noTimeout:true};var subscriptionOptions={channel:this._decorateChannelName(channel.name)};if(channel.waitForAuth){options.waitForAuth=true;subscriptionOptions.waitForAuth=options.waitForAuth}if(channel.data){subscriptionOptions.data=channel.data}channel._pendingSubscriptionCid=this.transport.emit("#subscribe",subscriptionOptions,options,function(err){delete channel._pendingSubscriptionCid;if(err){self._triggerChannelSubscribeFail(err,channel,subscriptionOptions)}else{self._triggerChannelSubscribe(channel,subscriptionOptions)}});SCEmitter.prototype.emit.call(this,"subscribeRequest",channel.name,subscriptionOptions)}};SCSocket.prototype.subscribe=function(channelName,options){var channel=this._channels[channelName];if(!channel){channel=new SCChannel(channelName,this,options);this._channels[channelName]=channel}else if(options){channel.setOptions(options)}if(channel.state==channel.UNSUBSCRIBED){channel.state=channel.PENDING;this._trySubscribe(channel)}return channel};SCSocket.prototype._triggerChannelUnsubscribe=function(channel,newState){var channelName=channel.name;var oldState=channel.state;if(newState){channel.state=newState}else{channel.state=channel.UNSUBSCRIBED}this._cancelPendingSubscribeCallback(channel);if(oldState==channel.SUBSCRIBED){var stateChangeData={channel:channelName,oldState:oldState,newState:channel.state};channel.emit("subscribeStateChange",stateChangeData);channel.emit("unsubscribe",channelName);SCEmitter.prototype.emit.call(this,"subscribeStateChange",stateChangeData);SCEmitter.prototype.emit.call(this,"unsubscribe",channelName)}};SCSocket.prototype._tryUnsubscribe=function(channel){var self=this;if(this.state==this.OPEN){var options={noTimeout:true};this._cancelPendingSubscribeCallback(channel);var decoratedChannelName=this._decorateChannelName(channel.name);this.transport.emit("#unsubscribe",decoratedChannelName,options)}};SCSocket.prototype.unsubscribe=function(channelName){var channel=this._channels[channelName];if(channel){if(channel.state!=channel.UNSUBSCRIBED){this._triggerChannelUnsubscribe(channel);this._tryUnsubscribe(channel)}}};SCSocket.prototype.channel=function(channelName,options){var currentChannel=this._channels[channelName];if(!currentChannel){currentChannel=new SCChannel(channelName,this,options);this._channels[channelName]=currentChannel}return currentChannel};SCSocket.prototype.destroyChannel=function(channelName){var channel=this._channels[channelName];channel.unwatch();channel.unsubscribe();delete this._channels[channelName]};SCSocket.prototype.subscriptions=function(includePending){var subs=[];var channel,includeChannel;for(var channelName in this._channels){if(this._channels.hasOwnProperty(channelName)){channel=this._channels[channelName];if(includePending){includeChannel=channel&&(channel.state==channel.SUBSCRIBED||channel.state==channel.PENDING)}else{includeChannel=channel&&channel.state==channel.SUBSCRIBED}if(includeChannel){subs.push(channelName)}}}return subs};SCSocket.prototype.isSubscribed=function(channelName,includePending){var channel=this._channels[channelName];if(includePending){return!!channel&&(channel.state==channel.SUBSCRIBED||channel.state==channel.PENDING)}return!!channel&&channel.state==channel.SUBSCRIBED};SCSocket.prototype.processPendingSubscriptions=function(){var self=this;this.pendingConnectCallback=false;for(var i in this._channels){if(this._channels.hasOwnProperty(i)){(function(channel){if(channel.state==channel.PENDING){self._trySubscribe(channel)}})(this._channels[i])}}};SCSocket.prototype.watch=function(channelName,handler){if(typeof handler!="function"){throw new InvalidArgumentsError("No handler function was provided")}this._channelEmitter.on(channelName,handler)};SCSocket.prototype.unwatch=function(channelName,handler){if(handler){this._channelEmitter.removeListener(channelName,handler)}else{this._channelEmitter.removeAllListeners(channelName)}};SCSocket.prototype.watchers=function(channelName){return this._channelEmitter.listeners(channelName)};module.exports=SCSocket}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer)},{"./auth":2,"./response":3,"./sctransport":6,"base-64":7,buffer:19,"linked-list":10,querystring:24,"sc-channel":11,"sc-emitter":12,"sc-errors":14}],5:[function(require,module,exports){(function(global){var SCSocket=require("./scsocket");var _connections={};function getMultiplexId(options){var protocolPrefix=options.secure?"https://":"http://";var queryString="";if(options.query){if(typeof options.query=="string"){queryString=options.query}else{var queryArray=[];var queryMap=options.query;for(var key in queryMap){if(queryMap.hasOwnProperty(key)){queryArray.push(key+"="+queryMap[key])}}if(queryArray.length){queryString="?"+queryArray.join("&")}}}return protocolPrefix+options.hostname+":"+options.port+options.path+queryString}function isUrlSecure(){return global.location&&location.protocol=="https:"}function getPort(options,isSecureDefault){var isSecure=options.secure==null?isSecureDefault:options.secure;return options.port||(global.location&&location.port?location.port:isSecure?443:80)}function connect(options){var self=this;options=options||{};var isSecureDefault=isUrlSecure();var opts={port:getPort(options,isSecureDefault),hostname:global.location&&location.hostname,path:"/socketcluster/",secure:isSecureDefault,autoReconnect:true,autoProcessSubscriptions:true,connectTimeout:2e4,ackTimeout:1e4,timestampRequests:false,timestampParam:"t",authEngine:null,authTokenName:"socketCluster.authToken",binaryType:"arraybuffer",multiplex:true};for(var i in options){if(options.hasOwnProperty(i)){opts[i]=options[i]}}var multiplexId=getMultiplexId(opts);if(opts.multiplex===false){return new SCSocket(opts)}if(_connections[multiplexId]){_connections[multiplexId].connect()}else{_connections[multiplexId]=new SCSocket(opts)}return _connections[multiplexId]}function destroy(options){var self=this;options=options||{};var isSecureDefault=isUrlSecure();var opts={port:getPort(options,isSecureDefault),hostname:global.location&&location.hostname,path:"/socketcluster/",secure:isSecureDefault};for(var i in options){if(options.hasOwnProperty(i)){opts[i]=options[i]}}var multiplexId=getMultiplexId(opts);delete _connections[multiplexId]}module.exports={connect:connect,destroy:destroy}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./scsocket":4}],6:[function(require,module,exports){var SCEmitter=require("sc-emitter").SCEmitter;var formatter=require("sc-formatter");var Response=require("./response").Response;var querystring=require("querystring");var WebSocket=require("sc-ws");var scErrors=require("sc-errors");var TimeoutError=scErrors.TimeoutError;var SCTransport=function(authEngine,options){this.state=this.CLOSED;this.auth=authEngine;this.options=options;this.connectTimeout=options.connectTimeout;this.pingTimeout=options.ackTimeout;this.callIdGenerator=options.callIdGenerator;this._pingTimeoutTicker=null;this._callbackMap={};this.open()};SCTransport.prototype=Object.create(SCEmitter.prototype);SCTransport.CONNECTING=SCTransport.prototype.CONNECTING="connecting";SCTransport.OPEN=SCTransport.prototype.OPEN="open";SCTransport.CLOSED=SCTransport.prototype.CLOSED="closed";SCTransport.prototype.uri=function(){var query=this.options.query||{};var schema=this.options.secure?"wss":"ws";var port="";if(this.options.port&&("wss"==schema&&this.options.port!=443||"ws"==schema&&this.options.port!=80)){port=":"+this.options.port}if(this.options.timestampRequests){query[this.options.timestampParam]=(new Date).getTime()}query=querystring.stringify(query);if(query.length){query="?"+query}return schema+"://"+this.options.hostname+port+this.options.path+query};SCTransport.prototype.open=function(){var self=this;this.state=this.CONNECTING;var uri=this.uri();var wsSocket=new WebSocket(uri,null,this.options);wsSocket.binaryType=this.options.binaryType;this.socket=wsSocket;wsSocket.onopen=function(){self._onOpen()};wsSocket.onclose=function(event){self._onClose(event.code,event.reason)};wsSocket.onmessage=function(message,flags){self._onMessage(message.data)};wsSocket.onerror=function(error){if(self.state===self.CONNECTING){self._onClose(1006)}};this._connectTimeoutRef=setTimeout(function(){self._onClose(4007);self.socket.close(4007)},this.connectTimeout)};SCTransport.prototype._onOpen=function(){var self=this;clearTimeout(this._connectTimeoutRef);this._resetPingTimeout();this._handshake(function(err,status){if(err){self._onError(err);self._onClose(4003);self.socket.close(4003)}else{self.state=self.OPEN;SCEmitter.prototype.emit.call(self,"open",status);self._resetPingTimeout()}})};SCTransport.prototype._handshake=function(callback){var self=this;this.auth.loadToken(this.options.authTokenName,function(err,token){if(err){callback(err)}else{var options={force:true};self.emit("#handshake",{authToken:token},options,function(err,status){if(status){status.authToken=token;if(status.authError){status.authError=scErrors.hydrateError(status.authError)}}callback(err,status)})}})};SCTransport.prototype._onClose=function(code,data){delete this.socket.onopen;delete this.socket.onclose;delete this.socket.onmessage;delete this.socket.onerror;clearTimeout(this._connectTimeoutRef);if(this.state==this.OPEN){this.state=this.CLOSED;SCEmitter.prototype.emit.call(this,"close",code,data)}else if(this.state==this.CONNECTING){this.state=this.CLOSED;SCEmitter.prototype.emit.call(this,"openAbort",code,data)}};SCTransport.prototype._onMessage=function(message){SCEmitter.prototype.emit.call(this,"event","message",message);if(message=="#1"){this._resetPingTimeout();if(this.socket.readyState==this.socket.OPEN){this.socket.send("#2")}}else{var obj;try{obj=this.parse(message)}catch(err){obj=message}var event=obj.event;if(event){var response=new Response(this,obj.cid);SCEmitter.prototype.emit.call(this,"event",event,obj.data,response)}else if(obj.rid!=null){var eventObject=this._callbackMap[obj.rid];if(eventObject){clearTimeout(eventObject.timeout);delete this._callbackMap[obj.rid];if(eventObject.callback){var rehydratedError=scErrors.hydrateError(obj.error);eventObject.callback(rehydratedError,obj.data)}}}else{SCEmitter.prototype.emit.call(this,"event","raw",obj)}}};SCTransport.prototype._onError=function(err){SCEmitter.prototype.emit.call(this,"error",err)};SCTransport.prototype._resetPingTimeout=function(){var self=this;var now=(new Date).getTime();clearTimeout(this._pingTimeoutTicker);this._pingTimeoutTicker=setTimeout(function(){self._onClose(4e3);self.socket.close(4e3)},this.pingTimeout)};SCTransport.prototype.getBytesReceived=function(){return this.socket.bytesReceived};SCTransport.prototype.close=function(code,data){code=code||1e3;if(this.state==this.OPEN){var packet={code:code,data:data};this.emit("#disconnect",packet);this._onClose(code,data);this.socket.close(code)}else if(this.state==this.CONNECTING){this._onClose(code,data);this.socket.close(code)}};SCTransport.prototype.emitRaw=function(eventObject){eventObject.cid=this.callIdGenerator();if(eventObject.callback){this._callbackMap[eventObject.cid]=eventObject}var simpleEventObject={event:eventObject.event,data:eventObject.data,cid:eventObject.cid};this.sendObject(simpleEventObject);return eventObject.cid};SCTransport.prototype._handleEventAckTimeout=function(eventObject){var errorMessage="Event response for '"+eventObject.event+"' timed out";var error=new TimeoutError(errorMessage);if(eventObject.cid){delete this._callbackMap[eventObject.cid]}var callback=eventObject.callback;delete eventObject.callback;callback.call(eventObject,error,eventObject)};SCTransport.prototype.emit=function(event,data,a,b){var self=this;var callback,options;if(b){options=a;callback=b}else{if(a instanceof Function){options={};callback=a}else{options=a}}var eventObject={event:event,data:data,callback:callback};if(callback&&!options.noTimeout){eventObject.timeout=setTimeout(function(){self._handleEventAckTimeout(eventObject)},this.options.ackTimeout)}var cid=null;if(this.state==this.OPEN||options.force){cid=this.emitRaw(eventObject)}return cid};SCTransport.prototype.cancelPendingResponse=function(cid){delete this._callbackMap[cid]; +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.socketCluster=f()}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;omaxTimeout){throw new InvalidArgumentsError("The "+propertyName+" value provided exceeded the maximum amount allowed")}};verifyDuration("connectTimeout");verifyDuration("ackTimeout");verifyDuration("pingTimeout");this._localEvents={connect:1,connectAbort:1,disconnect:1,message:1,error:1,raw:1,fail:1,kickOut:1,subscribe:1,unsubscribe:1,subscribeStateChange:1,authStateChange:1,authenticate:1,deauthenticate:1,removeAuthToken:1,subscribeRequest:1};this.connectAttempts=0;this._emitBuffer=new LinkedList;this._channels={};this.options=opts;this._cid=1;this.options.callIdGenerator=function(){return self._callIdGenerator()};if(this.options.autoReconnect){if(this.options.autoReconnectOptions==null){this.options.autoReconnectOptions={}}var reconnectOptions=this.options.autoReconnectOptions;if(reconnectOptions.initialDelay==null){reconnectOptions.initialDelay=1e4}if(reconnectOptions.randomness==null){reconnectOptions.randomness=1e4}if(reconnectOptions.multiplier==null){reconnectOptions.multiplier=1.5}if(reconnectOptions.maxDelay==null){reconnectOptions.maxDelay=6e4}}if(this.options.subscriptionRetryOptions==null){this.options.subscriptionRetryOptions={}}if(this.options.authEngine){this.auth=this.options.authEngine}else{this.auth=new AuthEngine}this.options.path=this.options.path.replace(/\/$/,"")+"/";this.options.query=opts.query||{};if(typeof this.options.query=="string"){this.options.query=querystring.parse(this.options.query)}this.connect();this._channelEmitter=new SCEmitter;if(isBrowser){var unloadHandler=function(){self.disconnect()};if(global.attachEvent){global.attachEvent("onunload",unloadHandler)}else if(global.addEventListener){global.addEventListener("beforeunload",unloadHandler,false)}}};SCSocket.prototype=Object.create(SCEmitter.prototype);SCSocket.CONNECTING=SCSocket.prototype.CONNECTING=SCTransport.prototype.CONNECTING;SCSocket.OPEN=SCSocket.prototype.OPEN=SCTransport.prototype.OPEN;SCSocket.CLOSED=SCSocket.prototype.CLOSED=SCTransport.prototype.CLOSED;SCSocket.AUTHENTICATED=SCSocket.prototype.AUTHENTICATED="authenticated";SCSocket.UNAUTHENTICATED=SCSocket.prototype.UNAUTHENTICATED="unauthenticated";SCSocket.PENDING=SCSocket.prototype.PENDING="pending";SCSocket.ignoreStatuses=scErrors.socketProtocolIgnoreStatuses;SCSocket.errorStatuses=scErrors.socketProtocolErrorStatuses;SCSocket.prototype._privateEventHandlerMap={"#publish":function(data){var undecoratedChannelName=this._undecorateChannelName(data.channel);var isSubscribed=this.isSubscribed(undecoratedChannelName,true);if(isSubscribed){this._channelEmitter.emit(undecoratedChannelName,data.data)}},"#kickOut":function(data){var undecoratedChannelName=this._undecorateChannelName(data.channel);var channel=this._channels[undecoratedChannelName];if(channel){SCEmitter.prototype.emit.call(this,"kickOut",data.message,undecoratedChannelName);channel.emit("kickOut",data.message,undecoratedChannelName);this._triggerChannelUnsubscribe(channel)}},"#setAuthToken":function(data,response){var self=this;if(data){var triggerAuthenticate=function(err){if(err){response.error(err);self._onSCError(err)}else{self._changeToAuthenticatedState(data.token);response.end()}};this.auth.saveToken(this.options.authTokenName,data.token,{},triggerAuthenticate)}else{response.error(new InvalidMessageError("No token data provided by #setAuthToken event"))}},"#removeAuthToken":function(data,response){var self=this;this.auth.removeToken(this.options.authTokenName,function(err,oldToken){if(err){response.error(err);self._onSCError(err)}else{SCEmitter.prototype.emit.call(self,"removeAuthToken",oldToken);self._changeToUnauthenticatedState();response.end()}})},"#disconnect":function(data){this.transport.close(data.code,data.data)}};SCSocket.prototype._callIdGenerator=function(){return this._cid++};SCSocket.prototype.getState=function(){return this.state};SCSocket.prototype.getBytesReceived=function(){return this.transport.getBytesReceived()};SCSocket.prototype.deauthenticate=function(callback){var self=this;this.auth.removeToken(this.options.authTokenName,function(err,oldToken){self.emit("#removeAuthToken");callback&&callback(err);if(err){self._onSCError(err)}else{SCEmitter.prototype.emit.call(self,"removeAuthToken",oldToken);self._changeToUnauthenticatedState()}})};SCSocket.prototype.connect=SCSocket.prototype.open=function(){var self=this;if(this.state==this.CLOSED){this.pendingReconnect=false;this.pendingReconnectTimeout=null;clearTimeout(this._reconnectTimeoutRef);this.state=this.CONNECTING;this._changeToPendingAuthState();if(this.transport){this.transport.off()}this.transport=new SCTransport(this.auth,this.options);this.transport.on("open",function(status){self.state=self.OPEN;self._onSCOpen(status)});this.transport.on("error",function(err){self._onSCError(err)});this.transport.on("close",function(code,data){self.state=self.CLOSED;self._onSCClose(code,data)});this.transport.on("openAbort",function(code,data){self.state=self.CLOSED;self._onSCClose(code,data,true)});this.transport.on("event",function(event,data,res){self._onSCEvent(event,data,res)})}};SCSocket.prototype.reconnect=function(){this.disconnect();this.connect()};SCSocket.prototype.disconnect=function(code,data){code=code||1e3;if(this.state==this.OPEN){var packet={code:code,data:data};this.transport.emit("#disconnect",packet);this.transport.close(code,data)}else if(this.state==this.CONNECTING){this.transport.close(code,data)}else{this.pendingReconnect=false;this.pendingReconnectTimeout=null;clearTimeout(this._reconnectTimeoutRef)}};SCSocket.prototype._changeToPendingAuthState=function(){if(this.authState!=this.PENDING){var oldState=this.authState;this.authState=this.PENDING;var stateChangeData={oldState:oldState,newState:this.authState};SCEmitter.prototype.emit.call(this,"authStateChange",stateChangeData)}};SCSocket.prototype._changeToUnauthenticatedState=function(){if(this.authState!=this.UNAUTHENTICATED){var oldState=this.authState;this.authState=this.UNAUTHENTICATED;this.signedAuthToken=null;this.authToken=null;var stateChangeData={oldState:oldState,newState:this.authState};SCEmitter.prototype.emit.call(this,"authStateChange",stateChangeData);if(oldState==this.AUTHENTICATED){SCEmitter.prototype.emit.call(this,"deauthenticate")}}};SCSocket.prototype._changeToAuthenticatedState=function(signedAuthToken){if(this.authState!=this.AUTHENTICATED){var oldState=this.authState;this.authState=this.AUTHENTICATED;this.signedAuthToken=signedAuthToken;this.authToken=this._extractAuthTokenData(signedAuthToken);var stateChangeData={oldState:oldState,newState:this.authState,signedAuthToken:signedAuthToken,authToken:this.authToken};this.processPendingSubscriptions();SCEmitter.prototype.emit.call(this,"authStateChange",stateChangeData);SCEmitter.prototype.emit.call(this,"authenticate",signedAuthToken)}};SCSocket.prototype.decodeBase64=function(encodedString){var decodedString;if(typeof Buffer=="undefined"){if(global.atob){decodedString=global.atob(encodedString)}else{decodedString=base64.decode(encodedString)}}else{var buffer=new Buffer(encodedString,"base64");decodedString=buffer.toString("utf8")}return decodedString};SCSocket.prototype.encodeBase64=function(decodedString){var encodedString;if(typeof Buffer=="undefined"){if(global.btoa){encodedString=global.btoa(decodedString)}else{encodedString=base64.encode(decodedString)}}else{var buffer=new Buffer(decodedString,"utf8");encodedString=buffer.toString("base64")}return encodedString};SCSocket.prototype._extractAuthTokenData=function(signedAuthToken){var tokenParts=(signedAuthToken||"").split(".");var encodedTokenData=tokenParts[1];if(encodedTokenData!=null){var tokenData=encodedTokenData;try{tokenData=this.decodeBase64(tokenData);return JSON.parse(tokenData)}catch(e){return tokenData}}return null};SCSocket.prototype.getAuthToken=function(){return this.authToken};SCSocket.prototype.getSignedAuthToken=function(){return this.signedAuthToken};SCSocket.prototype.authenticate=function(signedAuthToken,callback){var self=this;this._changeToPendingAuthState();this.emit("#authenticate",signedAuthToken,function(err,authStatus){if(authStatus&&authStatus.authError){authStatus.authError=scErrors.hydrateError(authStatus.authError)}if(err){self._changeToUnauthenticatedState();callback&&callback(err,authStatus)}else{self.auth.saveToken(self.options.authTokenName,signedAuthToken,{},function(err){callback&&callback(err,authStatus);if(err){self._changeToUnauthenticatedState();self._onSCError(err)}else{if(authStatus.isAuthenticated){self._changeToAuthenticatedState(signedAuthToken)}else{self._changeToUnauthenticatedState()}}})}})};SCSocket.prototype._tryReconnect=function(initialDelay){var self=this;var exponent=this.connectAttempts++;var reconnectOptions=this.options.autoReconnectOptions;var timeout;if(initialDelay==null||exponent>0){var initialTimeout=Math.round(reconnectOptions.initialDelay+(reconnectOptions.randomness||0)*Math.random());timeout=Math.round(initialTimeout*Math.pow(reconnectOptions.multiplier,exponent))}else{timeout=initialDelay}if(timeout>reconnectOptions.maxDelay){timeout=reconnectOptions.maxDelay}clearTimeout(this._reconnectTimeoutRef);this.pendingReconnect=true;this.pendingReconnectTimeout=timeout;this._reconnectTimeoutRef=setTimeout(function(){self.connect()},timeout)};SCSocket.prototype._onSCOpen=function(status){var self=this;if(status){this.id=status.id;this.pingTimeout=status.pingTimeout;this.transport.pingTimeout=this.pingTimeout;if(status.isAuthenticated){this._changeToAuthenticatedState(status.authToken)}else{this._changeToUnauthenticatedState()}}else{this._changeToUnauthenticatedState()}this.connectAttempts=0;if(this.options.autoProcessSubscriptions){this.processPendingSubscriptions()}else{this.pendingConnectCallback=true}SCEmitter.prototype.emit.call(this,"connect",status,function(){self.processPendingSubscriptions()});this._flushEmitBuffer()};SCSocket.prototype._onSCError=function(err){var self=this;setTimeout(function(){if(self.listeners("error").length<1){throw err}else{SCEmitter.prototype.emit.call(self,"error",err)}},0)};SCSocket.prototype._suspendSubscriptions=function(){var channel,newState;for(var channelName in this._channels){if(this._channels.hasOwnProperty(channelName)){channel=this._channels[channelName];if(channel.state==channel.SUBSCRIBED||channel.state==channel.PENDING){newState=channel.PENDING}else{newState=channel.UNSUBSCRIBED}this._triggerChannelUnsubscribe(channel,newState)}}};SCSocket.prototype._onSCClose=function(code,data,openAbort){var self=this;this.id=null;if(this.transport){this.transport.off()}this.pendingReconnect=false;this.pendingReconnectTimeout=null;clearTimeout(this._reconnectTimeoutRef);this._changeToPendingAuthState();this._suspendSubscriptions();if(this.options.autoReconnect){if(code==4e3||code==4001||code==1005){this._tryReconnect(0)}else if(code!=1e3&&code<4500){this._tryReconnect()}}if(openAbort){SCEmitter.prototype.emit.call(self,"connectAbort",code,data)}else{SCEmitter.prototype.emit.call(self,"disconnect",code,data)}if(!SCSocket.ignoreStatuses[code]){var failureMessage;if(data){failureMessage="Socket connection failed: "+data}else{failureMessage="Socket connection failed for unknown reasons"}var err=new SocketProtocolError(SCSocket.errorStatuses[code]||failureMessage,code);this._onSCError(err)}};SCSocket.prototype._onSCEvent=function(event,data,res){var handler=this._privateEventHandlerMap[event];if(handler){handler.call(this,data,res)}else{SCEmitter.prototype.emit.call(this,event,data,function(){res&&res.callback.apply(res,arguments)})}};SCSocket.prototype.parse=function(message){return this.transport.parse(message)};SCSocket.prototype.stringify=function(object){return this.transport.stringify(object)};SCSocket.prototype._flushEmitBuffer=function(){var currentNode=this._emitBuffer.head;var nextNode;while(currentNode){nextNode=currentNode.next;var eventObject=currentNode.data;currentNode.detach();this.transport.emitRaw(eventObject);currentNode=nextNode}};SCSocket.prototype._handleEventAckTimeout=function(eventObject,eventNode){if(eventNode){eventNode.detach()}var error=new TimeoutError("Event response for '"+eventObject.event+"' timed out");var callback=eventObject.callback;if(callback){delete eventObject.callback;callback.call(eventObject,error,eventObject)}};SCSocket.prototype._emit=function(event,data,callback){var self=this;if(this.state==this.CLOSED){this.connect()}var eventObject={event:event,data:data,callback:callback};var eventNode=new LinkedList.Item;eventNode.data=eventObject;eventObject.timeout=setTimeout(function(){self._handleEventAckTimeout(eventObject,eventNode)},this.ackTimeout);this._emitBuffer.append(eventNode);if(this.state==this.OPEN){this._flushEmitBuffer()}};SCSocket.prototype.send=function(data){this.transport.send(data)};SCSocket.prototype.emit=function(event,data,callback){if(this._localEvents[event]==null){this._emit(event,data,callback)}else{SCEmitter.prototype.emit.call(this,event,data)}};SCSocket.prototype.publish=function(channelName,data,callback){var pubData={channel:this._decorateChannelName(channelName),data:data};this.emit("#publish",pubData,callback)};SCSocket.prototype._triggerChannelSubscribe=function(channel,subscriptionOptions){var channelName=channel.name;if(channel.state!=channel.SUBSCRIBED){var oldState=channel.state;channel.state=channel.SUBSCRIBED;var stateChangeData={channel:channelName,oldState:oldState,newState:channel.state,subscriptionOptions:subscriptionOptions};channel.emit("subscribeStateChange",stateChangeData);channel.emit("subscribe",channelName,subscriptionOptions);SCEmitter.prototype.emit.call(this,"subscribeStateChange",stateChangeData);SCEmitter.prototype.emit.call(this,"subscribe",channelName,subscriptionOptions)}};SCSocket.prototype._triggerChannelSubscribeFail=function(err,channel,subscriptionOptions){var channelName=channel.name;var meetsAuthRequirements=!channel.waitForAuth||this.authState==this.AUTHENTICATED;if(channel.state!=channel.UNSUBSCRIBED&&meetsAuthRequirements){channel.state=channel.UNSUBSCRIBED;channel.emit("subscribeFail",err,channelName,subscriptionOptions);SCEmitter.prototype.emit.call(this,"subscribeFail",err,channelName,subscriptionOptions)}};SCSocket.prototype._cancelPendingSubscribeCallback=function(channel){if(channel._pendingSubscriptionCid!=null){this.transport.cancelPendingResponse(channel._pendingSubscriptionCid);delete channel._pendingSubscriptionCid}};SCSocket.prototype._decorateChannelName=function(channelName){if(this.channelPrefix){channelName=this.channelPrefix+channelName}return channelName};SCSocket.prototype._undecorateChannelName=function(decoratedChannelName){if(this.channelPrefix&&decoratedChannelName.indexOf(this.channelPrefix)==0){return decoratedChannelName.replace(this.channelPrefix,"")}return decoratedChannelName};SCSocket.prototype._trySubscribe=function(channel){var self=this;var meetsAuthRequirements=!channel.waitForAuth||this.authState==this.AUTHENTICATED;if(this.state==this.OPEN&&!this.pendingConnectCallback&&channel._pendingSubscriptionCid==null&&meetsAuthRequirements){var options={noTimeout:true};var subscriptionOptions={channel:this._decorateChannelName(channel.name)};if(channel.waitForAuth){options.waitForAuth=true;subscriptionOptions.waitForAuth=options.waitForAuth}if(channel.data){subscriptionOptions.data=channel.data}channel._pendingSubscriptionCid=this.transport.emit("#subscribe",subscriptionOptions,options,function(err){delete channel._pendingSubscriptionCid;if(err){self._triggerChannelSubscribeFail(err,channel,subscriptionOptions)}else{self._triggerChannelSubscribe(channel,subscriptionOptions)}});SCEmitter.prototype.emit.call(this,"subscribeRequest",channel.name,subscriptionOptions)}};SCSocket.prototype.subscribe=function(channelName,options){var channel=this._channels[channelName];if(!channel){channel=new SCChannel(channelName,this,options);this._channels[channelName]=channel}else if(options){channel.setOptions(options)}if(channel.state==channel.UNSUBSCRIBED){channel.state=channel.PENDING;this._trySubscribe(channel)}return channel};SCSocket.prototype._triggerChannelUnsubscribe=function(channel,newState){var channelName=channel.name;var oldState=channel.state;if(newState){channel.state=newState}else{channel.state=channel.UNSUBSCRIBED}this._cancelPendingSubscribeCallback(channel);if(oldState==channel.SUBSCRIBED){var stateChangeData={channel:channelName,oldState:oldState,newState:channel.state};channel.emit("subscribeStateChange",stateChangeData);channel.emit("unsubscribe",channelName);SCEmitter.prototype.emit.call(this,"subscribeStateChange",stateChangeData);SCEmitter.prototype.emit.call(this,"unsubscribe",channelName)}};SCSocket.prototype._tryUnsubscribe=function(channel){var self=this;if(this.state==this.OPEN){var options={noTimeout:true};this._cancelPendingSubscribeCallback(channel);var decoratedChannelName=this._decorateChannelName(channel.name);this.transport.emit("#unsubscribe",decoratedChannelName,options)}};SCSocket.prototype.unsubscribe=function(channelName){var channel=this._channels[channelName];if(channel){if(channel.state!=channel.UNSUBSCRIBED){this._triggerChannelUnsubscribe(channel);this._tryUnsubscribe(channel)}}};SCSocket.prototype.channel=function(channelName,options){var currentChannel=this._channels[channelName];if(!currentChannel){currentChannel=new SCChannel(channelName,this,options);this._channels[channelName]=currentChannel}return currentChannel};SCSocket.prototype.destroyChannel=function(channelName){var channel=this._channels[channelName];channel.unwatch();channel.unsubscribe();delete this._channels[channelName]};SCSocket.prototype.subscriptions=function(includePending){var subs=[];var channel,includeChannel;for(var channelName in this._channels){if(this._channels.hasOwnProperty(channelName)){channel=this._channels[channelName];if(includePending){includeChannel=channel&&(channel.state==channel.SUBSCRIBED||channel.state==channel.PENDING)}else{includeChannel=channel&&channel.state==channel.SUBSCRIBED}if(includeChannel){subs.push(channelName)}}}return subs};SCSocket.prototype.isSubscribed=function(channelName,includePending){var channel=this._channels[channelName];if(includePending){return!!channel&&(channel.state==channel.SUBSCRIBED||channel.state==channel.PENDING)}return!!channel&&channel.state==channel.SUBSCRIBED};SCSocket.prototype.processPendingSubscriptions=function(){var self=this;this.pendingConnectCallback=false;for(var i in this._channels){if(this._channels.hasOwnProperty(i)){(function(channel){if(channel.state==channel.PENDING){self._trySubscribe(channel)}})(this._channels[i])}}};SCSocket.prototype.watch=function(channelName,handler){if(typeof handler!="function"){throw new InvalidArgumentsError("No handler function was provided")}this._channelEmitter.on(channelName,handler)};SCSocket.prototype.unwatch=function(channelName,handler){if(handler){this._channelEmitter.removeListener(channelName,handler)}else{this._channelEmitter.removeAllListeners(channelName)}};SCSocket.prototype.watchers=function(channelName){return this._channelEmitter.listeners(channelName)};module.exports=SCSocket}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer)},{"./auth":2,"./response":3,"./sctransport":6,"base-64":7,buffer:19,"linked-list":10,querystring:24,"sc-channel":11,"sc-emitter":12,"sc-errors":14}],5:[function(require,module,exports){(function(global){var SCSocket=require("./scsocket");var _connections={};function getMultiplexId(options){var protocolPrefix=options.secure?"https://":"http://";var queryString="";if(options.query){if(typeof options.query=="string"){queryString=options.query}else{var queryArray=[];var queryMap=options.query;for(var key in queryMap){if(queryMap.hasOwnProperty(key)){queryArray.push(key+"="+queryMap[key])}}if(queryArray.length){queryString="?"+queryArray.join("&")}}}return protocolPrefix+options.hostname+":"+options.port+options.path+queryString}function isUrlSecure(){return global.location&&location.protocol=="https:"}function getPort(options,isSecureDefault){var isSecure=options.secure==null?isSecureDefault:options.secure;return options.port||(global.location&&location.port?location.port:isSecure?443:80)}function connect(options){var self=this;options=options||{};var isSecureDefault=isUrlSecure();var opts={port:getPort(options,isSecureDefault),hostname:global.location&&location.hostname,path:"/socketcluster/",secure:isSecureDefault,autoReconnect:true,autoProcessSubscriptions:true,connectTimeout:2e4,ackTimeout:1e4,timestampRequests:false,timestampParam:"t",authEngine:null,authTokenName:"socketCluster.authToken",binaryType:"arraybuffer",multiplex:true};for(var i in options){if(options.hasOwnProperty(i)){opts[i]=options[i]}}var multiplexId=getMultiplexId(opts);if(opts.multiplex===false){return new SCSocket(opts)}if(_connections[multiplexId]){_connections[multiplexId].connect()}else{_connections[multiplexId]=new SCSocket(opts)}return _connections[multiplexId]}function destroy(options){var self=this;options=options||{};var isSecureDefault=isUrlSecure();var opts={port:getPort(options,isSecureDefault),hostname:global.location&&location.hostname,path:"/socketcluster/",secure:isSecureDefault};for(var i in options){if(options.hasOwnProperty(i)){opts[i]=options[i]}}var multiplexId=getMultiplexId(opts);delete _connections[multiplexId]}module.exports={connect:connect,destroy:destroy}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./scsocket":4}],6:[function(require,module,exports){var SCEmitter=require("sc-emitter").SCEmitter;var formatter=require("sc-formatter");var Response=require("./response").Response;var querystring=require("querystring");var WebSocket=require("sc-ws");var scErrors=require("sc-errors");var TimeoutError=scErrors.TimeoutError;var SCTransport=function(authEngine,options){this.state=this.CLOSED;this.auth=authEngine;this.options=options;this.connectTimeout=options.connectTimeout;this.pingTimeout=options.ackTimeout;this.callIdGenerator=options.callIdGenerator;this._pingTimeoutTicker=null;this._callbackMap={};this.open()};SCTransport.prototype=Object.create(SCEmitter.prototype);SCTransport.CONNECTING=SCTransport.prototype.CONNECTING="connecting";SCTransport.OPEN=SCTransport.prototype.OPEN="open";SCTransport.CLOSED=SCTransport.prototype.CLOSED="closed";SCTransport.prototype.uri=function(){var query=this.options.query||{};var schema=this.options.secure?"wss":"ws";var port="";if(this.options.port&&("wss"==schema&&this.options.port!=443||"ws"==schema&&this.options.port!=80)){port=":"+this.options.port}if(this.options.timestampRequests){query[this.options.timestampParam]=(new Date).getTime()}query=querystring.stringify(query);if(query.length){query="?"+query}return schema+"://"+this.options.hostname+port+this.options.path+query};SCTransport.prototype.open=function(){var self=this;this.state=this.CONNECTING;var uri=this.uri();var wsSocket=new WebSocket(uri,null,this.options);wsSocket.binaryType=this.options.binaryType;this.socket=wsSocket;wsSocket.onopen=function(){self._onOpen()};wsSocket.onclose=function(event){self._onClose(event.code,event.reason)};wsSocket.onmessage=function(message,flags){self._onMessage(message.data)};wsSocket.onerror=function(error){if(self.state===self.CONNECTING){self._onClose(1006)}};this._connectTimeoutRef=setTimeout(function(){self._onClose(4007);self.socket.close(4007)},this.connectTimeout)};SCTransport.prototype._onOpen=function(){var self=this;clearTimeout(this._connectTimeoutRef);this._resetPingTimeout();this._handshake(function(err,status){if(err){self._onError(err);self._onClose(4003);self.socket.close(4003)}else{self.state=self.OPEN;SCEmitter.prototype.emit.call(self,"open",status);self._resetPingTimeout()}})};SCTransport.prototype._handshake=function(callback){var self=this;this.auth.loadToken(this.options.authTokenName,function(err,token){if(err){callback(err)}else{var options={force:true};self.emit("#handshake",{authToken:token},options,function(err,status){if(status){status.authToken=token;if(status.authError){status.authError=scErrors.hydrateError(status.authError)}}callback(err,status)})}})};SCTransport.prototype._onClose=function(code,data){delete this.socket.onopen;delete this.socket.onclose;delete this.socket.onmessage;delete this.socket.onerror;clearTimeout(this._connectTimeoutRef);if(this.state==this.OPEN){this.state=this.CLOSED;SCEmitter.prototype.emit.call(this,"close",code,data)}else if(this.state==this.CONNECTING){this.state=this.CLOSED;SCEmitter.prototype.emit.call(this,"openAbort",code,data)}};SCTransport.prototype._onMessage=function(message){SCEmitter.prototype.emit.call(this,"event","message",message);if(message=="#1"){this._resetPingTimeout();if(this.socket.readyState==this.socket.OPEN){this.socket.send("#2")}}else{var obj;try{obj=this.parse(message)}catch(err){obj=message}var event=obj.event;if(event){var response=new Response(this,obj.cid);SCEmitter.prototype.emit.call(this,"event",event,obj.data,response)}else if(obj.rid!=null){var eventObject=this._callbackMap[obj.rid];if(eventObject){clearTimeout(eventObject.timeout);delete this._callbackMap[obj.rid];if(eventObject.callback){var rehydratedError=scErrors.hydrateError(obj.error);eventObject.callback(rehydratedError,obj.data)}}}else{SCEmitter.prototype.emit.call(this,"event","raw",obj)}}};SCTransport.prototype._onError=function(err){SCEmitter.prototype.emit.call(this,"error",err)};SCTransport.prototype._resetPingTimeout=function(){var self=this;var now=(new Date).getTime();clearTimeout(this._pingTimeoutTicker);this._pingTimeoutTicker=setTimeout(function(){self._onClose(4e3);self.socket.close(4e3)},this.pingTimeout)};SCTransport.prototype.getBytesReceived=function(){return this.socket.bytesReceived};SCTransport.prototype.close=function(code,data){code=code||1e3;if(this.state==this.OPEN){var packet={code:code,data:data};this.emit("#disconnect",packet);this._onClose(code,data);this.socket.close(code)}else if(this.state==this.CONNECTING){this._onClose(code,data);this.socket.close(code)}};SCTransport.prototype.emitRaw=function(eventObject){eventObject.cid=this.callIdGenerator();if(eventObject.callback){this._callbackMap[eventObject.cid]=eventObject}var simpleEventObject={event:eventObject.event,data:eventObject.data,cid:eventObject.cid};this.sendObject(simpleEventObject);return eventObject.cid};SCTransport.prototype._handleEventAckTimeout=function(eventObject){var errorMessage="Event response for '"+eventObject.event+"' timed out";var error=new TimeoutError(errorMessage);if(eventObject.cid){delete this._callbackMap[eventObject.cid]}var callback=eventObject.callback;delete eventObject.callback;callback.call(eventObject,error,eventObject)};SCTransport.prototype.emit=function(event,data,a,b){var self=this;var callback,options;if(b){options=a;callback=b}else{if(a instanceof Function){options={};callback=a}else{options=a}}var eventObject={event:event,data:data,callback:callback};if(callback&&!options.noTimeout){eventObject.timeout=setTimeout(function(){self._handleEventAckTimeout(eventObject)},this.options.ackTimeout)}var cid=null;if(this.state==this.OPEN||options.force){cid=this.emitRaw(eventObject)}return cid};SCTransport.prototype.cancelPendingResponse=function(cid){delete this._callbackMap[cid]; };SCTransport.prototype.parse=function(message){return formatter.parse(message)};SCTransport.prototype.stringify=function(object){return formatter.stringify(object)};SCTransport.prototype.send=function(data){if(this.socket.readyState!=this.socket.OPEN){this._onClose(1005)}else{this.socket.send(data)}};SCTransport.prototype.sendObject=function(object){var str,formatError;try{str=this.stringify(object)}catch(err){formatError=err;this._onError(formatError)}if(!formatError){this.send(str)}};module.exports.SCTransport=SCTransport},{"./response":3,querystring:24,"sc-emitter":12,"sc-errors":14,"sc-formatter":16,"sc-ws":17}],7:[function(require,module,exports){(function(global){(function(root){var freeExports=typeof exports=="object"&&exports;var freeModule=typeof module=="object"&&module&&module.exports==freeExports&&module;var freeGlobal=typeof global=="object"&&global;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal){root=freeGlobal}var InvalidCharacterError=function(message){this.message=message};InvalidCharacterError.prototype=new Error;InvalidCharacterError.prototype.name="InvalidCharacterError";var error=function(message){throw new InvalidCharacterError(message)};var TABLE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var REGEX_SPACE_CHARACTERS=/[\t\n\f\r ]/g;var decode=function(input){input=String(input).replace(REGEX_SPACE_CHARACTERS,"");var length=input.length;if(length%4==0){input=input.replace(/==?$/,"");length=input.length}if(length%4==1||/[^+a-zA-Z0-9\/]/.test(input)){error("Invalid character: the string to be decoded is not correctly encoded.")}var bitCounter=0;var bitStorage;var buffer;var output="";var position=-1;while(++position>(-2*bitCounter&6))}}return output};var encode=function(input){input=String(input);if(/[^\0-\xFF]/.test(input)){error("The string to be encoded contains characters outside of the "+"Latin1 range.")}var padding=input.length%3;var output="";var position=-1;var a;var b;var c;var d;var buffer;var length=input.length-padding;while(++position>18&63)+TABLE.charAt(buffer>>12&63)+TABLE.charAt(buffer>>6&63)+TABLE.charAt(buffer&63)}if(padding==2){a=input.charCodeAt(position)<<8;b=input.charCodeAt(++position);buffer=a+b;output+=TABLE.charAt(buffer>>10)+TABLE.charAt(buffer>>4&63)+TABLE.charAt(buffer<<2&63)+"="}else if(padding==1){buffer=input.charCodeAt(position);output+=TABLE.charAt(buffer>>2)+TABLE.charAt(buffer<<4&63)+"=="}return output};var base64={encode:encode,decode:decode,version:"0.1.0"};if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return base64})}else if(freeExports&&!freeExports.nodeType){if(freeModule){freeModule.exports=base64}else{for(var key in base64){base64.hasOwnProperty(key)&&(freeExports[key]=base64[key])}}}else{root.base64=base64}})(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],8:[function(require,module,exports){module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks["$"+event]=this._callbacks["$"+event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){function on(){this.off(event,on);fn.apply(this,arguments)}on.fn=fn;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks["$"+event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks["$"+event];return this}var cb;for(var i=0;i>2];base64+=base64Chars[(bytes[i]&3)<<4|bytes[i+1]>>4];base64+=base64Chars[(bytes[i+1]&15)<<2|bytes[i+2]>>6];base64+=base64Chars[bytes[i+2]&63]}if(len%3===2){base64=base64.substring(0,base64.length-1)+"="}else if(len%3===1){base64=base64.substring(0,base64.length-2)+"=="}return base64};var isOwnDescendant=function(object,ancestors){return ancestors.indexOf(object)>-1};var convertBuffersToBase64=function(object,ancestors){if(!ancestors){ancestors=[]}if(isOwnDescendant(object,ancestors)){throw new Error("Cannot traverse circular structure")}var newAncestors=ancestors.concat([object]);if(global.ArrayBuffer&&object instanceof global.ArrayBuffer){object={base64:true,data:arrayBufferToBase64(object)}}else if(global.Buffer&&object instanceof global.Buffer){object={base64:true,data:object.toString("base64")}}else if(object instanceof Array){for(var i in object){if(object.hasOwnProperty(i)){object[i]=convertBuffersToBase64(object[i],newAncestors)}}}else if(object instanceof Object){for(var j in object){if(object.hasOwnProperty(j)){object[j]=convertBuffersToBase64(object[j],newAncestors)}}}return object};module.exports.stringify=function(object){var base64Object=convertBuffersToBase64(object);return JSON.stringify(base64Object)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],17:[function(require,module,exports){var global=typeof window!="undefined"&&window||function(){return this}();var WebSocket=global.WebSocket||global.MozWebSocket;module.exports=WebSocket?ws:null;function ws(uri,protocols,opts){var instance;if(protocols){instance=new WebSocket(uri,protocols)}else{instance=new WebSocket(uri)}return instance}if(WebSocket)ws.prototype=WebSocket.prototype},{}],18:[function(require,module,exports){(function(exports){"use strict";var lookup="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var PLUS="+".charCodeAt(0);var SLASH="/".charCodeAt(0);var NUMBER="0".charCodeAt(0);var LOWER="a".charCodeAt(0);var UPPER="A".charCodeAt(0);var PLUS_URL_SAFE="-".charCodeAt(0);var SLASH_URL_SAFE="_".charCodeAt(0);function decode(elt){var code=elt.charCodeAt(0);if(code===PLUS||code===PLUS_URL_SAFE)return 62;if(code===SLASH||code===SLASH_URL_SAFE)return 63;if(code0){throw new Error("Invalid string. Length must be a multiple of 4")}var len=b64.length;placeHolders=b64.charAt(len-2)==="="?2:b64.charAt(len-1)==="="?1:0;arr=new Arr(b64.length*3/4-placeHolders);l=placeHolders>0?b64.length-4:b64.length;var L=0;function push(v){arr[L++]=v}for(i=0,j=0;i>16);push((tmp&65280)>>8);push(tmp&255)}if(placeHolders===2){tmp=decode(b64.charAt(i))<<2|decode(b64.charAt(i+1))>>4;push(tmp&255)}else if(placeHolders===1){tmp=decode(b64.charAt(i))<<10|decode(b64.charAt(i+1))<<4|decode(b64.charAt(i+2))>>2;push(tmp>>8&255);push(tmp&255)}return arr}function uint8ToBase64(uint8){var i;var extraBytes=uint8.length%3;var output="";var temp,length;function encode(num){return lookup.charAt(num)}function tripletToBase64(num){return encode(num>>18&63)+encode(num>>12&63)+encode(num>>6&63)+encode(num&63)}for(i=0,length=uint8.length-extraBytes;i>2);output+=encode(temp<<4&63);output+="==";break;case 2:temp=(uint8[uint8.length-2]<<8)+uint8[uint8.length-1];output+=encode(temp>>10);output+=encode(temp>>4&63);output+=encode(temp<<2&63);output+="=";break;default:break}return output}exports.toByteArray=b64ToByteArray;exports.fromByteArray=uint8ToBase64})(typeof exports==="undefined"?this.base64js={}:exports)},{}],19:[function(require,module,exports){(function(global){"use strict";var base64=require("base64-js");var ieee754=require("ieee754");var isArray=require("isarray");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;Buffer.poolSize=8192;var rootParent={};Buffer.TYPED_ARRAY_SUPPORT=global.TYPED_ARRAY_SUPPORT!==undefined?global.TYPED_ARRAY_SUPPORT:typedArraySupport();function typedArraySupport(){try{var arr=new Uint8Array(1);arr.foo=function(){return 42};return arr.foo()===42&&typeof arr.subarray==="function"&&arr.subarray(1,1).byteLength===0}catch(e){return false}}function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function Buffer(arg){if(!(this instanceof Buffer)){if(arguments.length>1)return new Buffer(arg,arguments[1]);return new Buffer(arg)}if(!Buffer.TYPED_ARRAY_SUPPORT){this.length=0;this.parent=undefined}if(typeof arg==="number"){return fromNumber(this,arg)}if(typeof arg==="string"){return fromString(this,arg,arguments.length>1?arguments[1]:"utf8")}return fromObject(this,arg)}function fromNumber(that,length){that=allocate(that,length<0?0:checked(length)|0);if(!Buffer.TYPED_ARRAY_SUPPORT){for(var i=0;i>>1;if(fromPool)that.parent=rootParent;return that}function checked(length){if(length>=kMaxLength()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength().toString(16)+" bytes")}return length|0}function SlowBuffer(subject,encoding){if(!(this instanceof SlowBuffer))return new SlowBuffer(subject,encoding);var buf=new Buffer(subject,encoding);delete buf.parent;return buf}Buffer.isBuffer=function isBuffer(b){return!!(b!=null&&b._isBuffer)};Buffer.compare=function compare(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError("Arguments must be Buffers")}if(a===b)return 0;var x=a.length;var y=b.length;var i=0;var len=Math.min(x,y);while(i>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;start=start|0;end=end===undefined||end===Infinity?this.length:end|0;if(!encoding)encoding="utf8";if(start<0)start=0;if(end>this.length)end=this.length;if(end<=start)return"";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"binary":return binarySlice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer.prototype._isBuffer=true;Buffer.prototype.toString=function toString(){var length=this.length|0;if(length===0)return"";if(arguments.length===0)return utf8Slice(this,0,length);return slowToString.apply(this,arguments)};Buffer.prototype.equals=function equals(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");if(this===b)return true;return Buffer.compare(this,b)===0};Buffer.prototype.inspect=function inspect(){var str="";var max=exports.INSPECT_MAX_BYTES;if(this.length>0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return""};Buffer.prototype.compare=function compare(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");if(this===b)return 0;return Buffer.compare(this,b)};Buffer.prototype.indexOf=function indexOf(val,byteOffset){if(byteOffset>2147483647)byteOffset=2147483647;else if(byteOffset<-2147483648)byteOffset=-2147483648;byteOffset>>=0;if(this.length===0)return-1;if(byteOffset>=this.length)return-1;if(byteOffset<0)byteOffset=Math.max(this.length+byteOffset,0);if(typeof val==="string"){if(val.length===0)return-1;return String.prototype.indexOf.call(this,val,byteOffset)}if(Buffer.isBuffer(val)){return arrayIndexOf(this,val,byteOffset)}if(typeof val==="number"){if(Buffer.TYPED_ARRAY_SUPPORT&&Uint8Array.prototype.indexOf==="function"){return Uint8Array.prototype.indexOf.call(this,val,byteOffset)}return arrayIndexOf(this,[val],byteOffset)}function arrayIndexOf(arr,val,byteOffset){var foundIndex=-1;for(var i=0;byteOffset+iremaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new Error("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;iremaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length); case"ascii":return asciiWrite(this,string,offset,length);case"binary":return binaryWrite(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(ilen)end=len;var out="";for(var i=start;ilen){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(endlength)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i0&&(mul*=256)){val+=this[offset+--byteLength]*mul}return val};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError("buffer must be a Buffer instance");if(value>max||valuebuf.length)throw new RangeError("index out of range")}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength),0);var mul=1;var i=0;this[offset]=value&255;while(++i=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,255,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value&255;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0;var mul=1;var sub=value<0?1:0;this[offset]=value&255;while(++i>0)-sub&255}return offset+byteLength};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1;var mul=1;var sub=value<0?1:0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(value>max||valuebuf.length)throw new RangeError("index out of range");if(offset<0)throw new RangeError("index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart=0;i--){target[i+targetStart]=this[i+start]}}else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){for(i=0;i=this.length)throw new RangeError("start out of bounds");if(end<0||end>this.length)throw new RangeError("end out of bounds");var i;if(typeof value==="number"){for(i=start;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"base64-js":18,ieee754:21,isarray:20}],20:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return toString.call(arr)=="[object Array]"}},{}],21:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},{}],22:[function(require,module,exports){"use strict";function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}module.exports=function(qs,sep,eq,options){sep=sep||"&";eq=eq||"=";var obj={};if(typeof qs!=="string"||qs.length===0){return obj}var regexp=/\+/g;qs=qs.split(sep);var maxKeys=1e3;if(options&&typeof options.maxKeys==="number"){maxKeys=options.maxKeys}var len=qs.length;if(maxKeys>0&&len>maxKeys){len=maxKeys}for(var i=0;i=0){kstr=x.substr(0,idx);vstr=x.substr(idx+1)}else{kstr=x;vstr=""}k=decodeURIComponent(kstr);v=decodeURIComponent(vstr);if(!hasOwnProperty(obj,k)){obj[k]=v}else if(isArray(obj[k])){obj[k].push(v)}else{obj[k]=[obj[k],v]}}return obj};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==="[object Array]"}},{}],23:[function(require,module,exports){"use strict";var stringifyPrimitive=function(v){switch(typeof v){case"string":return v;case"boolean":return v?"true":"false";case"number":return isFinite(v)?v:"";default:return""}};module.exports=function(obj,sep,eq,name){sep=sep||"&";eq=eq||"=";if(obj===null){obj=undefined}if(typeof obj==="object"){return map(objectKeys(obj),function(k){var ks=encodeURIComponent(stringifyPrimitive(k))+eq;if(isArray(obj[k])){return map(obj[k],function(v){return ks+encodeURIComponent(stringifyPrimitive(v))}).join(sep)}else{return ks+encodeURIComponent(stringifyPrimitive(obj[k]))}}).join(sep)}if(!name)return"";return encodeURIComponent(stringifyPrimitive(name))+eq+encodeURIComponent(stringifyPrimitive(obj))};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==="[object Array]"};function map(xs,f){if(xs.map)return xs.map(f);var res=[];for(var i=0;i