Skip to content

Instantly share code, notes, and snippets.

@kumavis kumavis/index.js
Created Jan 16, 2015

Embed
What would you like to do?
requirebin sketch
var quickconnect = require('rtc-quickconnect');
var createDataStream = require('rtc-dcstream');
quickconnect('http://rtc.io/switchboard', { room: 'dnode-test' })
.createDataChannel('primary')
.on('channel:opened:primary', function(id, dc) {
var stream = createDataStream(dc)
connectionReady(stream)
})
function connectionReady(ds) {
console.log('ready')
}
require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){var base64=require("base64-js");var ieee754=require("ieee754");var isArray=require("is-array");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;Buffer.poolSize=8192;var kMaxLength=1073741823;var rootParent={};Buffer.TYPED_ARRAY_SUPPORT=function(){try{var buf=new ArrayBuffer(0);var arr=new Uint8Array(buf);arr.foo=function(){return 42};return 42===arr.foo()&&typeof arr.subarray==="function"&&new Uint8Array(1).subarray(1,1).byteLength===0}catch(e){return false}}();function Buffer(subject,encoding,noZero){if(!(this instanceof Buffer))return new Buffer(subject,encoding,noZero);var type=typeof subject;var length;if(type==="number")length=subject>0?subject>>>0:0;else if(type==="string"){length=Buffer.byteLength(subject,encoding)}else if(type==="object"&&subject!==null){if(subject.type==="Buffer"&&isArray(subject.data))subject=subject.data;length=+subject.length>0?Math.floor(+subject.length):0}else throw new TypeError("must start with number, buffer, array or string");if(length>kMaxLength)throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength.toString(16)+" bytes");var buf;if(Buffer.TYPED_ARRAY_SUPPORT){buf=Buffer._augment(new Uint8Array(length))}else{buf=this;buf.length=length;buf._isBuffer=true}var i;if(Buffer.TYPED_ARRAY_SUPPORT&&typeof subject.byteLength==="number"){buf._set(subject)}else if(isArrayish(subject)){if(Buffer.isBuffer(subject)){for(i=0;i<length;i++)buf[i]=subject.readUInt8(i)}else{for(i=0;i<length;i++)buf[i]=(subject[i]%256+256)%256}}else if(type==="string"){buf.write(subject,0,encoding)}else if(type==="number"&&!Buffer.TYPED_ARRAY_SUPPORT&&!noZero){for(i=0;i<length;i++){buf[i]=0}}if(length>0&&length<=Buffer.poolSize)buf.parent=rootParent;return buf}function SlowBuffer(subject,encoding,noZero){if(!(this instanceof SlowBuffer))return new SlowBuffer(subject,encoding,noZero);var buf=new Buffer(subject,encoding,noZero);delete buf.parent;return buf}Buffer.isBuffer=function(b){return!!(b!=null&&b._isBuffer)};Buffer.compare=function(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("Arguments must be Buffers");var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i<len&&a[i]===b[i];i++){}if(i!==len){x=a[i];y=b[i]}if(x<y)return-1;if(y<x)return 1;return 0};Buffer.isEncoding=function(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return true;default:return false}};Buffer.concat=function(list,totalLength){if(!isArray(list))throw new TypeError("Usage: Buffer.concat(list[, length])");if(list.length===0){return new Buffer(0)}else if(list.length===1){return list[0]}var i;if(totalLength===undefined){totalLength=0;for(i=0;i<list.length;i++){totalLength+=list[i].length}}var buf=new Buffer(totalLength);var pos=0;for(i=0;i<list.length;i++){var item=list[i];item.copy(buf,pos);pos+=item.length}return buf};Buffer.byteLength=function(str,encoding){var ret;str=str+"";switch(encoding||"utf8"){case"ascii":case"binary":case"raw":ret=str.length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=str.length*2;break;case"hex":ret=str.length>>>1;break;case"utf8":case"utf-8":ret=utf8ToBytes(str).length;break;case"base64":ret=base64ToBytes(str).length;break;default:ret=str.length}return ret};Buffer.prototype.length=undefined;Buffer.prototype.parent=undefined;Buffer.prototype.toString=function(encoding,start,end){var loweredCase=false;start=start>>>0;end=end===undefined||end===Infinity?this.length:end>>>0;if(!encoding)encoding="utf8";if(start<0)start=0;if(end>this.length)end=this.length;if(end<=start)return"";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"binary":return binarySlice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}};Buffer.prototype.equals=function(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return Buffer.compare(this,b)===0};Buffer.prototype.inspect=function(){var str="";var max=exports.INSPECT_MAX_BYTES;if(this.length>0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return"<Buffer "+str+">"};Buffer.prototype.compare=function(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return Buffer.compare(this,b)};Buffer.prototype.get=function(offset){console.log(".get() is deprecated. Access using array indexes instead.");return this.readUInt8(offset)};Buffer.prototype.set=function(v,offset){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(v,offset)};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new Error("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i<length;i++){var byte=parseInt(string.substr(i*2,2),16);if(isNaN(byte))throw new Error("Invalid hex string");buf[offset+i]=byte}return i}function utf8Write(buf,string,offset,length){var charsWritten=blitBuffer(utf8ToBytes(string,buf.length-offset),buf,offset,length);return charsWritten}function asciiWrite(buf,string,offset,length){var charsWritten=blitBuffer(asciiToBytes(string),buf,offset,length);return charsWritten}function binaryWrite(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){var charsWritten=blitBuffer(base64ToBytes(string),buf,offset,length);return charsWritten}function utf16leWrite(buf,string,offset,length){var charsWritten=blitBuffer(utf16leToBytes(string,buf.length-offset),buf,offset,length,2);return charsWritten}Buffer.prototype.write=function(string,offset,length,encoding){if(isFinite(offset)){if(!isFinite(length)){encoding=length;length=undefined}}else{var swap=encoding;encoding=offset;offset=length;length=swap}offset=Number(offset)||0;if(length<0||offset<0||offset>this.length)throw new RangeError("attempt to write outside buffer bounds");var remaining=this.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}encoding=String(encoding||"utf8").toLowerCase();var ret;switch(encoding){case"hex":ret=hexWrite(this,string,offset,length);break;case"utf8":case"utf-8":ret=utf8Write(this,string,offset,length);break;case"ascii":ret=asciiWrite(this,string,offset,length);break;case"binary":ret=binaryWrite(this,string,offset,length);break;case"base64":ret=base64Write(this,string,offset,length);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=utf16leWrite(this,string,offset,length);break;default:throw new TypeError("Unknown encoding: "+encoding)}return ret};Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){var res="";var tmp="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){if(buf[i]<=127){res+=decodeUtf8Char(tmp)+String.fromCharCode(buf[i]);tmp=""}else{tmp+="%"+buf[i].toString(16)}}return res+decodeUtf8Char(tmp)}function asciiSlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){ret+=String.fromCharCode(buf[i]&127)}return ret}function binarySlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){ret+=String.fromCharCode(buf[i])}return ret}function hexSlice(buf,start,end){var len=buf.length;if(!start||start<0)start=0;if(!end||end<0||end>len)end=len;var out="";for(var i=start;i<end;i++){out+=toHex(buf[i])}return out}function utf16leSlice(buf,start,end){var bytes=buf.slice(start,end);var res="";for(var i=0;i<bytes.length;i+=2){res+=String.fromCharCode(bytes[i]+bytes[i+1]*256)}return res}Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start;end=end===undefined?len:~~end;if(start<0){start+=len;if(start<0)start=0}else if(start>len){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(end<start)end=start;var newBuf;if(Buffer.TYPED_ARRAY_SUPPORT){newBuf=Buffer._augment(this.subarray(start,end))}else{var sliceLen=end-start;newBuf=new Buffer(sliceLen,undefined,true);for(var i=0;i<sliceLen;i++){newBuf[i]=this[i+start]}}if(newBuf.length)newBuf.parent=this.parent||this;return newBuf};function checkOffset(offset,ext,length){if(offset%1!==0||offset<0)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUIntLE=function(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=256))val+=this[offset+i]*mul;return val};Buffer.prototype.readUIntBE=function(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset+--byteLength];var mul=1;while(byteLength>0&&(mul*=256))val+=this[offset+--byteLength]*mul;return val};Buffer.prototype.readUInt8=function(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=256))val+=this[offset+i]*mul;mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256))val+=this[offset+--i]*mul;mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError("buffer must be a Buffer instance");if(value>max||value<min)throw new RangeError("value is out of bounds");if(offset+ext>buf.length)throw new RangeError("index out of range")}Buffer.prototype.writeUIntLE=function(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength),0);var mul=1;var i=0;this[offset]=value&255;while(++i<byteLength&&(mul*=256))this[offset+i]=value/mul>>>0&255;return offset+byteLength};Buffer.prototype.writeUIntBE=function(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength),0);var i=byteLength-1;var mul=1;this[offset+i]=value&255;while(--i>=0&&(mul*=256))this[offset+i]=value/mul>>>0&255;return offset+byteLength};Buffer.prototype.writeUInt8=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i<j;i++){buf[offset+i]=(value&255<<8*(littleEndian?i:1-i))>>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8}else objectWriteUInt16(this,value,offset,true);return offset+2};Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value}else objectWriteUInt16(this,value,offset,false);return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i<j;i++){buf[offset+i]=value>>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value}else objectWriteUInt32(this,value,offset,true);return offset+4};Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value}else objectWriteUInt32(this,value,offset,false);return offset+4};Buffer.prototype.writeIntLE=function(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength-1)-1,-Math.pow(2,8*byteLength-1))}var i=0;var mul=1;var sub=value<0?1:0;this[offset]=value&255;while(++i<byteLength&&(mul*=256))this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength};Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength-1)-1,-Math.pow(2,8*byteLength-1))}var i=byteLength-1;var mul=1;var sub=value<0?1:0;this[offset+i]=value&255;while(--i>=0&&(mul*=256))this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength};Buffer.prototype.writeInt8=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+value+1;this[offset]=value;return offset+1};Buffer.prototype.writeInt16LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8}else objectWriteUInt16(this,value,offset,true);return offset+2};Buffer.prototype.writeInt16BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value}else objectWriteUInt16(this,value,offset,false);return offset+2};Buffer.prototype.writeInt32LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else objectWriteUInt32(this,value,offset,true);return offset+4};Buffer.prototype.writeInt32BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value}else objectWriteUInt32(this,value,offset,false);return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(value>max||value<min)throw new RangeError("value is out of bounds");if(offset+ext>buf.length)throw new RangeError("index out of range");if(offset<0)throw new RangeError("index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert)checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38);ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert)checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308);ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function(target,target_start,start,end){var source=this;if(!start)start=0;if(!end&&end!==0)end=this.length;if(target_start>=target.length)target_start=target.length;if(!target_start)target_start=0;if(end>0&&end<start)end=start;if(end===start)return 0;if(target.length===0||source.length===0)return 0;if(target_start<0)throw new RangeError("targetStart out of bounds");if(start<0||start>=source.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-target_start<end-start)end=target.length-target_start+start;var len=end-start;if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){for(var i=0;i<len;i++){target[i+target_start]=this[i+start]}}else{target._set(this.subarray(start,start+len),target_start)}return len};Buffer.prototype.fill=function(value,start,end){if(!value)value=0;if(!start)start=0;if(!end)end=this.length;if(end<start)throw new RangeError("end < start");if(end===start)return;if(this.length===0)return;if(start<0||start>=this.length)throw new RangeError("start out of bounds");if(end<0||end>this.length)throw new RangeError("end out of bounds");var i;if(typeof value==="number"){for(i=start;i<end;i++){this[i]=value}}else{var bytes=utf8ToBytes(value.toString());var len=bytes.length;for(i=start;i<end;i++){this[i]=bytes[i%len]}}return this};Buffer.prototype.toArrayBuffer=function(){if(typeof Uint8Array!=="undefined"){if(Buffer.TYPED_ARRAY_SUPPORT){return new Buffer(this).buffer}else{var buf=new Uint8Array(this.length);for(var i=0,len=buf.length;i<len;i+=1){buf[i]=this[i]}return buf.buffer}}else{throw new TypeError("Buffer.toArrayBuffer not supported in this browser")}};var BP=Buffer.prototype;Buffer._augment=function(arr){arr.constructor=Buffer;arr._isBuffer=true;arr._get=arr.get;arr._set=arr.set;arr.get=BP.get;arr.set=BP.set;arr.write=BP.write;arr.toString=BP.toString;arr.toLocaleString=BP.toString;arr.toJSON=BP.toJSON;arr.equals=BP.equals;arr.compare=BP.compare;arr.copy=BP.copy;arr.slice=BP.slice;arr.readUIntLE=BP.readUIntLE;arr.readUIntBE=BP.readUIntBE;arr.readUInt8=BP.readUInt8;arr.readUInt16LE=BP.readUInt16LE;arr.readUInt16BE=BP.readUInt16BE;arr.readUInt32LE=BP.readUInt32LE;arr.readUInt32BE=BP.readUInt32BE;arr.readIntLE=BP.readIntLE;arr.readIntBE=BP.readIntBE;arr.readInt8=BP.readInt8;arr.readInt16LE=BP.readInt16LE;arr.readInt16BE=BP.readInt16BE;arr.readInt32LE=BP.readInt32LE;arr.readInt32BE=BP.readInt32BE;arr.readFloatLE=BP.readFloatLE;arr.readFloatBE=BP.readFloatBE;arr.readDoubleLE=BP.readDoubleLE;arr.readDoubleBE=BP.readDoubleBE;arr.writeUInt8=BP.writeUInt8;arr.writeUIntLE=BP.writeUIntLE;arr.writeUIntBE=BP.writeUIntBE;arr.writeUInt16LE=BP.writeUInt16LE;arr.writeUInt16BE=BP.writeUInt16BE;arr.writeUInt32LE=BP.writeUInt32LE;arr.writeUInt32BE=BP.writeUInt32BE;arr.writeIntLE=BP.writeIntLE;arr.writeIntBE=BP.writeIntBE;arr.writeInt8=BP.writeInt8;arr.writeInt16LE=BP.writeInt16LE;arr.writeInt16BE=BP.writeInt16BE;arr.writeInt32LE=BP.writeInt32LE;arr.writeInt32BE=BP.writeInt32BE;arr.writeFloatLE=BP.writeFloatLE;arr.writeFloatBE=BP.writeFloatBE;arr.writeDoubleLE=BP.writeDoubleLE;arr.writeDoubleBE=BP.writeDoubleBE;arr.fill=BP.fill;arr.inspect=BP.inspect;arr.toArrayBuffer=BP.toArrayBuffer;return arr};var INVALID_BASE64_RE=/[^+\/0-9A-z\-]/g;function base64clean(str){str=stringtrim(str).replace(INVALID_BASE64_RE,"");if(str.length<2)return"";while(str.length%4!==0){str=str+"="}return str}function stringtrim(str){if(str.trim)return str.trim();return str.replace(/^\s+|\s+$/g,"")}function isArrayish(subject){return isArray(subject)||Buffer.isBuffer(subject)||subject&&typeof subject==="object"&&typeof subject.length==="number"}function toHex(n){if(n<16)return"0"+n.toString(16);return n.toString(16)}function utf8ToBytes(string,units){var codePoint,length=string.length;var leadSurrogate=null;units=units||Infinity;var bytes=[];var i=0;for(;i<length;i++){codePoint=string.charCodeAt(i);if(codePoint>55295&&codePoint<57344){if(leadSurrogate){if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}else{codePoint=leadSurrogate-55296<<10|codePoint-56320|65536;leadSurrogate=null}}else{if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}else{leadSurrogate=codePoint;continue}}}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=null}if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<2097152){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){byteArray.push(str.charCodeAt(i)&255)}return byteArray}function utf16leToBytes(str,units){var c,hi,lo;var byteArray=[];for(var i=0;i<str.length;i++){if((units-=2)<0)break;c=str.charCodeAt(i);hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length,unitSize){if(unitSize)length-=length%unitSize;for(var i=0;i<length;i++){if(i+offset>=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function decodeUtf8Char(str){try{return decodeURIComponent(str)}catch(err){return String.fromCharCode(65533)}}},{"base64-js":2,ieee754:3,"is-array":4}],2:[function(require,module,exports){var lookup="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";(function(exports){"use strict";var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var PLUS="+".charCodeAt(0);var SLASH="/".charCodeAt(0);var NUMBER="0".charCodeAt(0);var LOWER="a".charCodeAt(0);var UPPER="A".charCodeAt(0);var PLUS_URL_SAFE="-".charCodeAt(0);var SLASH_URL_SAFE="_".charCodeAt(0);function decode(elt){var code=elt.charCodeAt(0);if(code===PLUS||code===PLUS_URL_SAFE)return 62;if(code===SLASH||code===SLASH_URL_SAFE)return 63;if(code<NUMBER)return-1;if(code<NUMBER+10)return code-NUMBER+26+26;if(code<UPPER+26)return code-UPPER;if(code<LOWER+26)return code-LOWER+26}function b64ToByteArray(b64){var i,j,l,tmp,placeHolders,arr;if(b64.length%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}var len=b64.length;placeHolders="="===b64.charAt(len-2)?2:"="===b64.charAt(len-1)?1:0;arr=new Arr(b64.length*3/4-placeHolders);l=placeHolders>0?b64.length-4:b64.length;var L=0;function push(v){arr[L++]=v}for(i=0,j=0;i<l;i+=4,j+=3){tmp=decode(b64.charAt(i))<<18|decode(b64.charAt(i+1))<<12|decode(b64.charAt(i+2))<<6|decode(b64.charAt(i+3));push((tmp&16711680)>>16);push((tmp&65280)>>8);push(tmp&255)}if(placeHolders===2){tmp=decode(b64.charAt(i))<<2|decode(b64.charAt(i+1))>>4;push(tmp&255)}else if(placeHolders===1){tmp=decode(b64.charAt(i))<<10|decode(b64.charAt(i+1))<<4|decode(b64.charAt(i+2))>>2;push(tmp>>8&255);push(tmp&255)}return arr}function uint8ToBase64(uint8){var i,extraBytes=uint8.length%3,output="",temp,length;function encode(num){return lookup.charAt(num)}function tripletToBase64(num){return encode(num>>18&63)+encode(num>>12&63)+encode(num>>6&63)+encode(num&63)}for(i=0,length=uint8.length-extraBytes;i<length;i+=3){temp=(uint8[i]<<16)+(uint8[i+1]<<8)+uint8[i+2];output+=tripletToBase64(temp)}switch(extraBytes){case 1:temp=uint8[uint8.length-1];output+=encode(temp>>2);output+=encode(temp<<4&63);output+="==";break;case 2:temp=(uint8[uint8.length-2]<<8)+uint8[uint8.length-1];output+=encode(temp>>10);output+=encode(temp>>4&63);output+=encode(temp<<2&63);output+="=";break}return output}exports.toByteArray=b64ToByteArray;exports.fromByteArray=uint8ToBase64})(typeof exports==="undefined"?this.base64js={}:exports)},{}],3:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8);m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8);if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8);e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=s*128}},{}],4:[function(require,module,exports){var isArray=Array.isArray;var str=Object.prototype.toString;module.exports=isArray||function(val){return!!val&&"[object Array]"==str.call(val)}},{}],5:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");this._maxListeners=n;return this};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};if(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}throw TypeError('Uncaught, unspecified "error" event.')}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];handler.apply(this,args)}}else if(isObject(handler)){len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];listeners=handler.slice();len=listeners.length;for(i=0;i<len;i++)listeners[i].apply(this,args)}return true};EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events)this._events={};if(this._events.newListener)this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])this._events[type]=listener;else if(isObject(this._events[type]))this._events[type].push(listener);else this._events[type]=[this._events[type],listener];if(isObject(this._events[type])&&!this._events[type].warned){var m;if(!isUndefined(this._maxListeners)){m=this._maxListeners}else{m=EventEmitter.defaultMaxListeners}if(m&&m>0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-->0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;
break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else{while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.listenerCount=function(emitter,type){var ret;if(!emitter._events||!emitter._events[type])ret=0;else if(isFunction(emitter._events[type]))ret=1;else ret=emitter._events[type].length;return ret};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],6:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],7:[function(require,module,exports){module.exports=Array.isArray||function(arr){return Object.prototype.toString.call(arr)=="[object Array]"}},{}],8:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canMutationObserver=typeof window!=="undefined"&&window.MutationObserver;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}var queue=[];if(canMutationObserver){var hiddenDiv=document.createElement("div");var observer=new MutationObserver(function(){var queueList=queue.slice();queue.length=0;queueList.forEach(function(fn){fn()})});observer.observe(hiddenDiv,{attributes:true});return function nextTick(fn){if(!queue.length){hiddenDiv.setAttribute("yes","no")}queue.push(fn)}}if(canPost){window.addEventListener("message",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")}},{}],9:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":10}],10:[function(require,module,exports){(function(process){module.exports=Duplex;var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};var util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable");var Writable=require("./_stream_writable");util.inherits(Duplex,Readable);forEach(objectKeys(Writable.prototype),function(method){if(!Duplex.prototype[method])Duplex.prototype[method]=Writable.prototype[method]});function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options);Writable.call(this,options);if(options&&options.readable===false)this.readable=false;if(options&&options.writable===false)this.writable=false;this.allowHalfOpen=true;if(options&&options.allowHalfOpen===false)this.allowHalfOpen=false;this.once("end",onend)}function onend(){if(this.allowHalfOpen||this._writableState.ended)return;process.nextTick(this.end.bind(this))}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}}).call(this,require("_process"))},{"./_stream_readable":12,"./_stream_writable":14,_process:8,"core-util-is":15,inherits:6}],11:[function(require,module,exports){module.exports=PassThrough;var Transform=require("./_stream_transform");var util=require("core-util-is");util.inherits=require("inherits");util.inherits(PassThrough,Transform);function PassThrough(options){if(!(this instanceof PassThrough))return new PassThrough(options);Transform.call(this,options)}PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"./_stream_transform":13,"core-util-is":15,inherits:6}],12:[function(require,module,exports){(function(process){module.exports=Readable;var isArray=require("isarray");var Buffer=require("buffer").Buffer;Readable.ReadableState=ReadableState;var EE=require("events").EventEmitter;if(!EE.listenerCount)EE.listenerCount=function(emitter,type){return emitter.listeners(type).length};var Stream=require("stream");var util=require("core-util-is");util.inherits=require("inherits");var StringDecoder;util.inherits(Readable,Stream);function ReadableState(options,stream){options=options||{};var hwm=options.highWaterMark;this.highWaterMark=hwm||hwm===0?hwm:16*1024;this.highWaterMark=~~this.highWaterMark;this.buffer=[];this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=false;this.ended=false;this.endEmitted=false;this.reading=false;this.calledRead=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.objectMode=!!options.objectMode;this.defaultEncoding=options.defaultEncoding||"utf8";this.ranOut=false;this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(options.encoding){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this.decoder=new StringDecoder(options.encoding);this.encoding=options.encoding}}function Readable(options){if(!(this instanceof Readable))return new Readable(options);this._readableState=new ReadableState(options,this);this.readable=true;Stream.call(this)}Readable.prototype.push=function(chunk,encoding){var state=this._readableState;if(typeof chunk==="string"&&!state.objectMode){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=new Buffer(chunk,encoding);encoding=""}}return readableAddChunk(this,state,chunk,encoding,false)};Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",true)};function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er){stream.emit("error",er)}else if(chunk===null||chunk===undefined){state.reading=false;if(!state.ended)onEofChunk(stream,state)}else if(state.objectMode||chunk&&chunk.length>0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else{if(state.decoder&&!addToFront&&!encoding)chunk=state.decoder.write(chunk);state.length+=state.objectMode?1:chunk.length;if(addToFront){state.buffer.unshift(chunk)}else{state.reading=false;state.buffer.push(chunk)}if(state.needReadable)emitReadable(stream);maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length<state.highWaterMark||state.length===0)}Readable.prototype.setEncoding=function(enc){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this._readableState.decoder=new StringDecoder(enc);this._readableState.encoding=enc};var MAX_HWM=8388608;function roundUpToNextPowerOf2(n){if(n>=MAX_HWM){n=MAX_HWM}else{n--;for(var p=1;p<32;p<<=1)n|=n>>p;n++}return n}function howMuchToRead(n,state){if(state.length===0&&state.ended)return 0;if(state.objectMode)return n===0?0:1;if(n===null||isNaN(n)){if(state.flowing&&state.buffer.length)return state.buffer[0].length;else return state.length}if(n<=0)return 0;if(n>state.highWaterMark)state.highWaterMark=roundUpToNextPowerOf2(n);if(n>state.length){if(!state.ended){state.needReadable=true;return 0}else return state.length}return n}Readable.prototype.read=function(n){var state=this._readableState;state.calledRead=true;var nOrig=n;var ret;if(typeof n!=="number"||n>0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){ret=null;if(state.length>0&&state.decoder){ret=fromList(n,state);state.length-=ret.length}if(state.length===0)endReadable(this);return ret}var doRead=state.needReadable;if(state.length-n<=state.highWaterMark)doRead=true;if(state.ended||state.reading)doRead=false;if(doRead){state.reading=true;state.sync=true;if(state.length===0)state.needReadable=true;this._read(state.highWaterMark);state.sync=false}if(doRead&&!state.reading)n=howMuchToRead(nOrig,state);if(n>0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}state.length-=n;if(state.length===0&&!state.ended)state.needReadable=true;if(state.ended&&!state.endEmitted&&state.length===0)endReadable(this);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer.isBuffer(chunk)&&"string"!==typeof chunk&&chunk!==null&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;if(state.length>0)emitReadable(stream);else endReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(state.emittedReadable)return;state.emittedReadable=true;if(state.sync)process.nextTick(function(){emitReadable_(stream)});else emitReadable_(stream)}function emitReadable_(stream){stream.emit("readable")}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;process.nextTick(function(){maybeReadMore_(stream,state)})}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length<state.highWaterMark){stream.read(0);if(len===state.length)break;else len=state.length}state.readingMore=false}Readable.prototype._read=function(n){this.emit("error",new Error("not implemented"))};Readable.prototype.pipe=function(dest,pipeOpts){var src=this;var state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest);break}state.pipesCount+=1;var doEnd=(!pipeOpts||pipeOpts.end!==false)&&dest!==process.stdout&&dest!==process.stderr;var endFn=doEnd?onend:cleanup;if(state.endEmitted)process.nextTick(endFn);else src.once("end",endFn);dest.on("unpipe",onunpipe);function onunpipe(readable){if(readable!==src)return;cleanup()}function onend(){dest.end()}var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);function cleanup(){dest.removeListener("close",onclose);dest.removeListener("finish",onfinish);dest.removeListener("drain",ondrain);dest.removeListener("error",onerror);dest.removeListener("unpipe",onunpipe);src.removeListener("end",onend);src.removeListener("end",cleanup);if(!dest._writableState||dest._writableState.needDrain)ondrain()}function onerror(er){unpipe();dest.removeListener("error",onerror);if(EE.listenerCount(dest,"error")===0)dest.emit("error",er)}if(!dest._events||!dest._events.error)dest.on("error",onerror);else if(isArray(dest._events.error))dest._events.error.unshift(onerror);else dest._events.error=[onerror,dest._events.error];function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){this.on("readable",pipeOnReadable);state.flowing=true;process.nextTick(function(){flow(src)})}return dest};function pipeOnDrain(src){return function(){var dest=this;var state=src._readableState;state.awaitDrain--;if(state.awaitDrain===0)flow(src)}}function flow(src){var state=src._readableState;var chunk;state.awaitDrain=0;function write(dest,i,list){var written=dest.write(chunk);if(false===written){state.awaitDrain++}}while(state.pipesCount&&null!==(chunk=src.read())){if(state.pipesCount===1)write(state.pipes,0,null);else forEach(state.pipes,write);src.emit("data",chunk);if(state.awaitDrain>0)return}if(state.pipesCount===0){state.flowing=false;if(EE.listenerCount(src,"data")>0)emitDataEvents(src);return}state.ranOut=true}function pipeOnReadable(){if(this._readableState.ranOut){this._readableState.ranOut=false;flow(this)}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;this.removeListener("readable",pipeOnReadable);state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;this.removeListener("readable",pipeOnReadable);state.flowing=false;for(var i=0;i<len;i++)dests[i].emit("unpipe",this);return this}var i=indexOf(state.pipes,dest);if(i===-1)return this;state.pipes.splice(i,1);state.pipesCount-=1;if(state.pipesCount===1)state.pipes=state.pipes[0];dest.emit("unpipe",this);return this};Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn);if(ev==="data"&&!this._readableState.flowing)emitDataEvents(this);if(ev==="readable"&&this.readable){var state=this._readableState;if(!state.readableListening){state.readableListening=true;state.emittedReadable=false;state.needReadable=true;if(!state.reading){this.read(0)}else if(state.length){emitReadable(this,state)}}}return res};Readable.prototype.addListener=Readable.prototype.on;Readable.prototype.resume=function(){emitDataEvents(this);this.read(0);this.emit("resume")};Readable.prototype.pause=function(){emitDataEvents(this,true);this.emit("pause")};function emitDataEvents(stream,startPaused){var state=stream._readableState;if(state.flowing){throw new Error("Cannot switch to old mode now.")}var paused=startPaused||false;var readable=false;stream.readable=true;stream.pipe=Stream.prototype.pipe;stream.on=stream.addListener=Stream.prototype.on;stream.on("readable",function(){readable=true;var c;while(!paused&&null!==(c=stream.read()))stream.emit("data",c);if(c===null){readable=false;stream._readableState.needReadable=true}});stream.pause=function(){paused=true;this.emit("pause")};stream.resume=function(){paused=false;if(readable)process.nextTick(function(){stream.emit("readable")});else this.read(0);this.emit("resume")};stream.emit("readable")}Readable.prototype.wrap=function(stream){var state=this._readableState;var paused=false;var self=this;stream.on("end",function(){if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length)self.push(chunk)}self.push(null)});stream.on("data",function(chunk){if(state.decoder)chunk=state.decoder.write(chunk);if(state.objectMode&&(chunk===null||chunk===undefined))return;else if(!state.objectMode&&(!chunk||!chunk.length))return;var ret=self.push(chunk);if(!ret){paused=true;stream.pause()}});for(var i in stream){if(typeof stream[i]==="function"&&typeof this[i]==="undefined"){this[i]=function(method){return function(){return stream[method].apply(stream,arguments)}}(i)}}var events=["error","close","destroy","pause","resume"];forEach(events,function(ev){stream.on(ev,self.emit.bind(self,ev))});self._read=function(n){if(paused){paused=false;stream.resume()}};return self};Readable._fromList=fromList;function fromList(n,state){var list=state.buffer;var length=state.length;var stringMode=!!state.decoder;var objectMode=!!state.objectMode;var ret;if(list.length===0)return null;if(length===0)ret=null;else if(objectMode)ret=list.shift();else if(!n||n>=length){if(stringMode)ret=list.join("");else ret=Buffer.concat(list,length);list.length=0}else{if(n<list[0].length){var buf=list[0];ret=buf.slice(0,n);list[0]=buf.slice(n)}else if(n===list[0].length){ret=list.shift()}else{if(stringMode)ret="";else ret=new Buffer(n);var c=0;for(var i=0,l=list.length;i<l&&c<n;i++){var buf=list[0];var cpy=Math.min(n-c,buf.length);if(stringMode)ret+=buf.slice(0,cpy);else buf.copy(ret,c,0,cpy);if(cpy<buf.length)list[0]=buf.slice(cpy);else list.shift();c+=cpy}}}return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error("endReadable called on non-empty stream");if(!state.endEmitted&&state.calledRead){state.ended=true;process.nextTick(function(){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}})}}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}function indexOf(xs,x){for(var i=0,l=xs.length;i<l;i++){if(xs[i]===x)return i}return-1}}).call(this,require("_process"))},{_process:8,buffer:1,"core-util-is":15,events:5,inherits:6,isarray:7,stream:20,"string_decoder/":21}],13:[function(require,module,exports){module.exports=Transform;var Duplex=require("./_stream_duplex");var util=require("core-util-is");util.inherits=require("inherits");util.inherits(Transform,Duplex);function TransformState(options,stream){this.afterTransform=function(er,data){return afterTransform(stream,er,data)};this.needTransform=false;this.transforming=false;this.writecb=null;this.writechunk=null}function afterTransform(stream,er,data){var ts=stream._transformState;ts.transforming=false;var cb=ts.writecb;if(!cb)return stream.emit("error",new Error("no writecb in Transform class"));ts.writechunk=null;ts.writecb=null;if(data!==null&&data!==undefined)stream.push(data);if(cb)cb(er);var rs=stream._readableState;rs.reading=false;if(rs.needReadable||rs.length<rs.highWaterMark){stream._read(rs.highWaterMark)}}function Transform(options){if(!(this instanceof Transform))return new Transform(options);Duplex.call(this,options);var ts=this._transformState=new TransformState(options,this);var stream=this;this._readableState.needReadable=true;this._readableState.sync=false;this.once("finish",function(){if("function"===typeof this._flush)this._flush(function(er){done(stream,er)});else done(stream)})}Transform.prototype.push=function(chunk,encoding){this._transformState.needTransform=false;return Duplex.prototype.push.call(this,chunk,encoding)};Transform.prototype._transform=function(chunk,encoding,cb){throw new Error("not implemented")};Transform.prototype._write=function(chunk,encoding,cb){var ts=this._transformState;ts.writecb=cb;ts.writechunk=chunk;ts.writeencoding=encoding;if(!ts.transforming){var rs=this._readableState;if(ts.needTransform||rs.needReadable||rs.length<rs.highWaterMark)this._read(rs.highWaterMark)}};Transform.prototype._read=function(n){var ts=this._transformState;if(ts.writechunk!==null&&ts.writecb&&!ts.transforming){ts.transforming=true;this._transform(ts.writechunk,ts.writeencoding,ts.afterTransform)}else{ts.needTransform=true}};function done(stream,er){if(er)return stream.emit("error",er);var ws=stream._writableState;var rs=stream._readableState;var ts=stream._transformState;if(ws.length)throw new Error("calling transform done when ws.length != 0");if(ts.transforming)throw new Error("calling transform done when still transforming");return stream.push(null)}},{"./_stream_duplex":10,"core-util-is":15,inherits:6}],14:[function(require,module,exports){(function(process){module.exports=Writable;var Buffer=require("buffer").Buffer;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var Stream=require("stream");util.inherits(Writable,Stream);function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb}function WritableState(options,stream){options=options||{};var hwm=options.highWaterMark;this.highWaterMark=hwm||hwm===0?hwm:16*1024;this.objectMode=!!options.objectMode;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.buffer=[];this.errorEmitted=false}function Writable(options){var Duplex=require("./_stream_duplex");if(!(this instanceof Writable)&&!(this instanceof Duplex))return new Writable(options);this._writableState=new WritableState(options,this);this.writable=true;Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe. Not readable."))};function writeAfterEnd(stream,state,cb){var er=new Error("write after end");stream.emit("error",er);process.nextTick(function(){cb(er)})}function validChunk(stream,state,chunk,cb){var valid=true;if(!Buffer.isBuffer(chunk)&&"string"!==typeof chunk&&chunk!==null&&chunk!==undefined&&!state.objectMode){var er=new TypeError("Invalid non-string/buffer chunk");stream.emit("error",er);process.nextTick(function(){cb(er)});valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;if(typeof encoding==="function"){cb=encoding;encoding=null}if(Buffer.isBuffer(chunk))encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=function(){};if(state.ended)writeAfterEnd(this,state,cb);else if(validChunk(this,state,chunk,cb))ret=writeOrBuffer(this,state,chunk,encoding,cb);return ret};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=new Buffer(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,chunk,encoding,cb){chunk=decodeChunk(state,chunk,encoding);if(Buffer.isBuffer(chunk))encoding="buffer";var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length<state.highWaterMark;if(!ret)state.needDrain=true;if(state.writing)state.buffer.push(new WriteReq(chunk,encoding,cb));else doWrite(stream,state,len,chunk,encoding,cb);return ret}function doWrite(stream,state,len,chunk,encoding,cb){state.writelen=len;state.writecb=cb;state.writing=true;state.sync=true;stream._write(chunk,encoding,state.onwrite);state.sync=false}function onwriteError(stream,state,sync,er,cb){if(sync)process.nextTick(function(){cb(er)});else cb(er);stream._writableState.errorEmitted=true;stream.emit("error",er)}function onwriteStateUpdate(state){state.writing=false;state.writecb=null;state.length-=state.writelen;state.writelen=0}function onwrite(stream,er){var state=stream._writableState;var sync=state.sync;var cb=state.writecb;onwriteStateUpdate(state);if(er)onwriteError(stream,state,sync,er,cb);else{var finished=needFinish(stream,state);if(!finished&&!state.bufferProcessing&&state.buffer.length)clearBuffer(stream,state);if(sync){process.nextTick(function(){afterWrite(stream,state,finished,cb)})}else{afterWrite(stream,state,finished,cb)}}}function afterWrite(stream,state,finished,cb){if(!finished)onwriteDrain(stream,state);cb();if(finished)finishMaybe(stream,state)}function onwriteDrain(stream,state){if(state.length===0&&state.needDrain){state.needDrain=false;stream.emit("drain")}}function clearBuffer(stream,state){state.bufferProcessing=true;for(var c=0;c<state.buffer.length;c++){var entry=state.buffer[c];var chunk=entry.chunk;var encoding=entry.encoding;var cb=entry.callback;var len=state.objectMode?1:chunk.length;doWrite(stream,state,len,chunk,encoding,cb);if(state.writing){c++;break}}state.bufferProcessing=false;if(c<state.buffer.length)state.buffer=state.buffer.slice(c);else state.buffer.length=0}Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("not implemented"))};Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;if(typeof chunk==="function"){cb=chunk;chunk=null;encoding=null}else if(typeof encoding==="function"){cb=encoding;encoding=null}if(typeof chunk!=="undefined"&&chunk!==null)this.write(chunk,encoding);if(!state.ending&&!state.finished)endWritable(this,state,cb)};function needFinish(stream,state){return state.ending&&state.length===0&&!state.finished&&!state.writing}function finishMaybe(stream,state){var need=needFinish(stream,state);if(need){state.finished=true;stream.emit("finish")}return need}function endWritable(stream,state,cb){state.ending=true;finishMaybe(stream,state);if(cb){if(state.finished)process.nextTick(cb);else stream.once("finish",cb)}state.ended=true}}).call(this,require("_process"))},{"./_stream_duplex":10,_process:8,buffer:1,"core-util-is":15,inherits:6,stream:20}],15:[function(require,module,exports){(function(Buffer){function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;function isBuffer(arg){return Buffer.isBuffer(arg)}exports.isBuffer=isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(this,require("buffer").Buffer)},{buffer:1}],16:[function(require,module,exports){module.exports=require("./lib/_stream_passthrough.js")},{"./lib/_stream_passthrough.js":11}],17:[function(require,module,exports){var Stream=require("stream");exports=module.exports=require("./lib/_stream_readable.js");exports.Stream=Stream;exports.Readable=exports;exports.Writable=require("./lib/_stream_writable.js");exports.Duplex=require("./lib/_stream_duplex.js");exports.Transform=require("./lib/_stream_transform.js");exports.PassThrough=require("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":10,"./lib/_stream_passthrough.js":11,"./lib/_stream_readable.js":12,"./lib/_stream_transform.js":13,"./lib/_stream_writable.js":14,stream:20}],18:[function(require,module,exports){module.exports=require("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":13}],19:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":14}],20:[function(require,module,exports){module.exports=Stream;var EE=require("events").EventEmitter;var inherits=require("inherits");inherits(Stream,EE);Stream.Readable=require("readable-stream/readable.js");Stream.Writable=require("readable-stream/writable.js");Stream.Duplex=require("readable-stream/duplex.js");Stream.Transform=require("readable-stream/transform.js");Stream.PassThrough=require("readable-stream/passthrough.js");Stream.Stream=Stream;function Stream(){EE.call(this)}Stream.prototype.pipe=function(dest,options){var source=this;function ondata(chunk){if(dest.writable){if(false===dest.write(chunk)&&source.pause){source.pause()}}}source.on("data",ondata);function ondrain(){if(source.readable&&source.resume){source.resume()}}dest.on("drain",ondrain);if(!dest._isStdio&&(!options||options.end!==false)){source.on("end",onend);source.on("close",onclose)}var didOnEnd=false;function onend(){if(didOnEnd)return;didOnEnd=true;dest.end()}function onclose(){if(didOnEnd)return;didOnEnd=true;if(typeof dest.destroy==="function")dest.destroy()}function onerror(er){cleanup();if(EE.listenerCount(this,"error")===0){throw er}}source.on("error",onerror);dest.on("error",onerror);function cleanup(){source.removeListener("data",ondata);dest.removeListener("drain",ondrain);source.removeListener("end",onend);source.removeListener("close",onclose);source.removeListener("error",onerror);dest.removeListener("error",onerror);source.removeListener("end",cleanup);source.removeListener("close",cleanup);dest.removeListener("close",cleanup)}source.on("end",cleanup);source.on("close",cleanup);dest.on("close",cleanup);dest.emit("pipe",source);return dest}},{events:5,inherits:6,"readable-stream/duplex.js":9,"readable-stream/passthrough.js":16,"readable-stream/readable.js":17,"readable-stream/transform.js":18,"readable-stream/writable.js":19}],21:[function(require,module,exports){var Buffer=require("buffer").Buffer;var isBufferEncoding=Buffer.isEncoding||function(encoding){switch(encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function assertEncoding(encoding){if(encoding&&!isBufferEncoding(encoding)){throw new Error("Unknown encoding: "+encoding)}}var StringDecoder=exports.StringDecoder=function(encoding){this.encoding=(encoding||"utf8").toLowerCase().replace(/[-_]/,"");assertEncoding(encoding);switch(this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2;this.detectIncompleteChar=utf16DetectIncompleteChar;break;case"base64":this.surrogateSize=3;this.detectIncompleteChar=base64DetectIncompleteChar;break;default:this.write=passThroughWrite;return}this.charBuffer=new Buffer(6);this.charReceived=0;this.charLength=0};StringDecoder.prototype.write=function(buffer){var charStr="";while(this.charLength){var available=buffer.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived<this.charLength){return""}buffer=buffer.slice(available,buffer.length);charStr=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var charCode=charStr.charCodeAt(charStr.length-1);if(charCode>=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;
this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}},{buffer:1}],22:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],23:[function(require,module,exports){(function(process,global){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i<arguments.length;i++){objects.push(inspect(arguments[i]))}return objects.join(" ")}var i=1;var args=arguments;var len=args.length;var str=String(f).replace(formatRegExp,function(x){if(x==="%%")return"%";if(i>=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i<len;x=args[++i]){if(isNull(x)||!isObject(x)){str+=" "+x}else{str+=" "+inspect(x)}}return str};exports.deprecate=function(fn,msg){if(isUndefined(global.process)){return function(){return exports.deprecate(fn,msg).apply(this,arguments)}}if(process.noDeprecation===true){return fn}var warned=false;function deprecated(){if(!warned){if(process.throwDeprecation){throw new Error(msg)}else if(process.traceDeprecation){console.trace(msg)}else{console.error(msg)}warned=true}return fn.apply(this,arguments)}return deprecated};var debugs={};var debugEnviron;exports.debuglog=function(set){if(isUndefined(debugEnviron))debugEnviron=process.env.NODE_DEBUG||"";set=set.toUpperCase();if(!debugs[set]){if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else{debugs[set]=function(){}}}return debugs[set]};function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};if(arguments.length>=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i<l;++i){if(hasOwnProperty(value,String(i))){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),true))}else{output.push("")}}keys.forEach(function(key){if(!key.match(/^\d+$/)){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,true))}});return output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]};if(desc.get){if(desc.set){str=ctx.stylize("[Getter/Setter]","special")}else{str=ctx.stylize("[Getter]","special")}}else{if(desc.set){str=ctx.stylize("[Setter]","special")}}if(!hasOwnProperty(visibleKeys,key)){name="["+key+"]"}if(!str){if(ctx.seen.indexOf(desc.value)<0){if(isNull(recurseTimes)){str=formatValue(ctx,desc.value,null)}else{str=formatValue(ctx,desc.value,recurseTimes-1)}if(str.indexOf("\n")>-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":22,_process:8,inherits:6}],24:[function(require,module,exports){"use strict";var active=[];var unleashListeners=[];var targets=[console];var logger=module.exports=function(name){var enabled=checkActive();function checkActive(){return enabled=active.indexOf("*")>=0||active.indexOf(name)>=0}unleashListeners[unleashListeners.length]=checkActive;return function(){var args=[].slice.call(arguments);if(typeof args[0]=="string"||args[0]instanceof String){args[0]=name+": "+args[0]}if(!enabled){return}targets.forEach(function(target){target.log.apply(target,args)})}};logger.reset=function(){targets=[];active=[];return logger.enable()};logger.to=function(target){targets=targets.concat(target||[]);return logger};logger.enable=function(){active=active.concat([].slice.call(arguments));unleashListeners.forEach(function(listener){listener()});return logger}},{}],25:[function(require,module,exports){(function(Buffer){var isTypedArray=require("is-typedarray").strict;module.exports=function(arr){var constructor=Buffer.TYPED_ARRAY_SUPPORT?Buffer._augment:function(arr){return new Buffer(arr)};if(arr instanceof Uint8Array){return constructor(arr)}else if(arr instanceof ArrayBuffer){return constructor(new Uint8Array(arr))}else if(isTypedArray(arr)){return constructor(new Uint8Array(arr.buffer,arr.byteOffset,arr.byteLength))}else{return new Buffer(arr)}}}).call(this,require("buffer").Buffer)},{buffer:1,"is-typedarray":26}],26:[function(require,module,exports){module.exports=isTypedArray;isTypedArray.strict=isStrictTypedArray;isTypedArray.loose=isLooseTypedArray;var toString=Object.prototype.toString;var names={"[object Int8Array]":true,"[object Int16Array]":true,"[object Int32Array]":true,"[object Uint8Array]":true,"[object Uint16Array]":true,"[object Uint32Array]":true,"[object Float32Array]":true,"[object Float64Array]":true};function isTypedArray(arr){return isStrictTypedArray(arr)||isLooseTypedArray(arr)}function isStrictTypedArray(arr){return arr instanceof Int8Array||arr instanceof Int16Array||arr instanceof Int32Array||arr instanceof Uint8Array||arr instanceof Uint16Array||arr instanceof Uint32Array||arr instanceof Float32Array||arr instanceof Float64Array}function isLooseTypedArray(arr){return names[toString.call(arr)]}},{}],"rtc-dcstream":[function(require,module,exports){(function(Buffer){"use strict";var debug=require("cog/logger")("rtc-dcstream");var stream=require("stream");var toBuffer=require("typedarray-to-buffer");var util=require("util");var closingStates=["closing","closed"];var ENDOFSTREAM="::endofstream";function RTCChannelStream(channel){if(!(this instanceof RTCChannelStream)){return new RTCChannelStream(channel)}stream.Duplex.call(this,{decodeStrings:false,objectMode:true});this._rq=[];this._wq=[];this.channel=channel;channel.binaryType="arraybuffer";this._handleClose=handleChannelClose.bind(this);this._handleMessage=handleChannelMessage.bind(this);this._handleOpen=handleChannelOpen.bind(this);channel.addEventListener("message",this._handleMessage);channel.addEventListener("close",this._handleClose);channel.addEventListener("open",this._handleOpen);this.once("finish",function(){if(channel.readyState==="open"){channel.send(ENDOFSTREAM)}})}module.exports=RTCChannelStream;util.inherits(RTCChannelStream,stream.Duplex);var prot=RTCChannelStream.prototype;prot._checkClear=function(){if(this.channel.bufferedAmount===0){clearInterval(this._clearTimer);this._handleOpen()}};prot._debindChannel=function(){var channel=this.channel;channel.removeEventListener("message",this._handleMessage);channel.removeEventListener("close",this._handleClose);channel.removeEventListener("open",this._handleOpen)};prot._read=function(n){var ready=true;var next;if(this._rq.length===0){return this.once("readable",this._read.bind(this,n))}while(ready&&this._rq.length>0){next=this._rq.shift();if(next instanceof ArrayBuffer){this.push(toBuffer(new Uint8Array(next)))}else{this.push(next)}}return ready};prot._write=function(chunk,encoding,callback){var closed=!this.channel||closingStates.indexOf(this.channel.readyState)>=0;if(closed){return callback(new Error("data channel is closed"))}if(this._wq.length||this.channel.readyState==="connecting"){return this._wq.push([chunk,encoding,callback])}if(this.channel.bufferedAmount>0){debug("data channel buffering "+this.channel.bufferedAmount+", backing off");this._clearTimer=setInterval(this._checkClear.bind(this),100);return this._wq.push([chunk,encoding,callback])}if(Buffer.isBuffer(chunk)){this.channel.send(chunk)}else{try{this.channel.send(chunk)}catch(e){debug("error sending text: ",e)}}return callback()};function handleChannelClose(evt){debug("dc closed");this.emit("close")}function handleChannelMessage(evt){var data=evt&&evt.data;if(typeof data=="string"&&data===ENDOFSTREAM){this._debindChannel();return this.emit("end")}this._rq.push(data);this.emit("readable")}function handleChannelOpen(evt){var peer=this;var queue=this._wq;function sendNext(args){var callback;if(!args){return queue.length?sendNext(queue.shift()):null}callback=args[2];args[2]=function(){sendNext(queue.shift());if(typeof callback=="function"){callback()}};peer._write.apply(peer,args)}debug("channel open, sending queued "+queue.length+" messages");sendNext(queue.shift())}}).call(this,require("buffer").Buffer)},{buffer:1,"cog/logger":24,stream:20,"typedarray-to-buffer":25,util:23}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canMutationObserver=typeof window!=="undefined"&&window.MutationObserver;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}var queue=[];if(canMutationObserver){var hiddenDiv=document.createElement("div");var observer=new MutationObserver(function(){var queueList=queue.slice();queue.length=0;queueList.forEach(function(fn){fn()})});observer.observe(hiddenDiv,{attributes:true});return function nextTick(fn){if(!queue.length){hiddenDiv.setAttribute("yes","no")}queue.push(fn)}}if(canPost){window.addEventListener("message",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")}},{}],2:[function(require,module,exports){module.exports=function(messenger){if(typeof messenger=="function"){return messenger}return require("rtc-switchboard-messenger")(messenger)}},{"rtc-switchboard-messenger":35}],3:[function(require,module,exports){"use strict";module.exports=function(target){target=target||{};[].slice.call(arguments,1).forEach(function(source){if(!source){return}for(var prop in source){if(target[prop]===void 0){target[prop]=source[prop]}}});return target}},{}],4:[function(require,module,exports){"use strict";module.exports=function(target){[].slice.call(arguments,1).forEach(function(source){if(!source){return}for(var prop in source){target[prop]=source[prop]}});return target}},{}],5:[function(require,module,exports){module.exports=function(target){function get(key){return target[key]}function set(key,value){target[key]=value}function remove(key){return delete target[key]}function keys(){return Object.keys(target)}function values(){return Object.keys(target).map(function(key){return target[key]})}if(typeof target!="object"){return target}return{get:get,set:set,remove:remove,"delete":remove,keys:keys,values:values}}},{}],6:[function(require,module,exports){"use strict";module.exports=function(input){var isString=typeof input=="string"||input instanceof String;var reNumeric=/^\-?\d+\.?\d*$/;var shouldParse;var firstChar;var lastChar;if(!isString||input.length<2){if(isString&&reNumeric.test(input)){return parseFloat(input)}return input}if(input==="true"||input==="false"){return input==="true"}if(input==="null"){return null}firstChar=input.charAt(0);lastChar=input.charAt(input.length-1);shouldParse=firstChar=="{"&&lastChar=="}"||firstChar=="["&&lastChar=="]"||firstChar=='"'&&lastChar=='"';if(shouldParse){try{return JSON.parse(input)}catch(e){}}return reNumeric.test(input)?parseFloat(input):input}},{}],7:[function(require,module,exports){"use strict";var active=[];var unleashListeners=[];var targets=[console];var logger=module.exports=function(name){var enabled=checkActive();function checkActive(){return enabled=active.indexOf("*")>=0||active.indexOf(name)>=0}unleashListeners[unleashListeners.length]=checkActive;return function(){var args=[].slice.call(arguments);if(typeof args[0]=="string"||args[0]instanceof String){args[0]=name+": "+args[0]}if(!enabled){return}targets.forEach(function(target){target.log.apply(target,args)})}};logger.reset=function(){targets=[];active=[];return logger.enable()};logger.to=function(target){targets=targets.concat(target||[]);return logger};logger.enable=function(){active=active.concat([].slice.call(arguments));unleashListeners.forEach(function(listener){listener()});return logger}},{}],8:[function(require,module,exports){"use strict";module.exports=function(fn,delay,opts){var lastExec=(opts||{}).leading!==false?0:Date.now();var trailing=(opts||{}).trailing;var timer;var queuedArgs;var queuedScope;trailing=trailing||trailing===undefined;function invokeDefered(){fn.apply(queuedScope,queuedArgs||[]);lastExec=Date.now()}return function(){var tick=Date.now();var elapsed=tick-lastExec;clearTimeout(timer);if(elapsed<delay){queuedArgs=[].slice.call(arguments,0);queuedScope=this;return trailing&&(timer=setTimeout(invokeDefered,delay-elapsed))}lastExec=tick;fn.apply(this,arguments)}}},{}],9:[function(require,module,exports){var createTrie=require("array-trie");var reDelim=/[\.\:]/;var createBus=module.exports=function(namespace,parent,scope){var registry=createTrie();var feeds=[];function bus(name){var args=[].slice.call(arguments,1);var parts=getNameParts(name);var delimited=parts.join(".");var handlers=registry.get(parts)||[];var results;feeds.forEach(function(feed){feed({name:delimited,args:args})});results=[].concat(handlers).map(function(handler){return handler.apply(scope||this,args)});if(bus.parent){results=results.concat(bus.parent.apply(scope||this,[namespace.concat(parts)].concat(args)))}return results}function clear(name){if(name){registry.set(getNameParts(name),[])}else{registry=createTrie()}}function feed(handler){function stop(){feeds.splice(feeds.indexOf(handler),1)}feeds.push(handler);return stop}function getNameParts(name){return Array.isArray(name)?name:name?name.split(reDelim):[]}function off(name,handler){var handlers=registry.get(getNameParts(name));var idx=handlers?handlers.indexOf(handler):-1;if(idx>=0){handlers.splice(idx,1)}}function on(name,handler){var parts=getNameParts(name);var handlers=registry.get(parts);if(handlers){handlers.push(handler)}else{registry.set(parts,[handler])}return bus}function once(name,handler){return on(name,function handleEvent(){var result=handler.apply(this,arguments);bus.off(name,handleEvent);return result})}if(typeof namespace=="function"){parent=namespace;namespace=""}namespace=namespace&&namespace.split(reDelim)||[];bus.clear=bus.removeAllListeners=clear;bus.feed=feed;bus.on=bus.addListener=on;bus.once=once;bus.off=bus.removeListener=off;bus.parent=parent||namespace&&namespace.length>0&&createBus();return bus}},{"array-trie":11}],10:[function(require,module,exports){"use strict";function compileSearch(funcName,predicate,reversed,extraArgs,useNdarray,earlyOut){var code=["function ",funcName,"(a,l,h,",extraArgs.join(","),"){",earlyOut?"":"var i=",reversed?"l-1":"h+1",";while(l<=h){var m=(l+h)>>>1,x=a",useNdarray?".get(m)":"[m]"];if(earlyOut){if(predicate.indexOf("c")<0){code.push(";if(x===y){return m}else if(x<=y){")}else{code.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){")}}else{code.push(";if(",predicate,"){i=m;")}if(reversed){code.push("l=m+1}else{h=m-1}")}else{code.push("h=m-1}else{l=m+1}")}code.push("}");if(earlyOut){code.push("return -1};")}else{code.push("return i};")}return code.join("")}function compileBoundsSearch(predicate,reversed,suffix,earlyOut){var result=new Function([compileSearch("A","x"+predicate+"y",reversed,["y"],false,earlyOut),compileSearch("B","x"+predicate+"y",reversed,["y"],true,earlyOut),compileSearch("P","c(x,y)"+predicate+"0",reversed,["y","c"],false,earlyOut),compileSearch("Q","c(x,y)"+predicate+"0",reversed,["y","c"],true,earlyOut),"function dispatchBsearch",suffix,"(a,y,c,l,h){if(a.shape){if(typeof(c)==='function'){return Q(a,(l===undefined)?0:l|0,(h===undefined)?a.shape[0]-1:h|0,y,c)}else{return B(a,(c===undefined)?0:c|0,(l===undefined)?a.shape[0]-1:l|0,y)}}else{if(typeof(c)==='function'){return P(a,(l===undefined)?0:l|0,(h===undefined)?a.length-1:h|0,y,c)}else{return A(a,(c===undefined)?0:c|0,(l===undefined)?a.length-1:l|0,y)}}}return dispatchBsearch",suffix].join(""));return result()}module.exports={ge:compileBoundsSearch(">=",false,"GE"),gt:compileBoundsSearch(">",false,"GT"),lt:compileBoundsSearch("<",true,"LT"),le:compileBoundsSearch("<=",true,"LE"),eq:compileBoundsSearch("-",true,"EQ",true)}},{}],11:[function(require,module,exports){"use strict";var bounds=require("binary-search-bounds");module.exports=createTrie;function Trie(symbols,children,value){this.symbols=symbols;this.children=children;this.value=value}var proto=Trie.prototype;proto.set=function(s,value){if(s.shape){var v=this;var n=s.shape[0];for(var i=0;i<n;++i){var c=s.get(i);var j=bounds.ge(v.symbols,c);if(j<v.symbols.length&&v.symbols[j]===c){v=v.children[j]}else{var l=new Trie([],[],value);for(var k=n-1;k>i;--k){l=new Trie([s.get(k)],[l])}v.symbols.splice(j,0,c);v.children.splice(j,0,l);return value}}return v.value=value}else{var v=this;var n=s.length;for(var i=0;i<n;++i){var c=s[i];var j=bounds.ge(v.symbols,c);if(j<v.symbols.length&&v.symbols[j]===c){v=v.children[j]}else{var l=new Trie([],[],value);for(var k=n-1;k>i;--k){l=new Trie([s[k]],[l])}v.symbols.splice(j,0,c);v.children.splice(j,0,l);return value}}return v.value=value}};proto.get=function(s){if(s.shape){var v=this;var n=s.shape[0];for(var i=0;i<n;++i){var c=s.get(i);var j=bounds.eq(v.symbols,c);if(j<0){return}v=v.children[j]}return v.value}else{var v=this;var n=s.length;for(var i=0;i<n;++i){var c=s[i];var j=bounds.eq(v.symbols,c);if(j<0){return}v=v.children[j]}return v.value}};function createTrie(){return new Trie([],[])}},{"binary-search-bounds":10}],12:[function(require,module,exports){"use strict";var browser=require("detect-browser");var detect=module.exports=function(target,opts){var attach=(opts||{}).attach;var prefixIdx;var prefix;var testName;var hostObject=this||(typeof window!="undefined"?window:undefined);var prefixes=((opts||{}).prefixes||["ms","o","moz","webkit"]).concat("");if(!hostObject){return}for(prefixIdx=prefixes.length;prefixIdx--;){prefix=prefixes[prefixIdx];testName=prefix+(prefix?target.charAt(0).toUpperCase()+target.slice(1):target);if(typeof hostObject[testName]!="undefined"){detect.browser=detect.browser||prefix.toLowerCase();if(attach){hostObject[target]=hostObject[testName]}return hostObject[testName]}}};detect.moz=typeof navigator!="undefined"&&!!navigator.mozGetUserMedia;detect.browser=browser.name;detect.browserVersion=detect.version=browser.version},{"detect-browser":14}],13:[function(require,module,exports){module.exports=function(opts,callback){var ice=(opts||{}).ice;var iceServers=(opts||{}).iceServers;if(typeof ice=="function"){return ice(opts,callback)}else if(Array.isArray(ice)){return callback(null,[].concat(ice))}callback(null,[].concat(iceServers||[]))}},{}],14:[function(require,module,exports){var browsers=[["chrome",/Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+)\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-6].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/iPad\;\sCPU\sOS\s([0-9\._]+)/],["ios",/iPhone\;\sCPU\siPhone\sOS\s([0-9\._]+)/],["safari",/Safari\/([0-9\._]+)/]];var match=browsers.map(match).filter(isMatch)[0];var parts=match&&match[3].split(/[._]/).slice(0,3);while(parts&&parts.length<3){parts.push("0")}exports.name=match&&match[0];exports.version=parts&&parts.join(".");function match(pair){return pair.concat(pair[1].exec(navigator.userAgent))}function isMatch(pair){return!!pair[2]}},{}],15:[function(require,module,exports){var detect=require("./detect");var requiredFunctions=["init"];function isSupported(plugin){return plugin&&typeof plugin.supported=="function"&&plugin.supported(detect)}function isValid(plugin){var supportedFunctions=requiredFunctions.filter(function(fn){return typeof plugin[fn]=="function"});return supportedFunctions.length===requiredFunctions.length}module.exports=function(plugins){return[].concat(plugins||[]).filter(isSupported).filter(isValid)[0]}},{"./detect":12}],16:[function(require,module,exports){module.exports={dataEvent:"data",openEvent:"open",closeEvent:"close",errorEvent:"error",writeMethod:"write",closeMethod:"close",leaveTimeout:3e3}},{}],17:[function(require,module,exports){"use strict";var extend=require("cog/extend");module.exports=function(signaller){function dataAllowed(data){var cloned=extend({allow:true},data);signaller("peer:filter",data.id,cloned);return cloned.allow}return function(args,messageType,srcData,srcState,isDM){var data=args[0];var peer;if(data&&data.id&&data.id!==signaller.id){if(!dataAllowed(data)){return}peer=signaller.peers.get(data.id);signaller("peer:connected",data.id,data);if(peer&&!peer.inactive){extend(peer.data,data);return signaller("peer:update",data,srcData)}peer={id:data.id,roleIdx:[data.id,signaller.id].sort().indexOf(data.id),data:{}};extend(peer.data,data);clearTimeout(peer.leaveTimer);peer.inactive=false;signaller.peers.set(data.id,peer);if(signaller.autoreply&&!isDM){signaller.to(data.id).send("/announce",signaller.attributes)}return signaller("peer:announce",data,peer)}}}},{"cog/extend":4}],18:[function(require,module,exports){"use strict";module.exports=function(signaller,opts){return{announce:require("./announce")(signaller,opts)}}},{"./announce":17}],19:[function(require,module,exports){"use strict";var detect=require("rtc-core/detect");var defaults=require("cog/defaults");var extend=require("cog/extend");var mbus=require("mbus");var getable=require("cog/getable");var uuid=require("cuid");var pull=require("pull-stream");var pushable=require("pull-pushable");var RS_DISCONNECTED=0;var RS_CONNECTING=1;var RS_CONNECTED=2;var metadata={version:"5.2.2"};module.exports=function(messenger,opts){var autoreply=(opts||{}).autoreply;var autoconnect=(opts||{}).autoconnect;var reconnect=(opts||{}).reconnect;var localMeta={};var signaller=mbus("",(opts||{}).logger);var id=signaller.id=(opts||{}).id||uuid();var attributes=signaller.attributes={browser:detect.browser,browserVersion:detect.browserVersion,id:id,agent:"signaller@"+metadata.version};var peers=signaller.peers=getable({});var queue=require("pull-pushable")();var processor;var announceTimer=0;var readyState=RS_DISCONNECTED;function announceOnReconnect(){signaller.announce()}function bufferMessage(args){queue.push(createDataLine(args));if(readyState===RS_DISCONNECTED&&(autoconnect===undefined||autoconnect)){connect()}}function createDataLine(args){return args.map(prepareArg).join("|")}function createMetadata(){return extend({},localMeta,{id:signaller.id})}function handleDisconnect(){if(reconnect===undefined||reconnect){setTimeout(connect,50)}}function prepareArg(arg){if(typeof arg=="object"&&!(arg instanceof String)){return JSON.stringify(arg)}else if(typeof arg=="function"){return null}return arg}var connect=signaller.connect=function(){if(readyState===RS_CONNECTING){return}readyState=RS_CONNECTING;messenger(function(err,source,sink){if(err){readyState=RS_DISCONNECTED;return signaller("error",err)}readyState=RS_CONNECTED;pull(source,pull.through(null,function(){readyState=RS_DISCONNECTED;signaller("disconnected")}),pull.drain(processor));pull(queue,sink);signaller.removeListener("disconnected",handleDisconnect);signaller.on("disconnected",handleDisconnect);signaller("connected")})};var send=signaller.send=function(){var args=[].slice.call(arguments);args.splice(1,0,createMetadata());bufferMessage(args)};signaller.announce=function(data,sender){function sendAnnounce(){(sender||send)("/announce",attributes);signaller("local:announce",attributes)}if(readyState===RS_CONNECTED){signaller.removeListener("connected",announceOnReconnect);
signaller.on("connected",announceOnReconnect)}clearTimeout(announceTimer);extend(attributes,data,{id:signaller.id});return announceTimer=setTimeout(sendAnnounce,(opts||{}).announceDelay||10)};signaller.isMaster=function(targetId){var peer=peers.get(targetId);return peer&&peer.roleIdx!==0};signaller.leave=signaller.close=function(){send("/leave",{id:id});signaller.removeListener("disconnected",handleDisconnect);signaller.removeListener("connected",announceOnReconnect);queue.end();queue=pushable();readyState=RS_DISCONNECTED};signaller.metadata=function(data){if(arguments.length===0){return extend({},localMeta)}localMeta=extend({},data)};signaller.to=function(targetId){var sender=function(){var peer=signaller.peers.get(targetId);var args;if(!peer){throw new Error("Unknown peer: "+targetId)}if(peer.inactive){return}args=["/to",targetId].concat([].slice.call(arguments));args.splice(3,0,createMetadata());bufferMessage(args)};return{announce:function(data){return signaller.announce(data,sender)},send:sender}};opts=defaults({},opts,require("./defaults"));signaller.autoreply=autoreply===undefined||autoreply;signaller.process=processor=require("./processor")(signaller,opts);if(autoconnect===undefined||autoconnect){connect()}return signaller}},{"./defaults":16,"./processor":34,"cog/defaults":3,"cog/extend":4,"cog/getable":5,cuid:20,mbus:9,"pull-pushable":21,"pull-stream":28,"rtc-core/detect":12}],20:[function(require,module,exports){(function(app){"use strict";var namespace="cuid",c=0,blockSize=4,base=36,discreteValues=Math.pow(base,blockSize),pad=function pad(num,size){var s="000000000"+num;return s.substr(s.length-size)},randomBlock=function randomBlock(){return pad((Math.random()*discreteValues<<0).toString(base),blockSize)},safeCounter=function(){c=c<discreteValues?c:0;c++;return c-1},api=function cuid(){var letter="c",timestamp=(new Date).getTime().toString(base),counter,fingerprint=api.fingerprint(),random=randomBlock()+randomBlock();counter=pad(safeCounter().toString(base),blockSize);return letter+timestamp+counter+fingerprint+random};api.slug=function slug(){var date=(new Date).getTime().toString(36),counter,print=api.fingerprint().slice(0,1)+api.fingerprint().slice(-1),random=randomBlock().slice(-2);counter=safeCounter().toString(36).slice(-4);return date.slice(-2)+counter+print+random};api.globalCount=function globalCount(){var cache=function calc(){var i,count=0;for(i in window){count++}return count}();api.globalCount=function(){return cache};return cache};api.fingerprint=function browserPrint(){return pad((navigator.mimeTypes.length+navigator.userAgent.length).toString(36)+api.globalCount().toString(36),4)};if(app.register){app.register(namespace,api)}else if(typeof module!=="undefined"){module.exports=api}else{app[namespace]=api}})(this.applitude||this)},{}],21:[function(require,module,exports){var pull=require("pull-stream");module.exports=pull.Source(function(onClose){var buffer=[],cbs=[],waiting=[],ended;function drain(){var l;while(waiting.length&&((l=buffer.length)||ended)){var data=buffer.shift();var cb=cbs.shift();waiting.shift()(l?null:ended,data);cb&&cb(ended===true?null:ended)}}function read(end,cb){ended=ended||end;waiting.push(cb);drain();if(ended)onClose&&onClose(ended===true?null:ended)}read.push=function(data,cb){if(ended)return cb&&cb(ended===true?null:ended);buffer.push(data);cbs.push(cb);drain()};read.end=function(end,cb){if("function"===typeof end)cb=end,end=true;ended=ended||end||true;if(cb)cbs.push(cb);drain();if(ended)onClose&&onClose(ended===true?null:ended)};return read})},{"pull-stream":22}],22:[function(require,module,exports){var sources=require("./sources");var sinks=require("./sinks");var throughs=require("./throughs");var u=require("pull-core");for(var k in sources)exports[k]=u.Source(sources[k]);for(var k in throughs)exports[k]=u.Through(throughs[k]);for(var k in sinks)exports[k]=u.Sink(sinks[k]);var maybe=require("./maybe")(exports);for(var k in maybe)exports[k]=maybe[k];exports.Duplex=exports.Through=exports.pipeable=u.Through;exports.Source=exports.pipeableSource=u.Source;exports.Sink=exports.pipeableSink=u.Sink},{"./maybe":23,"./sinks":25,"./sources":26,"./throughs":27,"pull-core":24}],23:[function(require,module,exports){var u=require("pull-core");var prop=u.prop;var id=u.id;var maybeSink=u.maybeSink;module.exports=function(pull){var exports={};var drain=pull.drain;var find=exports.find=function(test,cb){return maybeSink(function(cb){var ended=false;if(!cb)cb=test,test=id;else test=prop(test)||id;return drain(function(data){if(test(data)){ended=true;cb(null,data);return false}},function(err){if(ended)return;cb(err===true?null:err,null)})},cb)};var reduce=exports.reduce=function(reduce,acc,cb){return maybeSink(function(cb){return drain(function(data){acc=reduce(acc,data)},function(err){cb(err,acc)})},cb)};var collect=exports.collect=exports.writeArray=function(cb){return reduce(function(arr,item){arr.push(item);return arr},[],cb)};return exports}},{"pull-core":24}],24:[function(require,module,exports){exports.id=function(item){return item};exports.prop=function(map){if("string"==typeof map){var key=map;return function(data){return data[key]}}return map};exports.tester=function(test){if(!test)return exports.id;if("object"===typeof test&&"function"===typeof test.test)return test.test.bind(test);return exports.prop(test)||exports.id};exports.addPipe=addPipe;function addPipe(read){if("function"!==typeof read)return read;read.pipe=read.pipe||function(reader){if("function"!=typeof reader)throw new Error("must pipe to reader");return addPipe(reader(read))};read.type="Source";return read}var Source=exports.Source=function Source(createRead){function s(){var args=[].slice.call(arguments);return addPipe(createRead.apply(null,args))}s.type="Source";return s};var Through=exports.Through=function(createRead){return function(){var args=[].slice.call(arguments);var piped=[];function reader(read){args.unshift(read);read=createRead.apply(null,args);while(piped.length)read=piped.shift()(read);return read}reader.pipe=function(read){piped.push(read);if(read.type==="Source")throw new Error("cannot pipe "+reader.type+" to Source");reader.type=read.type==="Sink"?"Sink":"Through";return reader};reader.type="Through";return reader}};var Sink=exports.Sink=function Sink(createReader){return function(){var args=[].slice.call(arguments);if(!createReader)throw new Error("must be createReader function");function s(read){args.unshift(read);return createReader.apply(null,args)}s.type="Sink";return s}};exports.maybeSink=exports.maybeDrain=function(createSink,cb){if(!cb)return Through(function(read){var ended;return function(close,cb){if(close)return read(close,cb);if(ended)return cb(ended);createSink(function(err,data){ended=err||true;if(!err)cb(null,data);else cb(ended)})(read)}})();return Sink(function(read){return createSink(cb)(read)})()}},{}],25:[function(require,module,exports){var drain=exports.drain=function(read,op,done){(function next(){var loop=true,cbed=false;while(loop){cbed=false;read(null,function(end,data){cbed=true;if(end){loop=false;done&&done(end===true?null:end)}else if(op&&false===op(data)){loop=false;read(true,done||function(){})}else if(!loop){next()}});if(!cbed){loop=false;return}}})()};var onEnd=exports.onEnd=function(read,done){return drain(read,null,done)};var log=exports.log=function(read,done){return drain(read,function(data){console.log(data)},done)}},{}],26:[function(require,module,exports){var keys=exports.keys=function(object){return values(Object.keys(object))};var once=exports.once=function(value){return function(abort,cb){if(abort)return cb(abort);if(value!=null){var _value=value;value=null;cb(null,_value)}else cb(true)}};var values=exports.values=exports.readArray=function(array){if(!Array.isArray(array))array=Object.keys(array).map(function(k){return array[k]});var i=0;return function(end,cb){if(end)return cb&&cb(end);cb(i>=array.length||null,array[i++])}};var count=exports.count=function(max){var i=0;max=max||Infinity;return function(end,cb){if(end)return cb&&cb(end);if(i>max)return cb(true);cb(null,i++)}};var infinite=exports.infinite=function(generate){generate=generate||Math.random;return function(end,cb){if(end)return cb&&cb(end);return cb(null,generate())}};var defer=exports.defer=function(){var _read,cbs=[],_end;var read=function(end,cb){if(!_read){_end=end;cbs.push(cb)}else _read(end,cb)};read.resolve=function(read){if(_read)throw new Error("already resolved");_read=read;if(!_read)throw new Error("no read cannot resolve!"+_read);while(cbs.length)_read(_end,cbs.shift())};read.abort=function(err){read.resolve(function(_,cb){cb(err||true)})};return read};var empty=exports.empty=function(){return function(abort,cb){cb(true)}};var depthFirst=exports.depthFirst=function(start,createStream){var reads=[];reads.unshift(once(start));return function next(end,cb){if(!reads.length)return cb(true);reads[0](end,function(end,data){if(end){reads.shift();return next(null,cb)}reads.unshift(createStream(data));cb(end,data)})}};var widthFirst=exports.widthFirst=function(start,createStream){var reads=[];reads.push(once(start));return function next(end,cb){if(!reads.length)return cb(true);reads[0](end,function(end,data){if(end){reads.shift();return next(null,cb)}reads.push(createStream(data));cb(end,data)})}};var leafFirst=exports.leafFirst=function(start,createStream){var reads=[];var output=[];reads.push(once(start));return function next(end,cb){reads[0](end,function(end,data){if(end){reads.shift();if(!output.length)return cb(true);return cb(null,output.shift())}reads.unshift(createStream(data));output.unshift(data);next(null,cb)})}}},{}],27:[function(require,module,exports){(function(process){var u=require("pull-core");var sources=require("./sources");var sinks=require("./sinks");var prop=u.prop;var id=u.id;var tester=u.tester;var map=exports.map=function(read,map){map=prop(map)||id;return function(end,cb){read(end,function(end,data){var data=!end?map(data):null;cb(end,data)})}};var asyncMap=exports.asyncMap=function(read,map){if(!map)return read;return function(end,cb){if(end)return read(end,cb);read(null,function(end,data){if(end)return cb(end,data);map(data,cb)})}};var paraMap=exports.paraMap=function(read,map,width){if(!map)return read;var ended=false,queue=[],_cb;function drain(){if(!_cb)return;var cb=_cb;_cb=null;if(queue.length)return cb(null,queue.shift());else if(ended&&!n)return cb(ended);_cb=cb}function pull(){read(null,function(end,data){if(end){ended=end;return drain()}n++;map(data,function(err,data){n--;queue.push(data);drain()});if(n<width&&!ended)pull()})}var n=0;return function(end,cb){if(end)return read(end,cb);_cb=cb;if(queue.length||ended)pull(),drain();else pull()};return highWaterMark(asyncMap(read,map),width)};var filter=exports.filter=function(read,test){test=tester(test);return function next(end,cb){read(end,function(end,data){if(!end&&!test(data))return next(end,cb);cb(end,data)})}};var filterNot=exports.filterNot=function(read,test){test=tester(test);return filter(read,function(e){return!test(e)})};var through=exports.through=function(read,op,onEnd){var a=false;function once(abort){if(a||!onEnd)return;a=true;onEnd(abort===true?null:abort)}return function(end,cb){if(end)once(end);return read(end,function(end,data){if(!end)op&&op(data);else once(end);cb(end,data)})}};var take=exports.take=function(read,test){var ended=false;if("number"===typeof test){var n=test;test=function(){return n--}}return function(end,cb){if(ended)return cb(ended);if(ended=end)return read(ended,cb);read(null,function(end,data){if(ended=ended||end)return cb(ended);if(!test(data)){ended=true;read(true,function(end,data){cb(ended,data)})}else cb(null,data)})}};var unique=exports.unique=function(read,field,invert){field=prop(field)||id;var seen={};return filter(read,function(data){var key=field(data);if(seen[key])return!!invert;else seen[key]=true;return!invert})};var nonUnique=exports.nonUnique=function(read,field){return unique(read,field,true)};var group=exports.group=function(read,size){var ended;size=size||5;var queue=[];return function(end,cb){if(end)return read(ended=end,cb);if(ended)return cb(ended);read(null,function next(end,data){if(ended=ended||end){if(!queue.length)return cb(ended);var _queue=queue;queue=[];return cb(null,_queue)}queue.push(data);if(queue.length<size)return read(null,next);var _queue=queue;queue=[];cb(null,_queue)})}};var flatten=exports.flatten=function(read){var _read;return function(abort,cb){if(_read)nextChunk();else nextStream();function nextChunk(){_read(null,function(end,data){if(end)nextStream();else cb(null,data)})}function nextStream(){read(null,function(end,stream){if(end)return cb(end);if(Array.isArray(stream))stream=sources.values(stream);else if("function"!=typeof stream)throw new Error("expected stream of streams");_read=stream;nextChunk()})}}};var prepend=exports.prepend=function(read,head){return function(abort,cb){if(head!==null){if(abort)return read(abort,cb);var _head=head;head=null;cb(null,_head)}else{read(abort,cb)}}};var _reduce=exports._reduce=function(read,reduce,initial){return function(close,cb){if(close)return read(close,cb);if(ended)return cb(ended);sinks.drain(function(item){initial=reduce(initial,item)},function(err,data){ended=err||true;if(!err)cb(null,initial);else cb(ended)})(read)}};var nextTick=process.nextTick;var highWaterMark=exports.highWaterMark=function(read,highWaterMark){var buffer=[],waiting=[],ended,reading=false;highWaterMark=highWaterMark||10;function readAhead(){while(waiting.length&&(buffer.length||ended))waiting.shift()(ended,ended?null:buffer.shift())}function next(){if(ended||reading||buffer.length>=highWaterMark)return;reading=true;return read(ended,function(end,data){reading=false;ended=ended||end;if(data!=null)buffer.push(data);next();readAhead()})}nextTick(next);return function(end,cb){ended=ended||end;waiting.push(cb);next();readAhead()}}}).call(this,require("_process"))},{"./sinks":25,"./sources":26,_process:1,"pull-core":24}],28:[function(require,module,exports){var sources=require("./sources");var sinks=require("./sinks");var throughs=require("./throughs");var u=require("pull-core");function isFunction(fun){return"function"===typeof fun}function isReader(fun){return fun&&(fun.type==="Through"||fun.length===1)}var exports=module.exports=function pull(){var args=[].slice.call(arguments);if(isReader(args[0]))return function(read){args.unshift(read);return pull.apply(null,args)};var read=args.shift();if(isFunction(read.source))read=read.source;function next(){var s=args.shift();if(null==s)return next();if(isFunction(s))return s;return function(read){s.sink(read);return s.source}}while(args.length)read=next()(read);return read};for(var k in sources)exports[k]=u.Source(sources[k]);for(var k in throughs)exports[k]=u.Through(throughs[k]);for(var k in sinks)exports[k]=u.Sink(sinks[k]);var maybe=require("./maybe")(exports);for(var k in maybe)exports[k]=maybe[k];exports.Duplex=exports.Through=exports.pipeable=u.Through;exports.Source=exports.pipeableSource=u.Source;exports.Sink=exports.pipeableSink=u.Sink},{"./maybe":29,"./sinks":31,"./sources":32,"./throughs":33,"pull-core":30}],29:[function(require,module,exports){var u=require("pull-core");var prop=u.prop;var id=u.id;var maybeSink=u.maybeSink;module.exports=function(pull){var exports={};var drain=pull.drain;var find=exports.find=function(test,cb){return maybeSink(function(cb){var ended=false;if(!cb)cb=test,test=id;else test=prop(test)||id;return drain(function(data){if(test(data)){ended=true;cb(null,data);return false}},function(err){if(ended)return;cb(err===true?null:err,null)})},cb)};var reduce=exports.reduce=function(reduce,acc,cb){return maybeSink(function(cb){return drain(function(data){acc=reduce(acc,data)},function(err){cb(err,acc)})},cb)};var collect=exports.collect=exports.writeArray=function(cb){return reduce(function(arr,item){arr.push(item);return arr},[],cb)};var concat=exports.concat=function(cb){return reduce(function(a,b){return a+b},"",cb)};return exports}},{"pull-core":30}],30:[function(require,module,exports){arguments[4][24][0].apply(exports,arguments)},{dup:24}],31:[function(require,module,exports){var drain=exports.drain=function(read,op,done){(function next(){var loop=true,cbed=false;while(loop){cbed=false;read(null,function(end,data){cbed=true;if(end){loop=false;if(done)done(end===true?null:end);else if(end&&end!==true)throw end}else if(op&&false===op(data)){loop=false;read(true,done||function(){})}else if(!loop){next()}});if(!cbed){loop=false;return}}})()};var onEnd=exports.onEnd=function(read,done){return drain(read,null,done)};var log=exports.log=function(read,done){return drain(read,function(data){console.log(data)},done)}},{}],32:[function(require,module,exports){var keys=exports.keys=function(object){return values(Object.keys(object))};var once=exports.once=function(value){return function(abort,cb){if(abort)return cb(abort);if(value!=null){var _value=value;value=null;cb(null,_value)}else cb(true)}};var values=exports.values=exports.readArray=function(array){if(!Array.isArray(array))array=Object.keys(array).map(function(k){return array[k]});var i=0;return function(end,cb){if(end)return cb&&cb(end);cb(i>=array.length||null,array[i++])}};var count=exports.count=function(max){var i=0;max=max||Infinity;return function(end,cb){if(end)return cb&&cb(end);if(i>max)return cb(true);cb(null,i++)}};var infinite=exports.infinite=function(generate){generate=generate||Math.random;return function(end,cb){if(end)return cb&&cb(end);return cb(null,generate())}};var defer=exports.defer=function(){var _read,cbs=[],_end;var read=function(end,cb){if(!_read){_end=end;cbs.push(cb)}else _read(end,cb)};read.resolve=function(read){if(_read)throw new Error("already resolved");_read=read;if(!_read)throw new Error("no read cannot resolve!"+_read);while(cbs.length)_read(_end,cbs.shift())};read.abort=function(err){read.resolve(function(_,cb){cb(err||true)})};return read};var empty=exports.empty=function(){return function(abort,cb){cb(true)}};var error=exports.error=function(err){return function(abort,cb){cb(err)}};var depthFirst=exports.depthFirst=function(start,createStream){var reads=[];reads.unshift(once(start));return function next(end,cb){if(!reads.length)return cb(true);reads[0](end,function(end,data){if(end){reads.shift();return next(null,cb)}reads.unshift(createStream(data));cb(end,data)})}};var widthFirst=exports.widthFirst=function(start,createStream){var reads=[];reads.push(once(start));return function next(end,cb){if(!reads.length)return cb(true);reads[0](end,function(end,data){if(end){reads.shift();return next(null,cb)}reads.push(createStream(data));cb(end,data)})}};var leafFirst=exports.leafFirst=function(start,createStream){var reads=[];var output=[];reads.push(once(start));return function next(end,cb){reads[0](end,function(end,data){if(end){reads.shift();if(!output.length)return cb(true);return cb(null,output.shift())}reads.unshift(createStream(data));output.unshift(data);next(null,cb)})}}},{}],33:[function(require,module,exports){(function(process){var u=require("pull-core");var sources=require("./sources");var sinks=require("./sinks");var prop=u.prop;var id=u.id;var tester=u.tester;var map=exports.map=function(read,map){map=prop(map)||id;return function(abort,cb){read(abort,function(end,data){try{data=!end?map(data):null}catch(err){return read(err,function(){return cb(err)})}cb(end,data)})}};var asyncMap=exports.asyncMap=function(read,map){if(!map)return read;return function(end,cb){if(end)return read(end,cb);read(null,function(end,data){if(end)return cb(end,data);map(data,cb)})}};var paraMap=exports.paraMap=function(read,map,width){if(!map)return read;var ended=false,queue=[],_cb;function drain(){if(!_cb)return;var cb=_cb;_cb=null;if(queue.length)return cb(null,queue.shift());else if(ended&&!n)return cb(ended);_cb=cb}function pull(){read(null,function(end,data){if(end){ended=end;return drain()}n++;map(data,function(err,data){n--;queue.push(data);drain()});if(n<width&&!ended)pull()})}var n=0;return function(end,cb){if(end)return read(end,cb);_cb=cb;if(queue.length||ended)pull(),drain();else pull()};return highWaterMark(asyncMap(read,map),width)};var filter=exports.filter=function(read,test){test=tester(test);return function next(end,cb){var sync,loop=true;while(loop){loop=false;sync=true;read(end,function(end,data){if(!end&&!test(data))return sync?loop=true:next(end,cb);cb(end,data)});sync=false}}};var filterNot=exports.filterNot=function(read,test){test=tester(test);return filter(read,function(e){return!test(e)})};var through=exports.through=function(read,op,onEnd){var a=false;function once(abort){if(a||!onEnd)return;a=true;onEnd(abort===true?null:abort)}return function(end,cb){if(end)once(end);return read(end,function(end,data){if(!end)op&&op(data);else once(end);cb(end,data)})}};var take=exports.take=function(read,test){var ended=false;if("number"===typeof test){var n=test;test=function(){return n--}}return function(end,cb){if(ended)return cb(ended);if(ended=end)return read(ended,cb);read(null,function(end,data){if(ended=ended||end)return cb(ended);if(!test(data)){ended=true;read(true,function(end,data){cb(ended,data)})}else cb(null,data)})}};var unique=exports.unique=function(read,field,invert){field=prop(field)||id;var seen={};return filter(read,function(data){var key=field(data);if(seen[key])return!!invert;else seen[key]=true;return!invert})};var nonUnique=exports.nonUnique=function(read,field){return unique(read,field,true)};var group=exports.group=function(read,size){var ended;size=size||5;var queue=[];return function(end,cb){if(end)return read(ended=end,cb);if(ended)return cb(ended);read(null,function next(end,data){if(ended=ended||end){if(!queue.length)return cb(ended);var _queue=queue;queue=[];return cb(null,_queue)}queue.push(data);if(queue.length<size)return read(null,next);var _queue=queue;queue=[];cb(null,_queue)})}};var flatten=exports.flatten=function(read){var _read;return function(abort,cb){if(_read)nextChunk();else nextStream();function nextChunk(){_read(null,function(end,data){if(end)nextStream();else cb(null,data)})}function nextStream(){read(null,function(end,stream){if(end)return cb(end);if(Array.isArray(stream)||stream&&"object"===typeof stream)stream=sources.values(stream);else if("function"!=typeof stream)throw new Error("expected stream of streams");_read=stream;nextChunk()})}}};var prepend=exports.prepend=function(read,head){return function(abort,cb){if(head!==null){if(abort)return read(abort,cb);var _head=head;head=null;cb(null,_head)}else{read(abort,cb)}}};var _reduce=exports._reduce=function(read,reduce,initial){return function(close,cb){if(close)return read(close,cb);if(ended)return cb(ended);sinks.drain(function(item){initial=reduce(initial,item)},function(err,data){ended=err||true;if(!err)cb(null,initial);else cb(ended)})(read)}};var nextTick=process.nextTick;var highWaterMark=exports.highWaterMark=function(read,highWaterMark){var buffer=[],waiting=[],ended,ending,reading=false;highWaterMark=highWaterMark||10;function readAhead(){while(waiting.length&&(buffer.length||ended))waiting.shift()(ended,ended?null:buffer.shift());if(!buffer.length&&ending)ended=ending}function next(){if(ended||ending||reading||buffer.length>=highWaterMark)return;reading=true;return read(ended||ending,function(end,data){reading=false;ending=ending||end;if(data!=null)buffer.push(data);next();readAhead()})}process.nextTick(next);return function(end,cb){ended=ended||end;waiting.push(cb);next();readAhead()}};var flatMap=exports.flatMap=function(read,mapper){mapper=mapper||id;var queue=[],ended;return function(abort,cb){if(queue.length)return cb(null,queue.shift());else if(ended)return cb(ended);read(abort,function next(end,data){if(end)ended=end;else{var add=mapper(data);while(add&&add.length)queue.push(add.shift())}if(queue.length)cb(null,queue.shift());else if(ended)cb(ended);else read(null,next)})}}}).call(this,require("_process"))},{"./sinks":31,"./sources":32,_process:1,"pull-core":30}],34:[function(require,module,exports){"use strict";var jsonparse=require("cog/jsonparse");module.exports=function(signaller,opts){var handlers=require("./handlers")(signaller,opts);function sendEvent(parts,srcState,data){var evtName="message:"+parts[0].slice(1);var args=parts.slice(2).map(jsonparse);signaller.apply(signaller,[evtName].concat(args).concat([srcState,data]))}return function(originalData){var data=originalData;var isMatch=true;var parts;var handler;var srcData;var srcState;var isDirectMessage=false;if(data&&data.slice(0,6)==="primus"){return}var id=signaller.id+"";if(data.slice(0,3)==="/to"){isMatch=data.slice(4,id.length+4)===id;if(isMatch){parts=data.slice(5+id.length).split("|").map(jsonparse);isDirectMessage=true;parts=parts.map(jsonparse)}}if(!isMatch){return}signaller("rawdata",data);parts=parts||data.split("|").map(jsonparse);if(typeof parts[0]=="string"){srcData=parts[1];if(srcData&&srcData.id===signaller.id){return console.warn("got data from ourself, discarding")}srcState=signaller.peers.get(srcData&&srcData.id)||srcData;if(parts[0].charAt(0)==="/"){handler=handlers[parts[0].slice(1)];if(typeof handler=="function"){handler(parts.slice(2),parts[0].slice(1),srcData,srcState,isDirectMessage)}else{sendEvent(parts,srcState,originalData)}}else{signaller("data",parts.slice(0,1).concat(parts.slice(2)),srcData,srcState,isDirectMessage)}}}}},{"./handlers":18,"cog/jsonparse":6}],35:[function(require,module,exports){var extend=require("cog/extend");module.exports=function(switchboard,opts){return require("messenger-ws")(switchboard,extend({endpoints:["/primus","/"]},opts))}},{"cog/extend":4,"messenger-ws":36}],36:[function(require,module,exports){var WebSocket=require("ws");var wsurl=require("wsurl");var ps=require("pull-ws");var defaults=require("cog/defaults");var reTrailingSlash=/\/$/;module.exports=function(url,opts){var timeout=(opts||{}).timeout||1e3;var endpoints=((opts||{}).endpoints||["/"]).map(function(endpoint){return url.replace(reTrailingSlash,"")+endpoint});function connect(callback){var queue=[].concat(endpoints);var receivedData=false;var failTimer;var successTimer;function attemptNext(){var socket;function registerMessage(evt){receivedData=true;(socket.removeEventListener||socket.removeListener)("message",registerMessage)}if(queue.length===0){return callback(new Error("Unable to connect to url: "+url))}socket=new WebSocket(wsurl(queue.shift()));socket.addEventListener("error",handleError);socket.addEventListener("close",handleAbnormalClose);socket.addEventListener("open",function(){var source=ps.source(socket,opts);socket.addEventListener("message",registerMessage);successTimer=setTimeout(function(){clearTimeout(failTimer);callback(null,source,ps.sink(socket,opts))},100)});failTimer=setTimeout(attemptNext,timeout)}function handleAbnormalClose(evt){if(evt.wasClean&&receivedData&&queue.length===0){return}return handleError()}function handleError(){clearTimeout(successTimer);clearTimeout(failTimer);attemptNext()}attemptNext()}return connect}},{"cog/defaults":3,"pull-ws":37,ws:42,wsurl:43}],37:[function(require,module,exports){exports=module.exports=duplex;exports.source=require("./source");exports.sink=require("./sink");function duplex(ws,opts){return{source:exports.source(ws),sink:exports.sink(ws,opts)}}},{"./sink":40,"./source":41}],38:[function(require,module,exports){exports.id=function(item){return item};exports.prop=function(map){if("string"==typeof map){var key=map;return function(data){return data[key]}}return map};exports.tester=function(test){if(!test)return exports.id;if("object"===typeof test&&"function"===typeof test.test)return test.test.bind(test);return exports.prop(test)||exports.id};exports.addPipe=addPipe;function addPipe(read){if("function"!==typeof read)return read;read.pipe=read.pipe||function(reader){if("function"!=typeof reader&&"function"!=typeof reader.sink)throw new Error("must pipe to reader");var pipe=addPipe(reader.sink?reader.sink(read):reader(read));return reader.source||pipe};read.type="Source";return read}var Source=exports.Source=function Source(createRead){function s(){var args=[].slice.call(arguments);return addPipe(createRead.apply(null,args))}s.type="Source";return s};var Through=exports.Through=function(createRead){return function(){var args=[].slice.call(arguments);var piped=[];function reader(read){args.unshift(read);read=createRead.apply(null,args);while(piped.length)read=piped.shift()(read);return read}reader.pipe=function(read){piped.push(read);if(read.type==="Source")throw new Error("cannot pipe "+reader.type+" to Source");reader.type=read.type==="Sink"?"Sink":"Through";return reader};reader.type="Through";return reader}};var Sink=exports.Sink=function Sink(createReader){return function(){var args=[].slice.call(arguments);if(!createReader)throw new Error("must be createReader function");function s(read){args.unshift(read);return createReader.apply(null,args)}s.type="Sink";return s}};exports.maybeSink=exports.maybeDrain=function(createSink,cb){if(!cb)return Through(function(read){var ended;return function(close,cb){if(close)return read(close,cb);if(ended)return cb(ended);createSink(function(err,data){ended=err||true;if(!err)cb(null,data);else cb(ended)})(read)}})();return Sink(function(read){return createSink(cb)(read)})()}},{}],39:[function(require,module,exports){module.exports=function(socket,callback){var remove=socket&&(socket.removeEventListener||socket.removeListener);function cleanup(){if(typeof remove=="function"){remove.call(socket,"open",handleOpen);remove.call(socket,"error",handleErr)}}function handleOpen(evt){cleanup();callback()}function handleErr(evt){cleanup();callback(evt)}if(socket.readyState>=2){return callback(true)}if(socket.readyState===1){return callback()}socket.addEventListener("open",handleOpen);socket.addEventListener("error",handleErr)}},{}],40:[function(require,module,exports){(function(process){var pull=require("pull-core");var ready=require("./ready");module.exports=pull.Sink(function(read,socket,opts){opts=opts||{};var closeOnEnd=opts.closeOnEnd!==false;var onClose="function"===typeof opts?opts:opts.onClose;function next(end,data){if(end){if(closeOnEnd&&socket.readyState<=1){if(onClose)socket.addEventListener("close",function(ev){if(ev.wasClean)onClose();else{var err=new Error("ws error");err.event=ev;onClose(err)}});socket.close()}return}ready(socket,function(end){if(end){return read(end,function(){})}socket.send(data);process.nextTick(function(){read(null,next)})})}read(null,next)})}).call(this,require("_process"))},{"./ready":39,_process:1,"pull-core":38}],41:[function(require,module,exports){var pull=require("pull-core");var ready=require("./ready");module.exports=pull.Source(function(socket){var buffer=[];var receiver;var ended;socket.addEventListener("message",function(evt){if(receiver){return receiver(null,evt.data)}buffer.push(evt.data)});socket.addEventListener("close",function(evt){if(ended)return;if(receiver){return receiver(ended=true)}});socket.addEventListener("error",function(evt){if(ended)return;ended=evt;if(receiver){receiver(ended)}});function read(abort,cb){receiver=null;if(ended)return cb(ended);if(abort){receiver=cb;return socket.close()}ready(socket,function(end){if(end){return cb(ended=end)}if(ended&&ended!==true){return cb(ended)}else if(buffer.length>0){return cb(null,buffer.shift())}else if(ended){return cb(true)}receiver=cb})}return read})},{"./ready":39,"pull-core":38}],42:[function(require,module,exports){var global=function(){return this}();var WebSocket=global.WebSocket||global.MozWebSocket;module.exports=WebSocket?ws:null;function ws(uri,protocols,opts){var instance;if(protocols){instance=new WebSocket(uri,protocols)}else{instance=new WebSocket(uri)}return instance}if(WebSocket)ws.prototype=WebSocket.prototype},{}],43:[function(require,module,exports){var reHttpUrl=/^http(.*)$/;module.exports=function(url,opts){var current=(opts||{}).current||typeof location!="undefined"&&location.href;var currentProtocol=current&&current.slice(0,current.indexOf(":"));
var insecure=(opts||{}).insecure;var isRelative=url.slice(0,2)=="//";var forceWS=!currentProtocol||currentProtocol==="file:";if(isRelative){return forceWS?(insecure?"ws:":"wss:")+url:currentProtocol.replace(reHttpUrl,"ws$1")+":"+url}return url.replace(reHttpUrl,"ws$1")}},{}],44:[function(require,module,exports){"use strict";var debug=require("cog/logger")("rtc/cleanup");var CANNOT_CLOSE_STATES=["closed"];var EVENTS_DECOUPLE_BC=["addstream","datachannel","icecandidate","negotiationneeded","removestream","signalingstatechange"];var EVENTS_DECOUPLE_AC=["iceconnectionstatechange"];module.exports=function(pc){var currentState=pc.iceConnectionState;var canClose=CANNOT_CLOSE_STATES.indexOf(currentState)<0;function decouple(events){events.forEach(function(evtName){if(pc["on"+evtName]){pc["on"+evtName]=null}})}decouple(EVENTS_DECOUPLE_BC);if(canClose){debug("attempting connection close, current state: "+pc.iceConnectionState);pc.close()}setTimeout(function(){decouple(EVENTS_DECOUPLE_AC)},100)}},{"cog/logger":7}],45:[function(require,module,exports){"use strict";var mbus=require("mbus");var queue=require("rtc-taskqueue");var cleanup=require("./cleanup");var monitor=require("./monitor");var throttle=require("cog/throttle");var CLOSED_STATES=["closed","failed"];var CHECKING_STATES=["checking"];function couple(pc,targetId,signaller,opts){var debugLabel=(opts||{}).debugLabel||"rtc";var debug=require("cog/logger")(debugLabel+"/couple");var mon=monitor(pc,targetId,signaller,(opts||{}).logger);var emit=mbus("",mon);var reactive=(opts||{}).reactive;var endOfCandidates=true;var disconnectTimeout=(opts||{}).disconnectTimeout||1e4;var disconnectTimer;var isMaster=signaller.isMaster(targetId);var q=queue(pc,opts);var createOrRequestOffer=throttle(function(){if(!isMaster){return signaller.to(targetId).send("/negotiate")}q.createOffer()},100,{leading:false});var debounceOffer=throttle(q.createOffer,100,{leading:false});function decouple(){debug("decoupling "+signaller.id+" from "+targetId);mon.stop();cleanup(pc);signaller.removeListener("sdp",handleSdp);signaller.removeListener("candidate",handleCandidate);signaller.removeListener("negotiate",handleNegotiateRequest);signaller.removeListener("message:sdp",handleSdp);signaller.removeListener("message:candidate",handleCandidate);signaller.removeListener("message:negotiate",handleNegotiateRequest)}function handleCandidate(data){q.addIceCandidate(data)}function handleSdp(sdp,src){emit("sdp.remote",sdp);if(!src||src.id!==targetId){return}q.setRemoteDescription(sdp)}function handleConnectionClose(){debug("captured pc close, iceConnectionState = "+pc.iceConnectionState);decouple()}function handleDisconnect(){debug("captured pc disconnect, monitoring connection status");disconnectTimer=setTimeout(function(){debug("manually closing connection after disconnect timeout");cleanup(pc)},disconnectTimeout);mon.on("statechange",handleDisconnectAbort)}function handleDisconnectAbort(){debug("connection state changed to: "+pc.iceConnectionState);if(CHECKING_STATES.indexOf(pc.iceConnectionState)>=0){return}resetDisconnectTimer();if(CLOSED_STATES.indexOf(pc.iceConnectionState)>=0){return mon("closed")}mon.once("disconnect",handleDisconnect)}function handleLocalCandidate(evt){var data;if(evt.candidate){resetDisconnectTimer();data={candidate:evt.candidate.candidate,sdpMid:evt.candidate.sdpMid,sdpMLineIndex:evt.candidate.sdpMLineIndex};emit("ice.local",data);signaller.to(targetId).send("/candidate",data);endOfCandidates=false}else if(!endOfCandidates){endOfCandidates=true;emit("ice.gathercomplete");signaller.to(targetId).send("/endofcandidates",{})}}function handleNegotiateRequest(src){if(src.id===targetId){emit("negotiate.request",src.id);debounceOffer()}}function resetDisconnectTimer(){mon.off("statechange",handleDisconnectAbort);debug("reset disconnect timer, state: "+pc.iceConnectionState);clearTimeout(disconnectTimer)}if(reactive){pc.onnegotiationneeded=function(){emit("negotiate.renegotiate");createOrRequestOffer()}}pc.onicecandidate=handleLocalCandidate;q.on("sdp.local",function(desc){signaller.to(targetId).send("/sdp",desc)});signaller.on("sdp",handleSdp);signaller.on("candidate",handleCandidate);signaller.on("message:sdp",handleSdp);signaller.on("message:candidate",handleCandidate);if(isMaster){signaller.on("negotiate",handleNegotiateRequest);signaller.on("message:negotiate",handleNegotiateRequest)}mon.once("closed",handleConnectionClose);mon.once("disconnected",handleDisconnect);mon.createOffer=createOrRequestOffer;return mon}module.exports=couple},{"./cleanup":44,"./monitor":49,"cog/logger":7,"cog/throttle":8,mbus:9,"rtc-taskqueue":50}],46:[function(require,module,exports){"use strict";module.exports=require("rtc-core/detect")},{"rtc-core/detect":12}],47:[function(require,module,exports){"use strict";var debug=require("cog/logger")("generators");var detect=require("./detect");var defaults=require("cog/defaults");var mappings={create:{dtls:function(c){if(!detect.moz){c.optional=(c.optional||[]).concat({DtlsSrtpKeyAgreement:true})}}}};exports.config=function(config){var iceServerGenerator=(config||{}).iceServerGenerator;return defaults({},config,{iceServers:typeof iceServerGenerator=="function"?iceServerGenerator():[]})};exports.connectionConstraints=function(flags,constraints){var generated={};var m=mappings.create;var out;Object.keys(flags||{}).forEach(function(key){if(m[key]){m[key](generated)}});out=defaults({},constraints,generated);debug("generated connection constraints: ",out);return out}},{"./detect":46,"cog/defaults":3,"cog/logger":7}],48:[function(require,module,exports){"use strict";var gen=require("./generators");var detect=exports.detect=require("./detect");var findPlugin=require("rtc-core/plugin");exports.logger=require("cog/logger");var RTCPeerConnection=exports.RTCPeerConnection=detect("RTCPeerConnection");exports.couple=require("./couple");exports.createConnection=function(opts,constraints){var plugin=findPlugin((opts||{}).plugins);var PeerConnection=(opts||{}).RTCPeerConnection||RTCPeerConnection;var config=gen.config(opts);constraints=gen.connectionConstraints(opts,constraints);if(plugin&&typeof plugin.createConnection=="function"){return plugin.createConnection(config,constraints)}return new PeerConnection(config,constraints)}},{"./couple":45,"./detect":46,"./generators":47,"cog/logger":7,"rtc-core/plugin":15}],49:[function(require,module,exports){"use strict";var mbus=require("mbus");var stateMappings={completed:"connected"};var peerStateEvents=["signalingstatechange","iceconnectionstatechange"];module.exports=function(pc,targetId,signaller,parentBus){var monitor=mbus("",parentBus);var state;function checkState(){var newState=getMappedState(pc.iceConnectionState);monitor("statechange",pc,newState);if(state!==newState){monitor(newState);state=newState}}function handleClose(){monitor("closed")}pc.onclose=handleClose;peerStateEvents.forEach(function(evtName){pc["on"+evtName]=checkState});monitor.stop=function(){pc.onclose=null;peerStateEvents.forEach(function(evtName){pc["on"+evtName]=null})};monitor.checkState=checkState;if(!pc){return monitor}state=getMappedState(pc.iceConnectionState);return monitor};function getMappedState(state){return stateMappings[state]||state}},{mbus:9}],50:[function(require,module,exports){var detect=require("rtc-core/detect");var findPlugin=require("rtc-core/plugin");var PriorityQueue=require("priorityqueuejs");var checkCandidate=require("rtc-validator/candidate");var sdpclean=require("rtc-sdpclean");var PRIORITY_LOW=100;var PRIORITY_WAIT=1e3;var DEFAULT_PRIORITIES=["candidate","setLocalDescription","setRemoteDescription","createAnswer","createOffer"];var METHOD_EVENTS={setLocalDescription:"setlocaldesc",setRemoteDescription:"setremotedesc",createOffer:"offer",createAnswer:"answer"};var VALID_RESPONSE_STATES=["have-remote-offer","have-local-pranswer"];module.exports=function(pc,opts){var queue=new PriorityQueue(orderTasks);var tq=require("mbus")("",(opts||{}).logger);var priorities=(opts||{}).priorities||DEFAULT_PRIORITIES;var plugin=findPlugin((opts||{}).plugins);var checkQueueTimer=0;var currentTask;var defaultFail=tq.bind(tq,"fail");var sdpFilter=(opts||{}).sdpfilter||(opts||{}).sdpFilter;var RTCSessionDescription=(opts||{}).RTCSessionDescription||detect("RTCSessionDescription");var RTCIceCandidate=(opts||{}).RTCIceCandidate||detect("RTCIceCandidate");function abortQueue(err){console.error(err)}function applyCandidate(task,next){var data=task.args[0];var candidate=data&&data.candidate&&createIceCandidate(data);function handleOk(){tq("ice.remote.applied",candidate);next()}function handleFail(err){tq("ice.remote.invalid",candidate);next(err)}if(!candidate){return next()}pc.addIceCandidate(candidate,handleOk,handleFail)}function checkQueue(){var next=!queue.isEmpty()&&!currentTask&&queue.peek();var ready=next&&testReady(next);var retry=!queue.isEmpty()&&isNotClosed(pc);checkQueueTimer=0;if(!ready){return retry&&triggerQueueCheck()}currentTask=queue.deq();currentTask.fn(currentTask,function(err){var fail=currentTask.fail||defaultFail;var pass=currentTask.pass;var taskName=currentTask.name;if(err){console.error(taskName+" task failed: ",err);return fail(err)}if(typeof pass=="function"){pass.apply(currentTask,[].slice.call(arguments,1))}setTimeout(function(){currentTask=null;triggerQueueCheck()},0)})}function cleansdp(desc){var sdpErrors=[];var sdp=desc&&sdpclean(desc.sdp,{collector:sdpErrors});if(desc&&sdp!==desc.sdp){console.info("invalid lines removed from sdp: ",sdpErrors);desc.sdp=sdp}if(typeof sdpFilter=="function"){desc.sdp=sdpFilter(desc.sdp,pc)}return desc}function completeConnection(){if(VALID_RESPONSE_STATES.indexOf(pc.signalingState)>=0){return tq.createAnswer()}}function createIceCandidate(data){if(plugin&&typeof plugin.createIceCandidate=="function"){return plugin.createIceCandidate(data)}return new RTCIceCandidate(data)}function createSessionDescription(data){if(plugin&&typeof plugin.createSessionDescription=="function"){return plugin.createSessionDescription(data)}return new RTCSessionDescription(data)}function emitSdp(){tq("sdp.local",this.args[0])}function enqueue(name,handler,opts){return function(){var args=[].slice.call(arguments);if(opts&&typeof opts.processArgs=="function"){args=args.map(opts.processArgs)}queue.enq({args:args,name:name,fn:handler,checks:[isNotClosed].concat((opts||{}).checks||[]),pass:(opts||{}).pass,fail:(opts||{}).fail});triggerQueueCheck()}}function execMethod(task,next){var fn=pc[task.name];var eventName=METHOD_EVENTS[task.name]||(task.name||"").toLowerCase();var cbArgs=[success,fail];var isOffer=task.name==="createOffer";function fail(err){tq.apply(tq,["negotiate.error",task.name,err].concat(task.args));next(err)}function success(){tq.apply(tq,[["negotiate",eventName,"ok"],task.name].concat(task.args));next.apply(null,[null].concat([].slice.call(arguments)))}if(typeof fn!="function"){return next(new Error('cannot call "'+task.name+'" on RTCPeerConnection'))}tq.apply(tq,["negotiate."+eventName].concat(task.args));fn.apply(pc,task.args.concat(cbArgs).concat(isOffer?generateConstraints():[]))}function extractCandidateEventData(data){while(data&&data.candidate&&data.candidate.candidate){data=data.candidate}return data}function generateConstraints(){var allowedKeys={offertoreceivevideo:"OfferToReceiveVideo",offertoreceiveaudio:"OfferToReceiveAudio",icerestart:"IceRestart",voiceactivitydetection:"VoiceActivityDetection"};var constraints={OfferToReceiveVideo:true,OfferToReceiveAudio:true};Object.keys(opts||{}).forEach(function(key){if(allowedKeys[key.toLowerCase()]){constraints[allowedKeys[key.toLowerCase()]]=opts[key]}});return{mandatory:constraints}}function hasLocalOrRemoteDesc(pc,task){return pc.__hasDesc||(pc.__hasDesc=!!pc.remoteDescription)}function isNotNegotiating(pc){return pc.signalingState!=="have-local-offer"}function isNotClosed(pc){return pc.signalingState!=="closed"}function isStable(pc){return pc.signalingState==="stable"}function isValidCandidate(pc,data){return data.__valid||(data.__valid=checkCandidate(data.args[0]).length===0)}function orderTasks(a,b){var tasks=[a,b];var readiness=tasks.map(testReady);var taskPriorities=tasks.map(function(task,idx){var ready=readiness[idx];var priority=ready&&priorities.indexOf(task.name);return ready?priority>=0?priority:PRIORITY_LOW:PRIORITY_WAIT});return taskPriorities[1]-taskPriorities[0]}function testReady(task){return(task.checks||[]).reduce(function(memo,check){return memo&&check(pc,task)},true)}function triggerQueueCheck(){if(checkQueueTimer)return;checkQueueTimer=setTimeout(checkQueue,50)}tq.addIceCandidate=enqueue("addIceCandidate",applyCandidate,{processArgs:extractCandidateEventData,checks:[hasLocalOrRemoteDesc,isValidCandidate]});tq.setLocalDescription=enqueue("setLocalDescription",execMethod,{processArgs:cleansdp,pass:emitSdp});tq.setRemoteDescription=enqueue("setRemoteDescription",execMethod,{processArgs:createSessionDescription,pass:completeConnection});tq.createOffer=enqueue("createOffer",execMethod,{checks:[isNotNegotiating],pass:tq.setLocalDescription});tq.createAnswer=enqueue("createAnswer",execMethod,{pass:tq.setLocalDescription});return tq}},{mbus:9,priorityqueuejs:51,"rtc-core/detect":12,"rtc-core/plugin":15,"rtc-sdpclean":52,"rtc-validator/candidate":53}],51:[function(require,module,exports){module.exports=PriorityQueue;function PriorityQueue(comparator){this._comparator=comparator||PriorityQueue.DEFAULT_COMPARATOR;this._elements=[]}PriorityQueue.DEFAULT_COMPARATOR=function(a,b){if(a instanceof Number&&b instanceof Number){return a-b}else{a=a.toString();b=b.toString();if(a==b)return 0;return a>b?1:-1}};PriorityQueue.prototype.isEmpty=function(){return this.size()===0};PriorityQueue.prototype.peek=function(){if(this.isEmpty())throw new Error("PriorityQueue is empty");return this._elements[0]};PriorityQueue.prototype.deq=function(){var first=this.peek();var last=this._elements.pop();var size=this.size();if(size===0)return first;this._elements[0]=last;var current=0;while(current<size){var largest=current;var left=2*current+1;var right=2*current+2;if(left<size&&this._compare(left,largest)>0){largest=left}if(right<size&&this._compare(right,largest)>0){largest=right}if(largest===current)break;this._swap(largest,current);current=largest}return first};PriorityQueue.prototype.enq=function(element){var size=this._elements.push(element);var current=size-1;while(current>0){var parent=Math.floor((current-1)/2);if(this._compare(current,parent)<0)break;this._swap(parent,current);current=parent}return size};PriorityQueue.prototype.size=function(){return this._elements.length};PriorityQueue.prototype.forEach=function(fn){return this._elements.forEach(fn)};PriorityQueue.prototype._compare=function(a,b){return this._comparator(this._elements[a],this._elements[b])};PriorityQueue.prototype._swap=function(a,b){var aux=this._elements[a];this._elements[a]=this._elements[b];this._elements[b]=aux}},{}],52:[function(require,module,exports){var validators=[[/^(a\=candidate.*)$/,require("rtc-validator/candidate")]];var reSdpLineBreak=/(\r?\n|\\r\\n)/;module.exports=function(input,opts){var lineBreak=detectLineBreak(input);var lines=input.split(lineBreak);var collector=(opts||{}).collector;lines=lines.filter(function(line){var validator=validators.reduce(function(memo,data,idx){return typeof memo!="undefined"?memo:data[0].exec(line)&&{line:line.replace(data[0],"$1"),fn:data[1]}},undefined);var errors=validator?validator.fn(validator.line):[];if(collector){errors.forEach(function(err){collector.push(err)})}return errors.length===0});return lines.join(lineBreak)};function detectLineBreak(input){var match=reSdpLineBreak.exec(input);return match&&match[0]}},{"rtc-validator/candidate":53}],53:[function(require,module,exports){var debug=require("cog/logger")("rtc-validator");var rePrefix=/^(?:a=)?candidate:/;var reIP=/^(\d+\.){3}\d+$/;var partValidation=[[/.+/,"invalid foundation component","foundation"],[/\d+/,"invalid component id","component-id"],[/(UDP|TCP)/i,"transport must be TCP or UDP","transport"],[/\d+/,"numeric priority expected","priority"],[reIP,"invalid connection address","connection-address"],[/\d+/,"invalid connection port","connection-port"],[/typ/,'Expected "typ" identifier',"type classifier"],[/.+/,"Invalid candidate type specified","candidate-type"]];module.exports=function(data){var errors=[];var candidate=data&&(data.candidate||data);var prefixMatch=candidate&&rePrefix.exec(candidate);var parts=prefixMatch&&candidate.slice(prefixMatch[0].length).split(/\s/);if(!candidate){return[new Error("empty candidate")]}if(!prefixMatch){return[new Error("candidate did not match expected sdp line format")]}errors=errors.concat(parts.map(validateParts)).filter(Boolean);return errors};function validateParts(part,idx){var validator=partValidation[idx];if(validator&&!validator[0].test(part)){debug(validator[2]+" part failed validation: "+part);return new Error(validator[1])}}},{"cog/logger":7}],"rtc-quickconnect":[function(require,module,exports){(function(process){"use strict";var rtc=require("rtc-tools");var mbus=require("mbus");var cleanup=require("rtc-tools/cleanup");var detectPlugin=require("rtc-core/plugin");var debug=rtc.logger("rtc-quickconnect");var defaults=require("cog/defaults");var extend=require("cog/extend");var getable=require("cog/getable");var messenger=require("./messenger");var reTrailingSlash=/\/$/;module.exports=function(signalhost,opts){var hash=typeof location!="undefined"&&location.hash.slice(1);var signaller=require("rtc-signaller")(messenger(signalhost),opts);var ns=(opts||{}).ns||"";var room=(opts||{}).room;var debugging=(opts||{}).debug;var allowJoin=!(opts||{}).manualJoin;var heartbeat=(opts||{}).heartbeat||2500;var profile={};var announced=false;var iceServers;var localStreams=[];var calls=signaller.calls=getable({});var channels={};var plugins=signaller.plugins=(opts||{}).plugins||[];var plugin=detectPlugin(signaller.plugins);var pluginReady;var expectedLocalStreams=parseInt((opts||{}).expectedLocalStreams,10)||0;var announceTimer=0;var heartbeatTimer=0;var updateTimer=0;function callCreate(id,pc){calls.set(id,{active:false,pc:pc,channels:getable({}),streams:[],lastping:Date.now()})}function callEnd(id){var call=calls.get(id);if(!call){return}debug("ending call to: "+id);call.channels.keys().forEach(function(label){var channel=call.channels.get(label);var args=[id,channel,label];signaller.apply(signaller,["channel:closed"].concat(args));signaller.apply(signaller,["channel:closed:"+label].concat(args));channel.onopen=null});call.streams.forEach(function(stream){signaller("stream:removed",id,stream)});calls.delete(id);if(calls.keys().length===0){hbReset()}signaller("call:ended",id,call.pc);cleanup(call.pc)}function callStart(id,pc,data){var call=calls.get(id);var streams=[].concat(pc.getRemoteStreams());call.active=true;call.streams=[].concat(pc.getRemoteStreams());pc.onaddstream=createStreamAddHandler(id);pc.onremovestream=createStreamRemoveHandler(id);debug(signaller.id+" - "+id+" call start: "+streams.length+" streams");signaller("call:started",id,pc,data);hbInit();process.nextTick(function(){streams.forEach(receiveRemoteStream(id))})}function checkReadyToAnnounce(){clearTimeout(announceTimer);if(announced){return}if(!allowJoin){return}if(plugin&&!pluginReady){return}if(!iceServers){return}if(expectedLocalStreams&&localStreams.length<expectedLocalStreams){return}announceTimer=setTimeout(function(){var data=extend({room:room},profile);signaller.announce(data);announced=true},0)}function connect(id){var data=getPeerData(id);var pc;var monitor;if(data.room!==room){return}callEnd(id);pc=rtc.createConnection(extend({},opts,{iceServers:iceServers}),(opts||{}).constraints);signaller("peer:connect",data.id,pc,data);callCreate(data.id,pc);localStreams.forEach(function(stream,idx){pc.addStream(stream)});if(signaller.isMaster(data.id)){debug("is master, creating data channels: ",Object.keys(channels));Object.keys(channels).forEach(function(label){gotPeerChannel(pc.createDataChannel(label,channels[label]),pc,data)})}else{pc.ondatachannel=function(evt){var channel=evt&&evt.channel;if(!channel){return}if(channels[channel.label]!==undefined){gotPeerChannel(channel,pc,getPeerData(id))}}}debug("coupling "+signaller.id+" to "+data.id);monitor=rtc.couple(pc,id,signaller,extend({},opts,{logger:mbus("pc."+id,signaller)}));signaller("peer:couple",id,pc,data,monitor);monitor.once("connected",callStart.bind(null,id,pc,data));monitor.once("closed",callEnd.bind(null,id));if(signaller.isMaster(id)){monitor.createOffer()}}function createStreamAddHandler(id){return function(evt){debug("peer "+id+" added stream");updateRemoteStreams(id);receiveRemoteStream(id)(evt.stream)}}function createStreamRemoveHandler(id){return function(evt){debug("peer "+id+" removed stream");updateRemoteStreams(id);signaller("stream:removed",id,evt.stream)}}function getActiveCall(peerId){var call=calls.get(peerId);if(!call){throw new Error("No active call for peer: "+peerId)}return call}function getPeerData(id){var peer=signaller.peers.get(id);return peer&&peer.data}function gotPeerChannel(channel,pc,data){var channelMonitor;function channelReady(){var call=calls.get(data.id);var args=[data.id,channel,data,pc];debug('reporting channel "'+channel.label+'" ready, have call: '+!!call);clearInterval(channelMonitor);channel.onopen=null;if(call){call.channels.set(channel.label,channel)}debug("triggering channel:opened events for channel: "+channel.label);signaller.apply(signaller,["channel:opened"].concat(args));signaller.apply(signaller,["channel:opened:"+channel.label].concat(args))}debug("channel "+channel.label+" discovered for peer: "+data.id);if(channel.readyState==="open"){return channelReady()}debug("channel not ready, current state = "+channel.readyState);channel.onopen=channelReady;channelMonitor=setInterval(function(){debug("checking channel state, current state = "+channel.readyState);if(channel.readyState==="open"){channelReady()}},500)}function hbInit(){if(heartbeatTimer||!heartbeat){return}heartbeatTimer=setInterval(hbSend,heartbeat)}function hbSend(){var tickInactive=Date.now()-heartbeat*4;calls.keys().forEach(function(id){var call=calls.get(id);if(call.lastping<tickInactive){return callEnd(id)}signaller.to(id).send("/ping")})}function hbReset(){clearInterval(heartbeatTimer);heartbeatTimer=0}function initPlugin(){return plugin&&plugin.init(opts,function(err){if(err){return console.error("Could not initialize plugin: ",err)}pluginReady=true;checkReadyToAnnounce()})}function handleLocalAnnounce(data){if(data&&typeof data.room!="undefined"){room=data.room}}function handlePeerFilter(id,data){data.allow=data.allow&&localStreams.length>=expectedLocalStreams}function handlePeerUpdate(data){var id=data&&data.id;var activeCall=id&&calls.get(id);if(id&&!activeCall){debug("received peer update from peer "+id+", no active calls");signaller.to(id).send("/reconnect");return connect(id)}}function handlePing(sender){var call=calls.get(sender&&sender.id);if(call){call.lastping=Date.now()}}function receiveRemoteStream(id){var call=calls.get(id);return function(stream){signaller("stream:added",id,stream,getPeerData(id))}}function updateRemoteStreams(id){var call=calls.get(id);if(call&&call.pc){call.streams=[].concat(call.pc.getRemoteStreams())}}if(!room){if(!hash){hash=location.hash=""+Math.pow(2,53)*Math.random()}room=ns+"#"+hash}if(debugging){rtc.logger.enable.apply(rtc.logger,Array.isArray(debug)?debugging:["*"])}signaller.on("peer:announce",function(data){connect(data.id)});signaller.on("peer:update",handlePeerUpdate);signaller.on("message:reconnect",function(sender){connect(sender.id)});signaller.broadcast=signaller.addStream=function(stream){localStreams.push(stream);calls.values().forEach(function(data){data.pc.addStream(stream)});checkReadyToAnnounce();return signaller};signaller.endCalls=function(){calls.keys().forEach(callEnd)};signaller.close=function(){signaller.endCalls();signaller.leave()};signaller.createDataChannel=function(label,opts){calls.keys().forEach(function(peerId){var call=calls.get(peerId);var dc;if(call&&call.pc&&signaller.isMaster(peerId)){dc=call.pc.createDataChannel(label,opts);gotPeerChannel(dc,call.pc,getPeerData(peerId))}});channels[label]=opts||null;return signaller};signaller.join=function(){allowJoin=true;checkReadyToAnnounce()};signaller.get=function(name){return profile[name]};signaller.getLocalStreams=function(){return[].concat(localStreams)};signaller.reactive=function(){opts=opts||{};opts.reactive=true;return signaller};signaller.removeStream=function(stream){var localIndex=localStreams.indexOf(stream);calls.values().forEach(function(call){call.pc.removeStream(stream)});if(localIndex>=0){localStreams.splice(localIndex,1)}return signaller};signaller.requestChannel=function(targetId,label,callback){var call=getActiveCall(targetId);var channel=call&&call.channels.get(label);if(channel){callback(null,channel);return signaller}signaller.once("channel:opened:"+label,function(id,dc){callback(null,dc)});return signaller};signaller.requestStream=function(targetId,idx,callback){var call=getActiveCall(targetId);var stream;function waitForStream(peerId){if(peerId!==targetId){return}stream=call.pc.getRemoteStreams()[idx];if(stream){signaller.removeListener("stream:added",waitForStream);callback(null,stream)}}stream=call.pc.getRemoteStreams()[idx];if(stream){callback(null,stream);return signaller}signaller.on("stream:added",waitForStream);return signaller};signaller.profile=function(data){extend(profile,data);if(announced){clearTimeout(updateTimer);updateTimer=setTimeout(function(){signaller.announce(profile)},(opts||{}).updateDelay||1e3)}return signaller};signaller.waitForCall=function(targetId,callback){var call=calls.get(targetId);if(call&&call.active){callback(null,call.pc);return signaller}signaller.on("call:started",function handleNewCall(id){if(id===targetId){signaller.removeListener("call:started",handleNewCall);callback(null,calls.get(id).pc)}})};if(expectedLocalStreams){signaller.on("peer:filter",handlePeerFilter)}signaller.on("local:announce",handleLocalAnnounce);signaller.on("message:ping",handlePing);require("rtc-core/genice")(opts,function(err,servers){if(err){return console.error("could not find iceServers: ",err)}iceServers=servers;checkReadyToAnnounce()});if(plugin){initPlugin()}return signaller}}).call(this,require("_process"))},{"./messenger":2,_process:1,"cog/defaults":3,"cog/extend":4,"cog/getable":5,mbus:9,"rtc-core/genice":13,"rtc-core/plugin":15,"rtc-signaller":19,"rtc-tools":48,"rtc-tools/cleanup":44}]},{},[]);var quickconnect=require("rtc-quickconnect");var createDataStream=require("rtc-dcstream");quickconnect("http://rtc.io/switchboard",{room:"dnode-test"}).createDataChannel("primary").on("channel:opened:primary",function(id,dc){var stream=createDataStream(dc);connectionReady(stream)});function connectionReady(ds){console.log("ready")}
{
"name": "requirebin-sketch",
"version": "1.0.0",
"dependencies": {
"rtc-dcstream": "1.2.0",
"rtc-quickconnect": "4.1.0"
}
}
<style type='text/css'>html, body { margin: 0; padding: 0; border: 0; }
body, html { height: 100%; width: 100%; }</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.