Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

socketcluster-client

Package Overview
Dependencies
Maintainers
1
Versions
236
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

socketcluster-client - npm Package Compare versions

Comparing version 2.2.9 to 2.2.11

2

index.js
var SCSocket = require('./lib/scsocket');
module.exports.SCSocket = SCSocket;
module.exports.Emitter = require('emitter');
module.exports.Emitter = require('component-emitter');

@@ -6,0 +6,0 @@ module.exports.connect = function (options) {

@@ -1,2 +0,2 @@

var Emitter = require('emitter');
var Emitter = require('component-emitter');

@@ -3,0 +3,0 @@ if (!Object.create) {

var WebSocket = require('ws');
var Emitter = require('emitter');
var Emitter = require('component-emitter');
var SCChannel = require('./scchannel');

@@ -4,0 +4,0 @@ var Response = require('./response').Response;

{
"name": "socketcluster-client",
"description": "SocketCluster JavaScript client",
"version": "2.2.9",
"version": "2.2.11",
"homepage": "http://socketcluster.io",

@@ -17,3 +17,3 @@ "contributors": [

"dependencies": {
"emitter": "http://github.com/component/emitter/archive/1.0.1.tar.gz",
"component-emitter": "1.2.0",
"linked-list": "0.1.0",

@@ -20,0 +20,0 @@ "ws": "0.7.1"

@@ -184,3 +184,3 @@ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.socketCluster=e()}}(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;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){

module.exports.Emitter = require('emitter');
module.exports.Emitter = require('component-emitter');

@@ -190,3 +190,3 @@ module.exports.connect = function (options) {

};
},{"./lib/scsocket":8,"emitter":9}],5:[function(require,module,exports){
},{"./lib/scsocket":8,"component-emitter":9}],5:[function(require,module,exports){
module.exports.create = (function () {

@@ -257,3 +257,3 @@ function F() {};

},{}],7:[function(require,module,exports){
var Emitter = require('emitter');
var Emitter = require('component-emitter');

@@ -313,6 +313,6 @@ if (!Object.create) {

module.exports = SCChannel;
},{"./objectcreate":5,"emitter":9}],8:[function(require,module,exports){
},{"./objectcreate":5,"component-emitter":9}],8:[function(require,module,exports){
(function (global){
var WebSocket = require('ws');
var Emitter = require('emitter');
var Emitter = require('component-emitter');
var SCChannel = require('./scchannel');

@@ -1251,11 +1251,5 @@ var Response = require('./response').Response;

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./objectcreate":5,"./response":6,"./scchannel":7,"emitter":9,"linked-list":12,"querystring":3,"ws":13}],9:[function(require,module,exports){
},{"./objectcreate":5,"./response":6,"./scchannel":7,"component-emitter":9,"linked-list":11,"querystring":3,"ws":12}],9:[function(require,module,exports){
/**
* Module dependencies.
*/
var index = require('indexof');
/**
* Expose `Emitter`.

@@ -1300,5 +1294,6 @@ */

Emitter.prototype.on = function(event, fn){
Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
(this._callbacks[event] = this._callbacks[event] || [])
(this._callbacks['$' + event] = this._callbacks['$' + event] || [])
.push(fn);

@@ -1319,11 +1314,8 @@ return this;

Emitter.prototype.once = function(event, fn){
var self = this;
this._callbacks = this._callbacks || {};
function on() {
self.off(event, on);
this.off(event, on);
fn.apply(this, arguments);
}
fn._off = on;
on.fn = fn;
this.on(event, on);

@@ -1345,3 +1337,4 @@ return this;

Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners = function(event, fn){
Emitter.prototype.removeAllListeners =
Emitter.prototype.removeEventListener = function(event, fn){
this._callbacks = this._callbacks || {};

@@ -1356,3 +1349,3 @@

// specific event
var callbacks = this._callbacks[event];
var callbacks = this._callbacks['$' + event];
if (!callbacks) return this;

@@ -1362,3 +1355,3 @@

if (1 == arguments.length) {
delete this._callbacks[event];
delete this._callbacks['$' + event];
return this;

@@ -1368,4 +1361,10 @@ }

// remove specific handler
var i = index(callbacks, fn._off || fn);
if (~i) callbacks.splice(i, 1);
var cb;
for (var i = 0; i < callbacks.length; i++) {
cb = callbacks[i];
if (cb === fn || cb.fn === fn) {
callbacks.splice(i, 1);
break;
}
}
return this;

@@ -1385,3 +1384,3 @@ };

var args = [].slice.call(arguments, 1)
, callbacks = this._callbacks[event];
, callbacks = this._callbacks['$' + event];

@@ -1408,3 +1407,3 @@ if (callbacks) {

this._callbacks = this._callbacks || {};
return this._callbacks[event] || [];
return this._callbacks['$' + event] || [];
};

@@ -1424,14 +1423,3 @@

},{"indexof":10}],10:[function(require,module,exports){
var indexOf = [].indexOf;
module.exports = function(arr, obj){
if (indexOf) return arr.indexOf(obj);
for (var i = 0; i < arr.length; ++i) {
if (arr[i] === obj) return i;
}
return -1;
};
},{}],11:[function(require,module,exports){
},{}],10:[function(require,module,exports){
'use strict';

@@ -1824,3 +1812,3 @@

},{}],12:[function(require,module,exports){
},{}],11:[function(require,module,exports){
'use strict';

@@ -1830,3 +1818,3 @@

},{"./_source/linked-list.js":11}],13:[function(require,module,exports){
},{"./_source/linked-list.js":10}],12:[function(require,module,exports){

@@ -1833,0 +1821,0 @@ /**

@@ -1,1 +0,1 @@

!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.socketCluster=e()}}(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;o<r.length;o++)s(r[o]);return s}({1:[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<len;++i){var x=qs[i].replace(regexp,"%20"),idx=x.indexOf(eq),kstr,vstr,k,v;if(idx>=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]"}},{}],2:[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<xs.length;i++){res.push(f(xs[i],i))}return res}var objectKeys=Object.keys||function(obj){var res=[];for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))res.push(key)}return res}},{}],3:[function(require,module,exports){"use strict";exports.decode=exports.parse=require("./decode");exports.encode=exports.stringify=require("./encode")},{"./decode":1,"./encode":2}],4:[function(require,module,exports){var SCSocket=require("./lib/scsocket");module.exports.SCSocket=SCSocket;module.exports.Emitter=require("emitter");module.exports.connect=function(options){return new SCSocket(options)}},{"./lib/scsocket":8,emitter:9}],5:[function(require,module,exports){module.exports.create=function(){function F(){}return function(o){if(arguments.length!=1){throw new Error("Object.create implementation only accepts one parameter.")}F.prototype=o;return new F}}()},{}],6:[function(require,module,exports){var Response=function(socket,id){this.socket=socket;this.id=id};Response.prototype._respond=function(responseData){this.socket.send(this.socket.stringify(responseData))};Response.prototype.end=function(data){if(this.id){var responseData={rid:this.id};if(data!==undefined){responseData.data=data}this._respond(responseData)}};Response.prototype.error=function(error,data){if(this.id){var err;if(error instanceof Error){err={name:error.name,message:error.message,stack:error.stack}}else{err=error}var responseData={rid:this.id,error:err};if(data!==undefined){responseData.data=data}this._respond(responseData)}};Response.prototype.callback=function(error,data){if(error){this.error(error,data)}else{this.end(data)}};module.exports.Response=Response},{}],7:[function(require,module,exports){var Emitter=require("emitter");if(!Object.create){Object.create=require("./objectcreate")}var SCChannel=function(name,socket){var self=this;Emitter.call(this);this.PENDING="pending";this.SUBSCRIBED="subscribed";this.UNSUBSCRIBED="unsubscribed";this.name=name;this.state=this.UNSUBSCRIBED;this.socket=socket};SCChannel.prototype=Object.create(Emitter.prototype);SCChannel.prototype.getState=function(){return this.state};SCChannel.prototype.subscribe=function(){this.socket.subscribe(this.name)};SCChannel.prototype.unsubscribe=function(){this.socket.unsubscribe(this.name)};SCChannel.prototype.isSubscribed=function(includePending){return this.socket.isSubscribed(this.name,includePending)};SCChannel.prototype.publish=function(data,callback){this.socket.publish(this.name,data,callback)};SCChannel.prototype.watch=function(handler){this.socket.watch(this.name,handler)};SCChannel.prototype.unwatch=function(handler){this.socket.unwatch(this.name,handler)};SCChannel.prototype.destroy=function(){this.socket.destroyChannel(this.name)};module.exports=SCChannel},{"./objectcreate":5,emitter:9}],8:[function(require,module,exports){(function(global){var WebSocket=require("ws");var Emitter=require("emitter");var SCChannel=require("./scchannel");var Response=require("./response").Response;var querystring=require("querystring");var LinkedList=require("linked-list");if(!Object.create){Object.create=require("./objectcreate")}var isBrowser=typeof window!="undefined";var SCSocket=function(options){var self=this;Emitter.call(this);var opts={port:null,autoReconnect:true,ackTimeout:1e4,initTimeout:9e3,hostname:global.location&&location.hostname,path:"/socketcluster/",secure:global.location&&location.protocol=="https:",timestampRequests:false,timestampParam:"t",binaryType:"arraybuffer"};for(var i in options){opts[i]=options[i]}this.id=null;this.state=this.CLOSED;this.ackTimeout=opts.ackTimeout;this.pingTimeout=this.ackTimeout;this.initTimeout=opts.initTimeout;var maxTimeout=Math.pow(2,31)-1;var verifyDuration=function(propertyName){if(self[propertyName]>maxTimeout){throw new Error("The "+propertyName+" value provided exceeded the maximum amount allowed")}};verifyDuration("ackTimeout");verifyDuration("pingTimeout");verifyDuration("initTimeout");this._localEvents={open:1,connect:1,connectFail:1,disconnect:1,message:1,error:1,raw:1,fail:1,kickOut:1,subscribe:1,unsubscribe:1,setAuthToken:1,removeAuthToken:1,status:1};this._connectAttempts=0;this._cid=1;this._callbackMap={};this._emitBuffer=new LinkedList;this._channels={};this._base64Chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";this._tokenData=null;this._pingTimeoutTicker=null;this.options=opts;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={}}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.options.port=opts.port||(global.location&&location.port?location.port:this.options.secure?443:80);this.connect();this._channelEmitter=new Emitter;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(Emitter.prototype);SCSocket.CONNECTING=SCSocket.prototype.CONNECTING="connecting";SCSocket.OPEN=SCSocket.prototype.OPEN="open";SCSocket.CLOSED=SCSocket.prototype.CLOSED="closed";SCSocket.ignoreStatuses={1e3:"Socket closed normally",1001:"Socket hung up"};SCSocket.errorStatuses={1001:"Socket was disconnected",1002:"A WebSocket protocol error was encountered",1003:"Server terminated socket because it received invalid data",1005:"Socket closed without status code",1006:"Socket hung up",1007:"Message format was incorrect",1008:"Encountered a policy violation",1009:"Message was too big to process",1010:"Client ended the connection because the server did not comply with extension requirements",1011:"Server encountered an unexpected fatal condition",4e3:"Server ping timed out",4001:"Client pong timed out",4002:"Client socket initialization timed out - Client did not receive a 'status' event"};SCSocket.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};SCSocket.prototype.getState=function(){return this.state};SCSocket.prototype.getBytesReceived=function(){return this.socket.bytesReceived};SCSocket.prototype.connect=SCSocket.prototype.open=function(){var self=this;if(this.state==this.CLOSED){this._clearAllSocketBindings();this.state=this.CONNECTING;var uri=this.uri();var socket=new WebSocket(uri,null,this.options);socket.binaryType=this.options.binaryType;this.socket=socket;socket.onopen=function(){if(socket==self.socket){self._onSCOpen()}};socket.onclose=function(event){if(socket==self.socket){self._onSCClose(event.code,event.reason)}};socket.onmessage=function(message,flags){if(socket==self.socket){self._onSCMessage(message.data)}}}};SCSocket.prototype.disconnect=function(code,data){code=code||1e3;if(this.state==this.OPEN){var packet={code:code,data:data};this._emitDirect("#disconnect",packet);this._onSCClose(code,data);this.socket.close(code)}};SCSocket.prototype._onSCOpen=function(){var self=this;this.state=this.OPEN;this._connectAttempts=0;this._resubscribe();Emitter.prototype.emit.call(this,"connect");this._flushEmitBuffer();this._resetPingTimeout();clearTimeout(this._initTimeoutTicker);this._initTimeoutTicker=setTimeout(function(){self._onSCClose(4002);self.socket.close(4002)},this.initTimeout)};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._reconnectTimeout);this._reconnectTimeout=setTimeout(function(){self.connect()},timeout)};SCSocket.prototype._onSCError=function(err){var self=this;setTimeout(function(){if(self.listeners("error").length<1){throw err}else{Emitter.prototype.emit.call(self,"error",err)}},0)};SCSocket.prototype._suspendSubscriptions=function(){var channel,newState;for(var channelName in this._channels){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._clearAllSocketBindings=function(code,data){clearTimeout(this._initTimeoutTicker);clearTimeout(this._pingTimeoutTicker);clearTimeout(this._reconnectTimeout)};SCSocket.prototype._onSCClose=function(code,data){this._clearAllSocketBindings();delete this.socket.onopen;delete this.socket.onclose;delete this.socket.onmessage;if(this.state!=this.CLOSED){var oldState=this.state;this.id=null;this._suspendSubscriptions();this.state=this.CLOSED;if(oldState==this.OPEN){Emitter.prototype.emit.call(this,"disconnect",code,data)}else if(oldState==this.CONNECTING){Emitter.prototype.emit.call(this,"connectFail",code,data)}if(this.options.autoReconnect){if(code==4e3||code==4001||code==1005){this._tryReconnect(0)}else if(code==1006||code==4002){this._tryReconnect()}}if(!SCSocket.ignoreStatuses[code]){var err=new Error(SCSocket.errorStatuses[code]||"Socket connection failed for unknown reasons");err.code=code;this._onSCError(err)}}};SCSocket.prototype._setCookie=function(name,value,expirySeconds){var exdate=null;if(expirySeconds){exdate=new Date;exdate.setTime(exdate.getTime()+Math.round(expirySeconds*1e3))}var value=escape(value)+"; path=/;"+(exdate==null?"":" expires="+exdate.toUTCString()+";");document.cookie=name+"="+value};SCSocket.prototype._getCookie=function(name){var i,x,y,ARRcookies=document.cookie.split(";");for(i=0;i<ARRcookies.length;i++){x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);x=x.replace(/^\s+|\s+$/g,"");if(x==name){return unescape(y)}}};SCSocket.prototype._isPrivateTransmittedEvent=function(event){return!!event&&event.indexOf("#")==0};SCSocket.prototype._onSCMessage=function(message){Emitter.prototype.emit.call(this,"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 eventName=obj.event;if(eventName){var eventData=obj.data||{};if(this._isPrivateTransmittedEvent(eventName)){if(eventName=="#fail"){this._onSCError(eventData)}else if(eventName=="#publish"){var publishData=eventData;var isSubscribed=this.isSubscribed(publishData.channel,true);if(isSubscribed){this._channelEmitter.emit(publishData.channel,publishData.data)}}else if(eventName=="#kickOut"){var channelName=eventData.channel;var channel=this._channels[channelName];if(channel){Emitter.prototype.emit.call(this,"kickOut",eventData.message,channelName);channel.emit("kickOut",eventData.message,channelName);this._triggerChannelUnsubscribe(channel)}}else if(eventName=="#setAuthToken"){var tokenData=eventData;var response=new Response(this,obj.cid);if(tokenData){this._tokenData=tokenData;if(tokenData.persistent&&tokenData.expiresInMinutes!=null){this._setCookie(tokenData.cookieName,tokenData.token,tokenData.expiresInMinutes*60)}else{this._setCookie(tokenData.cookieName,tokenData.token)}Emitter.prototype.emit.call(this,"setAuthToken",tokenData.token);response.end()}else{response.error("No token data provided with setAuthToken event")}}else if(eventName=="#removeAuthToken"){if(this._tokenData){this._setCookie(this._tokenData.cookieName,null,-1);Emitter.prototype.emit.call(this,"removeAuthToken")}var response=new Response(this,obj.cid);response.end()}else if(eventName=="#status"){if(eventData){this.id=eventData.id;this.pingTimeout=eventData.pingTimeout}this._resetPingTimeout();clearTimeout(this._initTimeoutTicker);Emitter.prototype.emit.call(this,"status",eventData)}else if(eventName=="#disconnect"){this._onSCClose(eventData.code,eventData.data)}else{var response=new Response(this,obj.cid);Emitter.prototype.emit.call(this,eventName,eventData,function(error,data){response.callback(error,data)})}}else{var response=new Response(this,obj.cid);Emitter.prototype.emit.call(this,eventName,eventData,function(error,data){response.callback(error,data)})}}else if(obj.rid!=null){var ret=this._callbackMap[obj.rid];if(ret){clearTimeout(ret.timeout);delete this._callbackMap[obj.rid];ret.callback(obj.error,obj.data)}if(obj.error){this._onSCError(obj.error)}}else{Emitter.prototype.emit.call(this,"raw",obj)}}};SCSocket.prototype._resetPingTimeout=function(){var self=this;var now=(new Date).getTime();clearTimeout(this._pingTimeoutTicker);this._pingTimeoutTicker=setTimeout(function(){self._onSCClose(4e3);self.socket.close(4e3)},this.pingTimeout)};SCSocket.prototype._nextCallId=function(){return this._cid++};SCSocket.prototype._isOwnDescendant=function(object,ancestors){for(var i in ancestors){if(ancestors[i]===object){return true}}return false};SCSocket.prototype._arrayBufferToBase64=function(arraybuffer){var chars=this._base64Chars;var bytes=new Uint8Array(arraybuffer);var len=bytes.length;var base64="";for(var i=0;i<len;i+=3){base64+=chars[bytes[i]>>2];base64+=chars[(bytes[i]&3)<<4|bytes[i+1]>>4];base64+=chars[(bytes[i+1]&15)<<2|bytes[i+2]>>6];base64+=chars[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};SCSocket.prototype._convertBuffersToBase64=function(object,ancestors){if(!ancestors){ancestors=[]}if(this._isOwnDescendant(object,ancestors)){throw new Error("Cannot traverse circular structure")}var newAncestors=ancestors.concat([object]);if(typeof ArrayBuffer!="undefined"&&object instanceof ArrayBuffer){return{base64:true,data:this._arrayBufferToBase64(object)}}if(object instanceof Array){var base64Array=[];for(var i in object){base64Array[i]=this._convertBuffersToBase64(object[i],newAncestors)}return base64Array}if(object instanceof Object){var base64Object={};for(var j in object){base64Object[j]=this._convertBuffersToBase64(object[j],newAncestors)}return base64Object}return object};SCSocket.prototype.parse=function(message){return JSON.parse(message)};SCSocket.prototype.stringify=function(object){return JSON.stringify(this._convertBuffersToBase64(object))};SCSocket.prototype.send=function(data){if(this.socket.readyState!=this.socket.OPEN){this._onSCClose(1005)}else{this.socket.send(data)}};SCSocket.prototype.sendObject=function(object){this.send(this.stringify(object))};SCSocket.prototype._emitRaw=function(eventObject){eventObject.cid=this._nextCallId();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};SCSocket.prototype._flushEmitBuffer=function(){var currentNode=this._emitBuffer.head;var nextNode;while(currentNode){nextNode=currentNode.next;var eventObject=currentNode.data;currentNode.detach();this._emitRaw(eventObject);currentNode=nextNode}};SCSocket.prototype._handleEventAckTimeout=function(eventObject,eventNode){var errorMessage="Event response for '"+eventObject.event+"' timed out";var error=new Error(errorMessage);error.type="timeout";if(eventObject.cid){delete this._callbackMap[eventObject.cid]}var callback=eventObject.callback;delete eventObject.callback;if(eventNode){eventNode.detach()}callback.call(eventObject,error,eventObject);this._onSCError(error)};SCSocket.prototype._emitDirect=function(event,data,a,b){var self=this;var callback,options;if(b){options=a;callback=b}else{if(a instanceof Function){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.ackTimeout)}var cid=null;if(this.state==this.OPEN){cid=this._emitRaw(eventObject)}return cid};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;if(callback){eventObject.timeout=setTimeout(function(){self._handleEventAckTimeout(eventObject,eventNode)},this.ackTimeout)}this._emitBuffer.append(eventNode);if(this.state==this.OPEN){this._flushEmitBuffer()}};SCSocket.prototype.emit=function(event,data,callback){if(this._localEvents[event]==null){this._emit(event,data,callback)}else{Emitter.prototype.emit.call(this,event,data)}};SCSocket.prototype.publish=function(channelName,data,callback){var pubData={channel:channelName,data:data};this.emit("#publish",pubData,function(err){callback&&callback(err)})};SCSocket.prototype._triggerChannelSubscribe=function(channel){var channelName=channel.name;if(channel.state!=channel.SUBSCRIBED){channel.state=channel.SUBSCRIBED;channel.emit("subscribe",channelName);Emitter.prototype.emit.call(this,"subscribe",channelName)}};SCSocket.prototype._triggerChannelSubscribeFail=function(err,channel){var channelName=channel.name;if(channel.state!=channel.UNSUBSCRIBED){channel.state=channel.UNSUBSCRIBED;channel.emit("subscribeFail",err,channelName);Emitter.prototype.emit.call(this,"subscribeFail",err,channelName)}};SCSocket.prototype._cancelPendingSubUnsubCallback=function(channel){var lastCid=channel._lastSubUnsubCid;if(lastCid!=null){delete this._callbackMap[lastCid]}};SCSocket.prototype._trySubscribe=function(channel){var self=this;if(this.state==this.OPEN){var options={noTimeout:true};this._cancelPendingSubUnsubCallback(channel);channel._lastSubUnsubCid=this._emitDirect("#subscribe",channel.name,options,function(err){if(err){self._triggerChannelSubscribeFail(err,channel)}else{self._triggerChannelSubscribe(channel)}})}};SCSocket.prototype.subscribe=function(channelName){var channel=this._channels[channelName];if(!channel){channel=new SCChannel(channelName,this);this._channels[channelName]=channel}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}if(oldState==channel.SUBSCRIBED){channel.emit("unsubscribe",channelName);Emitter.prototype.emit.call(this,"unsubscribe",channelName)}};SCSocket.prototype._tryUnsubscribe=function(channel){var self=this;if(this.state==this.OPEN){var options={noTimeout:true};this._cancelPendingSubUnsubCallback(channel);channel._lastSubUnsubCid=this._emitDirect("#unsubscribe",channel.name,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){var currentChannel=this._channels[channelName];if(!currentChannel){currentChannel=new SCChannel(channelName,this);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){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(channel,includePending){var channel=this._channels[channel];if(includePending){return!!channel&&(channel.state==channel.SUBSCRIBED||channel.state==channel.PENDING)}return!!channel&&channel.state==channel.SUBSCRIBED};SCSocket.prototype._resubscribe=function(){var self=this;var channels=[];for(var channelName in this._channels){channels.push(channelName)}for(var i in this._channels){(function(channel){if(channel.state==channel.PENDING){self._trySubscribe(channel)}})(this._channels[i])}};SCSocket.prototype.watch=function(channelName,handler){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:{})},{"./objectcreate":5,"./response":6,"./scchannel":7,emitter:9,"linked-list":12,querystring:3,ws:13}],9:[function(require,module,exports){var index=require("indexof");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=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}fn._off=on;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=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 i=index(callbacks,fn._off||fn);if(~i)callbacks.splice(i,1);return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks[event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{indexof:10}],10:[function(require,module,exports){var indexOf=[].indexOf;module.exports=function(arr,obj){if(indexOf)return arr.indexOf(obj);for(var i=0;i<arr.length;++i){if(arr[i]===obj)return i}return-1}},{}],11:[function(require,module,exports){"use strict";var errorMessage;errorMessage="An argument without append, prepend, "+"or detach methods was given to `List";function List(){if(arguments.length){return List.from(arguments)}}var ListPrototype;ListPrototype=List.prototype;List.of=function(){return List.from.call(this,arguments)};List.from=function(items){var list=new this,length,iterator,item;if(items&&(length=items.length)){iterator=-1;while(++iterator<length){item=items[iterator];if(item!==null&&item!==undefined){list.append(item)}}}return list};ListPrototype.head=null;ListPrototype.tail=null;ListPrototype.toArray=function(){var item=this.head,result=[];while(item){result.push(item);item=item.next}return result};ListPrototype.prepend=function(item){if(!item){return false}if(!item.append||!item.prepend||!item.detach){throw new Error(errorMessage+"#prepend`.")}var self,head;self=this;head=self.head;if(head){return head.prepend(item)}item.detach();item.list=self;self.head=item;return item};ListPrototype.append=function(item){if(!item){return false}if(!item.append||!item.prepend||!item.detach){throw new Error(errorMessage+"#append`.")}var self,head,tail;self=this;tail=self.tail;if(tail){return tail.append(item)}head=self.head;if(head){return head.append(item)}item.detach();item.list=self;self.head=item;return item};function ListItem(){}List.Item=ListItem;var ListItemPrototype=ListItem.prototype;ListItemPrototype.next=null;ListItemPrototype.prev=null;ListItemPrototype.list=null;ListItemPrototype.detach=function(){var self=this,list=self.list,prev=self.prev,next=self.next;if(!list){return self}if(list.tail===self){list.tail=prev}if(list.head===self){list.head=next}if(list.tail===list.head){list.tail=null}if(prev){prev.next=next}if(next){next.prev=prev}self.prev=self.next=self.list=null;return self};ListItemPrototype.prepend=function(item){if(!item||!item.append||!item.prepend||!item.detach){throw new Error(errorMessage+"Item#prepend`.")}var self=this,list=self.list,prev=self.prev;if(!list){return false}item.detach();if(prev){item.prev=prev;prev.next=item}item.next=self;item.list=list;self.prev=item;if(self===list.head){list.head=item}if(!list.tail){list.tail=self}return item};ListItemPrototype.append=function(item){if(!item||!item.append||!item.prepend||!item.detach){throw new Error(errorMessage+"Item#append`.")}var self=this,list=self.list,next=self.next;if(!list){return false}item.detach();if(next){item.next=next;next.prev=item}item.prev=self;item.list=list;self.next=item;if(self===list.tail||!list.tail){list.tail=item}return item};module.exports=List},{}],12:[function(require,module,exports){"use strict";module.exports=require("./_source/linked-list.js")},{"./_source/linked-list.js":11}],13:[function(require,module,exports){var global=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},{}]},{},[4])(4)});
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.socketCluster=e()}}(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;o<r.length;o++)s(r[o]);return s}({1:[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<len;++i){var x=qs[i].replace(regexp,"%20"),idx=x.indexOf(eq),kstr,vstr,k,v;if(idx>=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]"}},{}],2:[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<xs.length;i++){res.push(f(xs[i],i))}return res}var objectKeys=Object.keys||function(obj){var res=[];for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))res.push(key)}return res}},{}],3:[function(require,module,exports){"use strict";exports.decode=exports.parse=require("./decode");exports.encode=exports.stringify=require("./encode")},{"./decode":1,"./encode":2}],4:[function(require,module,exports){var SCSocket=require("./lib/scsocket");module.exports.SCSocket=SCSocket;module.exports.Emitter=require("component-emitter");module.exports.connect=function(options){return new SCSocket(options)}},{"./lib/scsocket":8,"component-emitter":9}],5:[function(require,module,exports){module.exports.create=function(){function F(){}return function(o){if(arguments.length!=1){throw new Error("Object.create implementation only accepts one parameter.")}F.prototype=o;return new F}}()},{}],6:[function(require,module,exports){var Response=function(socket,id){this.socket=socket;this.id=id};Response.prototype._respond=function(responseData){this.socket.send(this.socket.stringify(responseData))};Response.prototype.end=function(data){if(this.id){var responseData={rid:this.id};if(data!==undefined){responseData.data=data}this._respond(responseData)}};Response.prototype.error=function(error,data){if(this.id){var err;if(error instanceof Error){err={name:error.name,message:error.message,stack:error.stack}}else{err=error}var responseData={rid:this.id,error:err};if(data!==undefined){responseData.data=data}this._respond(responseData)}};Response.prototype.callback=function(error,data){if(error){this.error(error,data)}else{this.end(data)}};module.exports.Response=Response},{}],7:[function(require,module,exports){var Emitter=require("component-emitter");if(!Object.create){Object.create=require("./objectcreate")}var SCChannel=function(name,socket){var self=this;Emitter.call(this);this.PENDING="pending";this.SUBSCRIBED="subscribed";this.UNSUBSCRIBED="unsubscribed";this.name=name;this.state=this.UNSUBSCRIBED;this.socket=socket};SCChannel.prototype=Object.create(Emitter.prototype);SCChannel.prototype.getState=function(){return this.state};SCChannel.prototype.subscribe=function(){this.socket.subscribe(this.name)};SCChannel.prototype.unsubscribe=function(){this.socket.unsubscribe(this.name)};SCChannel.prototype.isSubscribed=function(includePending){return this.socket.isSubscribed(this.name,includePending)};SCChannel.prototype.publish=function(data,callback){this.socket.publish(this.name,data,callback)};SCChannel.prototype.watch=function(handler){this.socket.watch(this.name,handler)};SCChannel.prototype.unwatch=function(handler){this.socket.unwatch(this.name,handler)};SCChannel.prototype.destroy=function(){this.socket.destroyChannel(this.name)};module.exports=SCChannel},{"./objectcreate":5,"component-emitter":9}],8:[function(require,module,exports){(function(global){var WebSocket=require("ws");var Emitter=require("component-emitter");var SCChannel=require("./scchannel");var Response=require("./response").Response;var querystring=require("querystring");var LinkedList=require("linked-list");if(!Object.create){Object.create=require("./objectcreate")}var isBrowser=typeof window!="undefined";var SCSocket=function(options){var self=this;Emitter.call(this);var opts={port:null,autoReconnect:true,ackTimeout:1e4,initTimeout:9e3,hostname:global.location&&location.hostname,path:"/socketcluster/",secure:global.location&&location.protocol=="https:",timestampRequests:false,timestampParam:"t",binaryType:"arraybuffer"};for(var i in options){opts[i]=options[i]}this.id=null;this.state=this.CLOSED;this.ackTimeout=opts.ackTimeout;this.pingTimeout=this.ackTimeout;this.initTimeout=opts.initTimeout;var maxTimeout=Math.pow(2,31)-1;var verifyDuration=function(propertyName){if(self[propertyName]>maxTimeout){throw new Error("The "+propertyName+" value provided exceeded the maximum amount allowed")}};verifyDuration("ackTimeout");verifyDuration("pingTimeout");verifyDuration("initTimeout");this._localEvents={open:1,connect:1,connectFail:1,disconnect:1,message:1,error:1,raw:1,fail:1,kickOut:1,subscribe:1,unsubscribe:1,setAuthToken:1,removeAuthToken:1,status:1};this._connectAttempts=0;this._cid=1;this._callbackMap={};this._emitBuffer=new LinkedList;this._channels={};this._base64Chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";this._tokenData=null;this._pingTimeoutTicker=null;this.options=opts;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={}}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.options.port=opts.port||(global.location&&location.port?location.port:this.options.secure?443:80);this.connect();this._channelEmitter=new Emitter;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(Emitter.prototype);SCSocket.CONNECTING=SCSocket.prototype.CONNECTING="connecting";SCSocket.OPEN=SCSocket.prototype.OPEN="open";SCSocket.CLOSED=SCSocket.prototype.CLOSED="closed";SCSocket.ignoreStatuses={1e3:"Socket closed normally",1001:"Socket hung up"};SCSocket.errorStatuses={1001:"Socket was disconnected",1002:"A WebSocket protocol error was encountered",1003:"Server terminated socket because it received invalid data",1005:"Socket closed without status code",1006:"Socket hung up",1007:"Message format was incorrect",1008:"Encountered a policy violation",1009:"Message was too big to process",1010:"Client ended the connection because the server did not comply with extension requirements",1011:"Server encountered an unexpected fatal condition",4e3:"Server ping timed out",4001:"Client pong timed out",4002:"Client socket initialization timed out - Client did not receive a 'status' event"};SCSocket.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};SCSocket.prototype.getState=function(){return this.state};SCSocket.prototype.getBytesReceived=function(){return this.socket.bytesReceived};SCSocket.prototype.connect=SCSocket.prototype.open=function(){var self=this;if(this.state==this.CLOSED){this._clearAllSocketBindings();this.state=this.CONNECTING;var uri=this.uri();var socket=new WebSocket(uri,null,this.options);socket.binaryType=this.options.binaryType;this.socket=socket;socket.onopen=function(){if(socket==self.socket){self._onSCOpen()}};socket.onclose=function(event){if(socket==self.socket){self._onSCClose(event.code,event.reason)}};socket.onmessage=function(message,flags){if(socket==self.socket){self._onSCMessage(message.data)}}}};SCSocket.prototype.disconnect=function(code,data){code=code||1e3;if(this.state==this.OPEN){var packet={code:code,data:data};this._emitDirect("#disconnect",packet);this._onSCClose(code,data);this.socket.close(code)}};SCSocket.prototype._onSCOpen=function(){var self=this;this.state=this.OPEN;this._connectAttempts=0;this._resubscribe();Emitter.prototype.emit.call(this,"connect");this._flushEmitBuffer();this._resetPingTimeout();clearTimeout(this._initTimeoutTicker);this._initTimeoutTicker=setTimeout(function(){self._onSCClose(4002);self.socket.close(4002)},this.initTimeout)};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._reconnectTimeout);this._reconnectTimeout=setTimeout(function(){self.connect()},timeout)};SCSocket.prototype._onSCError=function(err){var self=this;setTimeout(function(){if(self.listeners("error").length<1){throw err}else{Emitter.prototype.emit.call(self,"error",err)}},0)};SCSocket.prototype._suspendSubscriptions=function(){var channel,newState;for(var channelName in this._channels){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._clearAllSocketBindings=function(code,data){clearTimeout(this._initTimeoutTicker);clearTimeout(this._pingTimeoutTicker);clearTimeout(this._reconnectTimeout)};SCSocket.prototype._onSCClose=function(code,data){this._clearAllSocketBindings();delete this.socket.onopen;delete this.socket.onclose;delete this.socket.onmessage;if(this.state!=this.CLOSED){var oldState=this.state;this.id=null;this._suspendSubscriptions();this.state=this.CLOSED;if(oldState==this.OPEN){Emitter.prototype.emit.call(this,"disconnect",code,data)}else if(oldState==this.CONNECTING){Emitter.prototype.emit.call(this,"connectFail",code,data)}if(this.options.autoReconnect){if(code==4e3||code==4001||code==1005){this._tryReconnect(0)}else if(code==1006||code==4002){this._tryReconnect()}}if(!SCSocket.ignoreStatuses[code]){var err=new Error(SCSocket.errorStatuses[code]||"Socket connection failed for unknown reasons");err.code=code;this._onSCError(err)}}};SCSocket.prototype._setCookie=function(name,value,expirySeconds){var exdate=null;if(expirySeconds){exdate=new Date;exdate.setTime(exdate.getTime()+Math.round(expirySeconds*1e3))}var value=escape(value)+"; path=/;"+(exdate==null?"":" expires="+exdate.toUTCString()+";");document.cookie=name+"="+value};SCSocket.prototype._getCookie=function(name){var i,x,y,ARRcookies=document.cookie.split(";");for(i=0;i<ARRcookies.length;i++){x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);x=x.replace(/^\s+|\s+$/g,"");if(x==name){return unescape(y)}}};SCSocket.prototype._isPrivateTransmittedEvent=function(event){return!!event&&event.indexOf("#")==0};SCSocket.prototype._onSCMessage=function(message){Emitter.prototype.emit.call(this,"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 eventName=obj.event;if(eventName){var eventData=obj.data||{};if(this._isPrivateTransmittedEvent(eventName)){if(eventName=="#fail"){this._onSCError(eventData)}else if(eventName=="#publish"){var publishData=eventData;var isSubscribed=this.isSubscribed(publishData.channel,true);if(isSubscribed){this._channelEmitter.emit(publishData.channel,publishData.data)}}else if(eventName=="#kickOut"){var channelName=eventData.channel;var channel=this._channels[channelName];if(channel){Emitter.prototype.emit.call(this,"kickOut",eventData.message,channelName);channel.emit("kickOut",eventData.message,channelName);this._triggerChannelUnsubscribe(channel)}}else if(eventName=="#setAuthToken"){var tokenData=eventData;var response=new Response(this,obj.cid);if(tokenData){this._tokenData=tokenData;if(tokenData.persistent&&tokenData.expiresInMinutes!=null){this._setCookie(tokenData.cookieName,tokenData.token,tokenData.expiresInMinutes*60)}else{this._setCookie(tokenData.cookieName,tokenData.token)}Emitter.prototype.emit.call(this,"setAuthToken",tokenData.token);response.end()}else{response.error("No token data provided with setAuthToken event")}}else if(eventName=="#removeAuthToken"){if(this._tokenData){this._setCookie(this._tokenData.cookieName,null,-1);Emitter.prototype.emit.call(this,"removeAuthToken")}var response=new Response(this,obj.cid);response.end()}else if(eventName=="#status"){if(eventData){this.id=eventData.id;this.pingTimeout=eventData.pingTimeout}this._resetPingTimeout();clearTimeout(this._initTimeoutTicker);Emitter.prototype.emit.call(this,"status",eventData)}else if(eventName=="#disconnect"){this._onSCClose(eventData.code,eventData.data)}else{var response=new Response(this,obj.cid);Emitter.prototype.emit.call(this,eventName,eventData,function(error,data){response.callback(error,data)})}}else{var response=new Response(this,obj.cid);Emitter.prototype.emit.call(this,eventName,eventData,function(error,data){response.callback(error,data)})}}else if(obj.rid!=null){var ret=this._callbackMap[obj.rid];if(ret){clearTimeout(ret.timeout);delete this._callbackMap[obj.rid];ret.callback(obj.error,obj.data)}if(obj.error){this._onSCError(obj.error)}}else{Emitter.prototype.emit.call(this,"raw",obj)}}};SCSocket.prototype._resetPingTimeout=function(){var self=this;var now=(new Date).getTime();clearTimeout(this._pingTimeoutTicker);this._pingTimeoutTicker=setTimeout(function(){self._onSCClose(4e3);self.socket.close(4e3)},this.pingTimeout)};SCSocket.prototype._nextCallId=function(){return this._cid++};SCSocket.prototype._isOwnDescendant=function(object,ancestors){for(var i in ancestors){if(ancestors[i]===object){return true}}return false};SCSocket.prototype._arrayBufferToBase64=function(arraybuffer){var chars=this._base64Chars;var bytes=new Uint8Array(arraybuffer);var len=bytes.length;var base64="";for(var i=0;i<len;i+=3){base64+=chars[bytes[i]>>2];base64+=chars[(bytes[i]&3)<<4|bytes[i+1]>>4];base64+=chars[(bytes[i+1]&15)<<2|bytes[i+2]>>6];base64+=chars[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};SCSocket.prototype._convertBuffersToBase64=function(object,ancestors){if(!ancestors){ancestors=[]}if(this._isOwnDescendant(object,ancestors)){throw new Error("Cannot traverse circular structure")}var newAncestors=ancestors.concat([object]);if(typeof ArrayBuffer!="undefined"&&object instanceof ArrayBuffer){return{base64:true,data:this._arrayBufferToBase64(object)}}if(object instanceof Array){var base64Array=[];for(var i in object){base64Array[i]=this._convertBuffersToBase64(object[i],newAncestors)}return base64Array}if(object instanceof Object){var base64Object={};for(var j in object){base64Object[j]=this._convertBuffersToBase64(object[j],newAncestors)}return base64Object}return object};SCSocket.prototype.parse=function(message){return JSON.parse(message)};SCSocket.prototype.stringify=function(object){return JSON.stringify(this._convertBuffersToBase64(object))};SCSocket.prototype.send=function(data){if(this.socket.readyState!=this.socket.OPEN){this._onSCClose(1005)}else{this.socket.send(data)}};SCSocket.prototype.sendObject=function(object){this.send(this.stringify(object))};SCSocket.prototype._emitRaw=function(eventObject){eventObject.cid=this._nextCallId();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};SCSocket.prototype._flushEmitBuffer=function(){var currentNode=this._emitBuffer.head;var nextNode;while(currentNode){nextNode=currentNode.next;var eventObject=currentNode.data;currentNode.detach();this._emitRaw(eventObject);currentNode=nextNode}};SCSocket.prototype._handleEventAckTimeout=function(eventObject,eventNode){var errorMessage="Event response for '"+eventObject.event+"' timed out";var error=new Error(errorMessage);error.type="timeout";if(eventObject.cid){delete this._callbackMap[eventObject.cid]}var callback=eventObject.callback;delete eventObject.callback;if(eventNode){eventNode.detach()}callback.call(eventObject,error,eventObject);this._onSCError(error)};SCSocket.prototype._emitDirect=function(event,data,a,b){var self=this;var callback,options;if(b){options=a;callback=b}else{if(a instanceof Function){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.ackTimeout)}var cid=null;if(this.state==this.OPEN){cid=this._emitRaw(eventObject)}return cid};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;if(callback){eventObject.timeout=setTimeout(function(){self._handleEventAckTimeout(eventObject,eventNode)},this.ackTimeout)}this._emitBuffer.append(eventNode);if(this.state==this.OPEN){this._flushEmitBuffer()}};SCSocket.prototype.emit=function(event,data,callback){if(this._localEvents[event]==null){this._emit(event,data,callback)}else{Emitter.prototype.emit.call(this,event,data)}};SCSocket.prototype.publish=function(channelName,data,callback){var pubData={channel:channelName,data:data};this.emit("#publish",pubData,function(err){callback&&callback(err)})};SCSocket.prototype._triggerChannelSubscribe=function(channel){var channelName=channel.name;if(channel.state!=channel.SUBSCRIBED){channel.state=channel.SUBSCRIBED;channel.emit("subscribe",channelName);Emitter.prototype.emit.call(this,"subscribe",channelName)}};SCSocket.prototype._triggerChannelSubscribeFail=function(err,channel){var channelName=channel.name;if(channel.state!=channel.UNSUBSCRIBED){channel.state=channel.UNSUBSCRIBED;channel.emit("subscribeFail",err,channelName);Emitter.prototype.emit.call(this,"subscribeFail",err,channelName)}};SCSocket.prototype._cancelPendingSubUnsubCallback=function(channel){var lastCid=channel._lastSubUnsubCid;if(lastCid!=null){delete this._callbackMap[lastCid]}};SCSocket.prototype._trySubscribe=function(channel){var self=this;if(this.state==this.OPEN){var options={noTimeout:true};this._cancelPendingSubUnsubCallback(channel);channel._lastSubUnsubCid=this._emitDirect("#subscribe",channel.name,options,function(err){if(err){self._triggerChannelSubscribeFail(err,channel)}else{self._triggerChannelSubscribe(channel)}})}};SCSocket.prototype.subscribe=function(channelName){var channel=this._channels[channelName];if(!channel){channel=new SCChannel(channelName,this);this._channels[channelName]=channel}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}if(oldState==channel.SUBSCRIBED){channel.emit("unsubscribe",channelName);Emitter.prototype.emit.call(this,"unsubscribe",channelName)}};SCSocket.prototype._tryUnsubscribe=function(channel){var self=this;if(this.state==this.OPEN){var options={noTimeout:true};this._cancelPendingSubUnsubCallback(channel);channel._lastSubUnsubCid=this._emitDirect("#unsubscribe",channel.name,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){var currentChannel=this._channels[channelName];if(!currentChannel){currentChannel=new SCChannel(channelName,this);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){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(channel,includePending){var channel=this._channels[channel];if(includePending){return!!channel&&(channel.state==channel.SUBSCRIBED||channel.state==channel.PENDING)}return!!channel&&channel.state==channel.SUBSCRIBED};SCSocket.prototype._resubscribe=function(){var self=this;var channels=[];for(var channelName in this._channels){channels.push(channelName)}for(var i in this._channels){(function(channel){if(channel.state==channel.PENDING){self._trySubscribe(channel)}})(this._channels[i])}};SCSocket.prototype.watch=function(channelName,handler){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:{})},{"./objectcreate":5,"./response":6,"./scchannel":7,"component-emitter":9,"linked-list":11,querystring:3,ws:12}],9:[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<callbacks.length;i++){cb=callbacks[i];if(cb===fn||cb.fn===fn){callbacks.splice(i,1);break}}return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks["$"+event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks["$"+event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{}],10:[function(require,module,exports){"use strict";var errorMessage;errorMessage="An argument without append, prepend, "+"or detach methods was given to `List";function List(){if(arguments.length){return List.from(arguments)}}var ListPrototype;ListPrototype=List.prototype;List.of=function(){return List.from.call(this,arguments)};List.from=function(items){var list=new this,length,iterator,item;if(items&&(length=items.length)){iterator=-1;while(++iterator<length){item=items[iterator];if(item!==null&&item!==undefined){list.append(item)}}}return list};ListPrototype.head=null;ListPrototype.tail=null;ListPrototype.toArray=function(){var item=this.head,result=[];while(item){result.push(item);item=item.next}return result};ListPrototype.prepend=function(item){if(!item){return false}if(!item.append||!item.prepend||!item.detach){throw new Error(errorMessage+"#prepend`.")}var self,head;self=this;head=self.head;if(head){return head.prepend(item)}item.detach();item.list=self;self.head=item;return item};ListPrototype.append=function(item){if(!item){return false}if(!item.append||!item.prepend||!item.detach){throw new Error(errorMessage+"#append`.")}var self,head,tail;self=this;tail=self.tail;if(tail){return tail.append(item)}head=self.head;if(head){return head.append(item)}item.detach();item.list=self;self.head=item;return item};function ListItem(){}List.Item=ListItem;var ListItemPrototype=ListItem.prototype;ListItemPrototype.next=null;ListItemPrototype.prev=null;ListItemPrototype.list=null;ListItemPrototype.detach=function(){var self=this,list=self.list,prev=self.prev,next=self.next;if(!list){return self}if(list.tail===self){list.tail=prev}if(list.head===self){list.head=next}if(list.tail===list.head){list.tail=null}if(prev){prev.next=next}if(next){next.prev=prev}self.prev=self.next=self.list=null;return self};ListItemPrototype.prepend=function(item){if(!item||!item.append||!item.prepend||!item.detach){throw new Error(errorMessage+"Item#prepend`.")}var self=this,list=self.list,prev=self.prev;if(!list){return false}item.detach();if(prev){item.prev=prev;prev.next=item}item.next=self;item.list=list;self.prev=item;if(self===list.head){list.head=item}if(!list.tail){list.tail=self}return item};ListItemPrototype.append=function(item){if(!item||!item.append||!item.prepend||!item.detach){throw new Error(errorMessage+"Item#append`.")}var self=this,list=self.list,next=self.next;if(!list){return false}item.detach();if(next){item.next=next;next.prev=item}item.prev=self;item.list=list;self.next=item;if(self===list.tail||!list.tail){list.tail=item}return item};module.exports=List},{}],11:[function(require,module,exports){"use strict";module.exports=require("./_source/linked-list.js")},{"./_source/linked-list.js":10}],12:[function(require,module,exports){var global=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},{}]},{},[4])(4)});
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc