Anonymous avatar Anonymous committed c32c422

working, compiled Orbited.js! yay! YAY!

Comments (0)

Files changed (8)

daemon/orbited/js_src/Orbited.js

 jsio('import Class');
 jsio('from jsio.protocols.mspp import MSPPStream, MSPPProtocol');
 
+var multiplexer = null;
+
 // autodetect host + port!!!
 exports.settings = { 'host': 'localhost', 'port': 8000, 'path': '/csp'};
-exports.internal = { 'multiplexer': null };
 
 exports.TCPSocket = Class(MSPPStream, function() {
     this.init = function() {
         this.setEncoding('plain');
-        if (exports.internal.multiplexer == null) {
-            exports.internal.multiplexer = new MSPPProtocol();
-            exports.internal.multiplexer.setTransport('csp', {"url": "http://" + exports.settings.host + ":" + exports.settings.port + exports.settings.path});
+        if (multiplexer == null) {
+            multiplexer = new MSPPProtocol();
+            multiplexer.setTransport('csp', {"url": "http://" + exports.settings.host + ":" + exports.settings.port + exports.settings.path});
         }
-        this.setMultiplexer(exports.internal.multiplexer);
+        this.setMultiplexer(multiplexer);
     }
 });

daemon/orbited/js_src/compile.sh

 #!/bin/bash
-jsio_compile orbited.pkg -j /home/mario/Desktop/js.io/jsio -o ../static/Orbited.js
+jsio_compile orbited.pkg --vv -j /home/mario/stuff/js.io/jsio -o ../static/Orbited.js

daemon/orbited/static/Orbited.js

+;(function(){var preloaded_source={'jsio.std.base64':{"src":"\njsio('import jsio.logging');var logger=jsio.logging.getLogger('base64');var alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';var pad='=';var padChar=alphabet.charAt(alphabet.length-1);var shorten=function(array,number){for(var i=number;i>0;i--){array.pop();};};var decode_map={};for(var i=0,n=alphabet.length;i<n;i++){decode_map[alphabet.charAt(i)]=i;};var alphabet_inverse=new RegExp('[^'+alphabet+']');var Base64CodecError=exports.Base64CodecError=function(message){this.message=message;};Base64CodecError.prototype.toString=function(){return'Base64CodecError'+(this.message?': '+this.message:'');};var assertOrBadInput=function(exp,message){if(!exp){throw new Base64CodecError(message)};};exports.encode=function(bytes){assertOrBadInput(!(/[^\\x00-\\xFF]/.test(bytes)),'Input contains out-of-range characters.');var padding='\\x00\\x00\\x00'.slice((bytes.length%3)||3);bytes+=padding;var out_array=[];for(var i=0,n=bytes.length;i<n;i+=3){var newchars=((bytes.charCodeAt(i)<<020)+\n(bytes.charCodeAt(i+1)<<010)+\n(bytes.charCodeAt(i+2)));out_array.push(alphabet.charAt((newchars>>18)&077),alphabet.charAt((newchars>>12)&077),alphabet.charAt((newchars>>6)&077),alphabet.charAt((newchars)&077));};shorten(out_array,padding.length);return out_array.join('');};exports.decode=function(b64text){logger.debug('decode',b64text);b64text=b64text.replace(/\\s/g,'')\nvar i=b64text.length;while(b64text.charAt(--i)===pad){};b64text=b64text.slice(0,i+1);assertOrBadInput(!alphabet_inverse.test(b64text),'Input contains out-of-range characters.');var padding=Array(5-((b64text.length%4)||4)).join(padChar);b64text+=padding;var out_array=[];for(var i=0,n=b64text.length;i<n;i+=4){newchars=((decode_map[b64text.charAt(i)]<<18)+\n(decode_map[b64text.charAt(i+1)]<<12)+\n(decode_map[b64text.charAt(i+2)]<<6)+\n(decode_map[b64text.charAt(i+3)]));out_array.push((newchars>>020)&0xFF,(newchars>>010)&0xFF,(newchars)&0xFF);};shorten(out_array,padding.length);var result=String.fromCharCode.apply(String,out_array);logger.debug('decoded',result);return result;};","location":"jsio/std/base64.js"},'jsio.std.uri':{"src":"\njsio('import Class, bind')\njsio('import jsio.logging');var logger=jsio.logging.getLogger('uri');var attrs=[\"source\",\"protocol\",\"authority\",\"userInfo\",\"user\",\"password\",\"host\",\"port\",\"relative\",\"path\",\"directory\",\"file\",\"query\",\"anchor\"];exports.Uri=Class(function(supr){this.init=function(url,isStrict){var uriData=exports.parse(url,isStrict)\nfor(attr in uriData){this['_'+attr]=uriData[attr];}}\nfor(var i=0,attr;attr=attrs[i];++i){(function(attr){var fNameSuffix=attr.charAt(0).toUpperCase()+attr.slice(1);this['get'+fNameSuffix]=function(){return this['_'+attr];}\nthis['set'+fNameSuffix]=function(val){this['_'+attr]=val;}}).call(this,attr);}\nthis.toString=this.render=function(){return this._source;}});exports.buildQuery=function(kvp){var result='';for(key in kvp){result+=encodeURIComponent(key)+'='+encodeURIComponent(kvp[key])+'&';}\nreturn result;}\nvar strictRegex=/^(?:([^:\\/?#]+):)?(?:\\/\\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\\/?#]*)(?::(\\d*))?))?((((?:[^?#\\/]*\\/)*)([^?#]*))(?:\\?([^#]*))?(?:#(.*))?)/;var looseRegex=/^(?:(?![^:@]+:[^:@\\/]*@)([^:\\/?#.]+):)?(?:\\/\\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\\/?#]*)(?::(\\d*))?)(((\\/(?:[^?#](?![^?#\\/]*\\.[^?#\\/.]+(?:[?#]|$)))*\\/?)?([^?#\\/]*))(?:\\?([^#]*))?(?:#(.*))?)/;var queryStringRegex=/(?:^|&)([^&=]*)=?([^&]*)/g;exports.parse=function(str,isStrict){var regex=isStrict?strictRegex:looseRegex;var result={}\nvar match=regex.exec(str);for(var i=0,attr;attr=attrs[i];++i){result[attr]=match[i]||\"\";}\nvar qs=result['queryKey']={}\nresult['query'].replace(queryStringRegex,function(check,key,val){if(check){qs[key]=val;}})\nreturn result;}\nexports.isSameDomain=function(urlA,urlB){var a=exports.parse(urlA);var b=exports.parse(urlB);return((urlA.port==urlB.port)&&(urlA.host==urlB.host)&&(urlA.protocol=urlB.protocol))}","location":"jsio/std/uri.js"},'jsio.buffer':{"src":"\njsio('import Class, bind');jsio('import jsio.logging');jsio('from jsio.interfaces import Protocol');var logger=jsio.logging.getLogger('jsio.buffer.Buffer');var EmptyBufferError=exports.EmptyBufferError=Class(function(){this.init=function(message){this.message=message;}})\nexports.Buffer=Class(function(supr){this.init=function(rawBuffer){this._rawBuffer=!!rawBuffer?rawBuffer:\"\";}\nthis.getLength=function(){return this._rawBuffer.length;}\nthis.append=function(data){logger.info('append',JSON.stringify(data));this._rawBuffer+=data;}\nthis.peekBytes=function(num){if(!!num)\nreturn this._rawBuffer.slice(0,num);else\nreturn this._rawBuffer;}\nthis.peekToDelimiter=function(delimiter){delimiter=delimiter?delimiter:'\\n';var i=this._rawBuffer.indexOf(delimiter);if(i==-1)\nthrow new EmptyBufferError(\"delimiter \"+delmiter+\"not present in buffer\");else\nreturn this._rawBuffer.slice(0,i);}\nthis.consumeBytes=function(num){var output=this.peekBytes(num);this._rawBuffer=this._rawBuffer.slice(output.length);return output;}\nthis.consumeMaxBytes=function(num){var output=this._rawBuffer.slice(0,num);this._rawBuffer=this._rawBuffer(num);return output;}\nthis.consumeAllBytes=function(){var temp=this._rawBuffer;this._rawBuffer=\"\";return temp;}\nthis.consumeThroughDelimiter=function(delimiter){return this.consumeToDelimiter(delimiter)+this.consumeBytes(delimiter.length);}\nthis.consumeToDelimiter=function(delimiter){delimiter=!!delimiter?delimiter:\"\\n\"\nvar output=this.peekToDelimiter(delimiter);this._rawBuffer=this._rawBuffer.slice(output.length);return output;}\nthis.hasBytes=function(num){num=num?num:0;return this._rawBuffer.length>=num;}\nthis.hasDelimiter=function(delimiter){delimiter=!!delimiter?delimiter:'\\n';return(this._rawBuffer.indexOf(delimiter)!=-1);}})","location":"jsio/buffer.js"},'jsio.logging':{"src":"\njsio('import Class, bind, log');var loggers={}\nvar levels=exports.levels={DEBUG:0,LOG:1,INFO:2,WARN:3,ERROR:4};var production=false;exports.setProduction=function(prod){production=!!prod;}\nexports.getLogger=function(name){if(!(name in loggers)){loggers[name]=new exports.Logger(name);}\nreturn loggers[name];}\nexports.Logger=Class(function(){this.init=function(name,level){if(!level){level=levels.LOG;}\nthis.name=name;this.level=level;}\nthis.setLevel=function(level){this.level=level;}\nfunction makeLogFunction(level,type){return function(){if(level<this.level||production)return;log.apply(log,[type,this.name].concat(Array.prototype.slice.call(arguments,0)));}}\nthis.debug=makeLogFunction(levels.DEBUG,\"DEBUG\");this.log=makeLogFunction(levels.LOG,\"LOG\");this.info=makeLogFunction(levels.INFO,\"INFO\");this.warn=makeLogFunction(levels.WARN,\"WARN\");this.error=makeLogFunction(levels.ERROR,\"ERROR\");})","location":"jsio/logging.js"},'jsio.protocols.buffered':{"src":"\njsio('import Class, bind, jsio.logging');jsio('from jsio.interfaces import Protocol');jsio('from jsio.buffer import Buffer');var logger=jsio.logging.getLogger('Buffered');exports.BufferedProtocol=Class(Protocol,function(supr){this.init=function(){this.buffer=new Buffer();}\nthis.bufferUpdated=function(){}\nthis.dataReceived=function(data){this.buffer.append(data);this.bufferUpdated();}})","location":"jsio/protocols/buffered.js"},'jsio.env':{"src":"\njsio('import log, bind');function getObj(objectName,transportName,envName){jsio('from .env.'+(envName||jsio.__env)+'.'+transportName+' import '+objectName+' as result');return result;}\nexports.getListener=bind(this,getObj,'Listener');exports.getConnector=bind(this,getObj,'Connector');","location":"jsio/env.js"},'jsio.csp.transports':{"src":"\njsio('import Class, bind');jsio('import jsio.std.uri as uri');jsio('import jsio.std.base64 as base64');jsio('import jsio.logging');jsio('import .errors');jsio('from jsio.util.browserdetect import BrowserDetect');var logger=jsio.logging.getLogger(\"csp.transports\");exports.allTransports={};exports.registerTransport=function(name,transport){logger.debug('registering transport',name);if(name in exports.allTransports){throw new Error(\"Transport \"+name+\" already exists\");}\nexports.allTransports[name]=transport;}\nvar isLocalFile=function(url,options){var test=location.toString().match('file://');if(test&&test.index===0){logger.debug('Detected Local file');return true;};return false;};var haveCrossDomain=function(url,options){try{if(window.XDomainRequest||window.XMLHttpRequest&&(new XMLHttpRequest()).withCredentials!==undefined){logger.debug('Detected xdomain xhr capabilities');return true;}}catch(e){}\nreturn false;};var isSameDomain=function(url,options){if(uri.isSameDomain(url,location.toString())){logger.debug('Detected same domain');return true;}\nreturn false;};var canChooseXHR=function(url,options){return(!isLocalFile(url,options)||(haveCrossDomain(url,options)||isSameDomain(url,options)));};var preferXHR=function(url,options){if(canChooseXHR(url,options)){return exports.allTransports.xhr;};return exports.allTransports.jsonp;};var preferJSONP=function(url,options){return exports.allTransports.jsonp;};exports.chooseTransport=function(url,options){if(options.preferredTransport=='xhr'){return preferXHR(url,options);}else if(options.preferredTransport=='jsonp'){return preferJSONP(url,options);}else{return exports.allTransports.jsonp;}\nlogger.debug('Detected cross-domain;'+' no xdomain xhr capabilities present;'+' choosing transport jsonp');return exports.allTransports.jsonp;};var PARAMS={'xhrstream':{\"is\":\"1\",\"bs\":\"\\n\"},'xhrpoll':{\"du\":\"0\"},'xhrlongpoll':{},'sselongpoll':{\"bp\":\"data: \",\"bs\":\"\\r\\n\",\"se\":\"1\"},'ssestream':{\"bp\":\"data: \",\"bs\":\"\\r\\n\",\"se\":\"1\",\"is\":\"1\"}};exports.Transport=Class(function(supr){this.handshake=function(url,options){throw new Error(\"handshake Not Implemented\");}\nthis.comet=function(url,sessionKey,lastEventId,options){throw new Error(\"comet Not Implemented\");}\nthis.send=function(url,sessionKey,data,options){throw new Error(\"send Not Implemented\");}\nthis.encodePacket=function(packetId,data,options){throw new Error(\"encodePacket Not Implemented\");}\nthis.abort=function(){throw new Error(\"abort Not Implemented\");}});var baseTransport=Class(exports.Transport,function(supr){this.init=function(){this._handshakeArgs={d:'{}',ct:'application/javascript'};}\nthis.handshake=function(url,options){logger.debug('handshake:',url,options);this._makeRequest('send',url+'/handshake',this._handshakeArgs,this.handshakeSuccess,this.handshakeFailure);}\nthis.comet=function(url,sessionKey,lastEventId,options){logger.debug('comet:',url,sessionKey,lastEventId,options);args={s:sessionKey,a:lastEventId}\nthis._makeRequest('comet',url+'/comet',args,this.cometSuccess,this.cometFailure);}\nthis.send=function(url,sessionKey,data,options){logger.debug('send:',url,sessionKey,data,options);args={d:data,s:sessionKey}\nthis._makeRequest('send',url+'/send',args,this.sendSuccess,this.sendFailure);}});exports.registerTransport('xhr',Class(baseTransport,function(supr){var createXHR=function(){return window.XMLHttpRequest?new XMLHttpRequest():window.XDomainRequest?new XDomainRequest():window.ActiveXObject?new ActiveXObject(\"Msxml2.XMLHTTP\"):null;}\nvar abortXHR=function(xhr){logger.debug('aborting XHR');try{if('onload'in xhr){xhr.onload=xhr.onerror=null;}else if('onreadystatechange'in xhr){xhr.onreadystatechange=null;}\nif(xhr.abort){xhr.abort();}}catch(e){logger.debug('error aborting xhr',e);}}\nthis.init=function(){supr(this,'init');this._xhr={'send':createXHR(),'comet':createXHR()};}\nthis.abort=function(){var xhr;for(var i in this._xhr){if(this._xhr.hasOwnProperty(i)){abortXHR(xhr);}}}\nthis.encodePacket=function(packetId,data,options){return data.indexOf('\\0')==-1?[packetId,0,data]:[packetId,1,base64.encode(data)];}\nthis._onReadyStateChange=function(rType,cb,eb){try{var xhr=this._xhr[rType];if(xhr.readyState!=4){return;}\nif(xhr.status!=200){logger.debug('XHR failed with status ',xhr.status);eb();}\nlogger.debug('XHR data received');cb(eval(xhr.responseText));}catch(e){var xhr=this._xhr[rType];logger.debug('Error in XHR::onReadyStateChange',e);eb();abortXHR(xhr);logger.debug('done handling XHR error');}}\nthis._makeRequest=function(rType,url,args,cb,eb){var xhr=this._xhr[rType],data=args.d||null;if('d'in args){delete args.d;}\nxhr.open('POST',url+'?'+uri.buildQuery(args));xhr.setRequestHeader('Content-Type','text/plain');if('onload'in xhr){xhr.onload=bind(this,'_onReadyStateChange',rType,cb,eb);xhr.onerror=xhr.ontimeout=eb;}else if('onreadystatechange'in xhr){xhr.onreadystatechange=bind(this,'_onReadyStateChange',rType,cb,eb);}\nif(data){xhr.send(data);}else{xhr.send();}}}));exports.registerTransport('jsonp',Class(baseTransport,function(supr){var logger=jsio.logging.getLogger('csp.transports.jsonp');var createIframe=function(){var i=document.createElement(\"iframe\");with(i.style){display='block';width=height=border=margin=padding='0';overflow=visibility='hidden';}\ni.cbId=0;i.src='javascript:document.open();document.write(\"<html><body></body></html>\")';document.body.appendChild(i);return i;}\nvar abortIframe=function(ifr){var win=ifr.contentWindow,doc=win.document;logger.debug('removing scripts');var scripts=doc.getElementsByTagName('script');var s1=doc.getElementsByTagName('script')[0];var s2=doc.getElementsByTagName('script')[1];if(s1)s1.parentNode.removeChild(s1);if(s2)s2.parentNode.removeChild(s2);logger.debug('removed scripts');logger.debug('deleting callbacks');win['cb'+(ifr.cbId-1)]=function(){};win['eb'+(ifr.cbId-1)]=function(){};}\nvar removeIframe=function(ifr){$setTimeout(function(){if(ifr&&ifr.parentNode){ifr.parentNode.removeChild(ifr);}},60000);}\nthis.init=function(){supr(this,'init');this._onReady=[];this._isReady=false;this._createIframes();}\nthis._createIframes=function(){if(!document.body){setTimeout(bind(this,'_createIframes'),100);return;}\nthis._isReady=true;this._ifr={'send':createIframe(),'comet':createIframe()};var readyArgs=this._onReady;this._onReady=[];for(var i=0,args;args=readyArgs[i];++i){this._makeRequest.apply(this,args);}}\nthis.encodePacket=function(packetId,data,options){return[packetId,1,base64.encode(data)];}\nthis.abort=function(){for(var i in this._ifr){if(this._ifr.hasOwnProperty(i)){var ifr=this._ifr[i];abortIframe(ifr);removeIframe(ifr);}}}\nthis._makeRequest=function(rType,url,args,cb,eb){if(!this._isReady){this._onReady.push(arguments);return;}\nargs.n=Math.random();$setTimeout(bind(this,function(){var ifr=this._ifr[rType];var win=ifr.contentWindow,doc=win.document,body=doc.body;var completed=false;var jsonpId=ifr.cbId++;var onFinish=win['eb'+jsonpId]=function(scriptTag){if(scriptTag&&scriptTag.readyState!='loaded'){return;}\nlogger.debug('in onFinish');if(!completed){logger.debug('error making request:',fullUrl);}\nabortIframe(ifr);if(!completed){logger.debug('calling eb');eb.apply(null,arguments);}}\nwin['cb'+jsonpId]=function callback(){logger.debug('successful: ',fullUrl,[].slice.call(arguments,0));completed=true;logger.debug('calling the cb');cb.apply(null,arguments);logger.debug('cb called');}\nswitch(rType){case'send':args.rs=';';args.rp='cb'+jsonpId;break;case'comet':args.bs=';';args.bp='cb'+jsonpId;break;}\nvar fullUrl=url+'?'+uri.buildQuery(args);if(BrowserDetect.isWebKit){doc.open();doc.write('<scr'+'ipt src=\"'+fullUrl+'\"></scr'+'ipt>');doc.write('<scr'+'ipt>eb'+jsonpId+'(false)</scr'+'ipt>');}else{var s=doc.createElement('script');s.src=fullUrl;if(s.onreadystatechange===null){s.onreadystatechange=bind(window,onFinish,s);}\nbody.appendChild(s);if(!BrowserDetect.isIE){var s=doc.createElement('script');s.innerHTML='eb'+jsonpId+'(false)';body.appendChild(s);}}\nkillLoadingBar();}),0);}\nfunction killLoadingBar(){}}));","location":"jsio/csp/transports.js"},'jsio.interfaces':{"src":"\njsio('import Class, bind');exports.Protocol=Class(function(){this.connectionMade=function(isReconnect){}\nthis.dataReceived=function(data){}\nthis.connectionLost=function(reason){}\nthis.connectionFailed=function(){}});exports.Server=Class(function(){this.init=function(protocolClass){this._protocolClass=protocolClass;}\nthis.buildProtocol=function(){return new this._protocolClass();}});exports.Transport=Class(function(){this.write=function(data,encoding){throw new Error(\"Not implemented\");}\nthis.getPeer=function(){throw new Error(\"Not implemented\");}});exports.Listener=Class(function(){this.init=function(server,opts){this._server=server;this._opts=opts||{};}\nthis.onConnect=function(transport){var p=this._server.buildProtocol();p.transport=transport;p.server=this._server;transport.protocol=p;transport.makeConnection(p);p.connectionMade();}\nthis.listen=function(){throw new Error('Abstract class');}\nthis.stop=function(){}});exports.Connector=Class(function(){this.init=function(protocol,opts){this._protocol=protocol;this._opts=opts;}\nthis.onConnect=function(transport){transport.makeConnection(this._protocol);this._protocol.transport=transport;this._protocol.connectionMade();}\nthis.getProtocol=function(){return this._protocol;}});exports.PubSub=Class(function(){this.publish=function(signal){if(!this._subscribers){return;}\nvar args=Array.prototype.slice.call(arguments,1);if(this._subscribers.__any){var anyArgs=[signal].concat(args);for(var i=0,sub;sub=this._subscribers.__any[i];++i){sub.apply(window,args);}}\nif(!this._subscribers[signal]){return;}\nfor(var i=0,sub;sub=this._subscribers[signal][i];++i){sub.apply(window,args);}}\nthis.subscribe=function(signal){if(!this._subscribers){this._subscribers={};}\nif(!this._subscribers[signal]){this._subscribers[signal]=[];}\nthis._subscribers[signal].push(bind.apply(jsio,Array.prototype.slice.call(arguments,1)));}});","location":"jsio/interfaces.js"},'jsio.csp.client':{"src":"\njsio('import jsio.std.base64 as base64');jsio('import jsio.std.utf8 as utf8');jsio('import jsio.std.uri as uri');jsio('import jsio.logging');jsio('import .errors');jsio('import .transports');var logger=jsio.logging.getLogger(\"csp.client\");var READYSTATE=exports.READYSTATE={INITIAL:0,CONNECTING:1,CONNECTED:2,DISCONNECTING:3,DISCONNECTED:4};exports.CometSession=Class(function(supr){var id=0;var kDefaultBackoff=50;var kDefaultTimeoutInterval=45000;var kDefaultHandshakeTimeout=10000;this.init=function(){this._id=++id;this._url=null;this.readyState=READYSTATE.INITIAL;this._sessionKey=null;this._transport=null;this._options=null;this._utf8ReadBuffer=\"\";this._writeBuffer=\"\";this._packetsInFlight=null;this._lastEventId=null;this._lastSentId=null;this._handshakeLater=null;this._handshakeBackoff=kDefaultBackoff;this._handshakeRetryTimer=null;this._handshakeTimeoutTimer=null;this._timeoutTimer=null;this._writeBackoff=kDefaultBackoff;this._writeRetryTimer=null;this.cometBackoff=kDefaultBackoff;this._cometRetryTimer=null;}\nthis.setEncoding=function(encoding){if(encoding==this._options.encoding){return;}\nif(encoding!='utf8'&&encoding!='plain'){throw new errors.InvalidEncodingError();}\nif(encoding=='plain'&&this._buffer){var buffer=this._utf8ReadBuffer;this._utf8ReadBuffer=\"\";this._doOnRead(buffer);}\nthis._options.encoding=encoding;}\nthis.connect=function(url,options){this._url=url;this._options=options||{};this._options.encoding=this._options.encoding||'utf8';this.setEncoding(this._options.encoding);this._options.connectTimeout=this._options.connectTimeout||kDefaultHandshakeTimeout;var transportClass=transports.chooseTransport(url,this._options);this._transport=new transportClass();this._transport.handshakeFailure=bind(this,this._handshakeFailure);this._transport.handshakeSuccess=bind(this,this._handshakeSuccess);this._transport.cometFailure=bind(this,this._cometFailure);this._transport.cometSuccess=bind(this,this._cometSuccess);this._transport.sendFailure=bind(this,this._writeFailure);this._transport.sendSuccess=bind(this,this._writeSuccess);this.readyState=READYSTATE.CONNECTING;this._transport.handshake(this._url,this._options);this._handshakeTimeoutTimer=$setTimeout(bind(this,this._handshakeTimeout),this._options.connectTimeout);}\nthis.write=function(data,encoding){if(this.readyState!=READYSTATE.CONNECTED){throw new errors.ReadyStateError();}\nencoding=encoding||this._options.encoding||'utf8';if(encoding=='utf8'){data=utf8.encode(data);}\nthis._writeBuffer+=data;this._doWrite();}\nthis.close=function(err){switch(this.readyState){case READYSTATE.CONNECTING:clearTimeout(this._handshakeRetryTimer);clearTimeout(this._handshakeTimeoutTimer);break;case READYSTATE.CONNECTED:this._transport.abort();clearTimeout(this._cometRetryTimer);clearTimeout(this._writeRetryTimer);clearTimeout(this._timeoutTimer);break;case READYSTATE.DISCONNECTED:throw new errors.ReadyStateError(\"Session is already disconnected\");break;}\nthis._doOnDisconnect(err);}\nthis._handshakeTimeout=function(){logger.debug('handshake timeout');this._handshakeTimeoutTimer=null;this._doOnDisconnect(new errors.HandshakeTimeout());}\nthis._handshakeSuccess=function(d){logger.debug('handshake success',d);if(this.readyState!=READYSTATE.CONNECTING){logger.debug('received handshake success in invalid readyState:',this.readyState);return;}\nclearTimeout(this._handshakeTimeoutTimer);this._handshakeTimeoutTimer=null;this._sessionKey=d.session;this._opened=true;this.readyState=READYSTATE.CONNECTED;this._doOnConnect();this._doConnectComet();}\nthis._handshakeFailure=function(e){logger.debug('handshake failure',e);if(this.readyState!=READYSTATE.CONNECTING){return;}\nlogger.debug('trying again in ',this._handshakeBackoff);this._handshakeRetryTimer=$setTimeout(bind(this,function(){this._handshakeRetryTimer=null;this._transport.handshake(this._url,this._options);}),this._handshakeBackoff);this._handshakeBackoff*=2;}\nthis._writeSuccess=function(){if(this.readyState!=READYSTATE.CONNECTED){return;}\nthis._resetTimeoutTimer();this.writeBackoff=kDefaultBackoff;this._packetsInFlight=null;if(this._writeBuffer){this._doWrite();}}\nthis._writeFailure=function(){if(this.readyState!=READYSTATE.CONNECTED){return;}\nthis._writeTimer=$setTimeout(bind(this,function(){this._writeTimer=null;this._doWrite();}),this._writeBackoff);this._writeBackoff*=2;}\nthis._doWrite=function(){if(this._packetsInFlight){return;}\nlogger.debug('_writeBuffer:',this._writeBuffer);this._packetsInFlight=[this._transport.encodePacket(++this._lastSentId,this._writeBuffer,this._options)];this._writeBuffer=\"\";logger.debug('sending packets:',JSON.stringify(this._packetsInFlight));this._transport.send(this._url,this._sessionKey,JSON.stringify(this._packetsInFlight),this._options);}\nthis._doConnectComet=function(){logger.debug('_doConnectComet');this._transport.comet(this._url,this._sessionKey,this._lastEventId||0,this._options);}\nthis._cometFailure=function(){if(this.readyState!=READYSTATE.CONNECTED){return;}\nthis._cometTimer=$setTimeout(bind(this,function(){this._doConnectComet();}),this._cometBackoff);this._cometBackoff*=2;}\nthis._cometSuccess=function(packets){if(this.readyState!=READYSTATE.CONNECTED){return;}\nlogger.debug('comet Success:',packets);this._cometBackoff=kDefaultBackoff;this._resetTimeoutTimer();for(var i=0,packet;(packet=packets[i])||i<packets.length;i++){logger.debug('process packet:',packet);if(packet===null){return self.close();}\nlogger.debug('process packet',packet);var ackId=packet[0];var encoding=packet[1];var data=packet[2];if(typeof(this._lastEventId)=='number'&&ackId<=this._lastEventId){continue;}\nif(typeof(this._lastEventId)=='number'&&ackId!=this._lastEventId+1){return this.close(new errors.ServerProtocolError(201));}\nthis._lastEventId=ackId;if(encoding==1){try{logger.debug('before base64 decode:',data);data=base64.decode(data);logger.debug('after base64 decode:',data);}catch(e){return this.close(new errors.ServerProtocolError(202));}}\nif(this._options.encoding=='utf8'){this._utf8ReadBuffer+=data;logger.debug('before utf8 decode, _utf8ReadBuffer:',this._utf8ReadBuffer);var result=utf8.decode(this._utf8ReadBuffer);data=result[0];this._utf8ReadBuffer=this._utf8ReadBuffer.slice(result[1]);logger.debug('after utf8 decode, _utf8ReadBuffer:',this._utf8ReadBuffer,'data:',data);}\nlogger.debug('dispatching data:',data);try{this._doOnRead(data);}catch(e){logger.error('application code threw an error. (re-throwing in timeout):',e);setTimeout(function(){logger.debug('timeout fired, throwing error',e);throw e;},0);}}\nthis._doConnectComet();}\nthis._doOnRead=function(data){if(typeof(this.onread)=='function'){logger.debug('call onread function',data);this.onread(data);}\nelse{logger.debug('skipping onread callback (function missing)');}}\nthis._doOnDisconnect=function(err){if(typeof(this.ondisconnect)=='function'){logger.debug('call ondisconnect function',err);this.ondisconnect(err);}\nelse{logger.debug('skipping ondisconnect callback (function missing)');}}\nthis._doOnConnect=function(){if(typeof(this.onconnect)=='function'){logger.debug('call onconnect function');try{this.onconnect();}catch(e){logger.debug('onconnect caused errror',e);setTimeout(function(){throw e},0);}}\nelse{logger.debug('skipping onconnect callback (function missing)');}}\nthis._resetTimeoutTimer=function(){clearTimeout(this._timeoutTimer);this._timeoutTimer=$setTimeout(bind(this,function(){logger.debug('connection timeout expired');this.close(new errors.SessionTimeout())}),this._getTimeoutInterval())}\nthis._getTimeoutInterval=function(){return kDefaultTimeoutInterval;}})","location":"jsio/csp/client.js"},'jsio.protocols.mspp':{"src":"\njsio('import Class, log, jsio.logging');jsio('import jsio.std.utf8 as utf8');jsio('from jsio.protocols.buffered import BufferedProtocol');var loggers={};loggers.stream=jsio.logging.getLogger('MSPPStream');loggers.protocol=jsio.logging.getLogger('MSPPProtocol');loggers.stream.setLevel(0);loggers.protocol.setLevel(0);var frames={'OPEN':0,'CLOSE':1,'DATA':2};exports.MSPPStream=Class(function(){this.setMultiplexer=function(multiplexer){loggers.stream.debug('setMultiplexer: '+multiplexer);this.multiplexer=multiplexer;}\nthis.setEncoding=function(encoding){loggers.stream.debug('setEncoding: '+encoding);this.encoding=encoding;}\nthis.open=function(host,port,isBinary){if(isBinary)\nthis.encoding='utf8';this.id=this.multiplexer.openStream(this,host,port);loggers.stream.debug('open '+this.id+\": \"+host+\" \"+port+\" \"+isBinary);}\nthis.close=function(){loggers.stream.debug('close '+this.id);this.multiplexer.close(this.id);}\nthis.send=function(data,encoding){loggers.stream.debug('send '+this.id+\": \"+data+\" \"+encoding);if((encoding||this.encoding)=='utf8')\ndata=utf8.encode(data);this.multiplexer.writeToStream(this.id,data);}\nthis._onreadraw=function(data){if(this.encoding=='utf8')\ndata=utf8.decode(data);loggers.stream.debug('onreadraw: '+data);this.onread(data);}\nthis.onopen=function(){}\nthis.onclose=function(err){}\nthis.onread=function(data){}});var state={};state.closed=0;state.connecting=1;state.consuming=2;exports.MSPPProtocol=Class(BufferedProtocol,function(supr){this.init=function(){loggers.protocol.debug('new MSPPProtocol');supr(this,'init',[]);this.state=state.closed;this.transportType=null;this.transportOptions=null;this.currentId=0;this.streams={};this.writeBuffer=[];}\nthis.setTransport=function(transportType,transportOptions){this.transportType=transportType;this.transportOptions=transportOptions;}\nthis.connectionMade=function(isReconnect){loggers.protocol.debug('open');this.state=state.consuming;for(var i=0;i<this.writeBuffer.length;i++)\nthis._write(this.writeBuffer[i]);writeBuffer=[];}\nthis.connectionLost=this.connectionFailed=function(reason){loggers.protocol.debug('closed: '+reason);this.state=state.closed;for(stream in this.streams)\nthis.streams[stream].onclose(reason);}\nthis.openStream=function(stream,host,port){if(this.state==state.closed){this.state=state.connecting;jsio.connect(this,this.transportType,this.transportOptions);}\nvar id=++this.currentId;this.streams[id]=stream;this._write([id,frames.OPEN,host,port]);return id;}\nthis.closeStream=function(id){this._write([id,frames.CLOSE]);}\nthis.writeToStream=function(id,data){this._write([id,frames.DATA,data]);}\nthis.bufferUpdated=function(){loggers.protocol.debug('bufferUpdate: '+this.buffer._rawBuffer);if(this.state!=state.consuming)\nthrow new Error(\"buffer update in invalid MSPP state: \"+this.state);while(1){if(!this.buffer.hasDelimiter('['))\nbreak;var frameLength=this.buffer.peekToDelimiter('[');var frameLengthLength=frameLength.length;frameLength=parseInt(frameLength);if(!this.buffer.hasBytes(frameLengthLength+frameLength))\nbreak;this.buffer.consumeBytes(frameLengthLength);var data=this.buffer.consumeBytes(frameLength);loggers.protocol.debug('received: '+data);data=JSON.parse(data);switch(data[1]){case frames.OPEN:this.streams[data[0]].onopen();break;case frames.CLOSE:this.streams[data[0]].onclose(data[2]);break;case frames.DATA:this.streams[data[0]]._onreadraw(data[2]);break;default:throw new Error('invalid MSPP data type!');}}}\nthis._write=function(data){if(this.state!=state.consuming){loggers.protocol.debug(\"buffering write: \"+data);this.writeBuffer.push(data);return;}\ndata=JSON.stringify(data);data=data.length+data;loggers.protocol.debug('write: '+data);this.transport.write(data);}});","location":"jsio/protocols/mspp.js"},'jsio.csp.errors':{"src":"\nvar makeErrorClass=function(name,_code){var out=function(message,code){this.message=message;this.code=code||_code;}\nout.prototype.toString=function(){return name+(this.message?': '+this.message:'');}\nreturn out;}\nexports.ReadyStateError=makeErrorClass(\"ReadyStateError\");exports.InvalidEncodingError=makeErrorClass(\"InvalidEncodingError\");exports.HandshakeTimeout=makeErrorClass(\"HandshakeTimeout\",100);exports.SessionTimeout=makeErrorClass(\"HandshakeTimeout\",101);exports.ServerProtocolError=makeErrorClass(\"ServerProtocolError\",200);","location":"jsio/csp/errors.js"},'Orbited':{"src":"\njsio('import Class');jsio('from jsio.protocols.mspp import MSPPStream, MSPPProtocol');var multiplexer=null;exports.settings={'host':'localhost','port':8000,'path':'/csp'};exports.TCPSocket=Class(MSPPStream,function(){this.init=function(){this.setEncoding('plain');if(multiplexer==null){multiplexer=new MSPPProtocol();multiplexer.setTransport('csp',{\"url\":\"http://\"+exports.settings.host+\":\"+exports.settings.port+exports.settings.path});}\nthis.setMultiplexer(multiplexer);}});","location":"Orbited.js"},'jsio.std.JSON':{"src":"\nexports.createGlobal=function(){if(typeof JSON=='undefined'){JSON={};}\nif(typeof JSON.stringify!=='function'){JSON.stringify=exports.stringify;}\nif(typeof JSON.parse!=='function'){JSON.parse=exports.parse;}};;(function(){var cx=/[\\u0000\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]/g,escapable=/[\\\\\\\"\\x00-\\x1f\\x7f-\\x9f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]/g,gap,indent,meta={'\\b':'\\\\b','\\t':'\\\\t','\\n':'\\\\n','\\f':'\\\\f','\\r':'\\\\r','\"':'\\\\\"','\\\\':'\\\\\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'\"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'\"':'\"'+string+'\"';}\nfunction str(key,holder){var mind=gap,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}\nif(typeof rep==='function'){value=rep.call(holder,key,value);}\nswitch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':return String(value);case'object':if(value===null){return'null';}\nif(value.constructor===Date){return exports.stringifyDate(value);}\ngap+=indent;var partial=[];if(value.constructor===Array){var length=value.length;for(var i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}\nvar v=partial.length===0?'[]':gap?'[\\n'+gap+\npartial.join(',\\n'+gap)+'\\n'+\nmind+']':'['+partial.join(',')+']';gap=mind;return v;}\nif(rep&&typeof rep==='object'){var length=rep.length;for(var i=0;i<length;i+=1){var k=rep[i];if(typeof k==='string'){var v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(var k in value){if(Object.hasOwnProperty.call(value,k)){var v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}\nvar v=partial.length===0?'{}':gap?'{\\n'+gap+partial.join(',\\n'+gap)+'\\n'+\nmind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}\nexports.stringify=function(value,replacer,space){gap='';indent='';if(typeof space==='number'){for(var i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}\nrep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON stringify: invalid replacer');}\nreturn str('',{'':value});};exports.stringifyDate=function(d){var year=d.getUTCFullYear(),month=d.getUTCMonth()+1,day=d.getUTCDate(),hours=d.getUTCHours(),minutes=d.getUTCMinutes(),seconds=d.getUTCSeconds(),ms=d.getUTCMilliseconds();if(month<10){month='0'+month;}\nif(day<10){day='0'+day;}\nif(hours<10){hours='0'+hours;}\nif(minutes<10){minutes='0'+minutes;}\nif(seconds<10){seconds='0'+seconds;}\nif(ms<10){ms='00'+ms;}\nelse if(ms<100){ms='0'+ms;}\nreturn'\"'+year\n+'-'+month\n+'-'+day\n+'T'+hours\n+':'+minutes\n+':'+seconds\n+'.'+ms\n+'Z\"';}\nexports.parse=function(text,reviver){cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\\\u'+\n('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}\nif(/^[\\],:{}\\s]*$/.test(text.replace(/\\\\(?:[\"\\\\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/\"[^\"\\\\\\n\\r]*\"|true|false|null|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?/g,']').replace(/(?:^|:|,)(?:\\s*\\[)+/g,'')))\n{var j=eval('('+text+')');if(!reviver){return j;}else{var walk=function(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}\nreturn reviver.call(holder,key,value);}\nreturn walk({'':j},'');}}\nthrow new SyntaxError('JSON.parse');};}());","location":"jsio/std/JSON.js"},'jsio.env.browser.csp':{"src":"\njsio('import Class, bind, jsio.logging, jsio.interfaces');jsio('from jsio.csp.client import CometSession');var logger=jsio.logging.getLogger('env.browser.csp');exports.Connector=Class(jsio.interfaces.Connector,function(){this.connect=function(){var conn=new CometSession();conn.onconnect=bind(this,function(){logger.debug('conn has opened');this.onConnect(new Transport(conn));});conn.ondisconnect=bind(this,function(code){logger.debug('conn closed without opening, code:',code);});logger.debug('open the conection');this._opts.encoding='plain';var url=this._opts.url;delete this._opts.url;conn.connect(url,this._opts);}});var Transport=Class(jsio.interfaces.Transport,function(){this.init=function(conn){this._conn=conn;}\nthis.makeConnection=function(protocol){this._conn.onread=bind(protocol,'dataReceived');this._conn.ondisconnect=bind(protocol,'connectionLost');}\nthis.write=function(data,encoding){this._conn.write(data);}\nthis.loseConnection=function(protocol){this._conn.close();}});","location":"jsio/env/browser/csp.js"},'jsio.std.utf8':{"src":"\nexports.UnicodeCodecError=function(message){this.message=message;};var UnicodeCodecError=exports.UnicodeCodecError;UnicodeCodecError.prototype.toString=function(){return'UnicodeCodecError'+(this.message?': '+this.message:'');};exports.encode=function(unicode_string){try{return unescape(encodeURIComponent(unicode_string));}\ncatch(err){throw new UnicodeCodecError('invalid input string');};};exports.decode=function(bytes){if(/[^\\x00-\\xFF]/.test(bytes)){throw new UnicodeCodecError('invalid utf-8 bytes');};var len,len_parsed;len=len_parsed=bytes.length;var last=len-1;if(bytes.charCodeAt(last)>=0x80){for(var i=1;i<=3;i++){if(bytes.charCodeAt(len-i)>=0xC0){len_parsed=len-i;break;};};try{decodeURIComponent(escape(bytes.slice(len_parsed)));len_parsed=len;}\ncatch(err){};};try{return[decodeURIComponent(escape(bytes.slice(0,len_parsed))),len_parsed];}\ncatch(err){throw new UnicodeCodecError('invalid utf-8 bytes');};};","location":"jsio/std/utf8.js"},'jsio.util.browserdetect':{"src":"\nexports.BrowserDetect=new function(){var versionSearchString;var dataBrowser=[{string:navigator.userAgent,subString:\"Chrome\"},{string:navigator.userAgent,subString:\"OmniWeb\",versionSearch:\"OmniWeb/\"},{string:navigator.vendor,subString:\"Apple\",identity:\"Safari\",versionSearch:\"Version\"},{prop:window.opera,identity:\"Opera\"},{string:navigator.vendor,subString:\"iCab\"},{string:navigator.vendor,subString:\"KDE\",identity:\"Konqueror\"},{string:navigator.userAgent,subString:\"Firefox\"},{string:navigator.vendor,subString:\"Camino\"},{string:navigator.userAgent,subString:\"Netscape\"},{string:navigator.userAgent,subString:\"MSIE\",identity:\"IE\",versionSearch:\"MSIE\"},{string:navigator.userAgent,subString:\"Gecko\",identity:\"Mozilla\",versionSearch:\"rv\"},{string:navigator.userAgent,subString:\"Mozilla\",identity:\"Netscape\",versionSearch:\"Mozilla\"}];var dataOS=[{string:navigator.platform,subString:\"Win\",identity:\"Windows\"},{string:navigator.platform,subString:\"Mac\"},{string:navigator.userAgent,subString:\"iPhone\",identity:\"iPhone/iPod\"},{string:navigator.platform,subString:\"Linux\"}];function searchString(data){for(var i=0,item;item=data[i];i++){var dataString=item.string;var dataProp=item.prop;item.identity=item.identity||item.subString;versionSearchString=item.versionSearch||item.identity;if(dataString){if(dataString.indexOf(item.subString)!=-1)\nreturn item.identity;}else if(dataProp)\nreturn item.identity;}}\nfunction searchVersion(dataString){var index=dataString.indexOf(versionSearchString);if(index==-1)return;return parseFloat(dataString.substring(index+versionSearchString.length+1));}\nthis.browser=searchString(dataBrowser)||\"unknown\";this.version=searchVersion(navigator.userAgent)||searchVersion(navigator.appVersion)||\"unknown\";this.OS=searchString(dataOS)||\"unknown\";this.isWebKit=RegExp(\" AppleWebKit/\").test(navigator.userAgent);this['is'+this.browser]=this.version;};","location":"jsio/util/browserdetect.js"}};var pre_jsioImport=[];if(typeof exports=='undefined'){var jsio=window.jsio=bind(this,_jsioImport,window,'');}else if(typeof GLOBAL!='undefined'){var jsio=GLOBAL.jsio=bind(this,_jsioImport,GLOBAL,'');}
+jsio.script_src='Orbited.js';var modulePathCache={}
+function getModulePathPossibilities(pathString){var segments=pathString.split('.')
+var modPath=segments.join('/');var out;if(segments[0]in modulePathCache){out=[[modulePathCache[segments[0]]+'/'+modPath+'.js',null]];}else{out=[];for(var i=0,path;path=jsio.path[i];++i){out.push([path+'/'+modPath+'.js',path]);}}
+return out;}
+jsio.path=['.'];jsio.__env=typeof node!=='undefined'&&typeof process!=='undefined'&&process.version?'node':'browser';switch(jsio.__env){case'node':var posix=require('posix');var RUNTIME={cwd:process.cwd,argv:process.ARGV,argc:process.ARGC,write:process.stdio.writeError,writeAsync:process.stdio.write,readFile:function(filename){return posix.cat(filename,'utf8');},eval:function(code,location){return process.compile(code,location);}}
+break;case'browser':var src=browser_findScript();var segments=src.split('/');var cwd=segments.slice(0,segments.length-2).join('/');if(cwd){jsio.path.push(cwd);}else{cwd='.';};var RUNTIME={cwd:function(){return cwd;},argv:null,argc:null,write:browser_getLog(),writeAsync:browser_getLog(),readFile:function(){},eval:function(src){return eval(src);}}
+if(typeof eval('(function(){})')=='undefined'){RUNTIME.eval=function(src){try{eval('jsio.__f='+src);return jsio.__f;}finally{delete jsio.__f;}}}
+modulePathCache.jsio=cwd;break;}
+function browser_findScript(){try{var scripts=document.getElementsByTagName('script');for(var i=0,script;script=scripts[i];++i){if((script.src==jsio.script_src)||(script.src.slice(script.src.length-jsio.script_src.length)==jsio.script_src)){return makeAbsoluteURL(script.src,window.location);}}}catch(e){}}
+function browser_getLog(){if(typeof console!='undefined'&&console.log){return console.log;}else{return browser_oldLog;}}
+function browser_oldLog(){var d=document.createElement('div');document.body.appendChild(d);out=[]
+for(var i=0,item;(item=arguments[i])||i<arguments.length;++i){try{out.push(JSON.stringify(item));}catch(e){out.push(item.toString());}}
+d.innerHTML=out.join(", ");}
+function $each(i,context,f){if(!f){f=context;context=this;}
+for(var j in i){if(i.hasOwnProperty(j)){f(j,i[j],i);}}}
+function bind(context,method){var args=Array.prototype.slice.call(arguments,2);return function(){method=(typeof method=='string'?context[method]:method);return method.apply(context,args.concat(Array.prototype.slice.call(arguments,0)))}};function $setTimeout(f,t){var args=Array.prototype.slice.call(arguments,2);return setTimeout(function(){try{f.apply(this,args);}catch(e){}},t)}
+function $setInterval(f,t){var args=Array.prototype.slice.call(arguments,2);return setInterval(function(){try{f.apply(this,args);}catch(e){}},t)}
+function Class(parent,proto){if(!parent){throw new Error('parent or prototype not provided');}
+if(!proto){proto=parent;}
+else if(parent instanceof Array){proto.prototype={};for(var i=0,p;p=parent[i];++i){for(var item in p.prototype){if(!(item in proto.prototype)){proto.prototype[item]=p.prototype[item];}}}
+parent=parent[0];}else{proto.prototype=parent.prototype;}
+var cls=function(){if(this.init){this.init.apply(this,arguments);}}
+cls.prototype=new proto(function(context,method,args){var args=args||[];var target=parent;while(target=target.prototype){if(target[method]){return target[method].apply(context,args);}}
+throw new Error('method '+method+' does not exist');});cls.prototype.constructor=cls;return cls;}
+var strDuplicate=function(str,num){var out="";for(var i=0;i<num;++i){out+=str;}
+return out;}
+switch(jsio.__env){case'node':var nodeWrapper={require:require};var stringifyPretty=function(item){return _stringify(true,item,1);}
+var stringify=function(item){return _stringify(false,item);}
+var _stringify=function(pretty,item,tab){if(item instanceof Array){var str=[];for(var i=0,len=item.length;i<len;++i){str.push(_stringify(pretty,item[i]));}
+return'['+str.join(',')+']';}else if(typeof(item)=='object'){var str=[];for(var key in item){var value=key+':'+(pretty?' ':'');if(typeof item[key]=='function'){var def=item[key].toString();var match=def.match(/^function\s+\((.*?)\)/);value+=match?'f('+match[1]+') {...}':'[Function]';}else{value+=_stringify(pretty,item[key],tab+1);}
+str.push(value);}
+if(pretty&&str.length>1){var spacer=strDuplicate('\t',tab);return'{\n'+spacer+str.join(',\n'+spacer)+'\n'+strDuplicate('\t',tab-1)+'}';}else{return'{'+str.join(',')+'}';}}
+return item+"";}
+var log=function(){RUNTIME.write(Array.prototype.slice.call(arguments,0).map(stringifyPretty).join(' ')+"\n");}
+window=GLOBAL;var compile=function(context,args){try{var fn=RUNTIME.eval("(function(_) { with(_){delete _;(function(){"+args.src+"\n}).call(this)}})",args.location);}catch(e){if(e instanceof SyntaxError){log("Syntax Error loading ",args.location,e);}
+throw e;}
+try{fn.call(context.exports,context);}catch(e){if(e.type=="stack_overflow"){log("Stack overflow in",args.location,e);}else{log("error when loading",args.location);}
+throw e;}
+return true;}
+var windowCompile=function(context,args){var fn=RUNTIME.eval("(function(_){with(_){delete _;(function(){"+args.src+"\n}).call(this)}})",args.location);fn.call(context.exports,context);}
+var cwd=RUNTIME.cwd();var makeRelative=function(path){var i=path.match('^'+cwd);if(i&&i[0]==cwd){var offset=path[cwd.length]=='/'?1:0
+return path.slice(cwd.length+offset);}
+return path;}
+var getModuleSourceAndPath=function(pathString){var baseMod=pathString.split('.')[0];var paths=getModulePathPossibilities(pathString);var cwd=RUNTIME.cwd()+'/';for(var i=0,path;path=paths[i];++i){var cachePath=path[1];var path=path[0];try{var out={src:RUNTIME.readFile(path).wait(),location:path};if(!(baseMod in modulePathCache)){modulePathCache[baseMod]=cachePath;}
+return out;}catch(e){}}
+throw new Error("Module not found: "+pathString+"\n(looked in "+paths+")");}
+var segments=__filename.split('/');var jsioPath=segments.slice(0,segments.length-2).join('/');if(jsioPath){jsio.path.push(jsioPath);modulePathCache.jsio=jsioPath;}else{modulePathCache.jsio='.';}
+jsio.__path=makeRelative(RUNTIME.argv[1]);break;default:var log=browser_getLog();var compile=function(context,args){var code="(function(_){with(_){delete _;(function(){"
++args.src
++"\n}).call(this)}})\n//@ sourceURL="+args.location;try{var fn=RUNTIME.eval(code);}catch(e){if(e instanceof SyntaxError){var src='javascript:document.open();document.write("<scr"+"ipt src=\''
++args.location
++'\'></scr"+"ipt>")';var callback=function(){var el=document.createElement('iframe');with(el.style){position='absolute';top=left='-999px';width=height='1px';visibility='hidden';}
+el.src=src;$setTimeout(function(){document.body.appendChild(el);},0);}
+if(document.body){callback();}
+else{window.addEventListener('load',callback,false);}
+throw new Error("forcing halt on load of "+args.location);}
+throw e;}
+try{fn.call(context.exports,context);}catch(e){log('error when loading '+args.location);throw e;}
+return true;}
+var windowCompile=function(context,args){var f="(function(_){with(_){delete _;(function(){"+args.src+"\n}).call(this)}})\n//@ sourceURL="+args.location;var fn=RUNTIME.eval(f);fn.call(context.exports,context);}
+var createXHR=function(){return window.XMLHttpRequest?new XMLHttpRequest():window.ActiveXObject?new ActiveXObject("Msxml2.XMLHTTP"):null;}
+var getModuleSourceAndPath=function(pathString){if(preloaded_source[pathString]){return preloaded_source[pathString];}
+var baseMod=pathString.split('.')[0];var paths=getModulePathPossibilities(pathString);for(var i=0,path;path=paths[i];++i){var cachePath=path[1];var path=path[0];var xhr=createXHR();var failed=false;try{xhr.open('GET',path,false);xhr.send(null);}catch(e){failed=true;}
+if(failed||xhr.status==404||xhr.status==-1100||false)
+{continue;}
+if(!(baseMod in modulePathCache)){modulePathCache[baseMod]=cachePath;}
+return{src:xhr.responseText,location:path};}
+throw new Error("Module not found: "+pathString+" (looked in "+paths.join(', ')+")");}
+var makeRelative=function(path){return path.replace(cwd+'/','').replace(cwd,'');}
+jsio.__path=makeRelative(window.location.toString());break;}
+jsio.basePath=jsio.path[jsio.path.length-1];var modules={bind:bind,Class:Class,log:log,jsio:jsio};function makeAbsoluteURL(url,location){if(/^[A-Za-z]*:\/\//.test(url)){return url;}
+var prefix=location.protocol+'//'+location.host;if(url.charAt(0)=='/'){return prefix+url;}
+var result=location.pathname.match(/\/*(.*?\/?)\/*$/);var parts=result?result[1].split('/'):[];parts.pop();var urlParts=url.split('/');while(true){if(urlParts[0]=='.'){urlParts.shift();}else if(urlParts[0]=='..'){urlParts.shift();parts.pop();}else{break;}}
+var pathname=parts.join('/');if(pathname)pathname+='/';return prefix+'/'+pathname+urlParts.join('/');}
+function resolveRelativePath(pkg,path){if(pkg.charAt(0)=='.'){pkg=pkg.substring(1);var segments=path.split('.');while(pkg.charAt(0)=='.'){pkg=pkg.slice(1);segments.pop();}
+var prefix=segments.join('.');if(prefix){return prefix+'.'+pkg;}}
+return pkg;}
+function _jsioImport(context,path,what){var match,imports=[];if((match=what.match(/^(from|external)\s+([\w.$]+)\s+import\s+(.*)$/))){imports[0]={from:resolveRelativePath(match[2],path),external:match[1]=='external',"import":{}};match[3].replace(/\s*([\w.$*]+)(?:\s+as\s+([\w.$]+))?/g,function(_,item,as){imports[0]["import"][item]=as||item;});}else if((match=what.match(/^import\s+(.*)$/))){match[1].replace(/\s*([\w.$]+)(?:\s+as\s+([\w.$]+))?,?/g,function(_,pkg,as){fullPkg=resolveRelativePath(pkg,path);imports[imports.length]=as?{from:fullPkg,as:as}:{from:fullPkg,as:pkg};});}else{if(SyntaxError){throw new SyntaxError(what);}else{throw new Error("Syntax error: "+what);}}
+for(var i=0,item,len=imports.length;(item=imports[i])||i<len;++i){var pkg=item.from;var segments=pkg.split('.');if(!(pkg in modules)){try{var result=getModuleSourceAndPath(pkg);}catch(e){log('Error:',context.jsio.__path,'could not execute: "'+what+'"');throw e;}
+var newRelativePath=segments.slice(0,segments.length-1).join('.');if(!item.external){var newContext={exports:{},global:window,bind:bind,Class:Class,$setTimeout:$setTimeout,$setInterval:$setInterval};newContext.jsio=bind(this,_jsioImport,newContext,newRelativePath);for(var j in modules.jsio){newContext.jsio[j]=modules.jsio[j];}
+var tmp=result.location.split('/');newContext.jsio.__dir=makeRelative(tmp.slice(0,tmp.length-1).join('/'));newContext.jsio.__path=makeRelative(result.location);newContext.jsio.__env=jsio.__env;newContext.jsio.node=nodeWrapper;compile(newContext,result);modules[pkg]=newContext.exports;}else{var newContext={};for(var j in item["import"]){newContext[j]=undefined;}
+windowCompile(newContext,result);modules[pkg]=newContext;for(var j in item["import"]){if(newContext[j]===undefined){newContext[j]=window[j];}}}}
+if(item.as){var segments=item.as.match(/^\.*(.*?)\.*$/)[1].split('.');var c=context;for(var k=0,slen=segments.length-1,segment;(segment=segments[k])&&k<slen;++k){if(!segment)continue;if(!c[segment]){c[segment]={};}
+c=c[segment];}
+c[segments[slen]]=modules[pkg];}else if(item["import"]){if(item["import"]['*']){for(var k in modules[pkg]){context[k]=modules[pkg][k];}}else{try{for(var k in item["import"]){context[item["import"][k]]=modules[pkg][k];}}catch(e){log('module: ',modules);throw e;}}}}}
+var _localContext={};var _jsio=_localContext.jsio=bind(this,_jsioImport,_localContext,'jsio');_jsio('import jsio.env');_jsio('import jsio.std.JSON');_jsio.std.JSON.createGlobal();jsio.listen=function(server,transportName,opts){var listenerClass=_jsio.env.getListener(transportName);var listener=new listenerClass(server,opts);listener.listen();return listener;}
+jsio.connect=function(protocolInstance,transportName,opts){var connector=new(_jsio.env.getConnector(transportName))(protocolInstance,opts);connector.connect();return connector;}
+jsio.quickServer=function(protocolClass){_jsio('import .interfaces');return new _jsio.interfaces.Server(protocolClass);}
+for(var i=0,target;target=pre_jsioImport[i];++i){jsio.require(target);}})();jsio("import Orbited");delete jsio;

daemon/orbited/static/base64.js

-/*
-"URL-safe" Base64 Codec, by Jacob Rus
-
-This library happily strips off as many trailing '=' as are included in the
-input to 'decode', and doesn't worry whether its length is an even multiple
-of 4. It does not include trailing '=' in its own output. It uses the
-'URL safe' base64 alphabet, where the last two characters are '-' and '_'.
-
---------------------
-
-Copyright (c) 2009 Jacob Rus
-
-Permission is hereby granted, free of charge, to any person
-obtaining a copy of this software and associated documentation
-files (the "Software"), to deal in the Software without
-restriction, including without limitation the rights to use,
-copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the
-Software is furnished to do so, subject to the following
-conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-OTHER DEALINGS IN THE SOFTWARE.
-*/
-
-(function() {
-
-var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef' +
-               'ghijklmnopqrstuvwxyz0123456789-_';
-var pad = '=';
-
-var UnicodeCodecError = this.UnicodeCodecError = function (message) { this.message = message; };
-this.UnicodeCodecError.prototype.toString = function () {
-  return 'UnicodeCodecError' + (this.message ? ': ' + this.message : '');
-};
-
-var shorten = function (array, number) {
-  // remove 'number' characters from the end of 'array', in place (no return)
-  for (var i = number; i > 0; i--){ array.pop(); };
-};
-
-var decode_map = {};
-for (var i=0, n=alphabet.length; i < n; i++) {
-  decode_map[alphabet[i]] = i;
-};
-// use this regexp in the decode function to sniff out invalid characters.
-var alphabet_inverse = new RegExp('[^' + alphabet + ']');
-var Base64CodecError = this.Base64CodecError = function (message) { this.message = message; };
-Base64CodecError.prototype.toString = function () {
-  return 'Base64CodecError' + (this.message ? ': ' + this.message : '');
-};
-var assertOrBadInput = function (exp, message) {
-  if (!exp) { throw new Base64CodecError(message) };
-};
-this.encode = function (bytes) {
-  assertOrBadInput(!(/[^\x00-\xFF]/.test(bytes)), // disallow two-byte chars
-                   'Input contains out-of-range characters.');
-  var padding = '\x00\x00\x00'.slice((bytes.length % 3) || 3);
-  bytes += padding; // pad with null bytes
-  var out_array = [];
-  for (var i=0, n=bytes.length; i < n; i+=3) {
-    var newchars = (
-      (bytes.charCodeAt(i)   << 020) +
-      (bytes.charCodeAt(i+1) << 010) +
-      (bytes.charCodeAt(i+2)));
-    out_array.push(
-      alphabet[(newchars >> 18) & 077],
-      alphabet[(newchars >> 12) & 077],
-      alphabet[(newchars >> 6)  & 077], 
-      alphabet[(newchars)       & 077]);      
-  };
-  shorten(out_array, padding.length);
-  return out_array.join('');
-};
-this.decode = function (b64text) {
-  b64text = b64text.replace(/\s/g, '') // kill whitespace
-  // strip trailing pad characters from input; // XXX maybe some better way?
-  var i = b64text.length; while (b64text[--i] === pad) {}; b64text = b64text.slice(0, i + 1);
-  assertOrBadInput(!alphabet_inverse.test(b64text),
-                   'Input contains out-of-range characters.');
-  var padding = Array(5 - ((b64text.length % 4) || 4)).join(alphabet[alphabet.length - 1]);
-  b64text += padding; // pad with last letter of alphabet
-  var out_array = [];
-  for (var i=0, n=b64text.length; i < n; i+=4) {
-    newchars = (
-      (decode_map[b64text[i]]   << 18) +
-      (decode_map[b64text[i+1]] << 12) +
-      (decode_map[b64text[i+2]] << 6)  +
-      (decode_map[b64text[i+3]]));
-    out_array.push(
-      (newchars >> 020) & 0xFF,
-      (newchars >> 010) & 0xFF, 
-      (newchars)        & 0xFF);
-  };
-  shorten(out_array, padding.length);
-  return String.fromCharCode.apply(String, out_array);
-};
-}).call(typeof(exports) != 'undefined' ? exports : (function() { window.base64 = {}; return base64; })())

daemon/orbited/static/json2.js

-/*
-    http://www.JSON.org/json2.js
-    2009-08-17
-
-    Public Domain.
-
-    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
-
-    See http://www.JSON.org/js.html
-
-    This file creates a global JSON object containing two methods: stringify
-    and parse.
-
-        JSON.stringify(value, replacer, space)
-            value       any JavaScript value, usually an object or array.
-
-            replacer    an optional parameter that determines how object
-                        values are stringified for objects. It can be a
-                        function or an array of strings.
-
-            space       an optional parameter that specifies the indentation
-                        of nested structures. If it is omitted, the text will
-                        be packed without extra whitespace. If it is a number,
-                        it will specify the number of spaces to indent at each
-                        level. If it is a string (such as '\t' or '&nbsp;'),
-                        it contains the characters used to indent at each level.
-
-            This method produces a JSON text from a JavaScript value.
-
-            When an object value is found, if the object contains a toJSON
-            method, its toJSON method will be called and the result will be
-            stringified. A toJSON method does not serialize: it returns the
-            value represented by the name/value pair that should be serialized,
-            or undefined if nothing should be serialized. The toJSON method
-            will be passed the key associated with the value, and this will be
-            bound to the value
-
-            For example, this would serialize Dates as ISO strings.
-
-                Date.prototype.toJSON = function (key) {
-                    function f(n) {
-                        // Format integers to have at least two digits.
-                        return n < 10 ? '0' + n : n;
-                    }
-
-                    return this.getUTCFullYear()   + '-' +
-                         f(this.getUTCMonth() + 1) + '-' +
-                         f(this.getUTCDate())      + 'T' +
-                         f(this.getUTCHours())     + ':' +
-                         f(this.getUTCMinutes())   + ':' +
-                         f(this.getUTCSeconds())   + 'Z';
-                };
-
-            You can provide an optional replacer method. It will be passed the
-            key and value of each member, with this bound to the containing
-            object. The value that is returned from your method will be
-            serialized. If your method returns undefined, then the member will
-            be excluded from the serialization.
-
-            If the replacer parameter is an array of strings, then it will be
-            used to select the members to be serialized. It filters the results
-            such that only members with keys listed in the replacer array are
-            stringified.
-
-            Values that do not have JSON representations, such as undefined or
-            functions, will not be serialized. Such values in objects will be
-            dropped; in arrays they will be replaced with null. You can use
-            a replacer function to replace those with JSON values.
-            JSON.stringify(undefined) returns undefined.
-
-            The optional space parameter produces a stringification of the
-            value that is filled with line breaks and indentation to make it
-            easier to read.
-
-            If the space parameter is a non-empty string, then that string will
-            be used for indentation. If the space parameter is a number, then
-            the indentation will be that many spaces.
-
-            Example:
-
-            text = JSON.stringify(['e', {pluribus: 'unum'}]);
-            // text is '["e",{"pluribus":"unum"}]'
-
-
-            text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
-            // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
-
-            text = JSON.stringify([new Date()], function (key, value) {
-                return this[key] instanceof Date ?
-                    'Date(' + this[key] + ')' : value;
-            });
-            // text is '["Date(---current time---)"]'
-
-
-        JSON.parse(text, reviver)
-            This method parses a JSON text to produce an object or array.
-            It can throw a SyntaxError exception.
-
-            The optional reviver parameter is a function that can filter and
-            transform the results. It receives each of the keys and values,
-            and its return value is used instead of the original value.
-            If it returns what it received, then the structure is not modified.
-            If it returns undefined then the member is deleted.
-
-            Example:
-
-            // Parse the text. Values that look like ISO date strings will
-            // be converted to Date objects.
-
-            myData = JSON.parse(text, function (key, value) {
-                var a;
-                if (typeof value === 'string') {
-                    a =
-/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
-                    if (a) {
-                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
-                            +a[5], +a[6]));
-                    }
-                }
-                return value;
-            });
-
-            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
-                var d;
-                if (typeof value === 'string' &&
-                        value.slice(0, 5) === 'Date(' &&
-                        value.slice(-1) === ')') {
-                    d = new Date(value.slice(5, -1));
-                    if (d) {
-                        return d;
-                    }
-                }
-                return value;
-            });
-
-
-    This is a reference implementation. You are free to copy, modify, or
-    redistribute.
-
-    This code should be minified before deployment.
-    See http://javascript.crockford.com/jsmin.html
-
-    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
-    NOT CONTROL.
-*/
-
-/*jslint evil: true */
-
-/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
-    call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
-    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
-    lastIndex, length, parse, prototype, push, replace, slice, stringify,
-    test, toJSON, toString, valueOf
-*/
-
-"use strict";
-
-// Create a JSON object only if one does not already exist. We create the
-// methods in a closure to avoid creating global variables.
-
-if (!this.JSON) {
-    this.JSON = {};
-}
-
-(function () {
-
-    function f(n) {
-        // Format integers to have at least two digits.
-        return n < 10 ? '0' + n : n;
-    }
-
-    if (typeof Date.prototype.toJSON !== 'function') {
-
-        Date.prototype.toJSON = function (key) {
-
-            return isFinite(this.valueOf()) ?
-                   this.getUTCFullYear()   + '-' +
-                 f(this.getUTCMonth() + 1) + '-' +
-                 f(this.getUTCDate())      + 'T' +
-                 f(this.getUTCHours())     + ':' +
-                 f(this.getUTCMinutes())   + ':' +
-                 f(this.getUTCSeconds())   + 'Z' : null;
-        };
-
-        String.prototype.toJSON =
-        Number.prototype.toJSON =
-        Boolean.prototype.toJSON = function (key) {
-            return this.valueOf();
-        };
-    }
-
-    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
-        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
-        gap,
-        indent,
-        meta = {    // table of character substitutions
-            '\b': '\\b',
-            '\t': '\\t',
-            '\n': '\\n',
-            '\f': '\\f',
-            '\r': '\\r',
-            '"' : '\\"',
-            '\\': '\\\\'
-        },
-        rep;
-
-
-    function quote(string) {
-
-// If the string contains no control characters, no quote characters, and no
-// backslash characters, then we can safely slap some quotes around it.
-// Otherwise we must also replace the offending characters with safe escape
-// sequences.
-
-        escapable.lastIndex = 0;
-        return escapable.test(string) ?
-            '"' + string.replace(escapable, function (a) {
-                var c = meta[a];
-                return typeof c === 'string' ? c :
-                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
-            }) + '"' :
-            '"' + string + '"';
-    }
-
-
-    function str(key, holder) {
-
-// Produce a string from holder[key].
-
-        var i,          // The loop counter.
-            k,          // The member key.
-            v,          // The member value.
-            length,
-            mind = gap,
-            partial,
-            value = holder[key];
-
-// If the value has a toJSON method, call it to obtain a replacement value.
-
-        if (value && typeof value === 'object' &&
-                typeof value.toJSON === 'function') {
-            value = value.toJSON(key);
-        }
-
-// If we were called with a replacer function, then call the replacer to
-// obtain a replacement value.
-
-        if (typeof rep === 'function') {
-            value = rep.call(holder, key, value);
-        }
-
-// What happens next depends on the value's type.
-
-        switch (typeof value) {
-        case 'string':
-            return quote(value);
-
-        case 'number':
-
-// JSON numbers must be finite. Encode non-finite numbers as null.
-
-            return isFinite(value) ? String(value) : 'null';
-
-        case 'boolean':
-        case 'null':
-
-// If the value is a boolean or null, convert it to a string. Note:
-// typeof null does not produce 'null'. The case is included here in
-// the remote chance that this gets fixed someday.
-
-            return String(value);
-
-// If the type is 'object', we might be dealing with an object or an array or
-// null.
-
-        case 'object':
-
-// Due to a specification blunder in ECMAScript, typeof null is 'object',
-// so watch out for that case.
-
-            if (!value) {
-                return 'null';
-            }
-
-// Make an array to hold the partial results of stringifying this object value.
-
-            gap += indent;
-            partial = [];
-
-// Is the value an array?
-
-            if (Object.prototype.toString.apply(value) === '[object Array]') {
-
-// The value is an array. Stringify every element. Use null as a placeholder
-// for non-JSON values.
-
-                length = value.length;
-                for (i = 0; i < length; i += 1) {
-                    partial[i] = str(i, value) || 'null';
-                }
-
-// Join all of the elements together, separated with commas, and wrap them in
-// brackets.
-
-                v = partial.length === 0 ? '[]' :
-                    gap ? '[\n' + gap +
-                            partial.join(',\n' + gap) + '\n' +
-                                mind + ']' :
-                          '[' + partial.join(',') + ']';
-                gap = mind;
-                return v;
-            }
-
-// If the replacer is an array, use it to select the members to be stringified.
-
-            if (rep && typeof rep === 'object') {
-                length = rep.length;
-                for (i = 0; i < length; i += 1) {
-                    k = rep[i];
-                    if (typeof k === 'string') {
-                        v = str(k, value);
-                        if (v) {
-                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
-                        }
-                    }
-                }
-            } else {
-
-// Otherwise, iterate through all of the keys in the object.
-
-                for (k in value) {
-                    if (Object.hasOwnProperty.call(value, k)) {
-                        v = str(k, value);
-                        if (v) {
-                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
-                        }
-                    }
-                }
-            }
-
-// Join all of the member texts together, separated with commas,
-// and wrap them in braces.
-
-            v = partial.length === 0 ? '{}' :
-                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
-                        mind + '}' : '{' + partial.join(',') + '}';
-            gap = mind;
-            return v;
-        }
-    }
-
-// If the JSON object does not yet have a stringify method, give it one.
-
-    if (typeof JSON.stringify !== 'function') {
-        JSON.stringify = function (value, replacer, space) {
-
-// The stringify method takes a value and an optional replacer, and an optional
-// space parameter, and returns a JSON text. The replacer can be a function
-// that can replace values, or an array of strings that will select the keys.
-// A default replacer method can be provided. Use of the space parameter can
-// produce text that is more easily readable.
-
-            var i;
-            gap = '';
-            indent = '';
-
-// If the space parameter is a number, make an indent string containing that
-// many spaces.
-
-            if (typeof space === 'number') {
-                for (i = 0; i < space; i += 1) {
-                    indent += ' ';
-                }
-
-// If the space parameter is a string, it will be used as the indent string.
-
-            } else if (typeof space === 'string') {
-                indent = space;
-            }
-
-// If there is a replacer, it must be a function or an array.
-// Otherwise, throw an error.
-
-            rep = replacer;
-            if (replacer && typeof replacer !== 'function' &&
-                    (typeof replacer !== 'object' ||
-                     typeof replacer.length !== 'number')) {
-                throw new Error('JSON.stringify');
-            }
-
-// Make a fake root object containing our value under the key of ''.
-// Return the result of stringifying the value.
-
-            return str('', {'': value});
-        };
-    }
-
-
-// If the JSON object does not yet have a parse method, give it one.
-
-    if (typeof JSON.parse !== 'function') {
-        JSON.parse = function (text, reviver) {
-
-// The parse method takes a text and an optional reviver function, and returns
-// a JavaScript value if the text is a valid JSON text.
-
-            var j;
-
-            function walk(holder, key) {
-
-// The walk method is used to recursively walk the resulting structure so
-// that modifications can be made.
-
-                var k, v, value = holder[key];
-                if (value && typeof value === 'object') {
-                    for (k in value) {
-                        if (Object.hasOwnProperty.call(value, k)) {
-                            v = walk(value, k);
-                            if (v !== undefined) {
-                                value[k] = v;
-                            } else {
-                                delete value[k];
-                            }
-                        }
-                    }
-                }
-                return reviver.call(holder, key, value);
-            }
-
-
-// Parsing happens in four stages. In the first stage, we replace certain
-// Unicode characters with escape sequences. JavaScript handles many characters
-// incorrectly, either silently deleting them, or treating them as line endings.
-
-            cx.lastIndex = 0;
-            if (cx.test(text)) {
-                text = text.replace(cx, function (a) {
-                    return '\\u' +
-                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
-                });
-            }
-
-// In the second stage, we run the text against regular expressions that look
-// for non-JSON patterns. We are especially concerned with '()' and 'new'
-// because they can cause invocation, and '=' because it can cause mutation.
-// But just to be safe, we want to reject all unexpected forms.
-
-// We split the second stage into 4 regexp operations in order to work around
-// crippling inefficiencies in IE's and Safari's regexp engines. First we
-// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
-// replace all simple value tokens with ']' characters. Third, we delete all
-// open brackets that follow a colon or comma or that begin the text. Finally,
-// we look to see that the remaining characters are only whitespace or ']' or
-// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
-
-            if (/^[\],:{}\s]*$/.
-test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
-replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
-replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
-
-// In the third stage we use the eval function to compile the text into a
-// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
-// in JavaScript: it can begin a block or an object literal. We wrap the text
-// in parens to eliminate the ambiguity.
-
-                j = eval('(' + text + ')');
-
-// In the optional fourth stage, we recursively walk the new structure, passing
-// each name/value pair to a reviver function for possible transformation.
-
-                return typeof reviver === 'function' ?
-                    walk({'': j}, '') : j;
-            }
-
-// If the text is not JSON parseable, then a SyntaxError is thrown.
-
-            throw new SyntaxError('JSON.parse');
-        };
-    }
-}());

daemon/orbited/static/orbited.js

-
-var thisScriptName='orbited.js'ed_source={};var pre_jsioImport=[];if(typeof exports=='undefined'){var jsio=window.jsio=bind(this,_jsioImport,window,'');}else{var jsio=GLOBAL.jsio=bind(this,_jsioImport,GLOBAL,'');}
-jsio.script_src='jsio.js';var modulePathCache={}
-function getModulePathPossibilities(pathString){var segments=pathString.split('.')
-var modPath=segments.join('/');var out;if(segments[0]in modulePathCache){out=[[modulePathCache[segments[0]]+'/'+modPath+'.js',null]];}else{out=[];for(var i=0,path;path=jsio.path[i];++i){out.push([path+'/'+modPath+'.js',path]);}}
-return out;}
-jsio.path=['.'];jsio.__env=typeof node!=='undefined'&&typeof process!=='undefined'&&process.version?'node':'browser';switch(jsio.__env){case'node':var posix=require('posix');var RUNTIME={cwd:process.cwd,argv:process.ARGV,argc:process.ARGC,write:process.stdio.writeError,writeAsync:process.stdio.write,readFile:function(filename){return posix.cat(filename,'utf8');},eval:function(code,location){return process.compile(code,location);}}
-break;case'browser':var src=browser_findScript();var segments=src.split('/');var cwd=segments.slice(0,segments.length-2).join('/');if(cwd){jsio.path.push(cwd);}else{cwd='.';};var RUNTIME={cwd:function(){return cwd;},argv:null,argc:null,write:browser_getLog(),writeAsync:browser_getLog(),readFile:function(){},eval:function(src){return eval(src);}}
-if(typeof eval('(function(){})')=='undefined'){RUNTIME.eval=function(src){try{eval('jsio.__f='+src);return jsio.__f;}finally{delete jsio.__f;}}}
-modulePathCache.jsio=cwd;break;}
-function browser_findScript(){try{var scripts=document.getElementsByTagName('script');for(var i=0,script;script=scripts[i];++i){if((script.src==jsio.script_src)||(script.src.slice(script.src.length-jsio.script_src)==jsio.script_src)){return makeAbsoluteURL(script.src,window.location);}}}catch(e){}}
-function browser_getLog(){if(typeof console!='undefined'&&console.log){return console.log;}else{return browser_oldLog;}}
-function browser_oldLog(){var shouldScroll=document.body.scrollHeight==document.body.scrollTop+document.body.clientHeight;var d=document.createElement('div');document.body.appendChild(d);out=[]
-for(var i=0,item;(item=arguments[i])||i<arguments.length;++i){try{out.push(JSON.stringify(item));}catch(e){out.push(item.toString());}}
-d.innerHTML=out.join(", ");if(shouldScroll){window.scrollTo(0,10000);}}
-function $each(i,context,f){if(!f){f=context;context=this;}
-for(var j in i){if(i.hasOwnProperty(j)){f(j,i[j],i);}}}
-function bind(context,method){var args=Array.prototype.slice.call(arguments,2);return function(){method=(typeof method=='string'?context[method]:method);return method.apply(context,args.concat(Array.prototype.slice.call(arguments,0)))}};function $setTimeout(f,t){var args=Array.prototype.slice.call(arguments,2);return setTimeout(function(){try{f.apply(this,args);}catch(e){}},t)}
-function $setInterval(f,t){var args=Array.prototype.slice.call(arguments,2);return setInterval(function(){try{f.apply(this,args);}catch(e){}},t)}
-function Class(parent,proto){if(!parent){throw new Error('parent or prototype not provided');}
-if(!proto){proto=parent;}
-else if(parent instanceof Array){proto.prototype={};for(var i=0,p;p=parent[i];++i){for(var item in p.prototype){if(!(item in proto.prototype)){proto.prototype[item]=p.prototype[item];}}}
-parent=parent[0];}else{proto.prototype=parent.prototype;}
-var cls=function(){if(this.init){this.init.apply(this,arguments);}}
-cls.prototype=new proto(function(context,method,args){var args=args||[];var target=parent;while(target=target.prototype){if(target[method]){return target[method].apply(context,args);}}
-throw new Error('method '+method+' does not exist');});cls.prototype.constructor=cls;return cls;}
-var strDuplicate=function(str,num){var out="";for(var i=0;i<num;++i){out+=str;}
-return out;}
-switch(jsio.__env){case'node':var nodeWrapper={require:require};var stringifyPretty=function(item){return _stringify(true,item,1);}
-var stringify=function(item){return _stringify(false,item);}
-var _stringify=function(pretty,item,tab){if(item instanceof Array){var str=[];for(var i=0,len=item.length;i<len;++i){str.push(_stringify(pretty,item[i]));}
-return'['+str.join(',')+']';}else if(typeof(item)=='object'){var str=[];for(var key in item){var value=key+':'+(pretty?' ':'');if(typeof item[key]=='function'){var def=item[key].toString();var match=def.match(/^function\s+\((.*?)\)/);value+=match?'f('+match[1]+') {...}':'[Function]';}else{value+=_stringify(pretty,item[key],tab+1);}
-str.push(value);}
-if(pretty&&str.length>1){var spacer=strDuplicate('\t',tab);return'{\n'+spacer+str.join(',\n'+spacer)+'\n'+strDuplicate('\t',tab-1)+'}';}else{return'{'+str.join(',')+'}';}}
-return item+"";}
-var log=function(){RUNTIME.write(Array.prototype.slice.call(arguments,0).map(stringifyPretty).join(' ')+"\n");}
-window=GLOBAL;var compile=function(context,args){try{var fn=RUNTIME.eval("(function(_) { with(_){delete _;(function(){"+args.src+"\n}).call(this)}})",args.location);}catch(e){if(e instanceof SyntaxError){log("Syntax Error loading ",args.location,e);}
-throw e;}
-try{fn.call(context.exports,context);}catch(e){if(e.type=="stack_overflow"){log("Stack overflow in",args.location,e);}else{log("error when loading",args.location);}
-throw e;}
-return true;}
-var windowCompile=function(context,args){var fn=RUNTIME.eval("(function(_){with(_){with(_.window){delete _;(function(){"+args.src+"\n}).call(this)}}})",args.location);fn.call(context.exports,context);}
-var cwd=RUNTIME.cwd();var makeRelative=function(path){var i=path.match('^'+cwd);if(i&&i[0]==cwd){var offset=path[cwd.length]=='/'?1:0
-return path.slice(cwd.length+offset);}
-return path;}
-var getModuleSourceAndPath=function(pathString){var baseMod=pathString.split('.')[0];var paths=getModulePathPossibilities(pathString);var cwd=RUNTIME.cwd()+'/';for(var i=0,path;path=paths[i];++i){var cachePath=path[1];var path=path[0];try{var out={src:RUNTIME.readFile(path).wait(),location:path};if(!(baseMod in modulePathCache)){modulePathCache[baseMod]=cachePath;}
-return out;}catch(e){}}
-throw new Error("Module not found: "+pathString+"\n(looked in "+paths+")");}
-var segments=__filename.split('/');var jsioPath=segments.slice(0,segments.length-2).join('/');if(jsioPath){jsio.path.push(jsioPath);modulePathCache.jsio=jsioPath;}else{modulePathCache.jsio='.';}
-jsio.__path=makeRelative(RUNTIME.argv[1]);break;default:var log=browser_getLog();var compile=function(context,args){var code="(function(_){with(_){delete _;(function(){"
-+args.src
-+"\n}).call(this)}})\n//@ sourceURL="+args.location;try{var fn=RUNTIME.eval(code);}catch(e){if(e instanceof SyntaxError){var src='javascript:document.open();document.write("<scr"+"ipt src=\''
-+args.location
-+'\'></scr"+"ipt>")';var callback=function(){var el=document.createElement('iframe');with(el.style){position='absolute';top=left='-999px';width=height='1px';visibility='hidden';}
-el.src=src;$setTimeout(function(){document.body.appendChild(el);},0);}
-if(document.body){callback();}
-else{window.addEventListener('load',callback,false);}
-throw new Error("forcing halt on load of "+args.location);}
-throw e;}
-try{fn.call(context.exports,context);}catch(e){log('error when loading '+args.location);throw e;}
-return true;}
-var windowCompile=function(context,args){var f="(function(_){with(_){with(_.window){delete _;(function(){"+args.src+"\n}).call(this)}}})\n//@ sourceURL="+args.location;var fn=RUNTIME.eval(f);fn.call(context.exports,context);}
-var createXHR=function(){return window.XMLHttpRequest?new XMLHttpRequest():window.ActiveXObject?new ActiveXObject("Msxml2.XMLHTTP"):null;}
-var getModuleSourceAndPath=function(pathString){if(preloaded_source[pathString]){return preloaded_source[pathString];}
-var baseMod=pathString.split('.')[0];var paths=getModulePathPossibilities(pathString);for(var i=0,path;path=paths[i];++i){var cachePath=path[1];var path=path[0];var xhr=createXHR();var failed=false;try{xhr.open('GET',path,false);xhr.send(null);}catch(e){failed=true;}
-if(failed||xhr.status==404||xhr.status==-1100||false)
-{continue;}
-if(!(baseMod in modulePathCache)){modulePathCache[baseMod]=cachePath;}
-return{src:xhr.responseText,location:path};}
-throw new Error("Module not found: "+pathString+" (looked in "+paths.join(', ')+")");}
-var makeRelative=function(path){return path.replace(cwd+'/','').replace(cwd,'');}
-jsio.__path=makeRelative(window.location.toString());break;}
-jsio.basePath=jsio.path[jsio.path.length-1];var modules={bind:bind,Class:Class,log:log,jsio:jsio};function makeAbsoluteURL(url,location){if(/^[A-Za-z]*:\/\//.test(url)){return url;}
-var prefix=location.protocol+'//'+location.host;if(url.charAt(0)=='/'){return prefix+url;}
-var result=location.pathname.match(/\/*(.*?\/?)\/*$/);var parts=result?result[1].split('/'):[];parts.pop();var urlParts=url.split('/');while(true){if(urlParts[0]=='.'){urlParts.shift();}else if(urlParts[0]=='..'){urlParts.shift();parts.pop();}else{break;}}
-var pathname=parts.join('/');if(pathname)pathname+='/';return prefix+'/'+pathname+urlParts.join('/');}
-function resolveRelativePath(pkg,path){if(pkg.charAt(0)=='.'){pkg=pkg.substring(1);var segments=path.split('.');while(pkg.charAt(0)=='.'){pkg=pkg.slice(1);segments.pop();}
-var prefix=segments.join('.');if(prefix){return prefix+'.'+pkg;}}
-return pkg;}
-function _jsioImport(context,path,what){var match,imports=[];if((match=what.match(/^(from|external)\s+([\w.$]+)\s+import\s+(.*)$/))){imports[0]={from:resolveRelativePath(match[2],path),external:match[1]=='external',"import":{}};match[3].replace(/\s*([\w.$*]+)(?:\s+as\s+([\w.$]+))?/g,function(_,item,as){imports[0]["import"][item]=as||item;});}else if((match=what.match(/^import\s+(.*)$/))){match[1].replace(/\s*([\w.$]+)(?:\s+as\s+([\w.$]+))?,?/g,function(_,pkg,as){fullPkg=resolveRelativePath(pkg,path);imports[imports.length]=as?{from:fullPkg,as:as}:{from:fullPkg,as:pkg};});}else{if(SyntaxError){throw new SyntaxError(what);}else{throw new Error("Syntax error: "+what);}}
-for(var i=0,item,len=imports.length;(item=imports[i])||i<len;++i){var pkg=item.from;var segments=pkg.split('.');if(!(pkg in modules)){try{var result=getModuleSourceAndPath(pkg);}catch(e){log('Error:',context.jsio.__path,'could not execute: "'+what+'"');throw e;}
-var newRelativePath=segments.slice(0,segments.length-1).join('.');if(!item.external){var newContext={exports:{},global:window,bind:bind,Class:Class,$setTimeout:$setTimeout,$setInterval:$setInterval};newContext.jsio=bind(this,_jsioImport,newContext,newRelativePath);for(var j in modules.jsio){newContext.jsio[j]=modules.jsio[j];}
-var tmp=result.location.split('/');newContext.jsio.__dir=makeRelative(tmp.slice(0,tmp.length-1).join('/'));newContext.jsio.__path=makeRelative(result.location);newContext.jsio.__env=jsio.__env;newContext.jsio.node=nodeWrapper;compile(newContext,result);modules[pkg]=newContext.exports;}else{var newContext={};newContext['window']={};for(var j in item["import"]){newContext['window'][j]=null;}
-windowCompile(newContext,result);modules[pkg]=newContext.window;}}
-if(item.as){var segments=item.as.match(/^\.*(.*?)\.*$/)[1].split('.');var c=context;for(var k=0,slen=segments.length-1,segment;(segment=segments[k])&&k<slen;++k){if(!segment)continue;if(!c[segment]){c[segment]={};}
-c=c[segment];}
-c[segments[slen]]=modules[pkg];}else if(item["import"]){if(item["import"]['*']){for(var k in modules[pkg]){context[k]=modules[pkg][k];}}else{try{for(var k in item["import"]){context[item["import"][k]]=modules[pkg][k];}}catch(e){log('module: ',modules);throw e;}}}}}
-var _localContext={};var _jsio=_localContext.jsio=bind(this,_jsioImport,_localContext,'jsio');_jsio('import jsio.env');jsio.listen=function(server,transportName,opts){var listenerClass=_jsio.env.getListener(transportName);var listener=new listenerClass(server,opts);listener.listen();return listener;}
-jsio.connect=function(protocolInstance,transportName,opts){var connector=new(_jsio.env.getConnector(transportName))(protocolInstance,opts);connector.connect();return connector;}
-jsio.quickServer=function(protocolClass){_jsio('import .interfaces');return new jsio.interfaces.Server(protocolClass);}
-for(var i=0,target;target=pre_jsioImport[i];++i){jsio.require(target);}})();"use strict";if(!this.JSON){this.JSON={};}
-(function(){function f(n){return n<10?'0'+n:n;}
-if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+'-'+
-f(this.getUTCMonth()+1)+'-'+
-f(this.getUTCDate())+'T'+
-f(this.getUTCHours())+':'+
-f(this.getUTCMinutes())+':'+
-f(this.getUTCSeconds())+'Z':null;};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};}
-var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}
-function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}
-if(typeof rep==='function'){value=rep.call(holder,key,value);}
-switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
-gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}
-v=partial.length===0?'[]':gap?'[\n'+gap+
-partial.join(',\n'+gap)+'\n'+
-mind+']':'['+partial.join(',')+']';gap=mind;return v;}
-if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}
-v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+
-mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}
-if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}
-rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}
-return str('',{'':value});};}
-if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}
-return reviver.call(holder,key,value);}
-cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+
-('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}
-if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}
-throw new SyntaxError('JSON.parse');};}}());jsio("import orbited");delete jsio;

daemon/orbited/static/socket.js

-;(function() {
-
-socket = {};
-
-socket.readyState = {
-    'initial': 0,
-    'opening': 1,
-    'open':    2,
-    'closing': 3,
-    'closed':  4
-};
-
-socket.settings = {
-    hostname: 'localhost',
-    port: 8000
-};
-
-var multiplexer = null;
-var id = 0;
-var frames = {
-    'OPEN':  0,
-    'CLOSE': 1,
-    'DATA':  2
-};
-
-var Multiplexer = function(CometSession) {
-//    var JSON = CometSession.prototype.JSON || JSON;
-    if (multiplexer != null) {
-        throw new Error("Multiplexer is a singleton");      
-    }
-    var parseFrames = function() {
-        // parse frames grabs out a frame, then parses it as json, and fires
-        // onpacket on the socket of ID indicated in the frame
-        var frameBegin;
-        while ((frameBegin = self.buffer.indexOf('[')) > -1) {
-            var frameEnd = parseInt(self.buffer.slice(0, frameBegin)) + frameBegin;
-            if (self.buffer.length < frameEnd)
-                return;  // frame still incomplete
-            var frame = JSON.parse(self.buffer.slice(frameBegin, frameEnd));
-            self.buffer = self.buffer.slice(frameEnd); // shift packet out of buffer
-            var socketId = frame[0];
-            self.sockets[socketId].onpacket(frame.slice(1));
-        };
-    };
-    var self = multiplexer = this;
-    socket.TCPSocket.prototype.JSON = JSON; // XXX is this really necessary?
-    self.buffer = "";
-    self.sockets = {};
-    self.csp = new CometSession();
-    self.csp.connect("http://" + socket.settings.hostname + ":" + socket.settings.port + '/csp', { encoding: 'plain' });// XXX: detect properly
-    self.csp.onopen = function() {
-        for (id in self.sockets)
-            self.sockets[id].onopen();
-    }
-    self.csp.onclose = function(code) {
-        multiplexer = null;
-        for (id in self.sockets)
-            self.sockets[id].onclose(code);
-    }
-    self.csp.onread = function(data) {
-        self.buffer += data;
-        parseFrames();
-    }
-    self.register = function(socket, onopen, onclose, onpacket) {
-        self.sockets[socket.id] = {};
-        self.sockets[socket.id].socket = socket;
-        self.sockets[socket.id].onopen = onopen;
-        self.sockets[socket.id].onclose = onclose;
-        self.sockets[socket.id].onpacket = onpacket;
-        if (self.csp && self.csp.readyState == csp.readyState.open)
-            self.write([socket.id, frames.OPEN, socket.addr, socket.port]);
-    }
-    self.write = function(frame) {
-        var output = JSON.stringify(frame); // XXX: won't work in opera...
-        output = output.length + output;
-        self.csp.write(output);
-    }
-}
-
-
-
-socket.TCPSocket = function(CometSession) {    
-    var self = this;
-    if (!CometSession) {
-        if (typeof(csp) != 'undefined' && csp.CometSession) {
-            CometSession = csp.CometSession;
-        }
-        else if (window.csp && window.csp.CometSession) {
-            CometSession = window.csp.CometSession;
-        }
-        else {
-            throw new Error("Invalid CometSession implementation");
-        }
-    }
-    self.id = ++id;
-    self.readyState = socket.readyState.initial;
-    self.addr = null;
-    self.port = null;
-    self.binary = null;
-    self.onclose = function(code) {
-        console.log("TCPSocket onclose:", code);
-    }
-    self.onopen = function() {
-        console.log("TCPSocket onopen");
-    }
-    self.onread = function(data) {
-        console.log("TCPSocket onread:", data);
-    }
-    self.open = function(addr, port, isBinary) {
-        self.addr = addr;
-        self.port = port;
-        self.binary = !!isBinary;
-        if (typeof(addr) != 'string' || addr.length == 0) {
-            throw new Error('Invalid address: "' + addr + '"');
-        }
-        self.readyState = socket.readyState.opening;
-        if (multiplexer == null)
-            new Multiplexer(CometSession);
-        multiplexer.register(self,
-            function() { // onopen
-                multiplexer.write([self.id, frames.OPEN, self.addr, self.port]);
-            },
-            function(code) { // onclose
-                self.readyState = socket.readyState.closed;
-                self.onclose(code);
-            },
-            function(frame) { // onpacket
-                // console.log('GOT ' + ['OPEN', 'CLOSE', 'DATA'][frame[0]] + ' FRAME', uneval(frame[1]))
-                var frameType = frame[0];
-                switch(frameType) {
-                    case frames.OPEN:
-                        if (self.readyState == socket.readyState.opening) {
-                            self.readyState = socket.readyState.open;
-                            self.onopen();
-                        }
-                        break;
-                    case frames.CLOSE:
-                        self.readyState = socket.readyState.closed;
-                        self.onclose(frame[1]);
-                        break;
-                    case frames.DATA:
-                        // console.log('read', frame[1]);
-                        self.onread(frame[1]);
-                        break;
-                }
-            }
-        );
-    }
-    self.send = function(data) {
-        if (self.readyState != socket.readyState.open)
-            throw new Error("TCPSocket: invalid readystate!");
-        multiplexer.write([self.id, frames.DATA, data]);
-//        console.log('send', data);
-    }
-};
-
-// Try to auto detect the socket port and hostname
-(function() {
-    try {
-        var scripts = document.getElementsByTagName('script');
-        for (var i = 0, script; script = scripts[i]; ++i) {
-            if (script.src.match('socket\.js$')) {
-                var uri = csp.util.parseUri(script.src);
-                socket.settings.hostname = uri.hostname || document.domain || 'localhost';
-                socket.settings.port = uri.port || location.port || (document.domain && 80) || 8000;
-                break;
-            }
-        }
-    } catch(e) {
-    }
-})();
-
-
-
-})();

daemon/orbited/static/utf8.js

-/*
-JavaScript UTF-8 encoder/decoder, by Jacob Rus.
-
-Inspired by the observation by Johan Sundström published at:
-http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html
-
-Note that this code throws an error for invalid UTF-8. Because it is so much
-faster than other kinds of implementations, the recommended way to do lenient
-parsing is to first try this decoder, and then fall back on a slower lenient
-decoder if necessary for the particular use case.
-
---------------------
-
-Copyright (c) 2009 Jacob Rus
-
-Permission is hereby granted, free of charge, to any person
-obtaining a copy of this software and associated documentation
-files (the "Software"), to deal in the Software without
-restriction, including without limitation the rights to use,
-copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the
-Software is furnished to do so, subject to the following
-conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-OTHER DEALINGS IN THE SOFTWARE.
-*/
-(function() {
-var UnicodeCodecError = this.UnicodeCodecError = function (message) { this.message = message; };
-this.UnicodeCodecError.prototype.toString = function () {
-  return 'UnicodeCodecError' + (this.message ? ': ' + this.message : '');
-};
-this.encode = function (unicode_string) {
-  // Unicode encoder: Given an arbitrary unicode string, returns a string
-  // of characters with code points in range 0x00 - 0xFF corresponding to
-  // the bytes of the utf-8 representation of those characters.
-  try {
-    return unescape(encodeURIComponent(unicode_string));
-  }
-  catch (err) {
-    throw new UnicodeCodecError('invalid input string');
-  };
-};
-this.decode = function (bytes) {
-  // Unicode decoder: Given a string of characters with code points in
-  // range 0x00 - 0xFF, which, when interpreted as bytes, are valid UTF-8,
-  // returns the unicode string for those characters.
-  if (/[^\x00-\xFF]/.test(bytes)) {
-    throw new UnicodeCodecError('invalid utf-8 bytes');
-  };
-  try {
-    return decodeURIComponent(escape(bytes));
-  }
-  catch (err) {
-    throw new UnicodeCodecError('invalid utf-8 bytes');
-  };
-};
-}).call(typeof(exports) != 'undefined' ? exports : (function() { window.utf8 = {}; return utf8; })())
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.