made with requirebin
Created
July 22, 2016 14:37
-
-
Save timaschew/1d7ab901b6f7e00d283fa1fc68837b32 to your computer and use it in GitHub Desktop.
requirebin sketch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Welcome! require() some modules from npm (like you were using browserify) | |
// and then hit Run Code to run your code on the right side. | |
// Modules get downloaded from browserify-cdn and bundled in your browser. | |
const DEEPSTREAM_HOST = 'deepstream-test.herokuapp.com:80' | |
const deepstream = require('deepstream.io-client-js') | |
const result = document.getElementById('result') | |
result.textContent = window.location.pathname | |
/* | |
const client = deepstream(DEEPSTREAM_HOST).login({ | |
user: 'requirebin' | |
}, (success, data) => { | |
console.log('success', success) | |
console.log('data', data) | |
//client.record.getRecord('foobar').set('hello', 'world') | |
client.record.getRecord('foobar').whenReady((record) => { | |
console.log(record.get()) | |
}) | |
}) | |
*/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
setTimeout(function(){require=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){},{}],2:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");this._maxListeners=n;return this};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};if(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}throw TypeError('Uncaught, unspecified "error" event.')}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];handler.apply(this,args)}}else if(isObject(handler)){len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];listeners=handler.slice();len=listeners.length;for(i=0;i<len;i++)listeners[i].apply(this,args)}return true};EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events)this._events={};if(this._events.newListener)this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])this._events[type]=listener;else if(isObject(this._events[type]))this._events[type].push(listener);else this._events[type]=[this._events[type],listener];if(isObject(this._events[type])&&!this._events[type].warned){var m;if(!isUndefined(this._maxListeners)){m=this._maxListeners}else{m=EventEmitter.defaultMaxListeners}if(m&&m>0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-- >0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else{while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.listenerCount=function(emitter,type){var ret;if(!emitter._events||!emitter._events[type])ret=0;else if(isFunction(emitter._events[type]))ret=1;else ret=emitter._events[type].length;return ret};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],3:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],4:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canMutationObserver=typeof window!=="undefined"&&window.MutationObserver;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}var queue=[];if(canMutationObserver){var hiddenDiv=document.createElement("div");var observer=new MutationObserver(function(){var queueList=queue.slice();queue.length=0;queueList.forEach(function(fn){fn()})});observer.observe(hiddenDiv,{attributes:true});return function nextTick(fn){if(!queue.length){hiddenDiv.setAttribute("yes","no")}queue.push(fn)}}if(canPost){window.addEventListener("message",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")}},{}],5:[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 punycode,maxInt=2147483647,base=36,tMin=1,tMax=26,skew=38,damp=700,initialBias=72,initialN=128,delimiter="-",regexPunycode=/^xn--/,regexNonASCII=/[^ -~]/,regexSeparators=/\x2E|\u3002|\uFF0E|\uFF61/g,errors={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},baseMinusTMin=base-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode,key;function error(type){throw RangeError(errors[type])}function map(array,fn){var length=array.length;while(length--){array[length]=fn(array[length])}return array}function mapDomain(string,fn){return map(string.split(regexSeparators),fn).join(".")}function ucs2decode(string){var output=[],counter=0,length=string.length,value,extra;while(counter<length){value=string.charCodeAt(counter++);if(value>=55296&&value<=56319&&counter<length){extra=string.charCodeAt(counter++);if((extra&64512)==56320){output.push(((value&1023)<<10)+(extra&1023)+65536)}else{output.push(value);counter--}}else{output.push(value)}}return output}function ucs2encode(array){return map(array,function(value){var output="";if(value>65535){value-=65536;output+=stringFromCharCode(value>>>10&1023|55296);value=56320|value&1023}output+=stringFromCharCode(value);return output}).join("")}function basicToDigit(codePoint){if(codePoint-48<10){return codePoint-22}if(codePoint-65<26){return codePoint-65}if(codePoint-97<26){return codePoint-97}return base}function digitToBasic(digit,flag){return digit+22+75*(digit<26)-((flag!=0)<<5)}function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin)}return floor(k+(baseMinusTMin+1)*delta/(delta+skew))}function decode(input){var output=[],inputLength=input.length,out,i=0,n=initialN,bias=initialBias,basic,j,index,oldi,w,k,digit,t,baseMinusT;basic=input.lastIndexOf(delimiter);if(basic<0){basic=0}for(j=0;j<basic;++j){if(input.charCodeAt(j)>=128){error("not-basic")}output.push(input.charCodeAt(j))}for(index=basic>0?basic+1:0;index<inputLength;){for(oldi=i,w=1,k=base;;k+=base){if(index>=inputLength){error("invalid-input")}digit=basicToDigit(input.charCodeAt(index++));if(digit>=base||digit>floor((maxInt-i)/w)){error("overflow")}i+=digit*w;t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(digit<t){break}baseMinusT=base-t;if(w>floor(maxInt/baseMinusT)){error("overflow")}w*=baseMinusT}out=output.length+1;bias=adapt(i-oldi,out,oldi==0);if(floor(i/out)>maxInt-n){error("overflow")}n+=floor(i/out);i%=out;output.splice(i++,0,n)}return ucs2encode(output)}function encode(input){var n,delta,handledCPCount,basicLength,bias,j,m,q,k,t,currentValue,output=[],inputLength,handledCPCountPlusOne,baseMinusT,qMinusT;input=ucs2decode(input);inputLength=input.length;n=initialN;delta=0;bias=initialBias;for(j=0;j<inputLength;++j){currentValue=input[j];if(currentValue<128){output.push(stringFromCharCode(currentValue))}}handledCPCount=basicLength=output.length;if(basicLength){output.push(delimiter)}while(handledCPCount<inputLength){for(m=maxInt,j=0;j<inputLength;++j){currentValue=input[j];if(currentValue>=n&¤tValue<m){m=currentValue}}handledCPCountPlusOne=handledCPCount+1;if(m-n>floor((maxInt-delta)/handledCPCountPlusOne)){error("overflow")}delta+=(m-n)*handledCPCountPlusOne;n=m;for(j=0;j<inputLength;++j){currentValue=input[j];if(currentValue<n&&++delta>maxInt){error("overflow")}if(currentValue==n){for(q=delta,k=base;;k+=base){t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(q<t){break}qMinusT=q-t;baseMinusT=base-t;output.push(stringFromCharCode(digitToBasic(t+qMinusT%baseMinusT,0)));q=floor(qMinusT/baseMinusT)}output.push(stringFromCharCode(digitToBasic(q,0)));bias=adapt(delta,handledCPCountPlusOne,handledCPCount==basicLength);delta=0;++handledCPCount}}++delta;++n}return output.join("")}function toUnicode(domain){return mapDomain(domain,function(string){return regexPunycode.test(string)?decode(string.slice(4).toLowerCase()):string})}function toASCII(domain){return mapDomain(domain,function(string){return regexNonASCII.test(string)?"xn--"+encode(string):string})}punycode={version:"1.2.4",ucs2:{decode:ucs2decode,encode:ucs2encode},decode:decode,encode:encode,toASCII:toASCII,toUnicode:toUnicode};if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define("punycode",function(){return punycode})}else if(freeExports&&!freeExports.nodeType){if(freeModule){freeModule.exports=punycode}else{for(key in punycode){punycode.hasOwnProperty(key)&&(freeExports[key]=punycode[key])}}}else{root.punycode=punycode}})(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],6:[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]"}},{}],7:[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}},{}],8:[function(require,module,exports){"use strict";exports.decode=exports.parse=require("./decode");exports.encode=exports.stringify=require("./encode")},{"./decode":6,"./encode":7}],9:[function(require,module,exports){var punycode=require("punycode");exports.parse=urlParse;exports.resolve=urlResolve;exports.resolveObject=urlResolveObject;exports.format=urlFormat;exports.Url=Url;function Url(){this.protocol=null;this.slashes=null;this.auth=null;this.host=null;this.port=null;this.hostname=null;this.hash=null;this.search=null;this.query=null;this.pathname=null;this.path=null;this.href=null}var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,delims=["<",">",'"',"`"," ","\r","\n"," "],unwise=["{","}","|","\\","^","`"].concat(delims),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnameMaxLen=255,hostnamePartPattern=/^[a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:true,"javascript:":true},hostlessProtocol={javascript:true,"javascript:":true},slashedProtocol={http:true,https:true,ftp:true,gopher:true,file:true,"http:":true,"https:":true,"ftp:":true,"gopher:":true,"file:":true},querystring=require("querystring");function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&isObject(url)&&url instanceof Url)return url;var u=new Url;u.parse(url,parseQueryString,slashesDenoteHost);return u}Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!isString(url)){throw new TypeError("Parameter 'url' must be a string, not "+typeof url)}var rest=url;rest=rest.trim();var proto=protocolPattern.exec(rest);if(proto){proto=proto[0];var lowerProto=proto.toLowerCase();this.protocol=lowerProto;rest=rest.substr(proto.length)}if(slashesDenoteHost||proto||rest.match(/^\/\/[^@\/]+@[^@\/]+/)){var slashes=rest.substr(0,2)==="//";if(slashes&&!(proto&&hostlessProtocol[proto])){rest=rest.substr(2);this.slashes=true}}if(!hostlessProtocol[proto]&&(slashes||proto&&!slashedProtocol[proto])){var hostEnd=-1;for(var i=0;i<hostEndingChars.length;i++){var hec=rest.indexOf(hostEndingChars[i]);if(hec!==-1&&(hostEnd===-1||hec<hostEnd))hostEnd=hec}var auth,atSign;if(hostEnd===-1){atSign=rest.lastIndexOf("@")}else{atSign=rest.lastIndexOf("@",hostEnd)}if(atSign!==-1){auth=rest.slice(0,atSign);rest=rest.slice(atSign+1);this.auth=decodeURIComponent(auth)}hostEnd=-1;for(var i=0;i<nonHostChars.length;i++){var hec=rest.indexOf(nonHostChars[i]);if(hec!==-1&&(hostEnd===-1||hec<hostEnd))hostEnd=hec}if(hostEnd===-1)hostEnd=rest.length;this.host=rest.slice(0,hostEnd);rest=rest.slice(hostEnd);this.parseHost();this.hostname=this.hostname||"";var ipv6Hostname=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!ipv6Hostname){var hostparts=this.hostname.split(/\./);for(var i=0,l=hostparts.length;i<l;i++){var part=hostparts[i];if(!part)continue;if(!part.match(hostnamePartPattern)){var newpart="";for(var j=0,k=part.length;j<k;j++){if(part.charCodeAt(j)>127){newpart+="x"}else{newpart+=part[j]}}if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i);var notHost=hostparts.slice(i+1);var bit=part.match(hostnamePartStart);if(bit){validParts.push(bit[1]);notHost.unshift(bit[2])}if(notHost.length){rest="/"+notHost.join(".")+rest}this.hostname=validParts.join(".");break}}}}if(this.hostname.length>hostnameMaxLen){this.hostname=""}else{this.hostname=this.hostname.toLowerCase()}if(!ipv6Hostname){var domainArray=this.hostname.split(".");var newOut=[];for(var i=0;i<domainArray.length;++i){var s=domainArray[i];newOut.push(s.match(/[^A-Za-z0-9_-]/)?"xn--"+punycode.encode(s):s)}this.hostname=newOut.join(".")}var p=this.port?":"+this.port:"";var h=this.hostname||"";this.host=h+p;this.href+=this.host;if(ipv6Hostname){this.hostname=this.hostname.substr(1,this.hostname.length-2);if(rest[0]!=="/"){rest="/"+rest}}}if(!unsafeProtocol[lowerProto]){for(var i=0,l=autoEscape.length;i<l;i++){var ae=autoEscape[i];var esc=encodeURIComponent(ae);if(esc===ae){esc=escape(ae)}rest=rest.split(ae).join(esc)}}var hash=rest.indexOf("#");if(hash!==-1){this.hash=rest.substr(hash);rest=rest.slice(0,hash)}var qm=rest.indexOf("?");if(qm!==-1){this.search=rest.substr(qm);this.query=rest.substr(qm+1);if(parseQueryString){this.query=querystring.parse(this.query)}rest=rest.slice(0,qm)}else if(parseQueryString){this.search="";this.query={}}if(rest)this.pathname=rest;if(slashedProtocol[lowerProto]&&this.hostname&&!this.pathname){this.pathname="/"}if(this.pathname||this.search){var p=this.pathname||"";var s=this.search||"";this.path=p+s}this.href=this.format();return this};function urlFormat(obj){if(isString(obj))obj=urlParse(obj);if(!(obj instanceof Url))return Url.prototype.format.call(obj);return obj.format()}Url.prototype.format=function(){var auth=this.auth||"";if(auth){auth=encodeURIComponent(auth);auth=auth.replace(/%3A/i,":");auth+="@"}var protocol=this.protocol||"",pathname=this.pathname||"",hash=this.hash||"",host=false,query="";if(this.host){host=auth+this.host}else if(this.hostname){host=auth+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]");if(this.port){host+=":"+this.port}}if(this.query&&isObject(this.query)&&Object.keys(this.query).length){query=querystring.stringify(this.query)}var search=this.search||query&&"?"+query||"";if(protocol&&protocol.substr(-1)!==":")protocol+=":";if(this.slashes||(!protocol||slashedProtocol[protocol])&&host!==false){host="//"+(host||"");if(pathname&&pathname.charAt(0)!=="/")pathname="/"+pathname}else if(!host){host=""}if(hash&&hash.charAt(0)!=="#")hash="#"+hash;if(search&&search.charAt(0)!=="?")search="?"+search;pathname=pathname.replace(/[?#]/g,function(match){return encodeURIComponent(match)});search=search.replace("#","%23");return protocol+host+pathname+search+hash};function urlResolve(source,relative){return urlParse(source,false,true).resolve(relative)}Url.prototype.resolve=function(relative){return this.resolveObject(urlParse(relative,false,true)).format()};function urlResolveObject(source,relative){if(!source)return relative;return urlParse(source,false,true).resolveObject(relative)}Url.prototype.resolveObject=function(relative){if(isString(relative)){var rel=new Url;rel.parse(relative,false,true);relative=rel}var result=new Url;Object.keys(this).forEach(function(k){result[k]=this[k]},this);result.hash=relative.hash;if(relative.href===""){result.href=result.format();return result}if(relative.slashes&&!relative.protocol){Object.keys(relative).forEach(function(k){if(k!=="protocol")result[k]=relative[k]});if(slashedProtocol[result.protocol]&&result.hostname&&!result.pathname){result.path=result.pathname="/"}result.href=result.format();return result}if(relative.protocol&&relative.protocol!==result.protocol){if(!slashedProtocol[relative.protocol]){Object.keys(relative).forEach(function(k){result[k]=relative[k]});result.href=result.format();return result}result.protocol=relative.protocol;if(!relative.host&&!hostlessProtocol[relative.protocol]){var relPath=(relative.pathname||"").split("/");while(relPath.length&&!(relative.host=relPath.shift()));if(!relative.host)relative.host="";if(!relative.hostname)relative.hostname="";if(relPath[0]!=="")relPath.unshift("");if(relPath.length<2)relPath.unshift("");result.pathname=relPath.join("/")}else{result.pathname=relative.pathname}result.search=relative.search;result.query=relative.query;result.host=relative.host||"";result.auth=relative.auth;result.hostname=relative.hostname||relative.host;result.port=relative.port;if(result.pathname||result.search){var p=result.pathname||"";var s=result.search||"";result.path=p+s}result.slashes=result.slashes||relative.slashes;result.href=result.format();return result}var isSourceAbs=result.pathname&&result.pathname.charAt(0)==="/",isRelAbs=relative.host||relative.pathname&&relative.pathname.charAt(0)==="/",mustEndAbs=isRelAbs||isSourceAbs||result.host&&relative.pathname,removeAllDots=mustEndAbs,srcPath=result.pathname&&result.pathname.split("/")||[],relPath=relative.pathname&&relative.pathname.split("/")||[],psychotic=result.protocol&&!slashedProtocol[result.protocol];if(psychotic){result.hostname="";result.port=null;if(result.host){if(srcPath[0]==="")srcPath[0]=result.host;else srcPath.unshift(result.host)}result.host="";if(relative.protocol){relative.hostname=null;relative.port=null;if(relative.host){if(relPath[0]==="")relPath[0]=relative.host;else relPath.unshift(relative.host)}relative.host=null}mustEndAbs=mustEndAbs&&(relPath[0]===""||srcPath[0]==="")}if(isRelAbs){result.host=relative.host||relative.host===""?relative.host:result.host;result.hostname=relative.hostname||relative.hostname===""?relative.hostname:result.hostname;result.search=relative.search;result.query=relative.query;srcPath=relPath}else if(relPath.length){if(!srcPath)srcPath=[];srcPath.pop();srcPath=srcPath.concat(relPath);result.search=relative.search;result.query=relative.query}else if(!isNullOrUndefined(relative.search)){if(psychotic){result.hostname=result.host=srcPath.shift();var authInHost=result.host&&result.host.indexOf("@")>0?result.host.split("@"):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift()}}result.search=relative.search;result.query=relative.query;if(!isNull(result.pathname)||!isNull(result.search)){result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")}result.href=result.format();return result}if(!srcPath.length){result.pathname=null;if(result.search){result.path="/"+result.search}else{result.path=null}result.href=result.format();return result}var last=srcPath.slice(-1)[0];var hasTrailingSlash=(result.host||relative.host)&&(last==="."||last==="..")||last==="";var up=0;for(var i=srcPath.length;i>=0;i--){last=srcPath[i];if(last=="."){srcPath.splice(i,1)}else if(last===".."){srcPath.splice(i,1);up++}else if(up){srcPath.splice(i,1);up--}}if(!mustEndAbs&&!removeAllDots){for(;up--;up){srcPath.unshift("..")}}if(mustEndAbs&&srcPath[0]!==""&&(!srcPath[0]||srcPath[0].charAt(0)!=="/")){srcPath.unshift("")}if(hasTrailingSlash&&srcPath.join("/").substr(-1)!=="/"){srcPath.push("")}var isAbsolute=srcPath[0]===""||srcPath[0]&&srcPath[0].charAt(0)==="/";if(psychotic){result.hostname=result.host=isAbsolute?"":srcPath.length?srcPath.shift():"";var authInHost=result.host&&result.host.indexOf("@")>0?result.host.split("@"):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift()}}mustEndAbs=mustEndAbs||result.host&&srcPath.length;if(mustEndAbs&&!isAbsolute){srcPath.unshift("")}if(!srcPath.length){result.pathname=null;result.path=null}else{result.pathname=srcPath.join("/")}if(!isNull(result.pathname)||!isNull(result.search)){result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")}result.auth=relative.auth||result.auth;result.slashes=result.slashes||relative.slashes;result.href=result.format();return result};Url.prototype.parseHost=function(){var host=this.host;var port=portPattern.exec(host);if(port){port=port[0];if(port!==":"){this.port=port.substr(1)}host=host.substr(0,host.length-port.length)}if(host)this.hostname=host};function isString(arg){return typeof arg==="string"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isNull(arg){return arg===null}function isNullOrUndefined(arg){return arg==null}},{punycode:5,querystring:8}],10:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],11:[function(require,module,exports){(function(process,global){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i<arguments.length;i++){objects.push(inspect(arguments[i]))}return objects.join(" ")}var i=1;var args=arguments;var len=args.length;var str=String(f).replace(formatRegExp,function(x){if(x==="%%")return"%";if(i>=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i<len;x=args[++i]){if(isNull(x)||!isObject(x)){str+=" "+x}else{str+=" "+inspect(x)}}return str};exports.deprecate=function(fn,msg){if(isUndefined(global.process)){return function(){return exports.deprecate(fn,msg).apply(this,arguments)}}if(process.noDeprecation===true){return fn}var warned=false;function deprecated(){if(!warned){if(process.throwDeprecation){throw new Error(msg)}else if(process.traceDeprecation){console.trace(msg)}else{console.error(msg)}warned=true}return fn.apply(this,arguments)}return deprecated};var debugs={};var debugEnviron;exports.debuglog=function(set){if(isUndefined(debugEnviron))debugEnviron=process.env.NODE_DEBUG||"";set=set.toUpperCase();if(!debugs[set]){if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else{debugs[set]=function(){}}}return debugs[set]};function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};if(arguments.length>=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i<l;++i){if(hasOwnProperty(value,String(i))){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),true))}else{output.push("")}}keys.forEach(function(key){if(!key.match(/^\d+$/)){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,true))}});return output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]};if(desc.get){if(desc.set){str=ctx.stylize("[Getter/Setter]","special")}else{str=ctx.stylize("[Getter]","special")}}else{if(desc.set){str=ctx.stylize("[Setter]","special")}}if(!hasOwnProperty(visibleKeys,key)){name="["+key+"]"}if(!str){if(ctx.seen.indexOf(desc.value)<0){if(isNull(recurseTimes)){str=formatValue(ctx,desc.value,null)}else{str=formatValue(ctx,desc.value,recurseTimes-1)}if(str.indexOf("\n")>-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2); | |
}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":10,_process:4,inherits:3}],12:[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){var self=this;this._callbacks=this._callbacks||{};function on(){self.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}},{}],13:[function(require,module,exports){module.exports=require("./lib/")},{"./lib/":14}],14:[function(require,module,exports){module.exports=require("./socket");module.exports.parser=require("engine.io-parser")},{"./socket":15,"engine.io-parser":27}],15:[function(require,module,exports){(function(global){var transports=require("./transports");var Emitter=require("component-emitter");var debug=require("debug")("engine.io-client:socket");var index=require("indexof");var parser=require("engine.io-parser");var parseuri=require("parseuri");var parsejson=require("parsejson");var parseqs=require("parseqs");module.exports=Socket;function noop(){}function Socket(uri,opts){if(!(this instanceof Socket))return new Socket(uri,opts);opts=opts||{};if(uri&&"object"==typeof uri){opts=uri;uri=null}if(uri){uri=parseuri(uri);opts.hostname=uri.host;opts.secure=uri.protocol=="https"||uri.protocol=="wss";opts.port=uri.port;if(uri.query)opts.query=uri.query}else if(opts.host){opts.hostname=parseuri(opts.host).host}this.secure=null!=opts.secure?opts.secure:global.location&&"https:"==location.protocol;if(opts.hostname&&!opts.port){opts.port=this.secure?"443":"80"}this.agent=opts.agent||false;this.hostname=opts.hostname||(global.location?location.hostname:"localhost");this.port=opts.port||(global.location&&location.port?location.port:this.secure?443:80);this.query=opts.query||{};if("string"==typeof this.query)this.query=parseqs.decode(this.query);this.upgrade=false!==opts.upgrade;this.path=(opts.path||"/engine.io").replace(/\/$/,"")+"/";this.forceJSONP=!!opts.forceJSONP;this.jsonp=false!==opts.jsonp;this.forceBase64=!!opts.forceBase64;this.enablesXDR=!!opts.enablesXDR;this.timestampParam=opts.timestampParam||"t";this.timestampRequests=opts.timestampRequests;this.transports=opts.transports||["polling","websocket"];this.readyState="";this.writeBuffer=[];this.policyPort=opts.policyPort||843;this.rememberUpgrade=opts.rememberUpgrade||false;this.binaryType=null;this.onlyBinaryUpgrades=opts.onlyBinaryUpgrades;this.perMessageDeflate=false!==opts.perMessageDeflate?opts.perMessageDeflate||{}:false;if(true===this.perMessageDeflate)this.perMessageDeflate={};if(this.perMessageDeflate&&null==this.perMessageDeflate.threshold){this.perMessageDeflate.threshold=1024}this.pfx=opts.pfx||null;this.key=opts.key||null;this.passphrase=opts.passphrase||null;this.cert=opts.cert||null;this.ca=opts.ca||null;this.ciphers=opts.ciphers||null;this.rejectUnauthorized=opts.rejectUnauthorized===undefined?true:opts.rejectUnauthorized;var freeGlobal=typeof global=="object"&&global;if(freeGlobal.global===freeGlobal){if(opts.extraHeaders&&Object.keys(opts.extraHeaders).length>0){this.extraHeaders=opts.extraHeaders}}this.open()}Socket.priorWebsocketSuccess=false;Emitter(Socket.prototype);Socket.protocol=parser.protocol;Socket.Socket=Socket;Socket.Transport=require("./transport");Socket.transports=require("./transports");Socket.parser=require("engine.io-parser");Socket.prototype.createTransport=function(name){debug('creating transport "%s"',name);var query=clone(this.query);query.EIO=parser.protocol;query.transport=name;if(this.id)query.sid=this.id;var transport=new transports[name]({agent:this.agent,hostname:this.hostname,port:this.port,secure:this.secure,path:this.path,query:query,forceJSONP:this.forceJSONP,jsonp:this.jsonp,forceBase64:this.forceBase64,enablesXDR:this.enablesXDR,timestampRequests:this.timestampRequests,timestampParam:this.timestampParam,policyPort:this.policyPort,socket:this,pfx:this.pfx,key:this.key,passphrase:this.passphrase,cert:this.cert,ca:this.ca,ciphers:this.ciphers,rejectUnauthorized:this.rejectUnauthorized,perMessageDeflate:this.perMessageDeflate,extraHeaders:this.extraHeaders});return transport};function clone(obj){var o={};for(var i in obj){if(obj.hasOwnProperty(i)){o[i]=obj[i]}}return o}Socket.prototype.open=function(){var transport;if(this.rememberUpgrade&&Socket.priorWebsocketSuccess&&this.transports.indexOf("websocket")!=-1){transport="websocket"}else if(0===this.transports.length){var self=this;setTimeout(function(){self.emit("error","No transports available")},0);return}else{transport=this.transports[0]}this.readyState="opening";try{transport=this.createTransport(transport)}catch(e){this.transports.shift();this.open();return}transport.open();this.setTransport(transport)};Socket.prototype.setTransport=function(transport){debug("setting transport %s",transport.name);var self=this;if(this.transport){debug("clearing existing transport %s",this.transport.name);this.transport.removeAllListeners()}this.transport=transport;transport.on("drain",function(){self.onDrain()}).on("packet",function(packet){self.onPacket(packet)}).on("error",function(e){self.onError(e)}).on("close",function(){self.onClose("transport close")})};Socket.prototype.probe=function(name){debug('probing transport "%s"',name);var transport=this.createTransport(name,{probe:1}),failed=false,self=this;Socket.priorWebsocketSuccess=false;function onTransportOpen(){if(self.onlyBinaryUpgrades){var upgradeLosesBinary=!this.supportsBinary&&self.transport.supportsBinary;failed=failed||upgradeLosesBinary}if(failed)return;debug('probe transport "%s" opened',name);transport.send([{type:"ping",data:"probe"}]);transport.once("packet",function(msg){if(failed)return;if("pong"==msg.type&&"probe"==msg.data){debug('probe transport "%s" pong',name);self.upgrading=true;self.emit("upgrading",transport);if(!transport)return;Socket.priorWebsocketSuccess="websocket"==transport.name;debug('pausing current transport "%s"',self.transport.name);self.transport.pause(function(){if(failed)return;if("closed"==self.readyState)return;debug("changing transport and sending upgrade packet");cleanup();self.setTransport(transport);transport.send([{type:"upgrade"}]);self.emit("upgrade",transport);transport=null;self.upgrading=false;self.flush()})}else{debug('probe transport "%s" failed',name);var err=new Error("probe error");err.transport=transport.name;self.emit("upgradeError",err)}})}function freezeTransport(){if(failed)return;failed=true;cleanup();transport.close();transport=null}function onerror(err){var error=new Error("probe error: "+err);error.transport=transport.name;freezeTransport();debug('probe transport "%s" failed because of error: %s',name,err);self.emit("upgradeError",error)}function onTransportClose(){onerror("transport closed")}function onclose(){onerror("socket closed")}function onupgrade(to){if(transport&&to.name!=transport.name){debug('"%s" works - aborting "%s"',to.name,transport.name);freezeTransport()}}function cleanup(){transport.removeListener("open",onTransportOpen);transport.removeListener("error",onerror);transport.removeListener("close",onTransportClose);self.removeListener("close",onclose);self.removeListener("upgrading",onupgrade)}transport.once("open",onTransportOpen);transport.once("error",onerror);transport.once("close",onTransportClose);this.once("close",onclose);this.once("upgrading",onupgrade);transport.open()};Socket.prototype.onOpen=function(){debug("socket open");this.readyState="open";Socket.priorWebsocketSuccess="websocket"==this.transport.name;this.emit("open");this.flush();if("open"==this.readyState&&this.upgrade&&this.transport.pause){debug("starting upgrade probes");for(var i=0,l=this.upgrades.length;i<l;i++){this.probe(this.upgrades[i])}}};Socket.prototype.onPacket=function(packet){if("opening"==this.readyState||"open"==this.readyState){debug('socket receive: type "%s", data "%s"',packet.type,packet.data);this.emit("packet",packet);this.emit("heartbeat");switch(packet.type){case"open":this.onHandshake(parsejson(packet.data));break;case"pong":this.setPing();this.emit("pong");break;case"error":var err=new Error("server error");err.code=packet.data;this.onError(err);break;case"message":this.emit("data",packet.data);this.emit("message",packet.data);break}}else{debug('packet received with socket readyState "%s"',this.readyState)}};Socket.prototype.onHandshake=function(data){this.emit("handshake",data);this.id=data.sid;this.transport.query.sid=data.sid;this.upgrades=this.filterUpgrades(data.upgrades);this.pingInterval=data.pingInterval;this.pingTimeout=data.pingTimeout;this.onOpen();if("closed"==this.readyState)return;this.setPing();this.removeListener("heartbeat",this.onHeartbeat);this.on("heartbeat",this.onHeartbeat)};Socket.prototype.onHeartbeat=function(timeout){clearTimeout(this.pingTimeoutTimer);var self=this;self.pingTimeoutTimer=setTimeout(function(){if("closed"==self.readyState)return;self.onClose("ping timeout")},timeout||self.pingInterval+self.pingTimeout)};Socket.prototype.setPing=function(){var self=this;clearTimeout(self.pingIntervalTimer);self.pingIntervalTimer=setTimeout(function(){debug("writing ping packet - expecting pong within %sms",self.pingTimeout);self.ping();self.onHeartbeat(self.pingTimeout)},self.pingInterval)};Socket.prototype.ping=function(){var self=this;this.sendPacket("ping",function(){self.emit("ping")})};Socket.prototype.onDrain=function(){this.writeBuffer.splice(0,this.prevBufferLen);this.prevBufferLen=0;if(0===this.writeBuffer.length){this.emit("drain")}else{this.flush()}};Socket.prototype.flush=function(){if("closed"!=this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){debug("flushing %d packets in socket",this.writeBuffer.length);this.transport.send(this.writeBuffer);this.prevBufferLen=this.writeBuffer.length;this.emit("flush")}};Socket.prototype.write=Socket.prototype.send=function(msg,options,fn){this.sendPacket("message",msg,options,fn);return this};Socket.prototype.sendPacket=function(type,data,options,fn){if("function"==typeof data){fn=data;data=undefined}if("function"==typeof options){fn=options;options=null}if("closing"==this.readyState||"closed"==this.readyState){return}options=options||{};options.compress=false!==options.compress;var packet={type:type,data:data,options:options};this.emit("packetCreate",packet);this.writeBuffer.push(packet);if(fn)this.once("flush",fn);this.flush()};Socket.prototype.close=function(){if("opening"==this.readyState||"open"==this.readyState){this.readyState="closing";var self=this;if(this.writeBuffer.length){this.once("drain",function(){if(this.upgrading){waitForUpgrade()}else{close()}})}else if(this.upgrading){waitForUpgrade()}else{close()}}function close(){self.onClose("forced close");debug("socket closing - telling transport to close");self.transport.close()}function cleanupAndClose(){self.removeListener("upgrade",cleanupAndClose);self.removeListener("upgradeError",cleanupAndClose);close()}function waitForUpgrade(){self.once("upgrade",cleanupAndClose);self.once("upgradeError",cleanupAndClose)}return this};Socket.prototype.onError=function(err){debug("socket error %j",err);Socket.priorWebsocketSuccess=false;this.emit("error",err);this.onClose("transport error",err)};Socket.prototype.onClose=function(reason,desc){if("opening"==this.readyState||"open"==this.readyState||"closing"==this.readyState){debug('socket close with reason: "%s"',reason);var self=this;clearTimeout(this.pingIntervalTimer);clearTimeout(this.pingTimeoutTimer);this.transport.removeAllListeners("close");this.transport.close();this.transport.removeAllListeners();this.readyState="closed";this.id=null;this.emit("close",reason,desc);self.writeBuffer=[];self.prevBufferLen=0}};Socket.prototype.filterUpgrades=function(upgrades){var filteredUpgrades=[];for(var i=0,j=upgrades.length;i<j;i++){if(~index(this.transports,upgrades[i]))filteredUpgrades.push(upgrades[i])}return filteredUpgrades}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./transport":16,"./transports":17,"component-emitter":12,debug:24,"engine.io-parser":27,indexof:37,parsejson:38,parseqs:39,parseuri:40}],16:[function(require,module,exports){var parser=require("engine.io-parser");var Emitter=require("component-emitter");module.exports=Transport;function Transport(opts){this.path=opts.path;this.hostname=opts.hostname;this.port=opts.port;this.secure=opts.secure;this.query=opts.query;this.timestampParam=opts.timestampParam;this.timestampRequests=opts.timestampRequests;this.readyState="";this.agent=opts.agent||false;this.socket=opts.socket;this.enablesXDR=opts.enablesXDR;this.pfx=opts.pfx;this.key=opts.key;this.passphrase=opts.passphrase;this.cert=opts.cert;this.ca=opts.ca;this.ciphers=opts.ciphers;this.rejectUnauthorized=opts.rejectUnauthorized;this.extraHeaders=opts.extraHeaders}Emitter(Transport.prototype);Transport.prototype.onError=function(msg,desc){var err=new Error(msg);err.type="TransportError";err.description=desc;this.emit("error",err);return this};Transport.prototype.open=function(){if("closed"==this.readyState||""==this.readyState){this.readyState="opening";this.doOpen()}return this};Transport.prototype.close=function(){if("opening"==this.readyState||"open"==this.readyState){this.doClose();this.onClose()}return this};Transport.prototype.send=function(packets){if("open"==this.readyState){this.write(packets)}else{throw new Error("Transport not open")}};Transport.prototype.onOpen=function(){this.readyState="open";this.writable=true;this.emit("open")};Transport.prototype.onData=function(data){var packet=parser.decodePacket(data,this.socket.binaryType);this.onPacket(packet)};Transport.prototype.onPacket=function(packet){this.emit("packet",packet)};Transport.prototype.onClose=function(){this.readyState="closed";this.emit("close")}},{"component-emitter":12,"engine.io-parser":27}],17:[function(require,module,exports){(function(global){var XMLHttpRequest=require("xmlhttprequest-ssl");var XHR=require("./polling-xhr");var JSONP=require("./polling-jsonp");var websocket=require("./websocket");exports.polling=polling;exports.websocket=websocket;function polling(opts){var xhr;var xd=false;var xs=false;var jsonp=false!==opts.jsonp;if(global.location){var isSSL="https:"==location.protocol;var port=location.port;if(!port){port=isSSL?443:80}xd=opts.hostname!=location.hostname||port!=opts.port;xs=opts.secure!=isSSL}opts.xdomain=xd;opts.xscheme=xs;xhr=new XMLHttpRequest(opts);if("open"in xhr&&!opts.forceJSONP){return new XHR(opts)}else{if(!jsonp)throw new Error("JSONP disabled");return new JSONP(opts)}}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./polling-jsonp":18,"./polling-xhr":19,"./websocket":21,"xmlhttprequest-ssl":22}],18:[function(require,module,exports){(function(global){var Polling=require("./polling");var inherit=require("component-inherit");module.exports=JSONPPolling;var rNewline=/\n/g;var rEscapedNewline=/\\n/g;var callbacks;var index=0;function empty(){}function JSONPPolling(opts){Polling.call(this,opts);this.query=this.query||{};if(!callbacks){if(!global.___eio)global.___eio=[];callbacks=global.___eio}this.index=callbacks.length;var self=this;callbacks.push(function(msg){self.onData(msg)});this.query.j=this.index;if(global.document&&global.addEventListener){global.addEventListener("beforeunload",function(){if(self.script)self.script.onerror=empty},false)}}inherit(JSONPPolling,Polling);JSONPPolling.prototype.supportsBinary=false;JSONPPolling.prototype.doClose=function(){if(this.script){this.script.parentNode.removeChild(this.script);this.script=null}if(this.form){this.form.parentNode.removeChild(this.form);this.form=null;this.iframe=null}Polling.prototype.doClose.call(this)};JSONPPolling.prototype.doPoll=function(){var self=this;var script=document.createElement("script");if(this.script){this.script.parentNode.removeChild(this.script);this.script=null}script.async=true;script.src=this.uri();script.onerror=function(e){self.onError("jsonp poll error",e)};var insertAt=document.getElementsByTagName("script")[0];if(insertAt){insertAt.parentNode.insertBefore(script,insertAt)}else{(document.head||document.body).appendChild(script)}this.script=script;var isUAgecko="undefined"!=typeof navigator&&/gecko/i.test(navigator.userAgent);if(isUAgecko){setTimeout(function(){var iframe=document.createElement("iframe");document.body.appendChild(iframe);document.body.removeChild(iframe)},100)}};JSONPPolling.prototype.doWrite=function(data,fn){var self=this;if(!this.form){var form=document.createElement("form");var area=document.createElement("textarea");var id=this.iframeId="eio_iframe_"+this.index;var iframe;form.className="socketio";form.style.position="absolute";form.style.top="-1000px";form.style.left="-1000px";form.target=id;form.method="POST";form.setAttribute("accept-charset","utf-8");area.name="d";form.appendChild(area);document.body.appendChild(form);this.form=form;this.area=area}this.form.action=this.uri();function complete(){initIframe();fn()}function initIframe(){if(self.iframe){try{self.form.removeChild(self.iframe)}catch(e){self.onError("jsonp polling iframe removal error",e)}}try{var html='<iframe src="javascript:0" name="'+self.iframeId+'">';iframe=document.createElement(html)}catch(e){iframe=document.createElement("iframe");iframe.name=self.iframeId;iframe.src="javascript:0"}iframe.id=self.iframeId;self.form.appendChild(iframe);self.iframe=iframe}initIframe();data=data.replace(rEscapedNewline,"\\\n");this.area.value=data.replace(rNewline,"\\n");try{this.form.submit()}catch(e){}if(this.iframe.attachEvent){this.iframe.onreadystatechange=function(){if(self.iframe.readyState=="complete"){complete()}}}else{this.iframe.onload=complete}}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./polling":20,"component-inherit":23}],19:[function(require,module,exports){(function(global){var XMLHttpRequest=require("xmlhttprequest-ssl");var Polling=require("./polling");var Emitter=require("component-emitter");var inherit=require("component-inherit");var debug=require("debug")("engine.io-client:polling-xhr");module.exports=XHR;module.exports.Request=Request;function empty(){}function XHR(opts){Polling.call(this,opts);if(global.location){var isSSL="https:"==location.protocol;var port=location.port;if(!port){port=isSSL?443:80}this.xd=opts.hostname!=global.location.hostname||port!=opts.port;this.xs=opts.secure!=isSSL}else{this.extraHeaders=opts.extraHeaders}}inherit(XHR,Polling);XHR.prototype.supportsBinary=true;XHR.prototype.request=function(opts){opts=opts||{};opts.uri=this.uri();opts.xd=this.xd;opts.xs=this.xs;opts.agent=this.agent||false;opts.supportsBinary=this.supportsBinary;opts.enablesXDR=this.enablesXDR;opts.pfx=this.pfx;opts.key=this.key;opts.passphrase=this.passphrase;opts.cert=this.cert;opts.ca=this.ca;opts.ciphers=this.ciphers;opts.rejectUnauthorized=this.rejectUnauthorized;opts.extraHeaders=this.extraHeaders;return new Request(opts)};XHR.prototype.doWrite=function(data,fn){var isBinary=typeof data!=="string"&&data!==undefined;var req=this.request({method:"POST",data:data,isBinary:isBinary});var self=this;req.on("success",fn);req.on("error",function(err){self.onError("xhr post error",err)});this.sendXhr=req};XHR.prototype.doPoll=function(){debug("xhr poll");var req=this.request();var self=this;req.on("data",function(data){self.onData(data)});req.on("error",function(err){self.onError("xhr poll error",err)});this.pollXhr=req};function Request(opts){this.method=opts.method||"GET";this.uri=opts.uri;this.xd=!!opts.xd;this.xs=!!opts.xs;this.async=false!==opts.async;this.data=undefined!=opts.data?opts.data:null;this.agent=opts.agent;this.isBinary=opts.isBinary;this.supportsBinary=opts.supportsBinary;this.enablesXDR=opts.enablesXDR;this.pfx=opts.pfx;this.key=opts.key;this.passphrase=opts.passphrase;this.cert=opts.cert;this.ca=opts.ca;this.ciphers=opts.ciphers;this.rejectUnauthorized=opts.rejectUnauthorized;this.extraHeaders=opts.extraHeaders;this.create()}Emitter(Request.prototype);Request.prototype.create=function(){var opts={agent:this.agent,xdomain:this.xd,xscheme:this.xs,enablesXDR:this.enablesXDR};opts.pfx=this.pfx;opts.key=this.key;opts.passphrase=this.passphrase;opts.cert=this.cert;opts.ca=this.ca;opts.ciphers=this.ciphers;opts.rejectUnauthorized=this.rejectUnauthorized;var xhr=this.xhr=new XMLHttpRequest(opts);var self=this;try{debug("xhr open %s: %s",this.method,this.uri);xhr.open(this.method,this.uri,this.async);try{if(this.extraHeaders){xhr.setDisableHeaderCheck(true);for(var i in this.extraHeaders){if(this.extraHeaders.hasOwnProperty(i)){xhr.setRequestHeader(i,this.extraHeaders[i])}}}}catch(e){}if(this.supportsBinary){xhr.responseType="arraybuffer"}if("POST"==this.method){try{if(this.isBinary){xhr.setRequestHeader("Content-type","application/octet-stream")}else{xhr.setRequestHeader("Content-type","text/plain;charset=UTF-8")}}catch(e){}}if("withCredentials"in xhr){xhr.withCredentials=true}if(this.hasXDR()){xhr.onload=function(){self.onLoad()};xhr.onerror=function(){self.onError(xhr.responseText)}}else{xhr.onreadystatechange=function(){if(4!=xhr.readyState)return;if(200==xhr.status||1223==xhr.status){self.onLoad()}else{setTimeout(function(){self.onError(xhr.status)},0)}}}debug("xhr data %s",this.data);xhr.send(this.data)}catch(e){setTimeout(function(){self.onError(e)},0);return}if(global.document){this.index=Request.requestsCount++;Request.requests[this.index]=this}};Request.prototype.onSuccess=function(){this.emit("success");this.cleanup()};Request.prototype.onData=function(data){this.emit("data",data);this.onSuccess()};Request.prototype.onError=function(err){this.emit("error",err);this.cleanup(true)};Request.prototype.cleanup=function(fromError){if("undefined"==typeof this.xhr||null===this.xhr){return}if(this.hasXDR()){this.xhr.onload=this.xhr.onerror=empty}else{this.xhr.onreadystatechange=empty}if(fromError){try{this.xhr.abort()}catch(e){}}if(global.document){delete Request.requests[this.index]}this.xhr=null};Request.prototype.onLoad=function(){var data;try{var contentType;try{contentType=this.xhr.getResponseHeader("Content-Type").split(";")[0]}catch(e){}if(contentType==="application/octet-stream"){data=this.xhr.response}else{if(!this.supportsBinary){data=this.xhr.responseText}else{try{data=String.fromCharCode.apply(null,new Uint8Array(this.xhr.response))}catch(e){var ui8Arr=new Uint8Array(this.xhr.response);var dataArray=[];for(var idx=0,length=ui8Arr.length;idx<length;idx++){dataArray.push(ui8Arr[idx])}data=String.fromCharCode.apply(null,dataArray)}}}}catch(e){this.onError(e)}if(null!=data){this.onData(data)}};Request.prototype.hasXDR=function(){return"undefined"!==typeof global.XDomainRequest&&!this.xs&&this.enablesXDR};Request.prototype.abort=function(){this.cleanup()};if(global.document){Request.requestsCount=0;Request.requests={};if(global.attachEvent){global.attachEvent("onunload",unloadHandler)}else if(global.addEventListener){global.addEventListener("beforeunload",unloadHandler,false)}}function unloadHandler(){for(var i in Request.requests){if(Request.requests.hasOwnProperty(i)){Request.requests[i].abort()}}}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./polling":20,"component-emitter":12,"component-inherit":23,debug:24,"xmlhttprequest-ssl":22}],20:[function(require,module,exports){var Transport=require("../transport");var parseqs=require("parseqs");var parser=require("engine.io-parser");var inherit=require("component-inherit");var yeast=require("yeast");var debug=require("debug")("engine.io-client:polling");module.exports=Polling;var hasXHR2=function(){var XMLHttpRequest=require("xmlhttprequest-ssl");var xhr=new XMLHttpRequest({xdomain:false});return null!=xhr.responseType}();function Polling(opts){var forceBase64=opts&&opts.forceBase64;if(!hasXHR2||forceBase64){this.supportsBinary=false}Transport.call(this,opts)}inherit(Polling,Transport);Polling.prototype.name="polling";Polling.prototype.doOpen=function(){this.poll()};Polling.prototype.pause=function(onPause){var pending=0;var self=this;this.readyState="pausing";function pause(){debug("paused");self.readyState="paused";onPause()}if(this.polling||!this.writable){var total=0;if(this.polling){debug("we are currently polling - waiting to pause");total++;this.once("pollComplete",function(){debug("pre-pause polling complete");--total||pause()})}if(!this.writable){debug("we are currently writing - waiting to pause");total++;this.once("drain",function(){debug("pre-pause writing complete");--total||pause()})}}else{pause()}};Polling.prototype.poll=function(){debug("polling");this.polling=true;this.doPoll();this.emit("poll")};Polling.prototype.onData=function(data){var self=this;debug("polling got data %s",data);var callback=function(packet,index,total){if("opening"==self.readyState){self.onOpen()}if("close"==packet.type){self.onClose();return false}self.onPacket(packet)};parser.decodePayload(data,this.socket.binaryType,callback);if("closed"!=this.readyState){this.polling=false;this.emit("pollComplete");if("open"==this.readyState){this.poll()}else{debug('ignoring poll - transport state "%s"',this.readyState)}}};Polling.prototype.doClose=function(){var self=this;function close(){debug("writing close packet");self.write([{type:"close"}])}if("open"==this.readyState){debug("transport open - closing");close()}else{debug("transport not open - deferring close");this.once("open",close)}};Polling.prototype.write=function(packets){var self=this;this.writable=false;var callbackfn=function(){self.writable=true;self.emit("drain")};var self=this;parser.encodePayload(packets,this.supportsBinary,function(data){self.doWrite(data,callbackfn)})};Polling.prototype.uri=function(){var query=this.query||{};var schema=this.secure?"https":"http";var port="";if(false!==this.timestampRequests){query[this.timestampParam]=yeast()}if(!this.supportsBinary&&!query.sid){query.b64=1}query=parseqs.encode(query);if(this.port&&("https"==schema&&this.port!=443||"http"==schema&&this.port!=80)){port=":"+this.port}if(query.length){query="?"+query}var ipv6=this.hostname.indexOf(":")!==-1;return schema+"://"+(ipv6?"["+this.hostname+"]":this.hostname)+port+this.path+query}},{"../transport":16,"component-inherit":23,debug:24,"engine.io-parser":27,parseqs:39,"xmlhttprequest-ssl":22,yeast:41}],21:[function(require,module,exports){(function(global){var Transport=require("../transport");var parser=require("engine.io-parser");var parseqs=require("parseqs");var inherit=require("component-inherit");var yeast=require("yeast");var debug=require("debug")("engine.io-client:websocket");var BrowserWebSocket=global.WebSocket||global.MozWebSocket;var WebSocket=BrowserWebSocket;if(!WebSocket&&typeof window==="undefined"){try{WebSocket=require("ws")}catch(e){}}module.exports=WS;function WS(opts){var forceBase64=opts&&opts.forceBase64;if(forceBase64){this.supportsBinary=false}this.perMessageDeflate=opts.perMessageDeflate;Transport.call(this,opts)}inherit(WS,Transport);WS.prototype.name="websocket";WS.prototype.supportsBinary=true;WS.prototype.doOpen=function(){if(!this.check()){return}var self=this;var uri=this.uri();var protocols=void 0;var opts={agent:this.agent,perMessageDeflate:this.perMessageDeflate};opts.pfx=this.pfx;opts.key=this.key;opts.passphrase=this.passphrase;opts.cert=this.cert;opts.ca=this.ca;opts.ciphers=this.ciphers;opts.rejectUnauthorized=this.rejectUnauthorized;if(this.extraHeaders){opts.headers=this.extraHeaders}this.ws=BrowserWebSocket?new WebSocket(uri):new WebSocket(uri,protocols,opts);if(this.ws.binaryType===undefined){ | |
this.supportsBinary=false}if(this.ws.supports&&this.ws.supports.binary){this.supportsBinary=true;this.ws.binaryType="buffer"}else{this.ws.binaryType="arraybuffer"}this.addEventListeners()};WS.prototype.addEventListeners=function(){var self=this;this.ws.onopen=function(){self.onOpen()};this.ws.onclose=function(){self.onClose()};this.ws.onmessage=function(ev){self.onData(ev.data)};this.ws.onerror=function(e){self.onError("websocket error",e)}};if("undefined"!=typeof navigator&&/iPad|iPhone|iPod/i.test(navigator.userAgent)){WS.prototype.onData=function(data){var self=this;setTimeout(function(){Transport.prototype.onData.call(self,data)},0)}}WS.prototype.write=function(packets){var self=this;this.writable=false;var total=packets.length;for(var i=0,l=total;i<l;i++){(function(packet){parser.encodePacket(packet,self.supportsBinary,function(data){if(!BrowserWebSocket){var opts={};if(packet.options){opts.compress=packet.options.compress}if(self.perMessageDeflate){var len="string"==typeof data?global.Buffer.byteLength(data):data.length;if(len<self.perMessageDeflate.threshold){opts.compress=false}}}try{if(BrowserWebSocket){self.ws.send(data)}else{self.ws.send(data,opts)}}catch(e){debug("websocket closed before onclose event")}--total||done()})})(packets[i])}function done(){self.emit("flush");setTimeout(function(){self.writable=true;self.emit("drain")},0)}};WS.prototype.onClose=function(){Transport.prototype.onClose.call(this)};WS.prototype.doClose=function(){if(typeof this.ws!=="undefined"){this.ws.close()}};WS.prototype.uri=function(){var query=this.query||{};var schema=this.secure?"wss":"ws";var port="";if(this.port&&("wss"==schema&&this.port!=443||"ws"==schema&&this.port!=80)){port=":"+this.port}if(this.timestampRequests){query[this.timestampParam]=yeast()}if(!this.supportsBinary){query.b64=1}query=parseqs.encode(query);if(query.length){query="?"+query}var ipv6=this.hostname.indexOf(":")!==-1;return schema+"://"+(ipv6?"["+this.hostname+"]":this.hostname)+port+this.path+query};WS.prototype.check=function(){return!!WebSocket&&!("__initialize"in WebSocket&&this.name===WS.prototype.name)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../transport":16,"component-inherit":23,debug:24,"engine.io-parser":27,parseqs:39,ws:1,yeast:41}],22:[function(require,module,exports){var hasCORS=require("has-cors");module.exports=function(opts){var xdomain=opts.xdomain;var xscheme=opts.xscheme;var enablesXDR=opts.enablesXDR;try{if("undefined"!=typeof XMLHttpRequest&&(!xdomain||hasCORS)){return new XMLHttpRequest}}catch(e){}try{if("undefined"!=typeof XDomainRequest&&!xscheme&&enablesXDR){return new XDomainRequest}}catch(e){}if(!xdomain){try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}}},{"has-cors":36}],23:[function(require,module,exports){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}},{}],24:[function(require,module,exports){exports=module.exports=require("./debug");exports.log=log;exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:localstorage();exports.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"];function useColors(){return"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)||navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31}exports.formatters.j=function(v){return JSON.stringify(v)};function formatArgs(){var args=arguments;var useColors=this.useColors;args[0]=(useColors?"%c":"")+this.namespace+(useColors?" %c":" ")+args[0]+(useColors?"%c ":" ")+"+"+exports.humanize(this.diff);if(!useColors)return args;var c="color: "+this.color;args=[args[0],c,"color: inherit"].concat(Array.prototype.slice.call(args,1));var index=0;var lastC=0;args[0].replace(/%[a-z%]/g,function(match){if("%%"===match)return;index++;if("%c"===match){lastC=index}});args.splice(lastC,0,c);return args}function log(){return"object"===typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function save(namespaces){try{if(null==namespaces){exports.storage.removeItem("debug")}else{exports.storage.debug=namespaces}}catch(e){}}function load(){var r;try{r=exports.storage.debug}catch(e){}return r}exports.enable(load());function localstorage(){try{return window.localStorage}catch(e){}}},{"./debug":25}],25:[function(require,module,exports){exports=module.exports=debug;exports.coerce=coerce;exports.disable=disable;exports.enable=enable;exports.enabled=enabled;exports.humanize=require("ms");exports.names=[];exports.skips=[];exports.formatters={};var prevColor=0;var prevTime;function selectColor(){return exports.colors[prevColor++%exports.colors.length]}function debug(namespace){function disabled(){}disabled.enabled=false;function enabled(){var self=enabled;var curr=+new Date;var ms=curr-(prevTime||curr);self.diff=ms;self.prev=prevTime;self.curr=curr;prevTime=curr;if(null==self.useColors)self.useColors=exports.useColors();if(null==self.color&&self.useColors)self.color=selectColor();var args=Array.prototype.slice.call(arguments);args[0]=exports.coerce(args[0]);if("string"!==typeof args[0]){args=["%o"].concat(args)}var index=0;args[0]=args[0].replace(/%([a-z%])/g,function(match,format){if(match==="%%")return match;index++;var formatter=exports.formatters[format];if("function"===typeof formatter){var val=args[index];match=formatter.call(self,val);args.splice(index,1);index--}return match});if("function"===typeof exports.formatArgs){args=exports.formatArgs.apply(self,args)}var logFn=enabled.log||exports.log||console.log.bind(console);logFn.apply(self,args)}enabled.enabled=true;var fn=exports.enabled(namespace)?enabled:disabled;fn.namespace=namespace;return fn}function enable(namespaces){exports.save(namespaces);var split=(namespaces||"").split(/[\s,]+/);var len=split.length;for(var i=0;i<len;i++){if(!split[i])continue;namespaces=split[i].replace(/\*/g,".*?");if(namespaces[0]==="-"){exports.skips.push(new RegExp("^"+namespaces.substr(1)+"$"))}else{exports.names.push(new RegExp("^"+namespaces+"$"))}}}function disable(){exports.enable("")}function enabled(name){var i,len;for(i=0,len=exports.skips.length;i<len;i++){if(exports.skips[i].test(name)){return false}}for(i=0,len=exports.names.length;i<len;i++){if(exports.names[i].test(name)){return true}}return false}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{ms:26}],26:[function(require,module,exports){var s=1e3;var m=s*60;var h=m*60;var d=h*24;var y=d*365.25;module.exports=function(val,options){options=options||{};if("string"==typeof val)return parse(val);return options.long?long(val):short(val)};function parse(str){str=""+str;if(str.length>1e4)return;var match=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);if(!match)return;var n=parseFloat(match[1]);var type=(match[2]||"ms").toLowerCase();switch(type){case"years":case"year":case"yrs":case"yr":case"y":return n*y;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"hrs":case"hr":case"h":return n*h;case"minutes":case"minute":case"mins":case"min":case"m":return n*m;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n}}function short(ms){if(ms>=d)return Math.round(ms/d)+"d";if(ms>=h)return Math.round(ms/h)+"h";if(ms>=m)return Math.round(ms/m)+"m";if(ms>=s)return Math.round(ms/s)+"s";return ms+"ms"}function long(ms){return plural(ms,d,"day")||plural(ms,h,"hour")||plural(ms,m,"minute")||plural(ms,s,"second")||ms+" ms"}function plural(ms,n,name){if(ms<n)return;if(ms<n*1.5)return Math.floor(ms/n)+" "+name;return Math.ceil(ms/n)+" "+name+"s"}},{}],27:[function(require,module,exports){(function(global){var keys=require("./keys");var hasBinary=require("has-binary");var sliceBuffer=require("arraybuffer.slice");var base64encoder=require("base64-arraybuffer");var after=require("after");var utf8=require("utf8");var isAndroid=navigator.userAgent.match(/Android/i);var isPhantomJS=/PhantomJS/i.test(navigator.userAgent);var dontSendBlobs=isAndroid||isPhantomJS;exports.protocol=3;var packets=exports.packets={open:0,close:1,ping:2,pong:3,message:4,upgrade:5,noop:6};var packetslist=keys(packets);var err={type:"error",data:"parser error"};var Blob=require("blob");exports.encodePacket=function(packet,supportsBinary,utf8encode,callback){if("function"==typeof supportsBinary){callback=supportsBinary;supportsBinary=false}if("function"==typeof utf8encode){callback=utf8encode;utf8encode=null}var data=packet.data===undefined?undefined:packet.data.buffer||packet.data;if(global.ArrayBuffer&&data instanceof ArrayBuffer){return encodeArrayBuffer(packet,supportsBinary,callback)}else if(Blob&&data instanceof global.Blob){return encodeBlob(packet,supportsBinary,callback)}if(data&&data.base64){return encodeBase64Object(packet,callback)}var encoded=packets[packet.type];if(undefined!==packet.data){encoded+=utf8encode?utf8.encode(String(packet.data)):String(packet.data)}return callback(""+encoded)};function encodeBase64Object(packet,callback){var message="b"+exports.packets[packet.type]+packet.data.data;return callback(message)}function encodeArrayBuffer(packet,supportsBinary,callback){if(!supportsBinary){return exports.encodeBase64Packet(packet,callback)}var data=packet.data;var contentArray=new Uint8Array(data);var resultBuffer=new Uint8Array(1+data.byteLength);resultBuffer[0]=packets[packet.type];for(var i=0;i<contentArray.length;i++){resultBuffer[i+1]=contentArray[i]}return callback(resultBuffer.buffer)}function encodeBlobAsArrayBuffer(packet,supportsBinary,callback){if(!supportsBinary){return exports.encodeBase64Packet(packet,callback)}var fr=new FileReader;fr.onload=function(){packet.data=fr.result;exports.encodePacket(packet,supportsBinary,true,callback)};return fr.readAsArrayBuffer(packet.data)}function encodeBlob(packet,supportsBinary,callback){if(!supportsBinary){return exports.encodeBase64Packet(packet,callback)}if(dontSendBlobs){return encodeBlobAsArrayBuffer(packet,supportsBinary,callback)}var length=new Uint8Array(1);length[0]=packets[packet.type];var blob=new Blob([length.buffer,packet.data]);return callback(blob)}exports.encodeBase64Packet=function(packet,callback){var message="b"+exports.packets[packet.type];if(Blob&&packet.data instanceof global.Blob){var fr=new FileReader;fr.onload=function(){var b64=fr.result.split(",")[1];callback(message+b64)};return fr.readAsDataURL(packet.data)}var b64data;try{b64data=String.fromCharCode.apply(null,new Uint8Array(packet.data))}catch(e){var typed=new Uint8Array(packet.data);var basic=new Array(typed.length);for(var i=0;i<typed.length;i++){basic[i]=typed[i]}b64data=String.fromCharCode.apply(null,basic)}message+=global.btoa(b64data);return callback(message)};exports.decodePacket=function(data,binaryType,utf8decode){if(typeof data=="string"||data===undefined){if(data.charAt(0)=="b"){return exports.decodeBase64Packet(data.substr(1),binaryType)}if(utf8decode){try{data=utf8.decode(data)}catch(e){return err}}var type=data.charAt(0);if(Number(type)!=type||!packetslist[type]){return err}if(data.length>1){return{type:packetslist[type],data:data.substring(1)}}else{return{type:packetslist[type]}}}var asArray=new Uint8Array(data);var type=asArray[0];var rest=sliceBuffer(data,1);if(Blob&&binaryType==="blob"){rest=new Blob([rest])}return{type:packetslist[type],data:rest}};exports.decodeBase64Packet=function(msg,binaryType){var type=packetslist[msg.charAt(0)];if(!global.ArrayBuffer){return{type:type,data:{base64:true,data:msg.substr(1)}}}var data=base64encoder.decode(msg.substr(1));if(binaryType==="blob"&&Blob){data=new Blob([data])}return{type:type,data:data}};exports.encodePayload=function(packets,supportsBinary,callback){if(typeof supportsBinary=="function"){callback=supportsBinary;supportsBinary=null}var isBinary=hasBinary(packets);if(supportsBinary&&isBinary){if(Blob&&!dontSendBlobs){return exports.encodePayloadAsBlob(packets,callback)}return exports.encodePayloadAsArrayBuffer(packets,callback)}if(!packets.length){return callback("0:")}function setLengthHeader(message){return message.length+":"+message}function encodeOne(packet,doneCallback){exports.encodePacket(packet,!isBinary?false:supportsBinary,true,function(message){doneCallback(null,setLengthHeader(message))})}map(packets,encodeOne,function(err,results){return callback(results.join(""))})};function map(ary,each,done){var result=new Array(ary.length);var next=after(ary.length,done);var eachWithIndex=function(i,el,cb){each(el,function(error,msg){result[i]=msg;cb(error,result)})};for(var i=0;i<ary.length;i++){eachWithIndex(i,ary[i],next)}}exports.decodePayload=function(data,binaryType,callback){if(typeof data!="string"){return exports.decodePayloadAsBinary(data,binaryType,callback)}if(typeof binaryType==="function"){callback=binaryType;binaryType=null}var packet;if(data==""){return callback(err,0,1)}var length="",n,msg;for(var i=0,l=data.length;i<l;i++){var chr=data.charAt(i);if(":"!=chr){length+=chr}else{if(""==length||length!=(n=Number(length))){return callback(err,0,1)}msg=data.substr(i+1,n);if(length!=msg.length){return callback(err,0,1)}if(msg.length){packet=exports.decodePacket(msg,binaryType,true);if(err.type==packet.type&&err.data==packet.data){return callback(err,0,1)}var ret=callback(packet,i+n,l);if(false===ret)return}i+=n;length=""}}if(length!=""){return callback(err,0,1)}};exports.encodePayloadAsArrayBuffer=function(packets,callback){if(!packets.length){return callback(new ArrayBuffer(0))}function encodeOne(packet,doneCallback){exports.encodePacket(packet,true,true,function(data){return doneCallback(null,data)})}map(packets,encodeOne,function(err,encodedPackets){var totalLength=encodedPackets.reduce(function(acc,p){var len;if(typeof p==="string"){len=p.length}else{len=p.byteLength}return acc+len.toString().length+len+2},0);var resultArray=new Uint8Array(totalLength);var bufferIndex=0;encodedPackets.forEach(function(p){var isString=typeof p==="string";var ab=p;if(isString){var view=new Uint8Array(p.length);for(var i=0;i<p.length;i++){view[i]=p.charCodeAt(i)}ab=view.buffer}if(isString){resultArray[bufferIndex++]=0}else{resultArray[bufferIndex++]=1}var lenStr=ab.byteLength.toString();for(var i=0;i<lenStr.length;i++){resultArray[bufferIndex++]=parseInt(lenStr[i])}resultArray[bufferIndex++]=255;var view=new Uint8Array(ab);for(var i=0;i<view.length;i++){resultArray[bufferIndex++]=view[i]}});return callback(resultArray.buffer)})};exports.encodePayloadAsBlob=function(packets,callback){function encodeOne(packet,doneCallback){exports.encodePacket(packet,true,true,function(encoded){var binaryIdentifier=new Uint8Array(1);binaryIdentifier[0]=1;if(typeof encoded==="string"){var view=new Uint8Array(encoded.length);for(var i=0;i<encoded.length;i++){view[i]=encoded.charCodeAt(i)}encoded=view.buffer;binaryIdentifier[0]=0}var len=encoded instanceof ArrayBuffer?encoded.byteLength:encoded.size;var lenStr=len.toString();var lengthAry=new Uint8Array(lenStr.length+1);for(var i=0;i<lenStr.length;i++){lengthAry[i]=parseInt(lenStr[i])}lengthAry[lenStr.length]=255;if(Blob){var blob=new Blob([binaryIdentifier.buffer,lengthAry.buffer,encoded]);doneCallback(null,blob)}})}map(packets,encodeOne,function(err,results){return callback(new Blob(results))})};exports.decodePayloadAsBinary=function(data,binaryType,callback){if(typeof binaryType==="function"){callback=binaryType;binaryType=null}var bufferTail=data;var buffers=[];var numberTooLong=false;while(bufferTail.byteLength>0){var tailArray=new Uint8Array(bufferTail);var isString=tailArray[0]===0;var msgLength="";for(var i=1;;i++){if(tailArray[i]==255)break;if(msgLength.length>310){numberTooLong=true;break}msgLength+=tailArray[i]}if(numberTooLong)return callback(err,0,1);bufferTail=sliceBuffer(bufferTail,2+msgLength.length);msgLength=parseInt(msgLength);var msg=sliceBuffer(bufferTail,0,msgLength);if(isString){try{msg=String.fromCharCode.apply(null,new Uint8Array(msg))}catch(e){var typed=new Uint8Array(msg);msg="";for(var i=0;i<typed.length;i++){msg+=String.fromCharCode(typed[i])}}}buffers.push(msg);bufferTail=sliceBuffer(bufferTail,msgLength)}var total=buffers.length;buffers.forEach(function(buffer,i){callback(exports.decodePacket(buffer,binaryType,true),i,total)})}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./keys":28,after:29,"arraybuffer.slice":30,"base64-arraybuffer":31,blob:32,"has-binary":33,utf8:35}],28:[function(require,module,exports){module.exports=Object.keys||function keys(obj){var arr=[];var has=Object.prototype.hasOwnProperty;for(var i in obj){if(has.call(obj,i)){arr.push(i)}}return arr}},{}],29:[function(require,module,exports){module.exports=after;function after(count,callback,err_cb){var bail=false;err_cb=err_cb||noop;proxy.count=count;return count===0?callback():proxy;function proxy(err,result){if(proxy.count<=0){throw new Error("after called too many times")}--proxy.count;if(err){bail=true;callback(err);callback=err_cb}else if(proxy.count===0&&!bail){callback(null,result)}}}function noop(){}},{}],30:[function(require,module,exports){module.exports=function(arraybuffer,start,end){var bytes=arraybuffer.byteLength;start=start||0;end=end||bytes;if(arraybuffer.slice){return arraybuffer.slice(start,end)}if(start<0){start+=bytes}if(end<0){end+=bytes}if(end>bytes){end=bytes}if(start>=bytes||start>=end||bytes===0){return new ArrayBuffer(0)}var abv=new Uint8Array(arraybuffer);var result=new Uint8Array(end-start);for(var i=start,ii=0;i<end;i++,ii++){result[ii]=abv[i]}return result.buffer}},{}],31:[function(require,module,exports){(function(chars){"use strict";exports.encode=function(arraybuffer){var bytes=new Uint8Array(arraybuffer),i,len=bytes.length,base64="";for(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};exports.decode=function(base64){var bufferLength=base64.length*.75,len=base64.length,i,p=0,encoded1,encoded2,encoded3,encoded4;if(base64[base64.length-1]==="="){bufferLength--;if(base64[base64.length-2]==="="){bufferLength--}}var arraybuffer=new ArrayBuffer(bufferLength),bytes=new Uint8Array(arraybuffer);for(i=0;i<len;i+=4){encoded1=chars.indexOf(base64[i]);encoded2=chars.indexOf(base64[i+1]);encoded3=chars.indexOf(base64[i+2]);encoded4=chars.indexOf(base64[i+3]);bytes[p++]=encoded1<<2|encoded2>>4;bytes[p++]=(encoded2&15)<<4|encoded3>>2;bytes[p++]=(encoded3&3)<<6|encoded4&63}return arraybuffer}})("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")},{}],32:[function(require,module,exports){(function(global){var BlobBuilder=global.BlobBuilder||global.WebKitBlobBuilder||global.MSBlobBuilder||global.MozBlobBuilder;var blobSupported=function(){try{var a=new Blob(["hi"]);return a.size===2}catch(e){return false}}();var blobSupportsArrayBufferView=blobSupported&&function(){try{var b=new Blob([new Uint8Array([1,2])]);return b.size===2}catch(e){return false}}();var blobBuilderSupported=BlobBuilder&&BlobBuilder.prototype.append&&BlobBuilder.prototype.getBlob;function mapArrayBufferViews(ary){for(var i=0;i<ary.length;i++){var chunk=ary[i];if(chunk.buffer instanceof ArrayBuffer){var buf=chunk.buffer;if(chunk.byteLength!==buf.byteLength){var copy=new Uint8Array(chunk.byteLength);copy.set(new Uint8Array(buf,chunk.byteOffset,chunk.byteLength));buf=copy.buffer}ary[i]=buf}}}function BlobBuilderConstructor(ary,options){options=options||{};var bb=new BlobBuilder;mapArrayBufferViews(ary);for(var i=0;i<ary.length;i++){bb.append(ary[i])}return options.type?bb.getBlob(options.type):bb.getBlob()}function BlobConstructor(ary,options){mapArrayBufferViews(ary);return new Blob(ary,options||{})}module.exports=function(){if(blobSupported){return blobSupportsArrayBufferView?global.Blob:BlobConstructor}else if(blobBuilderSupported){return BlobBuilderConstructor}else{return undefined}}()}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],33:[function(require,module,exports){(function(global){var isArray=require("isarray");module.exports=hasBinary;function hasBinary(data){function _hasBinary(obj){if(!obj)return false;if(global.Buffer&&global.Buffer.isBuffer(obj)||global.ArrayBuffer&&obj instanceof ArrayBuffer||global.Blob&&obj instanceof Blob||global.File&&obj instanceof File){return true}if(isArray(obj)){for(var i=0;i<obj.length;i++){if(_hasBinary(obj[i])){return true}}}else if(obj&&"object"==typeof obj){if(obj.toJSON){obj=obj.toJSON()}for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key)&&_hasBinary(obj[key])){return true}}}return false}return _hasBinary(data)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{isarray:34}],34:[function(require,module,exports){module.exports=Array.isArray||function(arr){return Object.prototype.toString.call(arr)=="[object Array]"}},{}],35:[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 stringFromCharCode=String.fromCharCode;function ucs2decode(string){var output=[];var counter=0;var length=string.length;var value;var extra;while(counter<length){value=string.charCodeAt(counter++);if(value>=55296&&value<=56319&&counter<length){extra=string.charCodeAt(counter++);if((extra&64512)==56320){output.push(((value&1023)<<10)+(extra&1023)+65536)}else{output.push(value);counter--}}else{output.push(value)}}return output}function ucs2encode(array){var length=array.length;var index=-1;var value;var output="";while(++index<length){value=array[index];if(value>65535){value-=65536;output+=stringFromCharCode(value>>>10&1023|55296);value=56320|value&1023}output+=stringFromCharCode(value)}return output}function checkScalarValue(codePoint){if(codePoint>=55296&&codePoint<=57343){throw Error("Lone surrogate U+"+codePoint.toString(16).toUpperCase()+" is not a scalar value")}}function createByte(codePoint,shift){return stringFromCharCode(codePoint>>shift&63|128)}function encodeCodePoint(codePoint){if((codePoint&4294967168)==0){return stringFromCharCode(codePoint)}var symbol="";if((codePoint&4294965248)==0){symbol=stringFromCharCode(codePoint>>6&31|192)}else if((codePoint&4294901760)==0){checkScalarValue(codePoint);symbol=stringFromCharCode(codePoint>>12&15|224);symbol+=createByte(codePoint,6)}else if((codePoint&4292870144)==0){symbol=stringFromCharCode(codePoint>>18&7|240);symbol+=createByte(codePoint,12);symbol+=createByte(codePoint,6)}symbol+=stringFromCharCode(codePoint&63|128);return symbol}function utf8encode(string){var codePoints=ucs2decode(string);var length=codePoints.length;var index=-1;var codePoint;var byteString="";while(++index<length){codePoint=codePoints[index];byteString+=encodeCodePoint(codePoint)}return byteString}function readContinuationByte(){if(byteIndex>=byteCount){throw Error("Invalid byte index")}var continuationByte=byteArray[byteIndex]&255;byteIndex++;if((continuationByte&192)==128){return continuationByte&63}throw Error("Invalid continuation byte")}function decodeSymbol(){var byte1;var byte2;var byte3;var byte4;var codePoint;if(byteIndex>byteCount){throw Error("Invalid byte index")}if(byteIndex==byteCount){return false}byte1=byteArray[byteIndex]&255;byteIndex++;if((byte1&128)==0){return byte1}if((byte1&224)==192){var byte2=readContinuationByte();codePoint=(byte1&31)<<6|byte2;if(codePoint>=128){return codePoint}else{throw Error("Invalid continuation byte")}}if((byte1&240)==224){byte2=readContinuationByte();byte3=readContinuationByte();codePoint=(byte1&15)<<12|byte2<<6|byte3;if(codePoint>=2048){checkScalarValue(codePoint);return codePoint}else{throw Error("Invalid continuation byte")}}if((byte1&248)==240){byte2=readContinuationByte();byte3=readContinuationByte();byte4=readContinuationByte();codePoint=(byte1&15)<<18|byte2<<12|byte3<<6|byte4;if(codePoint>=65536&&codePoint<=1114111){return codePoint}}throw Error("Invalid UTF-8 detected")}var byteArray;var byteCount;var byteIndex;function utf8decode(byteString){byteArray=ucs2decode(byteString);byteCount=byteArray.length;byteIndex=0;var codePoints=[];var tmp;while((tmp=decodeSymbol())!==false){codePoints.push(tmp)}return ucs2encode(codePoints)}var utf8={version:"2.0.0",encode:utf8encode,decode:utf8decode};if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return utf8})}else if(freeExports&&!freeExports.nodeType){if(freeModule){freeModule.exports=utf8}else{var object={};var hasOwnProperty=object.hasOwnProperty;for(var key in utf8){hasOwnProperty.call(utf8,key)&&(freeExports[key]=utf8[key])}}}else{root.utf8=utf8}})(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],36:[function(require,module,exports){try{module.exports=typeof XMLHttpRequest!=="undefined"&&"withCredentials"in new XMLHttpRequest}catch(err){module.exports=false}},{}],37:[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}},{}],38:[function(require,module,exports){(function(global){var rvalidchars=/^[\],:{}\s]*$/;var rvalidescape=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;var rvalidtokens=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;var rvalidbraces=/(?:^|:|,)(?:\s*\[)+/g;var rtrimLeft=/^\s+/;var rtrimRight=/\s+$/;module.exports=function parsejson(data){if("string"!=typeof data||!data){return null}data=data.replace(rtrimLeft,"").replace(rtrimRight,"");if(global.JSON&&JSON.parse){return JSON.parse(data)}if(rvalidchars.test(data.replace(rvalidescape,"@").replace(rvalidtokens,"]").replace(rvalidbraces,""))){return new Function("return "+data)()}}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],39:[function(require,module,exports){exports.encode=function(obj){var str="";for(var i in obj){if(obj.hasOwnProperty(i)){if(str.length)str+="&";str+=encodeURIComponent(i)+"="+encodeURIComponent(obj[i])}}return str};exports.decode=function(qs){var qry={};var pairs=qs.split("&");for(var i=0,l=pairs.length;i<l;i++){var pair=pairs[i].split("=");qry[decodeURIComponent(pair[0])]=decodeURIComponent(pair[1])}return qry}},{}],40:[function(require,module,exports){var re=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;var parts=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];module.exports=function parseuri(str){var src=str,b=str.indexOf("["),e=str.indexOf("]");if(b!=-1&&e!=-1){str=str.substring(0,b)+str.substring(b,e).replace(/:/g,";")+str.substring(e,str.length)}var m=re.exec(str||""),uri={},i=14;while(i--){uri[parts[i]]=m[i]||""}if(b!=-1&&e!=-1){uri.source=src;uri.host=uri.host.substring(1,uri.host.length-1).replace(/;/g,":");uri.authority=uri.authority.replace("[","").replace("]","").replace(/;/g,":");uri.ipv6uri=true}return uri}},{}],41:[function(require,module,exports){"use strict";var alphabet="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),length=64,map={},seed=0,i=0,prev;function encode(num){var encoded="";do{encoded=alphabet[num%length]+encoded;num=Math.floor(num/length)}while(num>0);return encoded}function decode(str){var decoded=0;for(i=0;i<str.length;i++){decoded=decoded*length+map[str.charAt(i)]}return decoded}function yeast(){var now=encode(+new Date);if(now!==prev)return seed=0,prev=now;return now+"."+encode(seed++)}for(;i<length;i++)map[alphabet[i]]=i;yeast.encode=encode;yeast.decode=decode;module.exports=yeast},{}],42:[function(require,module,exports){exports.CONNECTION_STATE={};exports.CONNECTION_STATE.CLOSED="CLOSED";exports.CONNECTION_STATE.AWAITING_CONNECTION="AWAITING_CONNECTION";exports.CONNECTION_STATE.CHALLENGING="CHALLENGING";exports.CONNECTION_STATE.AWAITING_AUTHENTICATION="AWAITING_AUTHENTICATION";exports.CONNECTION_STATE.AUTHENTICATING="AUTHENTICATING";exports.CONNECTION_STATE.OPEN="OPEN";exports.CONNECTION_STATE.ERROR="ERROR";exports.CONNECTION_STATE.RECONNECTING="RECONNECTING";exports.MESSAGE_SEPERATOR=String.fromCharCode(30);exports.MESSAGE_PART_SEPERATOR=String.fromCharCode(31);exports.TYPES={};exports.TYPES.STRING="S";exports.TYPES.OBJECT="O";exports.TYPES.NUMBER="N";exports.TYPES.NULL="L";exports.TYPES.TRUE="T";exports.TYPES.FALSE="F";exports.TYPES.UNDEFINED="U";exports.TOPIC={};exports.TOPIC.CONNECTION="C";exports.TOPIC.AUTH="A";exports.TOPIC.ERROR="X";exports.TOPIC.EVENT="E";exports.TOPIC.RECORD="R";exports.TOPIC.RPC="P";exports.TOPIC.WEBRTC="W";exports.TOPIC.PRIVATE="PRIVATE/";exports.EVENT={};exports.EVENT.CONNECTION_ERROR="connectionError";exports.EVENT.CONNECTION_STATE_CHANGED="connectionStateChanged";exports.EVENT.ACK_TIMEOUT="ACK_TIMEOUT";exports.EVENT.NO_RPC_PROVIDER="NO_RPC_PROVIDER";exports.EVENT.RESPONSE_TIMEOUT="RESPONSE_TIMEOUT";exports.EVENT.DELETE_TIMEOUT="DELETE_TIMEOUT";exports.EVENT.UNSOLICITED_MESSAGE="UNSOLICITED_MESSAGE";exports.EVENT.MESSAGE_DENIED="MESSAGE_DENIED";exports.EVENT.MESSAGE_PARSE_ERROR="MESSAGE_PARSE_ERROR";exports.EVENT.VERSION_EXISTS="VERSION_EXISTS";exports.EVENT.NOT_AUTHENTICATED="NOT_AUTHENTICATED";exports.EVENT.MESSAGE_PERMISSION_ERROR="MESSAGE_PERMISSION_ERROR";exports.EVENT.LISTENER_EXISTS="LISTENER_EXISTS";exports.EVENT.NOT_LISTENING="NOT_LISTENING";exports.EVENT.TOO_MANY_AUTH_ATTEMPTS="TOO_MANY_AUTH_ATTEMPTS";exports.EVENT.IS_CLOSED="IS_CLOSED";exports.EVENT.UNKNOWN_CALLEE="UNKNOWN_CALLEE";exports.EVENT.RECORD_NOT_FOUND="RECORD_NOT_FOUND";exports.ACTIONS={};exports.ACTIONS.ACK="A";exports.ACTIONS.REDIRECT="RED";exports.ACTIONS.CHALLENGE="CH";exports.ACTIONS.CHALLENGE_RESPONSE="CHR";exports.ACTIONS.READ="R";exports.ACTIONS.CREATE="C";exports.ACTIONS.UPDATE="U";exports.ACTIONS.PATCH="P";exports.ACTIONS.DELETE="D";exports.ACTIONS.SUBSCRIBE="S";exports.ACTIONS.UNSUBSCRIBE="US";exports.ACTIONS.HAS="H";exports.ACTIONS.SNAPSHOT="SN";exports.ACTIONS.INVOKE="I";exports.ACTIONS.SUBSCRIPTION_FOR_PATTERN_FOUND="SP";exports.ACTIONS.SUBSCRIPTION_FOR_PATTERN_REMOVED="SR";exports.ACTIONS.LISTEN="L";exports.ACTIONS.UNLISTEN="UL";exports.ACTIONS.PROVIDER_UPDATE="PU";exports.ACTIONS.QUERY="Q";exports.ACTIONS.CREATEORREAD="CR";exports.ACTIONS.EVENT="EVT";exports.ACTIONS.ERROR="E";exports.ACTIONS.REQUEST="REQ";exports.ACTIONS.RESPONSE="RES";exports.ACTIONS.REJECTION="REJ";exports.ACTIONS.WEBRTC_REGISTER_CALLEE="RC";exports.ACTIONS.WEBRTC_UNREGISTER_CALLEE="URC";exports.ACTIONS.WEBRTC_OFFER="OF";exports.ACTIONS.WEBRTC_ANSWER="AN";exports.ACTIONS.WEBRTC_ICE_CANDIDATE="IC";exports.ACTIONS.WEBRTC_CALL_DECLINED="CD";exports.ACTIONS.WEBRTC_CALL_ENDED="CE";exports.ACTIONS.WEBRTC_LISTEN_FOR_CALLEES="LC";exports.ACTIONS.WEBRTC_UNLISTEN_FOR_CALLEES="ULC";exports.ACTIONS.WEBRTC_ALL_CALLEES="WAC";exports.ACTIONS.WEBRTC_CALLEE_ADDED="WCA";exports.ACTIONS.WEBRTC_CALLEE_REMOVED="WCR";exports.ACTIONS.WEBRTC_IS_ALIVE="WIA";exports.CALL_STATE={};exports.CALL_STATE.INITIAL="INITIAL";exports.CALL_STATE.CONNECTING="CONNECTING";exports.CALL_STATE.ESTABLISHED="ESTABLISHED"; | |
exports.CALL_STATE.ACCEPTED="ACCEPTED";exports.CALL_STATE.DECLINED="DECLINED";exports.CALL_STATE.ENDED="ENDED";exports.CALL_STATE.ERROR="ERROR"},{}],43:[function(require,module,exports){module.exports={REMOTE_WINS:function(record,remoteValue,remoteVersion,callback){callback(null,remoteValue)},LOCAL_WINS:function(record,remoteValue,remoteVersion,callback){callback(null,record.get())}}},{}],44:[function(require,module,exports){var MERGE_STRATEGIES=require("./constants/merge-strategies");module.exports={recordPersistDefault:true,reconnectIntervalIncrement:4e3,maxReconnectAttempts:5,rpcAckTimeout:6e3,rpcResponseTimeout:1e4,subscriptionTimeout:2e3,maxMessagesPerPacket:100,timeBetweenSendingQueuedPackages:16,recordReadAckTimeout:1e3,recordReadTimeout:3e3,recordDeleteTimeout:3e3,calleeAckTimeout:3e3,rtcPeerConnectionConfig:{iceServers:[{url:"stun:stun.services.mozilla.com"},{url:"stun:stun.l.google.com:19302"}]},agent:false,upgrade:true,forceJSONP:false,jsonp:true,forceBase64:false,enablesXDR:false,timestampRequests:false,timestampParam:"t",policyPort:843,path:"/deepstream",transports:["polling","websocket"],rememberUpgrade:false,mergeStrategy:MERGE_STRATEGIES.REMOTE_WINS}},{"./constants/merge-strategies":43}],45:[function(require,module,exports){var messageBuilder=require("../message/message-builder"),messageParser=require("../message/message-parser"),AckTimeoutRegistry=require("../utils/ack-timeout-registry"),ResubscribeNotifier=require("../utils/resubscribe-notifier"),C=require("../constants/constants"),Listener=require("../utils/listener"),EventEmitter=require("component-emitter");var EventHandler=function(options,connection,client){this._options=options;this._connection=connection;this._client=client;this._emitter=new EventEmitter;this._listener={};this._ackTimeoutRegistry=new AckTimeoutRegistry(client,C.TOPIC.EVENT,this._options.subscriptionTimeout);this._resubscribeNotifier=new ResubscribeNotifier(this._client,this._resubscribe.bind(this))};EventHandler.prototype.subscribe=function(eventName,callback){if(!this._emitter.hasListeners(eventName)){this._ackTimeoutRegistry.add(eventName,C.ACTIONS.SUBSCRIBE);this._connection.sendMsg(C.TOPIC.EVENT,C.ACTIONS.SUBSCRIBE,[eventName])}this._emitter.on(eventName,callback)};EventHandler.prototype.unsubscribe=function(eventName,callback){this._emitter.off(eventName,callback);if(!this._emitter.hasListeners(eventName)){this._ackTimeoutRegistry.add(eventName,C.ACTIONS.UNSUBSCRIBE);this._connection.sendMsg(C.TOPIC.EVENT,C.ACTIONS.UNSUBSCRIBE,[eventName])}};EventHandler.prototype.emit=function(name,data){this._connection.sendMsg(C.TOPIC.EVENT,C.ACTIONS.EVENT,[name,messageBuilder.typed(data)]);this._emitter.emit(name,data)};EventHandler.prototype.listen=function(pattern,callback){if(this._listener[pattern]){this._client._$onError(C.TOPIC.EVENT,C.EVENT.LISTENER_EXISTS,pattern)}else{this._listener[pattern]=new Listener(C.TOPIC.EVENT,pattern,callback,this._options,this._client,this._connection)}};EventHandler.prototype.unlisten=function(pattern){if(this._listener[pattern]){this._ackTimeoutRegistry.add(pattern,C.EVENT.UNLISTEN);this._listener[pattern].destroy();delete this._listener[pattern]}else{this._client._$onError(C.TOPIC.EVENT,C.EVENT.NOT_LISTENING,pattern)}};EventHandler.prototype._$handle=function(message){var name=message.data[message.action===C.ACTIONS.ACK?1:0];if(message.action===C.ACTIONS.EVENT){if(message.data&&message.data.length===2){this._emitter.emit(name,messageParser.convertTyped(message.data[1],this._client))}else{this._emitter.emit(name)}return}if(this._listener[name]){this._listener[name]._$onMessage(message);return}if(message.action===C.ACTIONS.ACK){this._ackTimeoutRegistry.clear(message);return}if(message.action===C.ACTIONS.ERROR){message.processedError=true;this._client._$onError(C.TOPIC.EVENT,message.data[0],message.data[1]);return}this._client._$onError(C.TOPIC.EVENT,C.EVENT.UNSOLICITED_MESSAGE,name)};EventHandler.prototype._resubscribe=function(){var callbacks=this._emitter._callbacks;for(var eventName in callbacks){this._connection.sendMsg(C.TOPIC.EVENT,C.ACTIONS.SUBSCRIBE,[eventName])}};module.exports=EventHandler},{"../constants/constants":42,"../message/message-builder":47,"../message/message-parser":48,"../utils/ack-timeout-registry":58,"../utils/listener":59,"../utils/resubscribe-notifier":60,"component-emitter":12}],46:[function(require,module,exports){var engineIoClient=require("engine.io-client"),messageParser=require("./message-parser"),messageBuilder=require("./message-builder"),TcpConnection=require("../tcp/tcp-connection"),utils=require("../utils/utils"),C=require("../constants/constants");var Connection=function(client,url,options){this._client=client;this._originalUrl=url;this._url=url;this._options=options;this._authParams=null;this._authCallback=null;this._deliberateClose=false;this._redirecting=false;this._tooManyAuthAttempts=false;this._challengeDenied=false;this._queuedMessages=[];this._reconnectTimeout=null;this._reconnectionAttempt=0;this._currentPacketMessageCount=0;this._sendNextPacketTimeout=null;this._currentMessageResetTimeout=null;this._endpoint=null;this._state=C.CONNECTION_STATE.CLOSED;this._createEndpoint()};Connection.prototype.getState=function(){return this._state};Connection.prototype.authenticate=function(authParams,callback){this._authParams=authParams;this._authCallback=callback;if(this._tooManyAuthAttempts||this._challengeDenied){this._client._$onError(C.TOPIC.ERROR,C.EVENT.IS_CLOSED,"this client's connection was closed");return}else if(this._deliberateClose===true&&this._state===C.CONNECTION_STATE.CLOSED){this._createEndpoint();this._deliberateClose=false;return}if(this._state===C.CONNECTION_STATE.AWAITING_AUTHENTICATION){this._sendAuthParams()}};Connection.prototype.sendMsg=function(topic,action,data){this.send(messageBuilder.getMsg(topic,action,data))};Connection.prototype.send=function(message){this._queuedMessages.push(message);this._currentPacketMessageCount++;if(this._currentMessageResetTimeout===null){this._currentMessageResetTimeout=utils.nextTick(this._resetCurrentMessageCount.bind(this))}if(this._state===C.CONNECTION_STATE.OPEN&&this._queuedMessages.length<this._options.maxMessagesPerPacket&&this._currentPacketMessageCount<this._options.maxMessagesPerPacket){this._sendQueuedMessages()}else if(this._sendNextPacketTimeout===null){this._queueNextPacket()}};Connection.prototype.close=function(){this._deliberateClose=true;this._endpoint.close()};Connection.prototype._createEndpoint=function(){if(utils.isNode){this._endpoint=new TcpConnection(this._url)}else{this._endpoint=engineIoClient(this._url,this._options)}this._endpoint.on("open",this._onOpen.bind(this));this._endpoint.on("error",this._onError.bind(this));this._endpoint.on("close",this._onClose.bind(this));this._endpoint.on("message",this._onMessage.bind(this))};Connection.prototype._resetCurrentMessageCount=function(){this._currentPacketMessageCount=0;this._currentMessageResetTimeout=null};Connection.prototype._sendQueuedMessages=function(){if(this._state!==C.CONNECTION_STATE.OPEN){return}if(this._queuedMessages.length===0){this._sendNextPacketTimeout=null;return}var message=this._queuedMessages.splice(0,this._options.maxMessagesPerPacket).join("");if(this._queuedMessages.length!==0){this._queueNextPacket()}else{this._sendNextPacketTimeout=null}this._endpoint.send(message)};Connection.prototype._queueNextPacket=function(){var fn=this._sendQueuedMessages.bind(this),delay=this._options.timeBetweenSendingQueuedPackages;this._sendNextPacketTimeout=setTimeout(fn,delay)};Connection.prototype._sendAuthParams=function(){this._setState(C.CONNECTION_STATE.AUTHENTICATING);var authMessage=messageBuilder.getMsg(C.TOPIC.AUTH,C.ACTIONS.REQUEST,[this._authParams]);this._endpoint.send(authMessage)};Connection.prototype._onOpen=function(){this._clearReconnect();this._setState(C.CONNECTION_STATE.AWAITING_CONNECTION)};Connection.prototype._onError=function(error){this._setState(C.CONNECTION_STATE.ERROR);setTimeout(function(){this._client._$onError(null,C.EVENT.CONNECTION_ERROR,error.toString())}.bind(this),1)};Connection.prototype._onClose=function(){if(this._redirecting===true){this._redirecting=false;this._createEndpoint()}else if(this._deliberateClose===true){this._setState(C.CONNECTION_STATE.CLOSED)}else{if(this._originalUrl!==this._url){this._url=this._originalUrl;this._createEndpoint()}this._tryReconnect()}};Connection.prototype._onMessage=function(message){var parsedMessages=messageParser.parse(message,this._client),i;for(i=0;i<parsedMessages.length;i++){if(parsedMessages[i]===null){continue}else if(parsedMessages[i].topic===C.TOPIC.CONNECTION){this._handleConnectionResponse(parsedMessages[i])}else if(parsedMessages[i].topic===C.TOPIC.AUTH){this._handleAuthResponse(parsedMessages[i])}else{this._client._$onMessage(parsedMessages[i])}}};Connection.prototype._handleConnectionResponse=function(message){var data;if(message.action===C.ACTIONS.ACK){this._setState(C.CONNECTION_STATE.AWAITING_AUTHENTICATION);if(this._authParams){this._sendAuthParams()}}else if(message.action===C.ACTIONS.CHALLENGE){this._setState(C.CONNECTION_STATE.CHALLENGING);this._endpoint.send(messageBuilder.getMsg(C.TOPIC.CONNECTION,C.ACTIONS.CHALLENGE_RESPONSE,[this._originalUrl]))}else if(message.action===C.ACTIONS.REJECTION){this._challengeDenied=true;this.close()}else if(message.action===C.ACTIONS.REDIRECT){this._url=message.data[0];this._redirecting=true;this._endpoint.close()}};Connection.prototype._handleAuthResponse=function(message){var data;if(message.action===C.ACTIONS.ERROR){if(message.data[0]===C.EVENT.TOO_MANY_AUTH_ATTEMPTS){this._deliberateClose=true;this._tooManyAuthAttempts=true}else{this._setState(C.CONNECTION_STATE.AWAITING_AUTHENTICATION)}if(this._authCallback){this._authCallback(false,this._getAuthData(message.data[1]))}}else if(message.action===C.ACTIONS.ACK){this._setState(C.CONNECTION_STATE.OPEN);if(this._authCallback){this._authCallback(true,this._getAuthData(message.data[0]))}this._sendQueuedMessages()}};Connection.prototype._getAuthData=function(data){if(data===undefined){return null}else{return messageParser.convertTyped(data,this._client)}};Connection.prototype._setState=function(state){this._state=state;this._client.emit(C.EVENT.CONNECTION_STATE_CHANGED,state)};Connection.prototype._tryReconnect=function(){if(this._reconnectTimeout!==null){return}if(this._reconnectionAttempt<this._options.maxReconnectAttempts){this._setState(C.CONNECTION_STATE.RECONNECTING);this._reconnectTimeout=setTimeout(this._tryOpen.bind(this),this._options.reconnectIntervalIncrement*this._reconnectionAttempt);this._reconnectionAttempt++}else{this._clearReconnect();this.close()}};Connection.prototype._tryOpen=function(){this._endpoint.open();this._reconnectTimeout=null};Connection.prototype._clearReconnect=function(){clearTimeout(this._reconnectTimeout);this._reconnectTimeout=null;this._reconnectionAttempt=0};module.exports=Connection},{"../constants/constants":42,"../tcp/tcp-connection":57,"../utils/utils":62,"./message-builder":47,"./message-parser":48,"engine.io-client":13}],47:[function(require,module,exports){var C=require("../constants/constants"),SEP=C.MESSAGE_PART_SEPERATOR;exports.getMsg=function(topic,action,data){if(data&&!(data instanceof Array)){throw new Error("data must be an array")}var sendData=[topic,action],i;if(data){for(i=0;i<data.length;i++){if(typeof data[i]==="object"){sendData.push(JSON.stringify(data[i]))}else{sendData.push(data[i])}}}return sendData.join(SEP)+C.MESSAGE_SEPERATOR};exports.typed=function(value){var type=typeof value;if(type==="string"){return C.TYPES.STRING+value}if(value===null){return C.TYPES.NULL}if(type==="object"){return C.TYPES.OBJECT+JSON.stringify(value)}if(type==="number"){return C.TYPES.NUMBER+value.toString()}if(value===true){return C.TYPES.TRUE}if(value===false){return C.TYPES.FALSE}if(value===undefined){return C.TYPES.UNDEFINED}throw new Error("Can't serialize type "+value)}},{"../constants/constants":42}],48:[function(require,module,exports){var C=require("../constants/constants");var MessageParser=function(){this._actions=this._getActions()};MessageParser.prototype.parse=function(message,client){var parsedMessages=[],rawMessages=message.split(C.MESSAGE_SEPERATOR),i;for(i=0;i<rawMessages.length;i++){if(rawMessages[i].length>2){parsedMessages.push(this._parseMessage(rawMessages[i],client))}}return parsedMessages};MessageParser.prototype.convertTyped=function(value,client){var type=value.charAt(0);if(type===C.TYPES.STRING){return value.substr(1)}if(type===C.TYPES.OBJECT){try{return JSON.parse(value.substr(1))}catch(e){client._$onError(C.TOPIC.ERROR,C.EVENT.MESSAGE_PARSE_ERROR,e.toString()+"("+value+")");return}}if(type===C.TYPES.NUMBER){return parseFloat(value.substr(1))}if(type===C.TYPES.NULL){return null}if(type===C.TYPES.TRUE){return true}if(type===C.TYPES.FALSE){return false}if(type===C.TYPES.UNDEFINED){return undefined}client._$onError(C.TOPIC.ERROR,C.EVENT.MESSAGE_PARSE_ERROR,"UNKNOWN_TYPE ("+value+")")};MessageParser.prototype._getActions=function(){var actions={},key;for(key in C.ACTIONS){actions[C.ACTIONS[key]]=key}return actions};MessageParser.prototype._parseMessage=function(message,client){var parts=message.split(C.MESSAGE_PART_SEPERATOR),messageObject={};if(parts.length<2){message.processedError=true;client._$onError(C.TOPIC.ERROR,C.EVENT.MESSAGE_PARSE_ERROR,"Insufficiant message parts");return null}if(this._actions[parts[1]]===undefined){message.processedError=true;client._$onError(C.TOPIC.ERROR,C.EVENT.MESSAGE_PARSE_ERROR,"Unknown action "+parts[1]);return null}messageObject.raw=message;messageObject.topic=parts[0];messageObject.action=parts[1];messageObject.data=parts.splice(2);return messageObject};module.exports=new MessageParser},{"../constants/constants":42}],49:[function(require,module,exports){var Record=require("./record"),EventEmitter=require("component-emitter");var AnonymousRecord=function(recordHandler){this.name=null;this._recordHandler=recordHandler;this._record=null;this._subscriptions=[];this._proxyMethod("delete");this._proxyMethod("set");this._proxyMethod("unsubscribe");this._proxyMethod("discard")};EventEmitter(AnonymousRecord.prototype);AnonymousRecord.prototype.get=function(path){if(this._record===null){return undefined}return this._record.get(path)};AnonymousRecord.prototype.subscribe=function(){var parameters=Record.prototype._normalizeArguments(arguments);parameters.triggerNow=true;this._subscriptions.push(parameters);if(this._record!==null){this._record.subscribe(parameters)}};AnonymousRecord.prototype.unsubscribe=function(){var parameters=Record.prototype._normalizeArguments(arguments),subscriptions=[],i;for(i=0;i<this._subscriptions.length;i++){if(this._subscriptions[i].path!==parameters.path||this._subscriptions[i].callback!==parameters.callback){subscriptions.push(this._subscriptions[i])}}this._subscriptions=subscriptions;if(this._record!==null){this._record.unsubscribe(parameters)}};AnonymousRecord.prototype.setName=function(recordName){this.name=recordName;var i;if(this._record!==null&&!this._record.isDestroyed){for(i=0;i<this._subscriptions.length;i++){this._record.unsubscribe(this._subscriptions[i])}this._record.discard()}this._record=this._recordHandler.getRecord(recordName);for(i=0;i<this._subscriptions.length;i++){this._record.subscribe(this._subscriptions[i])}this._record.whenReady(this.emit.bind(this,"ready"));this.emit("nameChanged",recordName)};AnonymousRecord.prototype._proxyMethod=function(methodName){this[methodName]=this._callMethodOnRecord.bind(this,methodName)};AnonymousRecord.prototype._callMethodOnRecord=function(methodName){if(this._record===null){throw new Error("Can`t invoke "+methodName+". AnonymousRecord not initialised. Call setName first")}if(typeof this._record[methodName]!=="function"){throw new Error(methodName+" is not a method on the record")}var args=Array.prototype.slice.call(arguments,1);return this._record[methodName].apply(this._record,args)};module.exports=AnonymousRecord},{"./record":53,"component-emitter":12}],50:[function(require,module,exports){var utils=require("../utils/utils"),SPLIT_REG_EXP=/[\.\[\]]/g,ASTERISK="*";var JsonPath=function(record,path){this._record=record;this._path=String(path);this._tokens=[];this._tokenize()};JsonPath.prototype.getValue=function(){var node=this._record._$data,i;for(i=0;i<this._tokens.length;i++){if(node[this._tokens[i]]!==undefined){node=node[this._tokens[i]]}else{return undefined}}return node};JsonPath.prototype.setValue=function(value){var node=this._record._$data,i;for(i=0;i<this._tokens.length-1;i++){if(node[this._tokens[i]]!==undefined){node=node[this._tokens[i]]}else if(this._tokens[i+1]&&!isNaN(this._tokens[i+1])){node=node[this._tokens[i]]=[]}else{node=node[this._tokens[i]]={}}}node[this._tokens[i]]=value};JsonPath.prototype._tokenize=function(){var parts=this._path.split(SPLIT_REG_EXP),part,i;for(i=0;i<parts.length;i++){part=utils.trim(parts[i]);if(part.length===0){continue}if(!isNaN(part)){this._tokens.push(parseInt(part,10));continue}if(part===ASTERISK){this._tokens.push(true);continue}this._tokens.push(part)}};module.exports=JsonPath},{"../utils/utils":62}],51:[function(require,module,exports){var EventEmitter=require("component-emitter"),Record=require("./record"),C=require("../constants/constants"),ENTRY_ADDED_EVENT="entry-added",ENTRY_REMOVED_EVENT="entry-removed",ENTRY_MOVED_EVENT="entry-moved";var List=function(recordHandler,name,options){this._recordHandler=recordHandler;this._record=this._recordHandler.getRecord(name,options);this._record._applyUpdate=this._applyUpdate.bind(this);this._record.on("delete",this.emit.bind(this,"delete"));this._record.on("discard",this._onDiscard.bind(this));this._record.on("ready",this._onReady.bind(this));this.isDestroyed=this._record.isDestroyed;this.isReady=this._record.isReady;this.name=name;this._queuedMethods=[];this._beforeStructure=null;this._hasAddListener=null;this._hasRemoveListener=null;this._hasMoveListener=null;this.delete=this._record.delete.bind(this._record);this.discard=this._record.discard.bind(this._record);this.whenReady=this._record.whenReady.bind(this)};EventEmitter(List.prototype);List.prototype.getEntries=function(){var entries=this._record.get();if(!(entries instanceof Array)){return[]}return entries};List.prototype.isEmpty=function(){return this.getEntries().length===0};List.prototype.setEntries=function(entries){var errorMsg="entries must be an array of record names",i;if(!(entries instanceof Array)){throw new Error(errorMsg)}for(i=0;i<entries.length;i++){if(typeof entries[i]!=="string"){throw new Error(errorMsg)}}if(this._record.isReady===false){this._queuedMethods.push(this.setEntries.bind(this,entries))}else{this._beforeChange();this._record.set(entries);this._afterChange()}};List.prototype.removeEntry=function(entry,index){if(this._record.isReady===false){this._queuedMethods.push(this.removeEntry.bind(this,entry));return}var currentEntries=this._record.get(),hasIndex=this._hasIndex(index),entries=[],i;for(i=0;i<currentEntries.length;i++){if(currentEntries[i]!==entry||hasIndex&&index!==i){entries.push(currentEntries[i])}}this._beforeChange();this._record.set(entries);this._afterChange()};List.prototype.addEntry=function(entry,index){if(typeof entry!=="string"){throw new Error("Entry must be a recordName")}if(this._record.isReady===false){this._queuedMethods.push(this.addEntry.bind(this,entry));return}var hasIndex=this._hasIndex(index);var entries=this.getEntries();if(hasIndex){entries.splice(index,0,entry)}else{entries.push(entry)}this._beforeChange();this._record.set(entries);this._afterChange()};List.prototype.subscribe=function(){var parameters=Record.prototype._normalizeArguments(arguments);if(parameters.path){throw new Error("path is not supported for List.subscribe")}parameters.callback=function(callback){callback(this.getEntries())}.bind(this,parameters.callback);this._record.subscribe(parameters)};List.prototype.unsubscribe=function(){var parameters=Record.prototype._normalizeArguments(arguments);if(parameters.path){throw new Error("path is not supported for List.unsubscribe")}this._record.unsubscribe(parameters)};List.prototype._onReady=function(){this.isReady=true;for(var i=0;i<this._queuedMethods.length;i++){this._queuedMethods[i]()}this.emit("ready")};List.prototype._onDiscard=function(){this.isDestroyed=true;this.emit("discard")};List.prototype._applyUpdate=function(message){if(message.action===C.ACTIONS.PATCH){throw new Error("PATCH is not supported for Lists")}if(message.data[2].charAt(0)!=="["){message.data[2]="[]"}this._beforeChange();Record.prototype._applyUpdate.call(this._record,message);this._afterChange()};List.prototype._hasIndex=function(index){var hasIndex=false;var entries=this.getEntries();if(index!==undefined){if(isNaN(index)){throw new Error("Index must be a number")}if(index!==entries.length&&(index>=entries.length||index<0)){throw new Error("Index must be within current entries")}hasIndex=true}return hasIndex};List.prototype._beforeChange=function(){this._hasAddListener=this.listeners(ENTRY_ADDED_EVENT).length>0;this._hasRemoveListener=this.listeners(ENTRY_REMOVED_EVENT).length>0;this._hasMoveListener=this.listeners(ENTRY_MOVED_EVENT).length>0;if(this._hasAddListener||this._hasRemoveListener||this._hasMoveListener){this._beforeStructure=this._getStructure()}else{this._beforeStructure=null}};List.prototype._afterChange=function(){if(this._beforeStructure===null){return}var after=this._getStructure();var before=this._beforeStructure;var entry,i;if(this._hasRemoveListener){for(entry in before){for(i=0;i<before[entry].length;i++){if(after[entry]===undefined||after[entry][i]===undefined){this.emit(ENTRY_REMOVED_EVENT,entry,before[entry][i])}}}}if(this._hasAddListener||this._hasMoveListener){for(entry in after){if(before[entry]===undefined){for(i=0;i<after[entry].length;i++){this.emit(ENTRY_ADDED_EVENT,entry,after[entry][i])}}else{for(i=0;i<after[entry].length;i++){if(before[entry][i]!==after[entry][i]){if(before[entry][i]===undefined){this.emit(ENTRY_ADDED_EVENT,entry,after[entry][i])}else{this.emit(ENTRY_MOVED_EVENT,entry,after[entry][i])}}}}}}};List.prototype._getStructure=function(){var structure={};var i;var entries=this._record.get();for(i=0;i<entries.length;i++){if(structure[entries[i]]===undefined){structure[entries[i]]=[i]}else{structure[entries[i]].push(i)}}return structure};module.exports=List},{"../constants/constants":42,"./record":53,"component-emitter":12}],52:[function(require,module,exports){var Record=require("./record"),AnonymousRecord=require("./anonymous-record"),List=require("./list"),Listener=require("../utils/listener"),SingleNotifier=require("../utils/single-notifier"),C=require("../constants/constants"),messageParser=require("../message/message-parser"),EventEmitter=require("component-emitter");var RecordHandler=function(options,connection,client){this._options=options;this._connection=connection;this._client=client;this._records={};this._lists={};this._listener={};this._destroyEventEmitter=new EventEmitter;this._hasRegistry=new SingleNotifier(client,connection,C.TOPIC.RECORD,C.ACTIONS.HAS,this._options.recordReadTimeout);this._snapshotRegistry=new SingleNotifier(client,connection,C.TOPIC.RECORD,C.ACTIONS.SNAPSHOT,this._options.recordReadTimeout)};RecordHandler.prototype.getRecord=function(name,recordOptions){if(!this._records[name]){this._records[name]=new Record(name,recordOptions||{},this._connection,this._options,this._client);this._records[name].on("error",this._onRecordError.bind(this,name));this._records[name].on("destroyPending",this._onDestroyPending.bind(this,name));this._records[name].on("delete",this._removeRecord.bind(this,name));this._records[name].on("discard",this._removeRecord.bind(this,name))}this._records[name].usages++;return this._records[name]};RecordHandler.prototype.getList=function(name,options){if(!this._lists[name]){this._lists[name]=new List(this,name,options)}else{this._records[name].usages++}return this._lists[name]};RecordHandler.prototype.getAnonymousRecord=function(){return new AnonymousRecord(this)};RecordHandler.prototype.listen=function(pattern,callback){if(this._listener[pattern]){this._client._$onError(C.TOPIC.RECORD,C.EVENT.LISTENER_EXISTS,pattern)}else{this._listener[pattern]=new Listener(C.TOPIC.RECORD,pattern,callback,this._options,this._client,this._connection)}};RecordHandler.prototype.unlisten=function(pattern){if(this._listener[pattern]){this._listener[pattern].destroy();delete this._listener[pattern]}else{this._client._$onError(C.TOPIC.RECORD,C.EVENT.NOT_LISTENING,pattern)}};RecordHandler.prototype.snapshot=function(name,callback){if(this._records[name]){callback(null,this._records[name].get())}else{this._snapshotRegistry.request(name,callback)}};RecordHandler.prototype.has=function(name,callback){if(this._records[name]){callback(null,true)}else{this._hasRegistry.request(name,callback)}};RecordHandler.prototype._$handle=function(message){var name;if(message.action===C.ACTIONS.ERROR&&(message.data[0]!==C.EVENT.VERSION_EXISTS&&message.data[0]!==C.ACTIONS.SNAPSHOT&&message.data[0]!==C.ACTIONS.HAS&&message.data[0]!==C.EVENT.MESSAGE_DENIED)){message.processedError=true;this._client._$onError(C.TOPIC.RECORD,message.data[0],message.data[1]);return}if(message.action===C.ACTIONS.ACK||message.action===C.ACTIONS.ERROR){name=message.data[1];if(message.data[0]===C.ACTIONS.DELETE||message.data[0]===C.ACTIONS.UNSUBSCRIBE||message.data[0]===C.EVENT.MESSAGE_DENIED&&message.data[2]===C.ACTIONS.DELETE){this._destroyEventEmitter.emit("destroy_ack_"+name,message);if(message.data[0]===C.ACTIONS.DELETE&&this._records[name]){this._records[name]._$onMessage(message)}return}if(message.data[0]===C.ACTIONS.SNAPSHOT){message.processedError=true;this._snapshotRegistry.recieve(name,message.data[2]);return}if(message.data[0]===C.ACTIONS.HAS){message.processedError=true;this._snapshotRegistry.recieve(name,message.data[2]);return}}else{name=message.data[0]}var processed=false;if(this._records[name]){processed=true;this._records[name]._$onMessage(message)}if(message.action===C.ACTIONS.READ&&this._snapshotRegistry.hasRequest(name)){processed=true;this._snapshotRegistry.recieve(name,null,JSON.parse(message.data[2]))}if(message.action===C.ACTIONS.HAS&&this._hasRegistry.hasRequest(name)){processed=true;this._hasRegistry.recieve(name,null,messageParser.convertTyped(message.data[1]))}if(this._listener[name]){processed=true;this._listener[name]._$onMessage(message)}if(!processed){this._client._$onError(C.TOPIC.RECORD,C.EVENT.UNSOLICITED_MESSAGE,name)}};RecordHandler.prototype._onRecordError=function(recordName,error){this._client._$onError(C.TOPIC.RECORD,error,recordName)};RecordHandler.prototype._onDestroyPending=function(recordName){var onMessage=this._records[recordName]._$onMessage.bind(this._records[recordName]);this._destroyEventEmitter.once("destroy_ack_"+recordName,onMessage);this._removeRecord(recordName)};RecordHandler.prototype._removeRecord=function(recordName){delete this._records[recordName];delete this._lists[recordName]};module.exports=RecordHandler},{"../constants/constants":42,"../message/message-parser":48,"../utils/listener":59,"../utils/single-notifier":61,"./anonymous-record":49,"./list":51,"./record":53,"component-emitter":12}],53:[function(require,module,exports){var JsonPath=require("./json-path"),utils=require("../utils/utils"),ResubscribeNotifier=require("../utils/resubscribe-notifier"),EventEmitter=require("component-emitter"),C=require("../constants/constants"),messageBuilder=require("../message/message-builder"),messageParser=require("../message/message-parser"),ALL_EVENT="ALL_EVENT";var Record=function(name,recordOptions,connection,options,client){this.name=name;this.usages=0;this._recordOptions=recordOptions;this._connection=connection;this._client=client;this._options=options;this.isReady=false;this.isDestroyed=false;this._$data={};this.version=null;this._paths={};this._oldValue=null;this._oldPathValues=null;this._eventEmitter=new EventEmitter;this._queuedMethodCalls=[];this._mergeStrategy=null;if(options.mergeStrategy){this.setMergeStrategy(options.mergeStrategy)}this._resubscribeNotifier=new ResubscribeNotifier(this._client,this._sendRead.bind(this));this._readAckTimeout=setTimeout(this._onTimeout.bind(this,C.EVENT.ACK_TIMEOUT),this._options.recordReadAckTimeout);this._readTimeout=setTimeout(this._onTimeout.bind(this,C.EVENT.RESPONSE_TIMEOUT),this._options.recordReadTimeout);this._sendRead()};EventEmitter(Record.prototype);Record.prototype.setMergeStrategy=function(mergeStrategy){if(typeof mergeStrategy==="function"){this._mergeStrategy=mergeStrategy}else{throw new Error("Invalid merge strategy: Must be a Function")}};Record.prototype.get=function(path){var value;if(path){value=this._getPath(path).getValue()}else{value=this._$data}return utils.deepCopy(value)};Record.prototype.set=function(pathOrData,data){if(arguments.length===1&&typeof pathOrData!=="object"){throw new Error("Invalid record data "+pathOrData+": Record data must be an object")}if(this._checkDestroyed("set")){return this}if(!this.isReady){this._queuedMethodCalls.push({method:"set",args:arguments});return this}if(arguments.length===2&&utils.deepEquals(this._getPath(pathOrData).getValue(),data)){return this}else if(arguments.length===1&&utils.deepEquals(this._$data,pathOrData)){return this}this._beginChange();this.version++;if(arguments.length===1){this._$data=typeof pathOrData=="object"?utils.deepCopy(pathOrData):pathOrData;this._connection.sendMsg(C.TOPIC.RECORD,C.ACTIONS.UPDATE,[this.name,this.version,this._$data])}else{this._getPath(pathOrData).setValue(typeof data=="object"?utils.deepCopy(data):data);this._connection.sendMsg(C.TOPIC.RECORD,C.ACTIONS.PATCH,[this.name,this.version,pathOrData,messageBuilder.typed(data)])}this._completeChange();return this};Record.prototype.subscribe=function(path,callback,triggerNow){var i,args=this._normalizeArguments(arguments);if(this._checkDestroyed("subscribe")){return}this._eventEmitter.on(args.path||ALL_EVENT,args.callback);if(args.triggerNow&&this.isReady){if(args.path){args.callback(this._getPath(args.path).getValue())}else{args.callback(this._$data)}}};Record.prototype.unsubscribe=function(pathOrCallback,callback){if(this._checkDestroyed("unsubscribe")){return}var event=arguments.length===2?pathOrCallback:ALL_EVENT;this._eventEmitter.off(event,callback)};Record.prototype.discard=function(){this.usages--;if(this.usages<=0){this.whenReady(function(){this.emit("destroyPending");this._discardTimeout=setTimeout(this._onTimeout.bind(this,C.EVENT.ACK_TIMEOUT),this._options.subscriptionTimeout);this._connection.sendMsg(C.TOPIC.RECORD,C.ACTIONS.UNSUBSCRIBE,[this.name])}.bind(this))}};Record.prototype.delete=function(){if(this._checkDestroyed("delete")){return}this.whenReady(function(){this.emit("destroyPending");this._deleteAckTimeout=setTimeout(this._onTimeout.bind(this,C.EVENT.DELETE_TIMEOUT),this._options.recordDeleteTimeout);this._connection.sendMsg(C.TOPIC.RECORD,C.ACTIONS.DELETE,[this.name])}.bind(this))};Record.prototype.whenReady=function(callback){if(this.isReady===true){callback(this)}else{this.once("ready",callback.bind(this,this))}};Record.prototype._$onMessage=function(message){if(message.action===C.ACTIONS.READ){if(this.version===null){clearTimeout(this._readTimeout);this._onRead(message)}else{this._applyUpdate(message,this._client)}}else if(message.action===C.ACTIONS.ACK){this._processAckMessage(message)}else if(message.action===C.ACTIONS.UPDATE||message.action===C.ACTIONS.PATCH){this._applyUpdate(message,this._client)}else if(message.data[0]===C.EVENT.VERSION_EXISTS){this._recoverRecord(message.data[2],JSON.parse(message.data[3]),message)}else if(message.data[0]===C.EVENT.MESSAGE_DENIED){clearInterval(this._readAckTimeout);clearInterval(this._readTimeout)}};Record.prototype._recoverRecord=function(remoteVersion,remoteData,message){message.processedError=true;if(this._mergeStrategy){this._mergeStrategy(this,remoteData,remoteVersion,this._onRecordRecovered.bind(this,remoteVersion)); | |
}else{this.emit("error",C.EVENT.VERSION_EXISTS,"received update for "+remoteVersion+" but version is "+this.version)}};Record.prototype._onRecordRecovered=function(remoteVersion,error,data){if(!error){this.version=remoteVersion;this.set(data)}else{this.emit("error",C.EVENT.VERSION_EXISTS,"received update for "+remoteVersion+" but version is "+this.version)}};Record.prototype._processAckMessage=function(message){var acknowledgedAction=message.data[0];if(acknowledgedAction===C.ACTIONS.SUBSCRIBE){clearTimeout(this._readAckTimeout)}else if(acknowledgedAction===C.ACTIONS.DELETE){this.emit("delete");this._destroy()}else if(acknowledgedAction===C.ACTIONS.UNSUBSCRIBE){this.emit("discard");this._destroy()}};Record.prototype._applyUpdate=function(message){var version=parseInt(message.data[1],10);var data;if(message.action===C.ACTIONS.PATCH){data=messageParser.convertTyped(message.data[3],this._client)}else{data=JSON.parse(message.data[2])}if(this.version===null){this.version=version}else if(this.version+1!==version){if(message.action===C.ACTIONS.PATCH){this._connection.sendMsg(C.TOPIC.RECORD,C.ACTIONS.SNAPSHOT,[this.name])}else{this._recoverRecord(version,data,message)}return}this._beginChange();this.version=version;if(message.action===C.ACTIONS.PATCH){this._getPath(message.data[2]).setValue(data)}else{this._$data=data}this._completeChange()};Record.prototype._onRead=function(message){this._beginChange();this.version=parseInt(message.data[1],10);this._$data=JSON.parse(message.data[2]);this._completeChange();this._setReady()};Record.prototype._setReady=function(){this.isReady=true;for(var i=0;i<this._queuedMethodCalls.length;i++){this[this._queuedMethodCalls[i].method].apply(this,this._queuedMethodCalls[i].args)}this._queuedMethodCalls=[];this.emit("ready")};Record.prototype._sendRead=function(){this._connection.sendMsg(C.TOPIC.RECORD,C.ACTIONS.CREATEORREAD,[this.name])};Record.prototype._getPath=function(path){if(!this._paths[path]){this._paths[path]=new JsonPath(this,path)}return this._paths[path]};Record.prototype._beginChange=function(){if(!this._eventEmitter._callbacks){return}var paths=Object.keys(this._eventEmitter._callbacks),i;this._oldPathValues={};if(this._eventEmitter.hasListeners(ALL_EVENT)){this._oldValue=this.get()}for(i=0;i<paths.length;i++){if(paths[i]!==ALL_EVENT){this._oldPathValues[paths[i]]=this._getPath(paths[i]).getValue()}}};Record.prototype._completeChange=function(){if(this._eventEmitter.hasListeners(ALL_EVENT)&&!utils.deepEquals(this._oldValue,this._$data)){this._eventEmitter.emit(ALL_EVENT,this.get())}this._oldValue=null;if(this._oldPathValues===null){return}var path,currentValue;for(path in this._oldPathValues){currentValue=this._getPath(path).getValue();if(currentValue!==this._oldPathValues[path]){this._eventEmitter.emit(path,currentValue)}}this._oldPathValues=null};Record.prototype._normalizeArguments=function(args){var result={},i;if(args.length===1&&typeof args[0]==="object"){return args[0]}for(i=0;i<args.length;i++){if(typeof args[i]==="string"){result.path=args[i]}else if(typeof args[i]==="function"){result.callback=args[i]}else if(typeof args[i]==="boolean"){result.triggerNow=args[i]}}return result};Record.prototype._clearTimeouts=function(){clearTimeout(this._readAckTimeout);clearTimeout(this._deleteAckTimeout);clearTimeout(this._discardTimeout)};Record.prototype._checkDestroyed=function(methodName){if(this.isDestroyed){this.emit("error","Can't invoke '"+methodName+"'. Record '"+this.name+"' is already destroyed");return true}return false};Record.prototype._onTimeout=function(timeoutType){this._clearTimeouts();this.emit("error",timeoutType)};Record.prototype._destroy=function(){this._clearTimeouts();this._eventEmitter.off();this._resubscribeNotifier.destroy();this.isDestroyed=true;this.isReady=false;this._client=null;this._eventEmitter=null;this._connection=null};module.exports=Record},{"../constants/constants":42,"../message/message-builder":47,"../message/message-parser":48,"../utils/resubscribe-notifier":60,"../utils/utils":62,"./json-path":50,"component-emitter":12}],54:[function(require,module,exports){var C=require("../constants/constants"),AckTimeoutRegistry=require("../utils/ack-timeout-registry"),ResubscribeNotifier=require("../utils/resubscribe-notifier"),RpcResponse=require("./rpc-response"),Rpc=require("./rpc"),messageParser=require("../message/message-parser"),messageBuilder=require("../message/message-builder");var RpcHandler=function(options,connection,client){this._options=options;this._connection=connection;this._client=client;this._rpcs={};this._providers={};this._provideAckTimeouts={};this._ackTimeoutRegistry=new AckTimeoutRegistry(client,C.TOPIC.RPC,this._options.subscriptionTimeout);this._resubscribeNotifier=new ResubscribeNotifier(this._client,this._reprovide.bind(this))};RpcHandler.prototype.provide=function(name,callback){if(this._providers[name]){throw new Error("RPC "+name+" already registered")}this._ackTimeoutRegistry.add(name,C.ACTIONS.SUBSCRIBE);this._providers[name]=callback;this._connection.sendMsg(C.TOPIC.RPC,C.ACTIONS.SUBSCRIBE,[name])};RpcHandler.prototype.unprovide=function(name){if(this._providers[name]){delete this._providers[name];this._ackTimeoutRegistry.add(name,C.ACTIONS.UNSUBSCRIBE);this._connection.sendMsg(C.TOPIC.RPC,C.ACTIONS.UNSUBSCRIBE,[name])}};RpcHandler.prototype.make=function(name,data,callback){var uid=this._client.getUid(),typedData=messageBuilder.typed(data);this._rpcs[uid]=new Rpc(this._options,callback,this._client);this._connection.sendMsg(C.TOPIC.RPC,C.ACTIONS.REQUEST,[name,uid,typedData])};RpcHandler.prototype._getRpc=function(correlationId,rpcName,rawMessage){var rpc=this._rpcs[correlationId];if(!rpc){this._client._$onError(C.TOPIC.RPC,C.EVENT.UNSOLICITED_MESSAGE,rawMessage);return null}return rpc};RpcHandler.prototype._respondToRpc=function(message){var name=message.data[0],correlationId=message.data[1],data=null,response;if(message.data[2]){data=messageParser.convertTyped(message.data[2],this._client)}if(this._providers[name]){response=new RpcResponse(this._connection,name,correlationId);this._providers[name](data,response)}else{this._connection.sendMsg(C.TOPIC.RPC,C.ACTIONS.REJECTION,[name,correlationId])}};RpcHandler.prototype._$handle=function(message){var rpcName,correlationId,rpc;if(message.action===C.ACTIONS.REQUEST){this._respondToRpc(message);return}if(message.action===C.ACTIONS.ACK&&(message.data[0]===C.ACTIONS.SUBSCRIBE||message.data[0]===C.ACTIONS.UNSUBSCRIBE)){this._ackTimeoutRegistry.clear(message);return}if(message.action===C.ACTIONS.ERROR){if(message.data[0]===C.EVENT.MESSAGE_PERMISSION_ERROR){return}else if(message.data[0]===C.EVENT.MESSAGE_DENIED){if(message.data[2]===C.ACTIONS.SUBSCRIBE){return}else if(message.data[2]===C.ACTIONS.REQUEST){rpcName=message.data[1];correlationId=message.data[3]}}else{rpcName=message.data[1];correlationId=message.data[2]}}else{rpcName=message.data[0];correlationId=message.data[1]}rpc=this._getRpc(correlationId,rpcName,message.raw);if(rpc===null){return}if(message.action===C.ACTIONS.ACK){rpc.ack()}else if(message.action===C.ACTIONS.RESPONSE){rpc.respond(message.data[2]);delete this._rpcs[correlationId]}else if(message.action===C.ACTIONS.ERROR){message.processedError=true;rpc.error(message.data[0]);delete this._rpcs[correlationId]}};RpcHandler.prototype._reprovide=function(){for(var rpcName in this._providers){this._connection.sendMsg(C.TOPIC.RPC,C.ACTIONS.SUBSCRIBE,[rpcName])}};module.exports=RpcHandler},{"../constants/constants":42,"../message/message-builder":47,"../message/message-parser":48,"../utils/ack-timeout-registry":58,"../utils/resubscribe-notifier":60,"./rpc":56,"./rpc-response":55}],55:[function(require,module,exports){var C=require("../constants/constants"),utils=require("../utils/utils"),messageBuilder=require("../message/message-builder");var RpcResponse=function(connection,name,correlationId){this._connection=connection;this._name=name;this._correlationId=correlationId;this._isAcknowledged=false;this._isComplete=false;this.autoAck=true;utils.nextTick(this._performAutoAck.bind(this))};RpcResponse.prototype.ack=function(){if(this._isAcknowledged===false){this._connection.sendMsg(C.TOPIC.RPC,C.ACTIONS.ACK,[this._name,this._correlationId]);this._isAcknowledged=true}};RpcResponse.prototype.reject=function(){this.autoAck=false;this._isComplete=true;this._isAcknowledged=true;this._connection.sendMsg(C.TOPIC.RPC,C.ACTIONS.REJECTION,[this._name,this._correlationId])};RpcResponse.prototype.error=function(errorMsg){this.autoAck=false;this._isComplete=true;this._isAcknowledged=true;this._connection.sendMsg(C.TOPIC.RPC,C.ACTIONS.ERROR,[errorMsg,this._name,this._correlationId])};RpcResponse.prototype.send=function(data){if(this._isComplete===true){throw new Error("Rpc "+this._name+" already completed")}var typedData=messageBuilder.typed(data);this._connection.sendMsg(C.TOPIC.RPC,C.ACTIONS.RESPONSE,[this._name,this._correlationId,typedData]);this._isComplete=true};RpcResponse.prototype._performAutoAck=function(){if(this.autoAck===true){this.ack()}};module.exports=RpcResponse},{"../constants/constants":42,"../message/message-builder":47,"../utils/utils":62}],56:[function(require,module,exports){var C=require("../constants/constants"),messageParser=require("../message/message-parser");var Rpc=function(options,callback,client){this._options=options;this._callback=callback;this._client=client;this._ackTimeout=setTimeout(this.error.bind(this,C.EVENT.ACK_TIMEOUT),this._options.rpcAckTimeout);this._responseTimeout=setTimeout(this.error.bind(this,C.EVENT.RESPONSE_TIMEOUT),this._options.rpcResponseTimeout)};Rpc.prototype.ack=function(){clearTimeout(this._ackTimeout)};Rpc.prototype.respond=function(data){var convertedData=messageParser.convertTyped(data,this._client);this._callback(null,convertedData);this._complete()};Rpc.prototype.error=function(errorMsg){this._callback(errorMsg);this._complete()};Rpc.prototype._complete=function(){clearTimeout(this._ackTimeout);clearTimeout(this._responseTimeout)};module.exports=Rpc},{"../constants/constants":42,"../message/message-parser":48}],57:[function(require,module,exports){(function(process){var net=require("net"),URL=require("url"),events=require("events"),util=require("util"),C=require("../constants/constants");var TcpConnection=function(url){this._socket=null;this._url=url;this._messageBuffer="";this._destroyFn=this._destroy.bind(this);process.on("exit",this._destroyFn);this.open();this._isOpen=false};util.inherits(TcpConnection,events.EventEmitter);TcpConnection.prototype.open=function(){this._socket=net.createConnection(this._getOptions());this._socket.setEncoding("utf8");this._socket.setKeepAlive(true,5e3);this._socket.setNoDelay(true);this._socket.on("data",this._onData.bind(this));this._socket.on("error",this._onError.bind(this));this._socket.on("connect",this._onConnect.bind(this));this._socket.on("close",this._onClose.bind(this))};TcpConnection.prototype.send=function(message){if(this._isOpen===true){this._socket.write(message)}else{this.emit("error","attempt to send message on closed socket: "+message)}};TcpConnection.prototype.close=function(){this._isOpen=false;process.removeListener("exit",this._destroyFn);this._socket.end()};TcpConnection.prototype._onError=function(error){var msg;if(error.code==="ECONNREFUSED"){msg="Can't connect! Deepstream server unreachable on "+this._url}else{msg=error.toString()}this.emit("error",msg)};TcpConnection.prototype._onConnect=function(){this._isOpen=true;this.emit("open")};TcpConnection.prototype._onClose=function(){this._isOpen=false;this.emit("close")};TcpConnection.prototype._onData=function(packet){if(typeof packet!=="string"){this.emit("error","received non-string message from socket");return}if(this._isOpen===false){this.emit("error","received message on half closed socket: "+packet);return}var message;if(packet.charAt(packet.length-1)!==C.MESSAGE_SEPERATOR){this._messageBuffer+=packet;return}if(this._messageBuffer.length!==0){message=this._messageBuffer+packet;this._messageBuffer=""}else{message=packet}this.emit("message",message)};TcpConnection.prototype._getOptions=function(){var parsedUrl={};if(this._url.indexOf("/")===-1){parsedUrl.hostname=this._url.split(":")[0];parsedUrl.port=this._url.split(":")[1]}else{parsedUrl=URL.parse(this._url)}return{host:parsedUrl.hostname,port:parseInt(parsedUrl.port,10),allowHalfOpen:false}};TcpConnection.prototype._destroy=function(){this._socket.destroy()};module.exports=TcpConnection}).call(this,require("_process"))},{"../constants/constants":42,_process:4,events:2,net:1,url:9,util:11}],58:[function(require,module,exports){var C=require("../constants/constants"),EventEmitter=require("component-emitter");var AckTimeoutRegistry=function(client,topic,timeoutDuration){this._client=client;this._topic=topic;this._timeoutDuration=timeoutDuration;this._register={}};EventEmitter(AckTimeoutRegistry.prototype);AckTimeoutRegistry.prototype.add=function(name,action){var uniqueName=action?action+name:name;if(this._register[uniqueName]){this.clear({data:[action,name]})}this._register[uniqueName]=setTimeout(this._onTimeout.bind(this,uniqueName,name),this._timeoutDuration)};AckTimeoutRegistry.prototype.clear=function(message){var name=message.data[1];var uniqueName=message.data[0]+name;var timeout=this._register[uniqueName]||this._register[name];if(timeout){clearTimeout(timeout)}else{this._client._$onError(this._topic,C.EVENT.UNSOLICITED_MESSAGE,message.raw)}};AckTimeoutRegistry.prototype._onTimeout=function(uniqueName,name){delete this._register[uniqueName];var msg="No ACK message received in time for "+name;this._client._$onError(this._topic,C.EVENT.ACK_TIMEOUT,msg);this.emit("timeout",name)};module.exports=AckTimeoutRegistry},{"../constants/constants":42,"component-emitter":12}],59:[function(require,module,exports){var C=require("../constants/constants");var ResubscribeNotifier=require("./resubscribe-notifier");var Listener=function(type,pattern,callback,options,client,connection){this._type=type;this._callback=callback;this._pattern=pattern;this._options=options;this._client=client;this._connection=connection;this._ackTimeout=setTimeout(this._onAckTimeout.bind(this),this._options.subscriptionTimeout);this._resubscribeNotifier=new ResubscribeNotifier(client,this._sendListen.bind(this));this._sendListen()};Listener.prototype.destroy=function(){this._connection.sendMsg(this._type,C.ACTIONS.UNLISTEN,[this._pattern]);this._resubscribeNotifier.destroy();this._callback=null;this._pattern=null;this._client=null;this._connection=null};Listener.prototype._$onMessage=function(message){if(message.action===C.ACTIONS.ACK){clearTimeout(this._ackTimeout)}else{var isFound=message.action===C.ACTIONS.SUBSCRIPTION_FOR_PATTERN_FOUND;this._callback(message.data[1],isFound)}};Listener.prototype._sendListen=function(){this._connection.sendMsg(this._type,C.ACTIONS.LISTEN,[this._pattern])};Listener.prototype._onAckTimeout=function(){this._client._$onError(this._type,C.EVENT.ACK_TIMEOUT,"No ACK message received in time for "+this._pattern)};module.exports=Listener},{"../constants/constants":42,"./resubscribe-notifier":60}],60:[function(require,module,exports){var C=require("../constants/constants");var ResubscribeNotifier=function(client,resubscribe){this._client=client;this._resubscribe=resubscribe;this._isReconnecting=false;this._connectionStateChangeHandler=this._handleConnectionStateChanges.bind(this);this._client.on("connectionStateChanged",this._connectionStateChangeHandler)};ResubscribeNotifier.prototype.destroy=function(){this._client.removeListener("connectionStateChanged",this._connectionStateChangeHandler);this._connectionStateChangeHandler=null;this._client=null};ResubscribeNotifier.prototype._handleConnectionStateChanges=function(){var state=this._client.getConnectionState();if(state===C.CONNECTION_STATE.RECONNECTING&&this._isReconnecting===false){this._isReconnecting=true}if(state===C.CONNECTION_STATE.OPEN&&this._isReconnecting===true){this._isReconnecting=false;this._resubscribe()}};module.exports=ResubscribeNotifier},{"../constants/constants":42}],61:[function(require,module,exports){var C=require("../constants/constants"),ResubscribeNotifier=require("./resubscribe-notifier");var SingleNotifier=function(client,connection,topic,action,timeoutDuration){this._client=client;this._connection=connection;this._topic=topic;this._action=action;this._timeoutDuration=timeoutDuration;this._requests={};this._resubscribeNotifier=new ResubscribeNotifier(this._client,this._resendRequests.bind(this))};SingleNotifier.prototype.hasRequest=function(name){return!!this._requests[name]};SingleNotifier.prototype.request=function(name,callback){var responseTimeout;if(!this._requests[name]){this._requests[name]=[];this._connection.sendMsg(this._topic,this._action,[name])}responseTimeout=setTimeout(this._onResponseTimeout.bind(this,name),this._timeoutDuration);this._requests[name].push({timeout:responseTimeout,callback:callback})};SingleNotifier.prototype.recieve=function(name,error,data){var entries=this._requests[name];for(i=0;i<entries.length;i++){entry=entries[i];clearTimeout(entry.timeout);entry.callback(error,data)}delete this._requests[name]};SingleNotifier.prototype._onResponseTimeout=function(name){var msg="No response received in time for "+this._topic+"|"+this._action+"|"+name;this._client._$onError(this._topic,C.EVENT.RESPONSE_TIMEOUT,msg)};SingleNotifier.prototype._resendRequests=function(){for(var request in this._requests){this._connection.sendMsg(this._topic,this._action,[this._requests[request]])}};module.exports=SingleNotifier},{"../constants/constants":42,"./resubscribe-notifier":60}],62:[function(require,module,exports){(function(process){var TRIM_REGULAR_EXPRESSION=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;var OBJECT="object";exports.isNode=typeof process!=="undefined"&&process.toString()==="[object process]";exports.nextTick=function(fn){if(exports.isNode){process.nextTick(fn)}else{setTimeout(fn,0)}};exports.trim=function(inputString){if(inputString.trim){return inputString.trim()}else{return inputString.replace(TRIM_REGULAR_EXPRESSION,"")}};exports.deepEquals=function(objA,objB){if(typeof objA!==OBJECT||typeof objB!==OBJECT){return objA===objB}else{return JSON.stringify(objA)===JSON.stringify(objB)}};exports.deepCopy=function(obj){if(typeof obj===OBJECT){return JSON.parse(JSON.stringify(obj))}else{return obj}}}).call(this,require("_process"))},{_process:4}],63:[function(require,module,exports){var WebRtcConnection=require("./webrtc-connection"),EventEmitter=require("component-emitter"),C=require("../constants/constants");var WebRtcCall=function(settings,options){this._connection=settings.connection;this._localId=settings.localId;this._remoteId=settings.remoteId;this._localStream=settings.localStream;this._offer=settings.offer;this._$webRtcConnection=null;this._bufferedIceCandidates=[];this._options=options;this.state=C.CALL_STATE.INITIAL;this.metaData=settings.metaData||null;this.callee=settings.isOutgoing?settings.remoteId:settings.localId;this.isOutgoing=settings.isOutgoing;this.isIncoming=!settings.isOutgoing;this.isAccepted=false;this.isDeclined=false;if(this.isOutgoing){this._initiate()}};EventEmitter(WebRtcCall.prototype);WebRtcCall.prototype.accept=function(localStream){if(this.isAccepted){throw new Error("Incoming call is already accepted")}if(this.isDeclined){throw new Error("Can't accept incoming call. Call was already declined")}this.isAccepted=true;this._$webRtcConnection=new WebRtcConnection(this._connection,this._options,this._localId,this._remoteId);if(localStream){this._$webRtcConnection.addStream(localStream)}this._$webRtcConnection.setRemoteDescription(new RTCSessionDescription(this._offer));this._$webRtcConnection.createAnswer();this._$webRtcConnection.on("stream",this._onEstablished.bind(this));this._$webRtcConnection.on("error",this.emit.bind(this,"error"));for(var i=0;i<this._bufferedIceCandidates.length;i++){this._$webRtcConnection.addIceCandidate(this._bufferedIceCandidates[i])}this._bufferedIceCandidates=[];this._stateChange(C.CALL_STATE.ACCEPTED)};WebRtcCall.prototype.decline=function(reason){if(this.isAccepted){throw new Error("Can't decline incoming call. Call was already accepted")}if(this.isDeclined){throw new Error("Incoming call was already declined")}this.isDeclined=true;this._connection.sendMsg(C.TOPIC.WEBRTC,C.ACTIONS.WEBRTC_CALL_DECLINED,[this._localId,this._remoteId,reason||null]);this._$declineReceived(reason||null)};WebRtcCall.prototype.end=function(){this._connection.sendMsg(C.TOPIC.WEBRTC,C.ACTIONS.WEBRTC_CALL_ENDED,[this._localId,this._remoteId,null]);this._$close()};WebRtcCall.prototype._$close=function(){this._stateChange(C.CALL_STATE.ENDED);if(this._$webRtcConnection){this._$webRtcConnection.close()}this.emit("ended")};WebRtcCall.prototype._$addIceCandidate=function(iceCandidate){if(this.isIncoming&&this.isAccepted===false){this._bufferedIceCandidates.push(iceCandidate)}else{this._$webRtcConnection.addIceCandidate(iceCandidate)}};WebRtcCall.prototype._$declineReceived=function(reason){this.isDeclined=true;this.isAccepted=false;this._stateChange(C.CALL_STATE.DECLINED);this.emit("declined",reason)};WebRtcCall.prototype._stateChange=function(state){this.state=state;this.emit("stateChange",state)};WebRtcCall.prototype._initiate=function(){this._stateChange(C.CALL_STATE.CONNECTING);this._$webRtcConnection=new WebRtcConnection(this._connection,this._options,this._localId,this._remoteId);this._$webRtcConnection.initiate(this._localStream,this.metaData);this._$webRtcConnection.on("stream",this._onEstablished.bind(this))};WebRtcCall.prototype._onEstablished=function(stream){this.isDeclined=false;this.isAccepted=true;this._stateChange(C.CALL_STATE.ESTABLISHED);this.emit("established",stream)};module.exports=WebRtcCall},{"../constants/constants":42,"./webrtc-connection":64,"component-emitter":12}],64:[function(require,module,exports){var Emitter=require("component-emitter");var C=require("../constants/constants");var noop=function(){};var WebRtcConnection=function(connection,options,localId,remoteId){this._connection=connection;this._remoteId=remoteId;this._localId=localId;this._peerConnection=new RTCPeerConnection(options.rtcPeerConnectionConfig);this._peerConnection.onaddstream=this._onStream.bind(this);this._peerConnection.onicecandidate=this._onIceCandidate.bind(this);this._peerConnection.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this);this._constraints={mandatory:{OfferToReceiveAudio:true,OfferToReceiveVideo:true}}};Emitter(WebRtcConnection.prototype);WebRtcConnection.prototype.initiate=function(stream,metaData){this._peerConnection.addStream(stream);this._peerConnection.createOffer(this._onOfferCreated.bind(this,metaData),this._onError.bind(this))};WebRtcConnection.prototype.close=function(){this._peerConnection.close()};WebRtcConnection.prototype.addStream=function(stream){this._peerConnection.addStream(stream)};WebRtcConnection.prototype.setRemoteDescription=function(remoteDescription){this._peerConnection.setRemoteDescription(remoteDescription,noop,this._onError.bind(this))};WebRtcConnection.prototype.createAnswer=function(){this._peerConnection.createAnswer(this._onAnswerCreated.bind(this),this._onError.bind(this),this._constraints)};WebRtcConnection.prototype.addIceCandidate=function(iceCandidate){this._peerConnection.addIceCandidate(iceCandidate,noop,this._onError.bind(this))};WebRtcConnection.prototype._onStream=function(event){this.emit("stream",event.stream)};WebRtcConnection.prototype._onOfferCreated=function(metaData,offer){this._sendMsg(C.ACTIONS.WEBRTC_OFFER,JSON.stringify({sdp:offer.sdp,type:offer.type,meta:metaData}));this._peerConnection.setLocalDescription(offer,noop,this._onError.bind(this))};WebRtcConnection.prototype._onAnswerCreated=function(answer){this._sendMsg(C.ACTIONS.WEBRTC_ANSWER,answer.toJSON());this._peerConnection.setLocalDescription(answer,noop,this._onError.bind(this))};WebRtcConnection.prototype._sendMsg=function(action,data){this._connection.sendMsg(C.TOPIC.WEBRTC,action,[this._localId,this._remoteId,data])};WebRtcConnection.prototype._onIceCandidate=function(event){if(event.candidate){this._sendMsg(C.ACTIONS.WEBRTC_ICE_CANDIDATE,event.candidate.toJSON())}};WebRtcConnection.prototype._onIceConnectionStateChange=function(){if(this._peerConnection.iceConnectionState==="disconnected"){this._connection.sendMsg(C.TOPIC.WEBRTC,C.ACTIONS.WEBRTC_IS_ALIVE,[this._remoteId])}};WebRtcConnection.prototype._onError=function(error){this.emit("error",error)};module.exports=WebRtcConnection},{"../constants/constants":42,"component-emitter":12}],65:[function(require,module,exports){var C=require("../constants/constants"),WebRtcConnection=require("./webrtc-connection"),WebRtcCall=require("./webrtc-call"),AckTimeoutRegistry=require("../utils/ack-timeout-registry"),CALLEE_UPDATE_EVENT="callee-update";var WebRtcHandler=function(options,connection,client){this._options=options;this._connection=connection;this._client=client;this._localCallees={};this._remoteCallees=[];this._remoteCalleesCallback=null;this._ackTimeoutRegistry=new AckTimeoutRegistry(client,C.TOPIC.WEBRTC,this._options.calleeAckTimeout);this._ackTimeoutRegistry.on("timeout",this._removeCallee.bind(this));this._calls={}};WebRtcHandler.prototype.registerCallee=function(name,onCallFn){this._checkCompatibility();if(typeof name!=="string"){throw new Error("Invalid callee name "+name)}if(typeof onCallFn!=="function"){throw new Error("Callback is not a function")}if(this._localCallees[name]){throw new Error("Callee "+name+" is already registered")}this._localCallees[name]=onCallFn;this._ackTimeoutRegistry.add(name);this._connection.sendMsg(C.TOPIC.WEBRTC,C.ACTIONS.WEBRTC_REGISTER_CALLEE,[name])};WebRtcHandler.prototype.unregisterCallee=function(name){if(!this._localCallees[name]){throw new Error("Callee is not registered")}this._removeCallee(name);this._ackTimeoutRegistry.add(name);this._connection.sendMsg(C.TOPIC.WEBRTC,C.ACTIONS.WEBRTC_UNREGISTER_CALLEE,[name])};WebRtcHandler.prototype.makeCall=function(calleeName,metaData,localStream){this._checkCompatibility();if(typeof calleeName!=="string"){throw new Error("Callee must be provided as string")}if(typeof metaData!=="object"){throw new Error("metaData must be provided")}if(this._calls[calleeName]){throw new Error("Call with "+calleeName+" is already in progress")}var localId=this._client.getUid();this._ackTimeoutRegistry.add(localId);return this._createCall(calleeName,{isOutgoing:true,connection:this._connection,localId:localId,remoteId:calleeName,localStream:localStream,offer:null,metaData:metaData})};WebRtcHandler.prototype.listenForCallees=function(callback){if(this._remoteCalleesCallback!==null){throw new Error("Already listening for callees")}this._remoteCalleesCallback=callback;this._ackTimeoutRegistry.add(CALLEE_UPDATE_EVENT);this._connection.sendMsg(C.TOPIC.WEBRTC,C.ACTIONS.WEBRTC_LISTEN_FOR_CALLEES)};WebRtcHandler.prototype.unlistenForCallees=function(){if(!this._remoteCalleesCallback){throw new Error("Not listening for callees")}this._remoteCalleesCallback=null;this._ackTimeoutRegistry.add(CALLEE_UPDATE_EVENT);this._connection.sendMsg(C.TOPIC.WEBRTC,C.ACTIONS.WEBRTC_UNLISTEN_FOR_CALLEES)};WebRtcHandler.prototype._handleIncomingCall=function(message){var remoteId=message.data[0],localId=message.data[1],offer=JSON.parse(message.data[2]),call=this._createCall(remoteId,{isOutgoing:false,connection:this._connection,localId:localId,remoteId:remoteId,localStream:null,metaData:offer.meta,offer:offer});this._localCallees[localId](call,offer.meta)};WebRtcHandler.prototype._removeCall=function(id){delete this._calls[id]};WebRtcHandler.prototype._createCall=function(id,settings){this._calls[id]=new WebRtcCall(settings,this._options);this._calls[id].on("ended",this._removeCall.bind(this,id));return this._calls[id]};WebRtcHandler.prototype._isValidMessage=function(message){return message.data.length===3&&typeof message.data[0]==="string"&&typeof message.data[1]==="string"&&typeof message.data[2]==="string"};WebRtcHandler.prototype._isCalleeUpdate=function(message){return message.action===C.ACTIONS.WEBRTC_ALL_CALLEES||message.action===C.ACTIONS.WEBRTC_CALLEE_ADDED||message.action===C.ACTIONS.WEBRTC_CALLEE_REMOVED};WebRtcHandler.prototype._checkCompatibility=function(){if(typeof RTCPeerConnection==="undefined"||typeof RTCSessionDescription==="undefined"||typeof RTCIceCandidate==="undefined"){var msg="RTC global objects not detected. \n";msg+="deepstream expects a standardized WebRtc implementation (e.g. no vendor prefixes etc.) \n";msg+="until WebRtc is fully supported, we recommend including the official WebRTC adapter script \n";msg+="which can be found at https://github.com/webrtc/adapter";throw new Error(msg)}};WebRtcHandler.prototype._removeCallee=function(calleeName){delete this._localCallees[calleeName]};WebRtcHandler.prototype._processCalleeUpdate=function(message){if(this._remoteCalleesCallback===null){this._client._$onError(C.TOPIC.WEBRTC,C.EVENT.UNSOLICITED_MESSAGE,message.raw);return}if(message.action===C.ACTIONS.WEBRTC_ALL_CALLEES){this._remoteCallees=message.data}var index=this._remoteCallees.indexOf(message.data[0]);if(message.action===C.ACTIONS.WEBRTC_CALLEE_ADDED){if(index!==-1){return}this._remoteCallees.push(message.data[0])}else if(message.action===C.ACTIONS.WEBRTC_CALLEE_REMOVED){if(index===-1){return}this._remoteCallees.splice(index,1)}this._remoteCalleesCallback(this._remoteCallees)};WebRtcHandler.prototype._$handle=function(message){var call,sessionDescription,iceCandidate;if(message.action===C.ACTIONS.ERROR){this._client._$onError(C.TOPIC.WEBRTC,message.data[0],message.data[1]);return}if(message.action===C.ACTIONS.ACK){this._ackTimeoutRegistry.clear(message);return}if(this._isCalleeUpdate(message)){this._processCalleeUpdate(message);return}if(message.action===C.ACTIONS.WEBRTC_IS_ALIVE){if(message.data[1]==="false"&&this._calls[message.data[0]]){this._calls[message.data[0]]._$close()}return}if(!this._isValidMessage(message)){this._client._$onError(C.TOPIC.WEBRTC,C.EVENT.MESSAGE_PARSE_ERROR,message);return}if(message.action===C.ACTIONS.WEBRTC_OFFER){this._handleIncomingCall(message);return}call=this._calls[message.data[0]]||this._calls[message.data[1]];if(!call){this._client._$onError(C.TOPIC.WEBRTC,C.EVENT.UNSOLICITED_MESSAGE,message.raw);return}if(message.action===C.ACTIONS.WEBRTC_ANSWER){sessionDescription=new RTCSessionDescription(JSON.parse(message.data[2]));call._$webRtcConnection.setRemoteDescription(sessionDescription);return}if(message.action===C.ACTIONS.WEBRTC_ICE_CANDIDATE){iceCandidate=new RTCIceCandidate(JSON.parse(message.data[2]));call._$addIceCandidate(iceCandidate);return}if(message.action===C.ACTIONS.WEBRTC_CALL_DECLINED){call._$declineReceived(message.data[2]);return}if(message.action===C.ACTIONS.WEBRTC_CALL_ENDED){call._$close();return}this._client._$onError(C.TOPIC.WEBRTC,C.EVENT.EVENT.MESSAGE_PARSE_ERROR,"unsupported action "+message.action)};module.exports=WebRtcHandler},{"../constants/constants":42,"../utils/ack-timeout-registry":58,"./webrtc-call":63,"./webrtc-connection":64}],"deepstream.io-client-js":[function(require,module,exports){var C=require("./constants/constants"),MS=require("./constants/merge-strategies"),Emitter=require("component-emitter"),Connection=require("./message/connection"),EventHandler=require("./event/event-handler"),RpcHandler=require("./rpc/rpc-handler"),RecordHandler=require("./record/record-handler"),WebRtcHandler=require("./webrtc/webrtc-handler"),defaultOptions=require("./default-options");var Client=function(url,options){this._url=url;this._options=this._getOptions(options||{});this._connection=new Connection(this,this._url,this._options);this.event=new EventHandler(this._options,this._connection,this);this.rpc=new RpcHandler(this._options,this._connection,this);this.record=new RecordHandler(this._options,this._connection,this);this.webrtc=new WebRtcHandler(this._options,this._connection,this);this._messageCallbacks={}; | |
this._messageCallbacks[C.TOPIC.WEBRTC]=this.webrtc._$handle.bind(this.webrtc);this._messageCallbacks[C.TOPIC.EVENT]=this.event._$handle.bind(this.event);this._messageCallbacks[C.TOPIC.RPC]=this.rpc._$handle.bind(this.rpc);this._messageCallbacks[C.TOPIC.RECORD]=this.record._$handle.bind(this.record);this._messageCallbacks[C.TOPIC.ERROR]=this._onErrorMessage.bind(this)};Emitter(Client.prototype);Client.prototype.login=function(authParams,callback){this._connection.authenticate(authParams||{},callback);return this};Client.prototype.close=function(){this._connection.close()};Client.prototype.getConnectionState=function(){return this._connection.getState()};Client.prototype.getUid=function(){var timestamp=(new Date).getTime().toString(36),randomString=(Math.random()*1e16).toString(36).replace(".","");return timestamp+"-"+randomString};Client.prototype._$onMessage=function(message){if(this._messageCallbacks[message.topic]){this._messageCallbacks[message.topic](message)}else{message.processedError=true;this._$onError(message.topic,C.EVENT.MESSAGE_PARSE_ERROR,"Received message for unknown topic "+message.topic)}if(message.action===C.ACTIONS.ERROR&&!message.processedError){this._$onError(message.topic,message.data[0],message.data.slice(0))}};Client.prototype._$onError=function(topic,event,msg){var errorMsg;if(event===C.EVENT.ACK_TIMEOUT||event===C.EVENT.RESPONSE_TIMEOUT){if(this.getConnectionState()===C.CONNECTION_STATE.AWAITING_AUTHENTICATION){errorMsg="Your message timed out because you're not authenticated. Have you called login()?";setTimeout(this._$onError.bind(this,C.EVENT.NOT_AUTHENTICATED,C.TOPIC.ERROR,errorMsg),1)}}if(this.hasListeners("error")){this.emit("error",msg,event,topic);this.emit(event,topic,msg)}else{console.log("--- You can catch all deepstream errors by subscribing to the error event ---");errorMsg=event+": "+msg;if(topic){errorMsg+=" ("+topic+")"}throw new Error(errorMsg)}};Client.prototype._onErrorMessage=function(errorMessage){this._$onError(errorMessage.topic,errorMessage.data[0],errorMessage.data[1])};Client.prototype._getOptions=function(options){var mergedOptions={},key;for(key in defaultOptions){if(typeof options[key]==="undefined"){mergedOptions[key]=defaultOptions[key]}else{mergedOptions[key]=options[key]}}return mergedOptions};function createDeepstream(url,options){return new Client(url,options)}Client.prototype.CONSTANTS=C;createDeepstream.CONSTANTS=C;Client.prototype.MERGE_STRATEGIES=MS;createDeepstream.MERGE_STRATEGIES=MS;module.exports=createDeepstream},{"./constants/constants":42,"./constants/merge-strategies":43,"./default-options":44,"./event/event-handler":45,"./message/connection":46,"./record/record-handler":52,"./rpc/rpc-handler":54,"./webrtc/webrtc-handler":65,"component-emitter":12}]},{},[]);const DEEPSTREAM_HOST="deepstream-test.herokuapp.com:80";const deepstream=require("deepstream.io-client-js");const result=document.getElementById("result");result.textContent=window.location.pathname},0); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "requirebin-sketch", | |
"version": "1.0.0", | |
"dependencies": { | |
"deepstream.io-client-js": "1.0.1" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- contents of this file will be placed inside the <body> --> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- contents of this file will be placed inside the <head> --> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment