made with requirebin
Created
November 8, 2014 05:45
-
-
Save miketamis/00a5d23120b8bafed6b4 to your computer and use it in GitHub Desktop.
requirebin sketch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var WebTorrent = require('webtorrent'); | |
var domify = require('domify') | |
document.body.appendChild(domify("loading...")); | |
var infohash = "3a3cca2992987699def85776f58c3c510bc2b166"; | |
var client = new WebTorrent() | |
function onTorrent(torrent) { | |
// Got torrent metadata! | |
torrent.files[0].createReadStream().on('data', function(data) { | |
document.write(data); | |
}); | |
} | |
client.add({ | |
infoHash: infohash, | |
announce: [ 'wss://tracker.webtorrent.io' ] | |
}, onTorrent) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){},{}],2:[function(require,module,exports){var util=require("util/");var pSlice=Array.prototype.slice;var hasOwn=Object.prototype.hasOwnProperty;var assert=module.exports=ok;assert.AssertionError=function AssertionError(options){this.name="AssertionError";this.actual=options.actual;this.expected=options.expected;this.operator=options.operator;if(options.message){this.message=options.message;this.generatedMessage=false}else{this.message=getMessage(this);this.generatedMessage=true}var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace){Error.captureStackTrace(this,stackStartFunction)}else{var err=new Error;if(err.stack){var out=err.stack;var fn_name=stackStartFunction.name;var idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}};util.inherits(assert.AssertionError,Error);function replacer(key,value){if(util.isUndefined(value)){return""+value}if(util.isNumber(value)&&(isNaN(value)||!isFinite(value))){return value.toString()}if(util.isFunction(value)||util.isRegExp(value)){return value.toString()}return value}function truncate(s,n){if(util.isString(s)){return s.length<n?s:s.slice(0,n)}else{return s}}function getMessage(self){return truncate(JSON.stringify(self.actual,replacer),128)+" "+self.operator+" "+truncate(JSON.stringify(self.expected,replacer),128)}function fail(actual,expected,message,operator,stackStartFunction){throw new assert.AssertionError({message:message,actual:actual,expected:expected,operator:operator,stackStartFunction:stackStartFunction})}assert.fail=fail;function ok(value,message){if(!value)fail(value,true,message,"==",assert.ok)}assert.ok=ok;assert.equal=function equal(actual,expected,message){if(actual!=expected)fail(actual,expected,message,"==",assert.equal)};assert.notEqual=function notEqual(actual,expected,message){if(actual==expected){fail(actual,expected,message,"!=",assert.notEqual)}};assert.deepEqual=function deepEqual(actual,expected,message){if(!_deepEqual(actual,expected)){fail(actual,expected,message,"deepEqual",assert.deepEqual)}};function _deepEqual(actual,expected){if(actual===expected){return true}else if(util.isBuffer(actual)&&util.isBuffer(expected)){if(actual.length!=expected.length)return false;for(var i=0;i<actual.length;i++){if(actual[i]!==expected[i])return false}return true}else if(util.isDate(actual)&&util.isDate(expected)){return actual.getTime()===expected.getTime()}else if(util.isRegExp(actual)&&util.isRegExp(expected)){return actual.source===expected.source&&actual.global===expected.global&&actual.multiline===expected.multiline&&actual.lastIndex===expected.lastIndex&&actual.ignoreCase===expected.ignoreCase}else if(!util.isObject(actual)&&!util.isObject(expected)){return actual==expected}else{return objEquiv(actual,expected)}}function isArguments(object){return Object.prototype.toString.call(object)=="[object Arguments]"}function objEquiv(a,b){if(util.isNullOrUndefined(a)||util.isNullOrUndefined(b))return false;if(a.prototype!==b.prototype)return false;if(isArguments(a)){if(!isArguments(b)){return false}a=pSlice.call(a);b=pSlice.call(b);return _deepEqual(a,b)}try{var ka=objectKeys(a),kb=objectKeys(b),key,i}catch(e){return false}if(ka.length!=kb.length)return false;ka.sort();kb.sort();for(i=ka.length-1;i>=0;i--){if(ka[i]!=kb[i])return false}for(i=ka.length-1;i>=0;i--){key=ka[i];if(!_deepEqual(a[key],b[key]))return false}return true}assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(_deepEqual(actual,expected)){fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)}};assert.strictEqual=function strictEqual(actual,expected,message){if(actual!==expected){fail(actual,expected,message,"===",assert.strictEqual)}};assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(actual===expected){fail(actual,expected,message,"!==",assert.notStrictEqual)}};function expectedException(actual,expected){if(!actual||!expected){return false}if(Object.prototype.toString.call(expected)=="[object RegExp]"){return expected.test(actual)}else if(actual instanceof expected){return true}else if(expected.call({},actual)===true){return true}return false}function _throws(shouldThrow,block,expected,message){var actual;if(util.isString(expected)){message=expected;expected=null}try{block()}catch(e){actual=e}message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:".");if(shouldThrow&&!actual){fail(actual,expected,"Missing expected exception"+message)}if(!shouldThrow&&expectedException(actual,expected)){fail(actual,expected,"Got unwanted exception"+message)}if(shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual){throw actual}}assert.throws=function(block,error,message){_throws.apply(this,[true].concat(pSlice.call(arguments)))};assert.doesNotThrow=function(block,message){_throws.apply(this,[false].concat(pSlice.call(arguments)))};assert.ifError=function(err){if(err){throw err}};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){if(hasOwn.call(obj,key))keys.push(key)}return keys}},{"util/":4}],3:[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"}},{}],4:[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":3,_process:13,inherits:10}],5:[function(require,module,exports){module.exports=require(1)},{}],6:[function(require,module,exports){var base64=require("base64-js");var ieee754=require("ieee754");exports.Buffer=Buffer;exports.SlowBuffer=Buffer;exports.INSPECT_MAX_BYTES=50;Buffer.poolSize=8192;var 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"){if(encoding==="base64")subject=base64clean(subject);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 Error("First argument needs to be a number, array or string.");var buf;if(TYPED_ARRAY_SUPPORT){buf=Buffer._augment(new Uint8Array(length))}else{buf=this;buf.length=length;buf._isBuffer=true}var i;if(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"&&!TYPED_ARRAY_SUPPORT&&!noZero){for(i=0;i<length;i++){buf[i]=0}}return buf}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.isBuffer=function(b){return!!(b!=null&&b._isBuffer)};Buffer.byteLength=function(str,encoding){var ret;str=str.toString();switch(encoding||"utf8"){case"hex":ret=str.length/2;break;case"utf8":case"utf-8":ret=utf8ToBytes(str).length;break;case"ascii":case"binary":case"raw":ret=str.length;break;case"base64":ret=base64ToBytes(str).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=str.length*2;break;default:throw new Error("Unknown encoding")}return ret};Buffer.concat=function(list,totalLength){assert(isArray(list),"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.compare=function(a,b){assert(Buffer.isBuffer(a)&&Buffer.isBuffer(b),"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};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;assert(strLen%2===0,"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);assert(!isNaN(byte),"Invalid hex string");buf[offset+i]=byte}return i}function utf8Write(buf,string,offset,length){var charsWritten=blitBuffer(utf8ToBytes(string),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,offset,length);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;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 Error("Unknown encoding")}return ret};Buffer.prototype.toString=function(encoding,start,end){var self=this;encoding=String(encoding||"utf8").toLowerCase();start=Number(start)||0;end=end===undefined?self.length:Number(end);if(end===start)return"";var ret;switch(encoding){case"hex":ret=hexSlice(self,start,end);break;case"utf8":case"utf-8":ret=utf8Slice(self,start,end);break;case"ascii":ret=asciiSlice(self,start,end);break;case"binary":ret=binarySlice(self,start,end);break;case"base64":ret=base64Slice(self,start,end);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=utf16leSlice(self,start,end);break;default:throw new Error("Unknown encoding")}return ret};Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};Buffer.prototype.equals=function(b){assert(Buffer.isBuffer(b),"Argument must be a Buffer");return Buffer.compare(this,b)===0};Buffer.prototype.compare=function(b){assert(Buffer.isBuffer(b),"Argument must be a Buffer");return Buffer.compare(this,b)};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_start=0;if(end===start)return;if(target.length===0||source.length===0)return;assert(end>=start,"sourceEnd < sourceStart");assert(target_start>=0&&target_start<target.length,"targetStart out of bounds");assert(start>=0&&start<source.length,"sourceStart out of bounds");assert(end>=0&&end<=source.length,"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<100||!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)}};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])}return ret}function binarySlice(buf,start,end){return asciiSlice(buf,start,end)}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;if(TYPED_ARRAY_SUPPORT){return Buffer._augment(this.subarray(start,end))}else{var sliceLen=end-start;var newBuf=new Buffer(sliceLen,undefined,true);for(var i=0;i<sliceLen;i++){newBuf[i]=this[i+start]}return newBuf}};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)};Buffer.prototype.readUInt8=function(offset,noAssert){if(!noAssert){assert(offset!==undefined&&offset!==null,"missing offset");assert(offset<this.length,"Trying to read beyond buffer length")}if(offset>=this.length)return;return this[offset]};function readUInt16(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+1<buf.length,"Trying to read beyond buffer length")}var len=buf.length;if(offset>=len)return;var val;if(littleEndian){val=buf[offset];if(offset+1<len)val|=buf[offset+1]<<8}else{val=buf[offset]<<8;if(offset+1<len)val|=buf[offset+1]}return val}Buffer.prototype.readUInt16LE=function(offset,noAssert){return readUInt16(this,offset,true,noAssert)};Buffer.prototype.readUInt16BE=function(offset,noAssert){return readUInt16(this,offset,false,noAssert)};function readUInt32(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3<buf.length,"Trying to read beyond buffer length")}var len=buf.length;if(offset>=len)return;var val;if(littleEndian){if(offset+2<len)val=buf[offset+2]<<16;if(offset+1<len)val|=buf[offset+1]<<8;val|=buf[offset];if(offset+3<len)val=val+(buf[offset+3]<<24>>>0)}else{if(offset+1<len)val=buf[offset+1]<<16;if(offset+2<len)val|=buf[offset+2]<<8;if(offset+3<len)val|=buf[offset+3];val=val+(buf[offset]<<24>>>0)}return val}Buffer.prototype.readUInt32LE=function(offset,noAssert){return readUInt32(this,offset,true,noAssert)};Buffer.prototype.readUInt32BE=function(offset,noAssert){return readUInt32(this,offset,false,noAssert)};Buffer.prototype.readInt8=function(offset,noAssert){if(!noAssert){assert(offset!==undefined&&offset!==null,"missing offset");assert(offset<this.length,"Trying to read beyond buffer length")}if(offset>=this.length)return;var neg=this[offset]&128;if(neg)return(255-this[offset]+1)*-1;else return this[offset]};function readInt16(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+1<buf.length,"Trying to read beyond buffer length")}var len=buf.length;if(offset>=len)return;var val=readUInt16(buf,offset,littleEndian,true);var neg=val&32768;if(neg)return(65535-val+1)*-1;else return val}Buffer.prototype.readInt16LE=function(offset,noAssert){return readInt16(this,offset,true,noAssert)};Buffer.prototype.readInt16BE=function(offset,noAssert){return readInt16(this,offset,false,noAssert)};function readInt32(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3<buf.length,"Trying to read beyond buffer length")}var len=buf.length;if(offset>=len)return;var val=readUInt32(buf,offset,littleEndian,true);var neg=val&2147483648;if(neg)return(4294967295-val+1)*-1;else return val}Buffer.prototype.readInt32LE=function(offset,noAssert){return readInt32(this,offset,true,noAssert)};Buffer.prototype.readInt32BE=function(offset,noAssert){return readInt32(this,offset,false,noAssert)};function readFloat(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset+3<buf.length,"Trying to read beyond buffer length")}return ieee754.read(buf,offset,littleEndian,23,4)}Buffer.prototype.readFloatLE=function(offset,noAssert){return readFloat(this,offset,true,noAssert)};Buffer.prototype.readFloatBE=function(offset,noAssert){return readFloat(this,offset,false,noAssert)};function readDouble(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset+7<buf.length,"Trying to read beyond buffer length")}return ieee754.read(buf,offset,littleEndian,52,8)}Buffer.prototype.readDoubleLE=function(offset,noAssert){return readDouble(this,offset,true,noAssert)};Buffer.prototype.readDoubleBE=function(offset,noAssert){return readDouble(this,offset,false,noAssert)};Buffer.prototype.writeUInt8=function(value,offset,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset<this.length,"trying to write beyond buffer length");verifuint(value,255)}if(offset>=this.length)return;this[offset]=value;return offset+1};function writeUInt16(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+1<buf.length,"trying to write beyond buffer length");verifuint(value,65535)}var len=buf.length;if(offset>=len)return;for(var i=0,j=Math.min(len-offset,2);i<j;i++){buf[offset+i]=(value&255<<8*(littleEndian?i:1-i))>>>(littleEndian?i:1-i)*8}return offset+2}Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){return writeUInt16(this,value,offset,true,noAssert)};Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){return writeUInt16(this,value,offset,false,noAssert)};function writeUInt32(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3<buf.length,"trying to write beyond buffer length");verifuint(value,4294967295)}var len=buf.length;if(offset>=len)return;for(var i=0,j=Math.min(len-offset,4);i<j;i++){buf[offset+i]=value>>>(littleEndian?i:3-i)*8&255}return offset+4}Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){return writeUInt32(this,value,offset,true,noAssert)};Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){return writeUInt32(this,value,offset,false,noAssert)};Buffer.prototype.writeInt8=function(value,offset,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset<this.length,"Trying to write beyond buffer length");verifsint(value,127,-128)}if(offset>=this.length)return;if(value>=0)this.writeUInt8(value,offset,noAssert);else this.writeUInt8(255+value+1,offset,noAssert);return offset+1};function writeInt16(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+1<buf.length,"Trying to write beyond buffer length");verifsint(value,32767,-32768)}var len=buf.length;if(offset>=len)return;if(value>=0)writeUInt16(buf,value,offset,littleEndian,noAssert);else writeUInt16(buf,65535+value+1,offset,littleEndian,noAssert);return offset+2}Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return writeInt16(this,value,offset,true,noAssert)};Buffer.prototype.writeInt16BE=function(value,offset,noAssert){return writeInt16(this,value,offset,false,noAssert)};function writeInt32(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3<buf.length,"Trying to write beyond buffer length");verifsint(value,2147483647,-2147483648)}var len=buf.length;if(offset>=len)return;if(value>=0)writeUInt32(buf,value,offset,littleEndian,noAssert);else writeUInt32(buf,4294967295+value+1,offset,littleEndian,noAssert);return offset+4}Buffer.prototype.writeInt32LE=function(value,offset,noAssert){return writeInt32(this,value,offset,true,noAssert)};Buffer.prototype.writeInt32BE=function(value,offset,noAssert){return writeInt32(this,value,offset,false,noAssert)};function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3<buf.length,"Trying to write beyond buffer length");verifIEEE754(value,3.4028234663852886e38,-3.4028234663852886e38)}var len=buf.length;if(offset>=len)return;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){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+7<buf.length,"Trying to write beyond buffer length");verifIEEE754(value,1.7976931348623157e308,-1.7976931348623157e308)}var len=buf.length;if(offset>=len)return;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.fill=function(value,start,end){if(!value)value=0;if(!start)start=0;if(!end)end=this.length;assert(end>=start,"end < start");if(end===start)return;if(this.length===0)return;assert(start>=0&&start<this.length,"start out of bounds");assert(end>=0&&end<=this.length,"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.inspect=function(){var out=[];var len=this.length;for(var i=0;i<len;i++){out[i]=toHex(this[i]);if(i===exports.INSPECT_MAX_BYTES){out[i+1]="...";break}}return"<Buffer "+out.join(" ")+">"};Buffer.prototype.toArrayBuffer=function(){if(typeof Uint8Array!=="undefined"){if(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 Error("Buffer.toArrayBuffer not supported in this browser")}};var BP=Buffer.prototype;Buffer._augment=function(arr){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.readUInt8=BP.readUInt8;arr.readUInt16LE=BP.readUInt16LE;arr.readUInt16BE=BP.readUInt16BE;arr.readUInt32LE=BP.readUInt32LE;arr.readUInt32BE=BP.readUInt32BE;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.writeUInt16LE=BP.writeUInt16LE;arr.writeUInt16BE=BP.writeUInt16BE;arr.writeUInt32LE=BP.writeUInt32LE;arr.writeUInt32BE=BP.writeUInt32BE;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,"");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 isArray(subject){return(Array.isArray||function(subject){return Object.prototype.toString.call(subject)==="[object Array]"})(subject)}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(str){var byteArray=[];for(var i=0;i<str.length;i++){var b=str.charCodeAt(i);if(b<=127){byteArray.push(b)}else{var start=i;if(b>=55296&&b<=57343)i++;var h=encodeURIComponent(str.slice(start,i+1)).substr(1).split("%");for(var j=0;j<h.length;j++){byteArray.push(parseInt(h[j],16))}}}return byteArray}function asciiToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){byteArray.push(str.charCodeAt(i)&255)}return byteArray}function utf16leToBytes(str){var c,hi,lo;var byteArray=[];for(var i=0;i<str.length;i++){c=str.charCodeAt(i);hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(str)}function blitBuffer(src,dst,offset,length){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)}}function verifuint(value,max){assert(typeof value==="number","cannot write a non-number as a number");assert(value>=0,"specified a negative value for writing an unsigned value");assert(value<=max,"value is larger than maximum value for type");assert(Math.floor(value)===value,"value has a fractional component")}function verifsint(value,max,min){assert(typeof value==="number","cannot write a non-number as a number");assert(value<=max,"value larger than maximum allowed value");assert(value>=min,"value smaller than minimum allowed value");assert(Math.floor(value)===value,"value has a fractional component")}function verifIEEE754(value,max,min){assert(typeof value==="number","cannot write a non-number as a number");assert(value<=max,"value larger than maximum allowed value");assert(value>=min,"value smaller than minimum allowed value")}function assert(test,message){if(!test)throw new Error(message||"Failed assertion")}},{"base64-js":7,ieee754:8}],7:[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);function decode(elt){var code=elt.charCodeAt(0);if(code===PLUS)return 62;if(code===SLASH)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)},{}],8:[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}},{}],9:[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}else{throw TypeError('Uncaught, unspecified "error" event.')}return false}}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}},{}],10:[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}}},{}],11:[function(require,module,exports){module.exports=Array.isArray||function(arr){return Object.prototype.toString.call(arr)=="[object Array]"}},{}],12:[function(require,module,exports){(function(process){function normalizeArray(parts,allowAboveRoot){var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up--;up){parts.unshift("..")}}return parts}var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var splitPath=function(filename){return splitPathRe.exec(filename).slice(1)};exports.resolve=function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:process.cwd();if(typeof path!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){continue}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=path.charAt(0)==="/"}resolvedPath=normalizeArray(filter(resolvedPath.split("/"),function(p){return!!p}),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."};exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash=substr(path,-1)==="/";path=normalizeArray(filter(path.split("/"),function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path};exports.isAbsolute=function(path){return path.charAt(0)==="/"};exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p,index){if(typeof p!=="string"){throw new TypeError("Arguments to path.join must be strings")}return p}).join("/"))};exports.relative=function(from,to){from=exports.resolve(from).substr(1);to=exports.resolve(to).substr(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")};exports.sep="/";exports.delimiter=":";exports.dirname=function(path){var result=splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir};exports.basename=function(path,ext){var f=splitPath(path)[2];if(ext&&f.substr(-1*ext.length)===ext){f=f.substr(0,f.length-ext.length)}return f};exports.extname=function(path){return splitPath(path)[3]};function filter(xs,f){if(xs.filter)return xs.filter(f);var res=[];for(var i=0;i<xs.length;i++){if(f(xs[i],i,xs))res.push(xs[i])}return res}var substr="ab".substr(-1)==="b"?function(str,start,len){return str.substr(start,len)}:function(str,start,len){if(start<0)start=str.length+start;return str.substr(start,len)}}).call(this,require("_process"))},{_process:13}],13:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}if(canPost){var queue=[];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")}},{}],14:[function(require,module,exports){(function(global){(function(root){var freeExports=typeof exports=="object"&&exports;var freeModule=typeof module=="object"&&module&&module.exports==freeExports&&module;var freeGlobal=typeof global=="object"&&global;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal){root=freeGlobal}var punycode,maxInt=2147483647,base=36,tMin=1,tMax=26,skew=38,damp=700,initialBias=72,initialN=128,delimiter="-",regexPunycode=/^xn--/,regexNonASCII=/[^ -~]/,regexSeparators=/\x2E|\u3002|\uFF0E|\uFF61/g,errors={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},baseMinusTMin=base-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode,key;function error(type){throw RangeError(errors[type])}function map(array,fn){var length=array.length;while(length--){array[length]=fn(array[length])}return array}function mapDomain(string,fn){return map(string.split(regexSeparators),fn).join(".")}function ucs2decode(string){var output=[],counter=0,length=string.length,value,extra;while(counter<length){value=string.charCodeAt(counter++);if(value>=55296&&value<=56319&&counter<length){extra=string.charCodeAt(counter++);if((extra&64512)==56320){output.push(((value&1023)<<10)+(extra&1023)+65536)}else{output.push(value);counter--}}else{output.push(value)}}return output}function ucs2encode(array){return map(array,function(value){var output="";if(value>65535){value-=65536;output+=stringFromCharCode(value>>>10&1023|55296);value=56320|value&1023}output+=stringFromCharCode(value);return output}).join("")}function basicToDigit(codePoint){if(codePoint-48<10){return codePoint-22}if(codePoint-65<26){return codePoint-65}if(codePoint-97<26){return codePoint-97}return base}function digitToBasic(digit,flag){return digit+22+75*(digit<26)-((flag!=0)<<5)}function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin)}return floor(k+(baseMinusTMin+1)*delta/(delta+skew))}function decode(input){var output=[],inputLength=input.length,out,i=0,n=initialN,bias=initialBias,basic,j,index,oldi,w,k,digit,t,baseMinusT;basic=input.lastIndexOf(delimiter);if(basic<0){basic=0}for(j=0;j<basic;++j){if(input.charCodeAt(j)>=128){error("not-basic")}output.push(input.charCodeAt(j))}for(index=basic>0?basic+1:0;index<inputLength;){for(oldi=i,w=1,k=base;;k+=base){if(index>=inputLength){error("invalid-input")}digit=basicToDigit(input.charCodeAt(index++));if(digit>=base||digit>floor((maxInt-i)/w)){error("overflow")}i+=digit*w;t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(digit<t){break}baseMinusT=base-t;if(w>floor(maxInt/baseMinusT)){error("overflow")}w*=baseMinusT}out=output.length+1;bias=adapt(i-oldi,out,oldi==0);if(floor(i/out)>maxInt-n){error("overflow")}n+=floor(i/out);i%=out;output.splice(i++,0,n)}return ucs2encode(output)}function encode(input){var n,delta,handledCPCount,basicLength,bias,j,m,q,k,t,currentValue,output=[],inputLength,handledCPCountPlusOne,baseMinusT,qMinusT;input=ucs2decode(input);inputLength=input.length;n=initialN;delta=0;bias=initialBias;for(j=0;j<inputLength;++j){currentValue=input[j];if(currentValue<128){output.push(stringFromCharCode(currentValue))}}handledCPCount=basicLength=output.length;if(basicLength){output.push(delimiter)}while(handledCPCount<inputLength){for(m=maxInt,j=0;j<inputLength;++j){currentValue=input[j];if(currentValue>=n&¤tValue<m){m=currentValue}}handledCPCountPlusOne=handledCPCount+1;if(m-n>floor((maxInt-delta)/handledCPCountPlusOne)){error("overflow")}delta+=(m-n)*handledCPCountPlusOne;n=m;for(j=0;j<inputLength;++j){currentValue=input[j];if(currentValue<n&&++delta>maxInt){error("overflow")}if(currentValue==n){for(q=delta,k=base;;k+=base){t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(q<t){break}qMinusT=q-t;baseMinusT=base-t;output.push(stringFromCharCode(digitToBasic(t+qMinusT%baseMinusT,0)));q=floor(qMinusT/baseMinusT)}output.push(stringFromCharCode(digitToBasic(q,0)));bias=adapt(delta,handledCPCountPlusOne,handledCPCount==basicLength);delta=0;++handledCPCount}}++delta;++n}return output.join("")}function toUnicode(domain){return mapDomain(domain,function(string){return regexPunycode.test(string)?decode(string.slice(4).toLowerCase()):string})}function toASCII(domain){return mapDomain(domain,function(string){return regexNonASCII.test(string)?"xn--"+encode(string):string})}punycode={version:"1.2.4",ucs2:{decode:ucs2decode,encode:ucs2encode},decode:decode,encode:encode,toASCII:toASCII,toUnicode:toUnicode};if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define("punycode",function(){return punycode})}else if(freeExports&&!freeExports.nodeType){if(freeModule){freeModule.exports=punycode}else{for(key in punycode){punycode.hasOwnProperty(key)&&(freeExports[key]=punycode[key])}}}else{root.punycode=punycode}})(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],15:[function(require,module,exports){"use strict";function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}module.exports=function(qs,sep,eq,options){sep=sep||"&";eq=eq||"=";var obj={};if(typeof qs!=="string"||qs.length===0){return obj}var regexp=/\+/g;qs=qs.split(sep);var maxKeys=1e3;if(options&&typeof options.maxKeys==="number"){maxKeys=options.maxKeys}var len=qs.length;if(maxKeys>0&&len>maxKeys){len=maxKeys}for(var i=0;i<len;++i){var x=qs[i].replace(regexp,"%20"),idx=x.indexOf(eq),kstr,vstr,k,v;if(idx>=0){kstr=x.substr(0,idx);vstr=x.substr(idx+1)}else{kstr=x;vstr=""}k=decodeURIComponent(kstr);v=decodeURIComponent(vstr);if(!hasOwnProperty(obj,k)){obj[k]=v}else if(isArray(obj[k])){obj[k].push(v)}else{obj[k]=[obj[k],v]}}return obj};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==="[object Array]"}},{}],16:[function(require,module,exports){"use strict";var stringifyPrimitive=function(v){switch(typeof v){case"string":return v;case"boolean":return v?"true":"false";case"number":return isFinite(v)?v:"";default:return""}};module.exports=function(obj,sep,eq,name){sep=sep||"&";eq=eq||"=";if(obj===null){obj=undefined}if(typeof obj==="object"){return map(objectKeys(obj),function(k){var ks=encodeURIComponent(stringifyPrimitive(k))+eq;if(isArray(obj[k])){return map(obj[k],function(v){return ks+encodeURIComponent(stringifyPrimitive(v))}).join(sep)}else{return ks+encodeURIComponent(stringifyPrimitive(obj[k]))}}).join(sep)}if(!name)return"";return encodeURIComponent(stringifyPrimitive(name))+eq+encodeURIComponent(stringifyPrimitive(obj))};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==="[object Array]"};function map(xs,f){if(xs.map)return xs.map(f);var res=[];for(var i=0;i<xs.length;i++){res.push(f(xs[i],i))}return res}var objectKeys=Object.keys||function(obj){var res=[];for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))res.push(key)}return res}},{}],17:[function(require,module,exports){"use strict";exports.decode=exports.parse=require("./decode");exports.encode=exports.stringify=require("./encode")},{"./decode":15,"./encode":16}],18:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":19}],19:[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":21,"./_stream_writable":23,_process:13,"core-util-is":24,inherits:10}],20:[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":22,"core-util-is":24,inherits:10}],21:[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:13,buffer:6,"core-util-is":24,events:9,inherits:10,isarray:11,stream:30,"string_decoder/":25}],22:[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":19,"core-util-is":24,inherits:10}],23:[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":19,_process:13,buffer:6,"core-util-is":24,inherits:10,stream:30}],24:[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:6}],25:[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="";var offset=0;while(this.charLength){var i=buffer.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,offset,i);this.charReceived+=i-offset;offset=i;if(this.charReceived<this.charLength){return""}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(i==buffer.length)return charStr;buffer=buffer.slice(i,buffer.length);break}var lenIncomplete=this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-lenIncomplete,end);this.charReceived=lenIncomplete;end-=lenIncomplete}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);this.charBuffer.write(charStr.charAt(charStr.length-1),this.encoding);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}}return 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){var incomplete=this.charReceived=buffer.length%2;this.charLength=incomplete?2:0;return incomplete}function base64DetectIncompleteChar(buffer){var incomplete=this.charReceived=buffer.length%3;this.charLength=incomplete?3:0;return incomplete}},{buffer:6}],26:[function(require,module,exports){module.exports=require("./lib/_stream_passthrough.js")},{"./lib/_stream_passthrough.js":20}],27:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js");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":19,"./lib/_stream_passthrough.js":20,"./lib/_stream_readable.js":21,"./lib/_stream_transform.js":22,"./lib/_stream_writable.js":23}],28:[function(require,module,exports){module.exports=require("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":22}],29:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":23}],30:[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:9,inherits:10,"readable-stream/duplex.js":18,"readable-stream/passthrough.js":26,"readable-stream/readable.js":27,"readable-stream/transform.js":28,"readable-stream/writable.js":29}],31:[function(require,module,exports){var punycode=require("punycode");exports.parse=urlParse;exports.resolve=urlResolve;exports.resolveObject=urlResolveObject;exports.format=urlFormat;exports.Url=Url;function Url(){this.protocol=null;this.slashes=null;this.auth=null;this.host=null;this.port=null;this.hostname=null;this.hash=null;this.search=null;this.query=null;this.pathname=null;this.path=null;this.href=null}var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,delims=["<",">",'"',"`"," ","\r","\n"," "],unwise=["{","}","|","\\","^","`"].concat(delims),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnameMaxLen=255,hostnamePartPattern=/^[a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:true,"javascript:":true},hostlessProtocol={javascript:true,"javascript:":true},slashedProtocol={http:true,https:true,ftp:true,gopher:true,file:true,"http:":true,"https:":true,"ftp:":true,"gopher:":true,"file:":true},querystring=require("querystring");function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&isObject(url)&&url instanceof Url)return url;var u=new Url;u.parse(url,parseQueryString,slashesDenoteHost);return u}Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!isString(url)){throw new TypeError("Parameter 'url' must be a string, not "+typeof url)}var rest=url;rest=rest.trim();var proto=protocolPattern.exec(rest);if(proto){proto=proto[0];var lowerProto=proto.toLowerCase();this.protocol=lowerProto;rest=rest.substr(proto.length)}if(slashesDenoteHost||proto||rest.match(/^\/\/[^@\/]+@[^@\/]+/)){var slashes=rest.substr(0,2)==="//";if(slashes&&!(proto&&hostlessProtocol[proto])){rest=rest.substr(2);this.slashes=true}}if(!hostlessProtocol[proto]&&(slashes||proto&&!slashedProtocol[proto])){var hostEnd=-1;for(var i=0;i<hostEndingChars.length;i++){var hec=rest.indexOf(hostEndingChars[i]);if(hec!==-1&&(hostEnd===-1||hec<hostEnd))hostEnd=hec}var auth,atSign;if(hostEnd===-1){atSign=rest.lastIndexOf("@")}else{atSign=rest.lastIndexOf("@",hostEnd)}if(atSign!==-1){auth=rest.slice(0,atSign);rest=rest.slice(atSign+1);this.auth=decodeURIComponent(auth)}hostEnd=-1;for(var i=0;i<nonHostChars.length;i++){var hec=rest.indexOf(nonHostChars[i]);if(hec!==-1&&(hostEnd===-1||hec<hostEnd))hostEnd=hec}if(hostEnd===-1)hostEnd=rest.length;this.host=rest.slice(0,hostEnd);rest=rest.slice(hostEnd);this.parseHost();this.hostname=this.hostname||"";var ipv6Hostname=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!ipv6Hostname){var hostparts=this.hostname.split(/\./);for(var i=0,l=hostparts.length;i<l;i++){var part=hostparts[i];if(!part)continue;if(!part.match(hostnamePartPattern)){var newpart="";for(var j=0,k=part.length;j<k;j++){if(part.charCodeAt(j)>127){newpart+="x"}else{newpart+=part[j]}}if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i);var notHost=hostparts.slice(i+1);var bit=part.match(hostnamePartStart);if(bit){validParts.push(bit[1]);notHost.unshift(bit[2])}if(notHost.length){rest="/"+notHost.join(".")+rest}this.hostname=validParts.join(".");break}}}}if(this.hostname.length>hostnameMaxLen){this.hostname=""}else{this.hostname=this.hostname.toLowerCase()}if(!ipv6Hostname){var domainArray=this.hostname.split(".");var newOut=[];for(var i=0;i<domainArray.length;++i){var s=domainArray[i];newOut.push(s.match(/[^A-Za-z0-9_-]/)?"xn--"+punycode.encode(s):s)}this.hostname=newOut.join(".")}var p=this.port?":"+this.port:"";var h=this.hostname||"";this.host=h+p;this.href+=this.host;if(ipv6Hostname){this.hostname=this.hostname.substr(1,this.hostname.length-2);if(rest[0]!=="/"){rest="/"+rest}}}if(!unsafeProtocol[lowerProto]){for(var i=0,l=autoEscape.length;i<l;i++){var ae=autoEscape[i];var esc=encodeURIComponent(ae);if(esc===ae){esc=escape(ae)}rest=rest.split(ae).join(esc)}}var hash=rest.indexOf("#");if(hash!==-1){this.hash=rest.substr(hash);rest=rest.slice(0,hash)}var qm=rest.indexOf("?");if(qm!==-1){this.search=rest.substr(qm);this.query=rest.substr(qm+1);if(parseQueryString){this.query=querystring.parse(this.query)}rest=rest.slice(0,qm)}else if(parseQueryString){this.search="";this.query={}}if(rest)this.pathname=rest;if(slashedProtocol[lowerProto]&&this.hostname&&!this.pathname){this.pathname="/"}if(this.pathname||this.search){var p=this.pathname||"";var s=this.search||"";this.path=p+s}this.href=this.format();return this};function urlFormat(obj){if(isString(obj))obj=urlParse(obj);if(!(obj instanceof Url))return Url.prototype.format.call(obj);return obj.format()}Url.prototype.format=function(){var auth=this.auth||"";if(auth){auth=encodeURIComponent(auth);auth=auth.replace(/%3A/i,":");auth+="@"}var protocol=this.protocol||"",pathname=this.pathname||"",hash=this.hash||"",host=false,query="";if(this.host){host=auth+this.host}else if(this.hostname){host=auth+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]");if(this.port){host+=":"+this.port}}if(this.query&&isObject(this.query)&&Object.keys(this.query).length){query=querystring.stringify(this.query)}var search=this.search||query&&"?"+query||"";if(protocol&&protocol.substr(-1)!==":")protocol+=":";if(this.slashes||(!protocol||slashedProtocol[protocol])&&host!==false){host="//"+(host||"");if(pathname&&pathname.charAt(0)!=="/")pathname="/"+pathname}else if(!host){host=""}if(hash&&hash.charAt(0)!=="#")hash="#"+hash;if(search&&search.charAt(0)!=="?")search="?"+search;pathname=pathname.replace(/[?#]/g,function(match){return encodeURIComponent(match)});search=search.replace("#","%23");return protocol+host+pathname+search+hash};function urlResolve(source,relative){return urlParse(source,false,true).resolve(relative)}Url.prototype.resolve=function(relative){return this.resolveObject(urlParse(relative,false,true)).format()};function urlResolveObject(source,relative){if(!source)return relative;return urlParse(source,false,true).resolveObject(relative)}Url.prototype.resolveObject=function(relative){if(isString(relative)){var rel=new Url;rel.parse(relative,false,true);relative=rel}var result=new Url;Object.keys(this).forEach(function(k){result[k]=this[k]},this);result.hash=relative.hash;if(relative.href===""){result.href=result.format();return result}if(relative.slashes&&!relative.protocol){Object.keys(relative).forEach(function(k){if(k!=="protocol")result[k]=relative[k]});if(slashedProtocol[result.protocol]&&result.hostname&&!result.pathname){result.path=result.pathname="/"}result.href=result.format();return result}if(relative.protocol&&relative.protocol!==result.protocol){if(!slashedProtocol[relative.protocol]){Object.keys(relative).forEach(function(k){result[k]=relative[k]});result.href=result.format();return result}result.protocol=relative.protocol;if(!relative.host&&!hostlessProtocol[relative.protocol]){var relPath=(relative.pathname||"").split("/");while(relPath.length&&!(relative.host=relPath.shift()));if(!relative.host)relative.host="";if(!relative.hostname)relative.hostname="";if(relPath[0]!=="")relPath.unshift("");if(relPath.length<2)relPath.unshift("");result.pathname=relPath.join("/")}else{result.pathname=relative.pathname}result.search=relative.search;result.query=relative.query;result.host=relative.host||"";result.auth=relative.auth;result.hostname=relative.hostname||relative.host;result.port=relative.port;if(result.pathname||result.search){var p=result.pathname||"";var s=result.search||"";result.path=p+s}result.slashes=result.slashes||relative.slashes;result.href=result.format();return result}var isSourceAbs=result.pathname&&result.pathname.charAt(0)==="/",isRelAbs=relative.host||relative.pathname&&relative.pathname.charAt(0)==="/",mustEndAbs=isRelAbs||isSourceAbs||result.host&&relative.pathname,removeAllDots=mustEndAbs,srcPath=result.pathname&&result.pathname.split("/")||[],relPath=relative.pathname&&relative.pathname.split("/")||[],psychotic=result.protocol&&!slashedProtocol[result.protocol];if(psychotic){result.hostname="";result.port=null;if(result.host){if(srcPath[0]==="")srcPath[0]=result.host;else srcPath.unshift(result.host)}result.host="";if(relative.protocol){relative.hostname=null;relative.port=null;if(relative.host){if(relPath[0]==="")relPath[0]=relative.host;else relPath.unshift(relative.host)}relative.host=null}mustEndAbs=mustEndAbs&&(relPath[0]===""||srcPath[0]==="") | |
}if(isRelAbs){result.host=relative.host||relative.host===""?relative.host:result.host;result.hostname=relative.hostname||relative.hostname===""?relative.hostname:result.hostname;result.search=relative.search;result.query=relative.query;srcPath=relPath}else if(relPath.length){if(!srcPath)srcPath=[];srcPath.pop();srcPath=srcPath.concat(relPath);result.search=relative.search;result.query=relative.query}else if(!isNullOrUndefined(relative.search)){if(psychotic){result.hostname=result.host=srcPath.shift();var authInHost=result.host&&result.host.indexOf("@")>0?result.host.split("@"):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift()}}result.search=relative.search;result.query=relative.query;if(!isNull(result.pathname)||!isNull(result.search)){result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")}result.href=result.format();return result}if(!srcPath.length){result.pathname=null;if(result.search){result.path="/"+result.search}else{result.path=null}result.href=result.format();return result}var last=srcPath.slice(-1)[0];var hasTrailingSlash=(result.host||relative.host)&&(last==="."||last==="..")||last==="";var up=0;for(var i=srcPath.length;i>=0;i--){last=srcPath[i];if(last=="."){srcPath.splice(i,1)}else if(last===".."){srcPath.splice(i,1);up++}else if(up){srcPath.splice(i,1);up--}}if(!mustEndAbs&&!removeAllDots){for(;up--;up){srcPath.unshift("..")}}if(mustEndAbs&&srcPath[0]!==""&&(!srcPath[0]||srcPath[0].charAt(0)!=="/")){srcPath.unshift("")}if(hasTrailingSlash&&srcPath.join("/").substr(-1)!=="/"){srcPath.push("")}var isAbsolute=srcPath[0]===""||srcPath[0]&&srcPath[0].charAt(0)==="/";if(psychotic){result.hostname=result.host=isAbsolute?"":srcPath.length?srcPath.shift():"";var authInHost=result.host&&result.host.indexOf("@")>0?result.host.split("@"):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift()}}mustEndAbs=mustEndAbs||result.host&&srcPath.length;if(mustEndAbs&&!isAbsolute){srcPath.unshift("")}if(!srcPath.length){result.pathname=null;result.path=null}else{result.pathname=srcPath.join("/")}if(!isNull(result.pathname)||!isNull(result.search)){result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")}result.auth=relative.auth||result.auth;result.slashes=result.slashes||relative.slashes;result.href=result.format();return result};Url.prototype.parseHost=function(){var host=this.host;var port=portPattern.exec(host);if(port){port=port[0];if(port!==":"){this.port=port.substr(1)}host=host.substr(0,host.length-port.length)}if(host)this.hostname=host};function isString(arg){return typeof arg==="string"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isNull(arg){return arg===null}function isNullOrUndefined(arg){return arg==null}},{punycode:14,querystring:17}],32:[function(require,module,exports){module.exports=require(3)},{}],33:[function(require,module,exports){module.exports=require(4)},{"./support/isBuffer":32,_process:13,inherits:10}],34:[function(require,module,exports){module.exports=FileStream;var debug=require("debug")("webtorrent:file-stream");var inherits=require("inherits");var path=require("path");var stream=require("stream");var VideoStream=require("./video-stream");inherits(FileStream,stream.Readable);function FileStream(file,opts){var self=this;if(!(self instanceof FileStream))return new FileStream(file,opts);stream.Readable.call(self,opts);debug("new filestream %s",JSON.stringify(opts));if(!opts)opts={};if(!opts.start)opts.start=0;if(!opts.end)opts.end=file.length-1;self.length=opts.end-opts.start+1;var offset=opts.start+file.offset;var pieceLength=opts.pieceLength;self.startPiece=offset/pieceLength|0;self.endPiece=(opts.end+file.offset)/pieceLength|0;self._extname=path.extname(file.name);self._storage=file.storage;self._piece=self.startPiece;self._missing=self.length;self._reading=false;self._notifying=false;self._destroyed=false;self._criticalLength=Math.min(1024*1024/pieceLength|0,2);self._offset=offset-self.startPiece*pieceLength}FileStream.prototype._read=function(){debug("_read");var self=this;if(self._reading)return;self._reading=true;self.notify()};FileStream.prototype.notify=function(){debug("notify");var self=this;if(!self._reading||self._missing===0)return;if(!self._storage.bitfield.get(self._piece))return self._storage.emit("critical",self._piece,self._piece+self._criticalLength);if(self._notifying)return;self._notifying=true;var p=self._piece;debug("before read %s",p);self._storage.read(self._piece++,function(err,buffer){debug("after read %s (buffer.length %s) (err %s)",p,buffer.length,err&&err.message||err);self._notifying=false;if(self._destroyed)return;if(err){self._storage.emit("error",err);return self.destroy(err)}if(self._offset){buffer=buffer.slice(self._offset);self._offset=0}if(self._missing<buffer.length){buffer=buffer.slice(0,self._missing)}self._missing-=buffer.length;debug("pushing buffer of length %s",buffer.length);self._reading=false;self.push(buffer);if(self._missing===0)self.push(null)})};FileStream.prototype.pipe=function(dst){var self=this;var pipe=stream.Readable.prototype.pipe;if(dst&&dst.nodeName==="VIDEO"){var type=self._extname===".webm"?'video/webm; codecs="vorbis,vp8"':self._extname===".mp4"?'video/mp4; codecs="avc1.42c01e,mp4a.40.2"':undefined;return pipe.call(self,new VideoStream(dst,{type:type}))}else return pipe.call(self,dst)};FileStream.prototype.destroy=function(){var self=this;if(self._destroyed)return;self._destroyed=true}},{"./video-stream":38,debug:49,inherits:61,path:12,stream:30}],35:[function(require,module,exports){module.exports=RarityMap;function RarityMap(swarm,numPieces){var self=this;self.swarm=swarm;self.numPieces=numPieces;function initWire(wire){wire.on("have",function(index){self.pieces[index]++});wire.on("bitfield",self.recalculate.bind(self));wire.on("close",function(){for(var i=0;i<self.numPieces;++i){self.pieces[i]-=wire.peerPieces.get(i)}})}self.swarm.wires.forEach(initWire);self.swarm.on("wire",function(wire){self.recalculate();initWire(wire)});self.recalculate()}RarityMap.prototype.recalculate=function(){var self=this;self.pieces=[];for(var i=0;i<self.numPieces;++i){self.pieces[i]=0}self.swarm.wires.forEach(function(wire){for(var i=0;i<self.numPieces;++i){self.pieces[i]+=wire.peerPieces.get(i)}})};RarityMap.prototype.getRarestPiece=function(pieceFilterFunc){var self=this;var candidates=[];var min=Infinity;pieceFilterFunc=pieceFilterFunc||function(){return true};for(var i=0;i<self.numPieces;++i){if(!pieceFilterFunc(i))continue;var availability=self.pieces[i];if(availability===min){candidates.push(i)}else if(availability<min){candidates=[i];min=availability}}if(candidates.length>0){return candidates[Math.random()*candidates.length|0]}else{return-1}}},{}],36:[function(require,module,exports){(function(process,Buffer){module.exports=Storage;var BitField=require("bitfield");var BlockStream=require("block-stream");var debug=require("debug")("webtorrent:storage");var dezalgo=require("dezalgo");var eos=require("end-of-stream");var EventEmitter=require("events").EventEmitter;var extend=require("extend.js");var FileStream=require("./file-stream");var inherits=require("inherits");var MultiStream=require("multistream");var once=require("once");var sha1=require("git-sha1");var stream=require("stream");var BLOCK_LENGTH=16*1024;var BLOCK_BLANK=0;var BLOCK_RESERVED=1;var BLOCK_WRITTEN=2;function noop(){}inherits(Piece,EventEmitter);function Piece(index,hash,buffer){var self=this;EventEmitter.call(self);self.index=index;self.hash=hash;if(typeof buffer==="number"){self.buffer=null;self.length=buffer}else{self.buffer=buffer;self.length=buffer.length}self._reset()}Piece.prototype.readBlock=function(offset,length,cb){var self=this;cb=dezalgo(cb);if(!self.buffer||!self._verifyOffset(offset)){return cb(new Error("invalid block offset "+offset))}cb(null,self.buffer.slice(offset,offset+length))};Piece.prototype.writeBlock=function(offset,buffer,cb){var self=this;cb=dezalgo(cb);if(!self._verifyOffset(offset)||!self._verifyBlock(offset,buffer)){return cb(new Error("invalid block "+offset+":"+buffer.length))}self._lazyAllocBuffer();var i=offset/BLOCK_LENGTH;if(self.blocks[i]===BLOCK_WRITTEN){return cb(null)}buffer.copy(self.buffer,offset);self.blocks[i]=BLOCK_WRITTEN;self.blocksWritten+=1;if(self.blocksWritten===self.blocks.length){self.verify()}cb(null)};Piece.prototype.reserveBlock=function(endGame){var self=this;var len=self.blocks.length;for(var i=0;i<len;i++){if(self.blocks[i]&&!endGame||self.blocks[i]===BLOCK_WRITTEN){continue}self.blocks[i]=BLOCK_RESERVED;return{offset:i*BLOCK_LENGTH,length:i===len-1?self.length-i*BLOCK_LENGTH:BLOCK_LENGTH}}return null};Piece.prototype.cancelBlock=function(offset){var self=this;if(!self.buffer||!self._verifyOffset(offset)){return false}var i=offset/BLOCK_LENGTH;if(self.blocks[i]===BLOCK_RESERVED){self.blocks[i]=BLOCK_BLANK}return true};Piece.prototype._reset=function(){var self=this;self.verified=false;self.blocks=new Buffer(Math.ceil(self.length/BLOCK_LENGTH));self.blocks.fill(0);self.blocksWritten=0};Piece.prototype.verify=function(buffer){var self=this;buffer=buffer||self.buffer;if(self.verified||!buffer){return}self.verified=sha1(buffer)===self.hash;if(self.verified){self.emit("done")}else{self.emit("warning",new Error("piece "+self.index+" failed verification; "+sha1(buffer)+" expected "+self.hash));self._reset()}};Piece.prototype._verifyOffset=function(offset){var self=this;if(offset%BLOCK_LENGTH===0){return true}else{self.emit("warning",new Error("piece "+self.index+" invalid offset "+offset+" not multiple of "+BLOCK_LENGTH+" bytes"));return false}};Piece.prototype._verifyBlock=function(offset,buffer){var self=this;if(buffer.length===BLOCK_LENGTH){return true}else if(buffer.length===self.length-offset&&self.length-offset<BLOCK_LENGTH){return true}else{self.emit("warning",new Error("piece "+self.index+" invalid block of size "+buffer.length+" bytes"));return false}};Piece.prototype._lazyAllocBuffer=function(){var self=this;if(!self.buffer){self.buffer=new Buffer(self.length)}};inherits(File,EventEmitter);function File(storage,file,pieces,pieceLength){var self=this;EventEmitter.call(self);self.storage=storage;self.name=file.name;self.path=file.path;self.length=file.length;self.offset=file.offset;self.pieces=pieces;self.pieceLength=pieceLength;self.done=false;self.pieces.forEach(function(piece){piece.on("done",function(){self._checkDone()})});self._checkDone()}File.prototype.select=function(){var self=this;if(self.pieces.length>0){self.storage.emit("select",self.pieces[0].index,self.pieces[self.pieces.length-1].index,false)}};File.prototype.deselect=function(){var self=this;if(self.pieces.length>0){self.storage.emit("deselect",self.pieces[0].index,self.pieces[self.pieces.length-1].index,false)}};File.prototype.createReadStream=function(opts){var self=this;debug("createReadStream");opts=extend({pieceLength:self.pieceLength},opts);var stream=new FileStream(self,opts);self.storage.emit("select",stream.startPiece,stream.endPiece,true,stream.notify.bind(stream));eos(stream,function(){self.storage.emit("deselect",stream.startPiece,stream.endPiece,true)});return stream};File.prototype._checkDone=function(){var self=this;self.done=self.pieces.every(function(piece){return piece.verified});if(self.done){process.nextTick(function(){self.emit("done")})}};inherits(Storage,EventEmitter);function Storage(parsedTorrent,opts){var self=this;EventEmitter.call(self);opts=opts||{};self.bitfield=new BitField(parsedTorrent.pieces.length);self.done=false;self.closed=false;self.readonly=true;if(!opts.nobuffer){self.buffer=new Buffer(parsedTorrent.length)}var pieceLength=self.pieceLength=parsedTorrent.pieceLength;var lastPieceLength=parsedTorrent.lastPieceLength;var numPieces=parsedTorrent.pieces.length;self.pieces=parsedTorrent.pieces.map(function(hash,index){var start=index*pieceLength;var end=start+(index===numPieces-1?lastPieceLength:pieceLength);var buffer=self.buffer?self.buffer.slice(start,end):end-start;var piece=new Piece(index,hash,buffer);piece.on("done",self._onPieceDone.bind(self,piece));return piece});self.files=parsedTorrent.files.map(function(fileObj){var start=fileObj.offset;var end=start+fileObj.length-1;var startPiece=start/pieceLength|0;var endPiece=end/pieceLength|0;var pieces=self.pieces.slice(startPiece,endPiece+1);var file=new File(self,fileObj,pieces,pieceLength);file.on("done",self._onFileDone.bind(self,file));return file})}Storage.BLOCK_LENGTH=BLOCK_LENGTH;Storage.prototype.load=function(streams,cb){var self=this;if(!Array.isArray(streams))streams=[streams];if(!cb)cb=function(){};cb=once(cb);var pieceIndex=0;new MultiStream(streams).pipe(new BlockStream(self.pieceLength,{nopad:true})).on("data",function(piece){var index=pieceIndex;pieceIndex+=1;var blockIndex=0;var s=new BlockStream(BLOCK_LENGTH,{nopad:true});s.on("data",function(block){var offset=blockIndex*BLOCK_LENGTH;blockIndex+=1;self.writeBlock(index,offset,block)});s.end(piece)}).on("end",function(){cb(null)}).on("error",function(err){cb(err)})};Object.defineProperty(Storage.prototype,"downloaded",{get:function(){var self=this;return self.pieces.reduce(function(total,piece){return total+(piece.verified?piece.length:piece.blocksWritten*BLOCK_LENGTH)},0)}});Object.defineProperty(Storage.prototype,"numMissing",{get:function(){var self=this;var numMissing=self.pieces.length;for(var index=0,len=self.pieces.length;index<len;index++){numMissing-=self.bitfield.get(index)}return numMissing}});Storage.prototype.readBlock=function(index,offset,length,cb){var self=this;cb=dezalgo(cb);var piece=self.pieces[index];if(!piece)return cb(new Error("invalid piece index "+index));piece.readBlock(offset,length,cb)};Storage.prototype.writeBlock=function(index,offset,buffer,cb){var self=this;if(!cb)cb=noop;cb=dezalgo(cb);if(self.readonly)return cb(new Error("cannot write to readonly storage"));var piece=self.pieces[index];if(!piece)return cb(new Error("invalid piece index "+index));piece.writeBlock(offset,buffer,cb)};Storage.prototype.read=function(index,range,cb,force){var self=this;if(typeof range==="function"){force=cb;cb=range;range=null}cb=dezalgo(cb);var piece=self.pieces[index];if(!piece){return cb(new Error("invalid piece index "+index))}if(!piece.verified&&!force){return cb(new Error("Storage.read called on incomplete piece "+index))}var offset=0;var length=piece.length;if(range){offset=range.offset||0;length=range.length||length}if(piece.buffer){return cb(null,piece.buffer.slice(offset,offset+length))}var blocks=[];function readNextBlock(){if(length<=0)return cb(null,Buffer.concat(blocks));var blockOffset=offset;var blockLength=Math.min(BLOCK_LENGTH,length);offset+=blockLength;length-=blockLength;self.readBlock(index,blockOffset,blockLength,function(err,block){if(err)return cb(err);blocks.push(block);readNextBlock()})}readNextBlock()};Storage.prototype.reserveBlock=function(index,endGame){var self=this;var piece=self.pieces[index];if(!piece)return null;return piece.reserveBlock(endGame)};Storage.prototype.cancelBlock=function(index,offset){var self=this;var piece=self.pieces[index];if(!piece)return false;return piece.cancelBlock(offset)};Storage.prototype.remove=function(cb){if(cb)dezalgo(cb)(null)};Storage.prototype.close=function(cb){var self=this;self.closed=true;if(cb)dezalgo(cb)(null)};Storage.prototype._onPieceDone=function(piece){var self=this;self.bitfield.set(piece.index);debug("piece done "+piece.index+" ("+self.numMissing+" still missing)");self.emit("piece",piece)};Storage.prototype._onFileDone=function(file){var self=this;debug("file done "+file.name);self.emit("file",file);self._checkDone()};Storage.prototype._checkDone=function(){var self=this;if(!self.done&&self.files.every(function(file){return file.done})){self.done=true;self.emit("done")}}}).call(this,require("_process"),require("buffer").Buffer)},{"./file-stream":34,_process:13,bitfield:40,"block-stream":41,buffer:6,debug:49,dezalgo:52,"end-of-stream":55,events:9,"extend.js":56,"git-sha1":59,inherits:61,multistream:62,once:64,stream:30}],37:[function(require,module,exports){(function(process){module.exports=Torrent;var addrToIPPort=require("addr-to-ip-port");var concat=require("concat-stream");var debug=require("debug")("webtorrent:torrent");var Discovery=require("torrent-discovery");var EventEmitter=require("events").EventEmitter;var fs=require("fs");var hh=require("http-https");var inherits=require("inherits");var once=require("once");var parallel=require("run-parallel");var parseTorrent=require("parse-torrent");var RarityMap=require("./rarity-map");var reemit=require("re-emitter");var Server=require("./server");var Storage=require("./storage");var Swarm=require("bittorrent-swarm");var url=require("url");var ut_metadata=require("ut_metadata");var ut_pex=require("ut_pex");var MAX_BLOCK_LENGTH=128*1024;var MAX_OUTSTANDING_REQUESTS=5;var PIECE_TIMEOUT=1e4;var CHOKE_TIMEOUT=5e3;var SPEED_THRESHOLD=3*Storage.BLOCK_LENGTH;var RECHOKE_INTERVAL=1e4;var RECHOKE_OPTIMISTIC_DURATION=2;function noop(){}inherits(Torrent,EventEmitter);function Torrent(torrentId,opts){var self=this;EventEmitter.call(self);debug("new torrent");self.client=opts.client;self.hotswapEnabled="hotswap"in opts?opts.hotswap:true;self.verify=opts.verify;self.storageOpts=opts.storageOpts;self.chokeTimeout=opts.chokeTimeout||CHOKE_TIMEOUT;self.pieceTimeout=opts.pieceTimeout||PIECE_TIMEOUT;self.strategy=opts.strategy||"sequential";self._rechokeNumSlots=opts.uploads===false||opts.uploads===0?0:+opts.uploads||10;self._rechokeOptimisticWire=null;self._rechokeOptimisticTime=0;self._rechokeIntervalId=null;self.ready=false;self.files=[];self.metadata=null;self.parsedTorrent=null;self.storage=null;self.numBlockedPeers=0;self._amInterested=false;self._destroyed=false;self._selections=[];self._critical=[];self._storageImpl=opts.storage||Storage;var parsedTorrent=parseTorrent(torrentId);if(parsedTorrent&&parsedTorrent.infoHash){onTorrentId(parsedTorrent)}else if(typeof hh.get==="function"&&/^https?:/.test(torrentId)){httpGet(torrentId,function(err,torrent){if(err)return self.emit("error",new Error("error downloading torrent: "+err.message));onTorrentId(torrent)})}else if(typeof fs.readFile==="function"){fs.readFile(torrentId,function(err,torrent){if(err)return self.emit("error",new Error("invalid torrent id"));onTorrentId(torrent)})}else throw new Error("invalid torrent id");function onTorrentId(torrentId){parsedTorrent=parseTorrent(torrentId);self.infoHash=parsedTorrent.infoHash;if(parsedTorrent.name)self.name=parsedTorrent.name;self.swarm=new Swarm(self.infoHash,self.client.peerId,{handshake:{dht:!!self.client.dht}});reemit(self.swarm,self,["warning","error"]);self.swarm.on("wire",self._onWire.bind(self));self.swarm.on("download",self.client.downloadSpeed.bind(self.client));self.swarm.on("upload",self.client.uploadSpeed.bind(self.client));if(process.browser){self._onSwarmListening(parsedTorrent)}else{self.swarm.listen(self.client.torrentPort,self._onSwarmListening.bind(self,parsedTorrent))}process.nextTick(function(){self.emit("infoHash")})}}Object.defineProperty(Torrent.prototype,"length",{get:function(){return this.parsedTorrent&&this.parsedTorrent.length||0}});Object.defineProperty(Torrent.prototype,"timeRemaining",{get:function(){if(this.swarm.downloadSpeed()===0)return Infinity;else return(this.length-this.downloaded)/this.swarm.downloadSpeed()*1e3}});Object.defineProperty(Torrent.prototype,"progress",{get:function(){return this.parsedTorrent&&this.downloaded/this.parsedTorrent.length||0}});Object.defineProperty(Torrent.prototype,"downloaded",{get:function(){return this.storage&&this.storage.downloaded||0}});Object.defineProperty(Torrent.prototype,"uploaded",{get:function(){return this.swarm.uploaded}});Object.defineProperty(Torrent.prototype,"ratio",{get:function(){return this.uploaded&&this.downloaded/this.uploaded||0}});Torrent.prototype._onSwarmListening=function(parsed,port){var self=this;if(self._destroyed)return;self.client.torrentPort=port;self.discovery=new Discovery({announce:parsed.announce,dht:self.client.dht,tracker:self.client.tracker,peerId:self.client.peerId,port:port});self.discovery.setTorrent(self.infoHash);self.discovery.on("peer",self.addPeer.bind(self));reemit(self.discovery,self,["dhtAnnounce","warning","error"]);if(parsed.info)self._onMetadata(parsed);self.emit("listening",port)};Torrent.prototype._onMetadata=function(metadata){var self=this;if(self.metadata||self._destroyed)return;debug("got metadata");if(metadata&&metadata.infoHash){self.metadata=parseTorrent.toBuffer(metadata);self.parsedTorrent=metadata}else{self.metadata=metadata;try{self.parsedTorrent=parseTorrent(self.metadata)}catch(err){return self.emit("error",err)}}self.name=self.parsedTorrent.name;self.discovery.setTorrent(self.parsedTorrent);self.rarityMap=new RarityMap(self.swarm,self.parsedTorrent.pieces.length);self.storage=new self._storageImpl(self.parsedTorrent,self.storageOpts);self.storage.on("piece",self._onStoragePiece.bind(self));self.storage.on("file",function(file){self.emit("file",file)});self._reservations=self.storage.pieces.map(function(){return[]});self.storage.on("done",function(){if(self.discovery.tracker)self.discovery.tracker.complete();debug("torrent "+self.infoHash+" done");self.emit("done")});self.storage.on("select",self.select.bind(self));self.storage.on("deselect",self.deselect.bind(self));self.storage.on("critical",self.critical.bind(self));self.storage.files.forEach(function(file){self.files.push(file)});self.swarm.wires.forEach(function(wire){if(wire.ut_metadata)wire.ut_metadata.setMetadata(self.metadata);self._onWireWithMetadata(wire)});if(self.verify){process.nextTick(function(){debug("verifying existing torrent data");var numPieces=0;var numVerified=0;parallel(self.storage.pieces.map(function(piece){return function(cb){self.storage.read(piece.index,function(err,buffer){numPieces+=1;self.emit("verifying",{percentDone:100*numPieces/self.storage.pieces.length,percentVerified:100*numVerified/self.storage.pieces.length});if(!err&&buffer){piece.verify(buffer);numVerified+=piece.verified;debug("piece "+(piece.verified?"verified":"invalid")+" "+piece.index)}cb()},true)}}),self._onStorage.bind(self))})}else{process.nextTick(self._onStorage.bind(self))}process.nextTick(function(){self.emit("metadata")})};Torrent.prototype.destroy=function(cb){var self=this;debug("destroy");self._destroyed=true;clearInterval(self._rechokeIntervalId);var tasks=[];if(self.swarm)tasks.push(function(cb){self.swarm.destroy(cb)});if(self.discovery)tasks.push(function(cb){self.discovery.stop(cb)});if(self.storage)tasks.push(function(cb){self.storage.close(cb)});parallel(tasks,cb)};Torrent.prototype.addPeer=function(peer){var self=this;if(typeof peer==="string"&&self.client.blocked&&self.client.blocked.contains(addrToIPPort(peer)[0])){self.numBlockedPeers+=1;self.emit("blocked-peer",peer)}else{self.emit("peer",peer);self.swarm.addPeer(peer)}};Torrent.prototype.select=function(start,end,priority,notify){var self=this;if(start>end||start<0||end>=self.storage.pieces.length)throw new Error("invalid selection ",start,":",end);priority=Number(priority)||0;debug("select %s-%s (priority %s)",start,end,priority);self._selections.push({from:start,to:end,offset:0,priority:priority,notify:notify||noop});self._selections.sort(function(a,b){return b.priority-a.priority});self._updateSelections()};Torrent.prototype.deselect=function(start,end,priority){var self=this;priority=Number(priority)||0;debug("deselect %s-%s (priority %s)",start,end,priority);for(var i=0;i<self._selections.length;++i){var s=self._selections[i];if(s.from===start&&s.to===end&&s.priority===priority){self._selections.splice(i--,1);break}}self._updateSelections()};Torrent.prototype.critical=function(start,end){var self=this;debug("critical %s-%s",start,end);for(var i=start;i<=end;++i){self._critical[i]=true}self._updateSelections()};Torrent.prototype._onWire=function(wire){var self=this;wire.use(ut_metadata(self.metadata));if(!self.metadata){wire.ut_metadata.on("metadata",function(metadata){debug("got metadata via ut_metadata");self._onMetadata(metadata)});wire.ut_metadata.fetch()}if(typeof ut_pex==="function")wire.use(ut_pex());if(wire.ut_pex)wire.ut_pex.on("peer",function(peer){debug("got peer via ut_pex "+peer);self.addPeer(peer)});if(wire.ut_pex)wire.ut_pex.on("dropped",function(peer){if(!(peer in self.swarm._peers))self.swarm.removePeer(peer)});wire.setKeepAlive(true);if(wire.peerExtensions.dht&&self.client.dht&&self.client.dht.port){wire.port(self.client.dht.port)}wire.on("port",function(port){debug("port message from "+wire.remoteAddress)});wire.on("timeout",function(){debug("wire timeout from "+wire.remoteAddress);wire.destroy()});wire.setTimeout(self.pieceTimeout);if(self.metadata){self._onWireWithMetadata(wire)}};Torrent.prototype._onWireWithMetadata=function(wire){var self=this;var timeoutId=null;var timeoutMs=self.chokeTimeout;function onChokeTimeout(){if(self._destroyed||wire._destroyed)return;if(self.swarm.numQueued>2*(self.swarm.numConns-self.swarm.numPeers)&&wire.amInterested){wire.destroy()}else{timeoutId=setTimeout(onChokeTimeout,timeoutMs)}}var i=0;function updateSeedStatus(){if(wire.peerPieces.length!==self.storage.pieces.length)return;for(;i<self.storage.pieces.length;++i){if(!wire.peerPieces.get(i))return}wire.isSeeder=true;wire.choke()}wire.on("bitfield",function(){updateSeedStatus();self._update()});wire.on("have",function(){updateSeedStatus();self._update()});wire.once("interested",function(){wire.unchoke()});wire.on("close",function(){clearTimeout(timeoutId)});wire.on("choke",function(){clearTimeout(timeoutId);timeoutId=setTimeout(onChokeTimeout,timeoutMs)});wire.on("unchoke",function(){clearTimeout(timeoutId);self._update()});wire.on("request",function(index,offset,length,cb){if(length>MAX_BLOCK_LENGTH){debug(wire.remoteAddress,"requested invalid block size",length);return wire.destroy()}self.storage.readBlock(index,offset,length,cb)});wire.bitfield(self.storage.bitfield);wire.interested();timeoutId=setTimeout(onChokeTimeout,timeoutMs);wire.isSeeder=false;updateSeedStatus()};Torrent.prototype._onStorage=function(){var self=this;debug("on storage");self.storage.readonly=false;self.select(0,self.storage.pieces.length-1,false);self._rechokeIntervalId=setInterval(self._rechoke.bind(self),RECHOKE_INTERVAL);self._rechokeIntervalId.unref&&self._rechokeIntervalId.unref();process.nextTick(function(){self.ready=true;self.emit("ready")})};Torrent.prototype._onStoragePiece=function(piece){var self=this;debug("piece done %s",piece.index);self._reservations[piece.index]=null;self.swarm.wires.forEach(function(wire){wire.have(piece.index)});self._gcSelections()};Torrent.prototype._updateSelections=function(){var self=this;if(!self.swarm||self._destroyed)return;if(!self.metadata)return self.once("metadata",self._updateSelections.bind(self));process.nextTick(self._gcSelections.bind(self));self._updateInterest();self._update()};Torrent.prototype._gcSelections=function(){var self=this;for(var i=0;i<self._selections.length;i++){var s=self._selections[i];var oldOffset=s.offset;while(self.storage.bitfield.get(s.from+s.offset)&&s.from+s.offset<s.to){s.offset++}if(oldOffset!==s.offset)s.notify();if(s.to!==s.from+s.offset)continue;if(!self.storage.bitfield.get(s.from+s.offset))continue;self._selections.splice(i--,1);s.notify();self._updateInterest()}if(!self._selections.length)self.emit("idle")};Torrent.prototype._updateInterest=function(){var self=this;var prev=self._amInterested;self._amInterested=!!self._selections.length;self.swarm.wires.forEach(function(wire){if(self._amInterested)wire.interested();else wire.uninterested()});if(prev===self._amInterested)return;if(self._amInterested)self.emit("interested");else self.emit("uninterested")};Torrent.prototype._update=function(){var self=this;if(self._destroyed)return;randomizedForEach(self.swarm.wires,self._updateWire.bind(self))};Torrent.prototype._updateWire=function(wire){var self=this;if(wire.peerChoking)return;if(!wire.downloaded)return validateWire();trySelectWire(false)||trySelectWire(true);function genPieceFilterFunc(start,end,tried,rank){return function(i){return i>=start&&i<=end&&!(i in tried)&&wire.peerPieces.get(i)&&(!rank||rank(i))}}function validateWire(){if(wire.requests.length)return;for(var i=self._selections.length;i--;){var next=self._selections[i];var piece;if(self.strategy==="rarest"){var start=next.from+next.offset;var end=next.to;var len=end-start+1;var tried={};var tries=0;var filter=genPieceFilterFunc(start,end,tried);while(tries<len){piece=self.rarityMap.getRarestPiece(filter);if(piece<0)break;if(self._request(wire,piece,false))return;tried[piece]=true;tries+=1}}else{for(piece=next.to;piece>=next.from+next.offset;--piece){if(!wire.peerPieces.get(piece))continue;if(self._request(wire,piece,false))return}}}}function speedRanker(){var speed=wire.downloadSpeed()||1;if(speed>SPEED_THRESHOLD)return function(){return true};var secs=MAX_OUTSTANDING_REQUESTS*Storage.BLOCK_LENGTH/speed;var tries=10;var ptr=0;return function(index){if(!tries||self.storage.bitfield.get(index))return true;var piece=self.storage.pieces[index];var missing=piece.blocks.length-piece.blocksWritten;for(;ptr<self.swarm.wires.length;ptr++){var otherWire=self.swarm.wires[ptr];var otherSpeed=otherWire.downloadSpeed();if(otherSpeed<SPEED_THRESHOLD)continue;if(otherSpeed<=speed)continue;if(!otherWire.peerPieces.get(index))continue;if((missing-=otherSpeed*secs)>0)continue;tries--;return false}return true}}function shufflePriority(i){var last=i;for(var j=i;j<self._selections.length&&self._selections[j].priority;j++){last=j}var tmp=self._selections[i];self._selections[i]=self._selections[last];self._selections[last]=tmp}function trySelectWire(hotswap){if(wire.requests.length>=MAX_OUTSTANDING_REQUESTS)return true;var rank=speedRanker();for(var i=0;i<self._selections.length;i++){var next=self._selections[i];var piece;if(self.strategy==="rarest"){var start=next.from+next.offset;var end=next.to;var len=end-start+1;var tried={};var tries=0;var filter=genPieceFilterFunc(start,end,tried,rank);while(tries<len){piece=self.rarityMap.getRarestPiece(filter);if(piece<0)break;while(self._request(wire,piece,self._critical[piece]||hotswap)){}if(wire.requests.length<MAX_OUTSTANDING_REQUESTS){tried[piece]=true;tries++;continue}if(next.priority)shufflePriority(i);return true}}else{for(piece=next.from+next.offset;piece<=next.to;piece++){if(!wire.peerPieces.get(piece)||!rank(piece))continue;while(self._request(wire,piece,self._critical[piece]||hotswap)){}if(wire.requests.length<MAX_OUTSTANDING_REQUESTS)continue;if(next.priority)shufflePriority(i);return true}}}return false}};Torrent.prototype._rechoke=function(){var self=this;if(self._rechokeOptimisticTime>0)self._rechokeOptimisticTime-=1;else self._rechokeOptimisticWire=null;var peers=[];self.swarm.wires.forEach(function(wire){if(!wire.isSeeder&&wire!==self._rechokeOptimisticWire){peers.push({wire:wire,downloadSpeed:wire.downloadSpeed(),uploadSpeed:wire.uploadSpeed(),salt:Math.random(),isChoked:true})}});peers.sort(rechokeSort);var unchokeInterested=0;var i=0;for(;i<peers.length&&unchokeInterested<self._rechokeNumSlots;++i){peers[i].isChoked=false;if(peers[i].wire.peerInterested)unchokeInterested+=1}if(!self._rechokeOptimisticWire&&i<peers.length&&self._rechokeNumSlots){var candidates=peers.slice(i).filter(function(peer){return peer.wire.peerInterested});var optimistic=candidates[randomInt(candidates.length)];if(optimistic){optimistic.isChoked=false;self._rechokeOptimisticWire=optimistic.wire;self._rechokeOptimisticTime=RECHOKE_OPTIMISTIC_DURATION}}peers.forEach(function(peer){if(peer.wire.amChoking!==peer.isChoked){if(peer.isChoked)peer.wire.choke();else peer.wire.unchoke()}});function rechokeSort(peerA,peerB){if(peerA.downloadSpeed!==peerB.downloadSpeed)return peerB.downloadSpeed-peerA.downloadSpeed;if(peerA.uploadSpeed!==peerB.uploadSpeed)return peerB.uploadSpeed-peerA.uploadSpeed; | |
if(peerA.wire.amChoking!==peerB.wire.amChoking)return peerA.wire.amChoking?1:-1;return peerA.salt-peerB.salt}};Torrent.prototype._hotswap=function(wire,index){var self=this;if(!self.hotswapEnabled)return false;var speed=wire.downloadSpeed();if(speed<Storage.BLOCK_LENGTH)return false;if(!self._reservations[index])return false;var r=self._reservations[index];if(!r){return false}var minSpeed=Infinity;var minWire;var i;for(i=0;i<r.length;i++){var otherWire=r[i];if(!otherWire||otherWire===wire)continue;var otherSpeed=otherWire.downloadSpeed();if(otherSpeed>=SPEED_THRESHOLD)continue;if(2*otherSpeed>speed||otherSpeed>minSpeed)continue;minWire=otherWire;minSpeed=otherSpeed}if(!minWire)return false;for(i=0;i<r.length;i++){if(r[i]===minWire)r[i]=null}for(i=0;i<minWire.requests.length;i++){var req=minWire.requests[i];if(req.piece!==index)continue;self.storage.cancelBlock(index,req.offset)}self.emit("hotswap",minWire,wire,index);return true};Torrent.prototype._request=function(wire,index,hotswap){var self=this;var numRequests=wire.requests.length;if(self.storage.bitfield.get(index))return false;if(numRequests>=MAX_OUTSTANDING_REQUESTS)return false;var endGame=wire.requests.length===0&&self.storage.numMissing<30;var block=self.storage.reserveBlock(index,endGame);if(!block&&!endGame&&hotswap&&self._hotswap(wire,index))block=self.storage.reserveBlock(index,false);if(!block)return false;var r=self._reservations[index];if(!r){r=self._reservations[index]=[]}var i=r.indexOf(null);if(i===-1)i=r.length;r[i]=wire;function gotPiece(err,buffer){if(!self.ready){self.once("ready",function(){gotPiece(err,buffer)});return}if(r[i]===wire)r[i]=null;if(err){debug("error getting piece "+index+"(offset: "+block.offset+" length: "+block.length+") from "+wire.remoteAddress+" "+err.message);self.storage.cancelBlock(index,block.offset);process.nextTick(self._update.bind(self));return false}else{self.storage.writeBlock(index,block.offset,buffer,function(err){if(err){debug("error writing block");self.storage.cancelBlock(index,block.offset)}process.nextTick(self._update.bind(self))})}}wire.request(index,block.offset,block.length,gotPiece);return true};Torrent.prototype.createServer=function(opts){var self=this;if(typeof Server==="function"){return new Server(self,opts)}};function randomInt(high){return Math.random()*high|0}function randomizedForEach(array,cb){var indices=array.map(function(value,index){return index});for(var i=indices.length-1;i>0;--i){var j=randomInt(i+1);var tmp=indices[i];indices[i]=indices[j];indices[j]=tmp}indices.forEach(function(index){cb(array[index],index,array)})}function httpGet(u,cb,maxRedirects){cb=once(cb);if(!maxRedirects)maxRedirects=5;if(maxRedirects===0)return cb(new Error("too many redirects"));hh.get(u,function(res){if(res.statusCode>=300&&res.statusCode<400&&"location"in res.headers){var location=res.headers.location;if(!url.parse(location).host){var parsed=url.parse(u);location=parsed.protocol+"//"+parsed.host+location}res.resume();return httpGet(location,cb,--maxRedirects)}res.pipe(concat(function(data){cb(null,data)}))}).on("error",cb)}}).call(this,require("_process"))},{"./rarity-map":35,"./server":5,"./storage":36,_process:13,"addr-to-ip-port":39,"bittorrent-swarm":86,"concat-stream":5,debug:49,events:9,fs:1,"http-https":5,inherits:61,once:64,"parse-torrent":65,"re-emitter":73,"run-parallel":74,"torrent-discovery":76,url:31,ut_metadata:82,ut_pex:5}],38:[function(require,module,exports){module.exports=VideoStream;var debug=require("debug")("webtorrent:video-stream");var inherits=require("inherits");var once=require("once");var stream=require("stream");var MediaSource=typeof window!=="undefined"&&(window.MediaSource||window.WebKitMediaSource);inherits(VideoStream,stream.Writable);function VideoStream(video,opts){var self=this;if(!(self instanceof VideoStream))return new VideoStream($video,opts);stream.Writable.call(self,opts);self.video=video;opts=opts||{};opts.type=opts.type||'video/webm; codecs="vorbis,vp8"';debug("new videostream %s %s",video,JSON.stringify(opts));self._mediaSource=new MediaSource;self._playing=false;self._sourceBuffer=null;self._cb=null;self.video.src=window.URL.createObjectURL(self._mediaSource);var sourceopen=once(function(){self._sourceBuffer=self._mediaSource.addSourceBuffer(opts.type);self._sourceBuffer.addEventListener("updateend",self._flow.bind(self));self._flow()});self._mediaSource.addEventListener("webkitsourceopen",sourceopen,false);self._mediaSource.addEventListener("sourceopen",sourceopen,false);self.on("finish",function(){debug("finish");self._mediaSource.endOfStream()});window.vs=self}VideoStream.prototype._write=function(chunk,encoding,cb){var self=this;if(!self._sourceBuffer)return self._cb=function(){self._write(chunk,encoding,cb)};if(self._sourceBuffer.updating)return cb(new Error("Cannot append buffer while source buffer updating"));self._sourceBuffer.appendBuffer(chunk);debug("appendBuffer %s",chunk.length);self._cb=cb;if(!self._playing){self.video.play();self._playing=true}};VideoStream.prototype._flow=function(){var self=this;debug("flow");if(self._cb){self._cb(null)}}},{debug:49,inherits:61,once:64,stream:30}],39:[function(require,module,exports){var cache={};module.exports=function addrToIPPort(addr){if(!cache[addr]){var s=addr.split(":");cache[addr]=[s[0],Number(s[1])]}return cache[addr]}},{}],40:[function(require,module,exports){(function(Buffer){var Container=typeof Buffer!=="undefined"?Buffer:typeof Int8Array!=="undefined"?Int8Array:function(l){var a=new Array(l);for(var i=0;i<l;i++)a[i]=0};function BitField(data,opts){if(!(this instanceof BitField)){return new BitField(data)}if(arguments.length===0){data=0}this.grow=opts&&(isFinite(opts.grow)&&getByteSize(opts.grow)||opts.grow)||0;if(typeof data==="number"||data===undefined){data=new Container(getByteSize(data));if(data.fill)data.fill(0)}this.buffer=data}function getByteSize(num){var out=num>>3;if(num%8!==0)out++;return out}BitField.prototype.get=function(i){var j=i>>3;return j<this.buffer.length&&!!(this.buffer[j]&128>>i%8)};BitField.prototype.set=function(i,b){var j=i>>3;if(b||arguments.length===1){this._grow(j+1);this.buffer[j]|=128>>i%8}else if(j<this.buffer.length){this.buffer[j]&=~(128>>i%8)}};BitField.prototype._grow=function(length){if(this.buffer.length<length&&length<=this.grow){var newBuffer=new Container(length);if(newBuffer.fill)newBuffer.fill(0);for(var i=0;i<this.buffer.length;i++){newBuffer[i]=this.buffer[i]}this.buffer=newBuffer}};if(typeof module!=="undefined")module.exports=BitField}).call(this,require("buffer").Buffer)},{buffer:6}],41:[function(require,module,exports){(function(process,Buffer){module.exports=BlockStream;var Stream=require("stream").Stream,inherits=require("inherits"),assert=require("assert").ok,debug=process.env.DEBUG?console.error:function(){};function BlockStream(size,opt){this.writable=this.readable=true;this._opt=opt||{};this._chunkSize=size||512;this._offset=0;this._buffer=[];this._bufferLength=0;if(this._opt.nopad)this._zeroes=false;else{this._zeroes=new Buffer(this._chunkSize);for(var i=0;i<this._chunkSize;i++){this._zeroes[i]=0}}}inherits(BlockStream,Stream);BlockStream.prototype.write=function(c){if(this._ended)throw new Error("BlockStream: write after end");if(c&&!Buffer.isBuffer(c))c=new Buffer(c+"");if(c.length){this._buffer.push(c);this._bufferLength+=c.length}if(this._bufferLength>=this._chunkSize){if(this._paused){this._needDrain=true;return false}this._emitChunk()}return true};BlockStream.prototype.pause=function(){this._paused=true};BlockStream.prototype.resume=function(){this._paused=false;return this._emitChunk()};BlockStream.prototype.end=function(chunk){if(typeof chunk==="function")cb=chunk,chunk=null;if(chunk)this.write(chunk);this._ended=true;this.flush()};BlockStream.prototype.flush=function(){this._emitChunk(true)};BlockStream.prototype._emitChunk=function(flush){if(flush&&this._zeroes){var padBytes=this._bufferLength%this._chunkSize;if(padBytes!==0)padBytes=this._chunkSize-padBytes;if(padBytes>0){this._buffer.push(this._zeroes.slice(0,padBytes));this._bufferLength+=padBytes}}if(this._emitting||this._paused)return;this._emitting=true;var bufferIndex=0;while(this._bufferLength>=this._chunkSize&&(flush||!this._paused)){var out,outOffset=0,outHas=this._chunkSize;while(outHas>0&&(flush||!this._paused)){var cur=this._buffer[bufferIndex],curHas=cur.length-this._offset;if(out||curHas<outHas){out=out||new Buffer(this._chunkSize);cur.copy(out,outOffset,this._offset,this._offset+Math.min(curHas,outHas))}else if(cur.length===outHas&&this._offset===0){out=cur}else{out=cur.slice(this._offset,this._offset+outHas)}if(curHas>outHas){this._offset+=outHas;outHas=0}else{outHas-=curHas;outOffset+=curHas;bufferIndex++;this._offset=0}}this._bufferLength-=this._chunkSize;assert(out.length===this._chunkSize);this.emit("data",out);out=null}this._buffer=this._buffer.slice(bufferIndex);if(this._paused){this._needsDrain=true;this._emitting=false;return}var l=this._buffer.length;if(flush&&!this._zeroes&&l){if(l===1){if(this._offset){this.emit("data",this._buffer[0].slice(this._offset))}else{this.emit("data",this._buffer[0])}}else{var outHas=this._bufferLength,out=new Buffer(outHas),outOffset=0;for(var i=0;i<l;i++){var cur=this._buffer[i],curHas=cur.length-this._offset;cur.copy(out,outOffset,this._offset);this._offset=0;outOffset+=curHas;this._bufferLength-=curHas}this.emit("data",out)}this._buffer.length=0;this._bufferLength=0;this._offset=0}if(this._needDrain){this._needDrain=false;this.emit("drain")}if(this._bufferLength===0&&this._ended&&!this._endEmitted){this._endEmitted=true;this.emit("end")}this._emitting=false}}).call(this,require("_process"),require("buffer").Buffer)},{_process:13,assert:2,buffer:6,inherits:61,stream:30}],42:[function(require,module,exports){(function(Buffer){module.exports=createTorrent;var bencode=require("bencode");var BlockStream=require("block-stream");var calcPieceLength=require("piece-length");var corePath=require("path");var FileReadStream=require("filestream/read");var flatten=require("flatten");var fs=require("fs");var MultiStream=require("multistream");var once=require("once");var parallel=require("run-parallel");var sha1=require("git-sha1");var stream=require("stream");function createTorrent(input,opts,cb){if(typeof opts==="function"){cb=opts;opts={}}var files;if(typeof FileList==="function"&&input instanceof FileList){input=Array.prototype.slice.call(input)}if(isBlob(input)||Buffer.isBuffer(input)){input=[input]}if(Array.isArray(input)&&input.length>0){opts.name=opts.name||input[0].name;files=input.map(function(item){if(!item)return;var file={length:item.size,path:[item.name]};if(isBlob(item))file.getStream=getBlobStream(item);else if(Buffer.isBuffer(item))file.getStream=getBufferStream(item);else throw new Error("Array must contain only File objects");return file});onFiles(files,opts,cb)}else if(typeof input==="string"){opts.name=opts.name||corePath.basename(input);traversePath(getFileInfo,input,function(err,files){if(err)return cb(err);if(Array.isArray(files)){files=flatten(files)}else{files=[files]}var dirName=corePath.normalize(input)+corePath.sep;files.forEach(function(file){file.getStream=getFSStream(file.path);file.path=file.path.replace(dirName,"").split(corePath.sep)});onFiles(files,opts,cb)})}else{throw new Error("invalid input type")}}function getBlobStream(data){return function(){return new FileReadStream(data)}}function getBufferStream(data){return function(){var stream=new stream.PassThrough;stream.end(data);return stream}}function getFSStream(data){return function(){return fs.createReadStream(data)}}createTorrent.announceList=[["udp://tracker.publicbt.com:80"],["udp://tracker.openbittorrent.com:80"],["udp://tracker.webtorrent.io:80"],["wss://tracker.webtorrent.io"]];function each(arr,fn,cb){var tasks=arr.map(function(item){return function(cb){fn(item,cb)}});parallel(tasks,cb)}function getFileInfo(path,cb){cb=once(cb);fs.stat(path,function(err,stat){if(err)return cb(err);var info={length:stat.size,path:path};cb(null,info)})}function traversePath(fn,path,cb){fs.readdir(path,function(err,entries){if(err&&err.code==="ENOTDIR"){fn(path,cb)}else if(err){cb(err)}else{each(entries,function(entry,cb){traversePath(fn,corePath.join(path,entry),cb)},cb)}})}function getPieceList(files,pieceLength,cb){cb=once(cb);var pieces="";var streams=files.map(function(file){return file.getStream});new MultiStream(streams).pipe(new BlockStream(pieceLength,{nopad:true})).on("data",function(chunk){pieces+=sha1(chunk)}).on("end",function(){cb(null,new Buffer(pieces,"hex"))}).on("error",cb)}function onFiles(files,opts,cb){var announceList=opts.announceList!==undefined?opts.announceList:createTorrent.announceList;var torrent={info:{name:opts.name},announce:announceList[0][0],"announce-list":announceList,"creation date":Number(opts.creationDate)||Date.now(),encoding:"UTF-8"};if(opts.comment!==undefined){torrent.info.comment=opts.comment}if(opts.createdBy!==undefined){torrent.info["created by"]=opts.createdBy}if(opts.private!==undefined){torrent.info.private=Number(opts.private)}if(opts.urlList!==undefined){torrent["url-list"]=opts.urlList}var singleFile=files.length===1;var length=files.reduce(sumLength,0);var pieceLength=opts.pieceLength||calcPieceLength(length);torrent.info["piece length"]=pieceLength;if(singleFile){torrent.info.length=length}getPieceList(files,pieceLength,function(err,pieces){if(err)return cb(err);torrent.info.pieces=pieces;files.forEach(function(file){delete file.getStream});if(!singleFile){torrent.info.files=files}cb(null,bencode.encode(torrent))})}function sumLength(sum,file){return sum+file.length}function isBlob(obj){return typeof Blob!=="undefined"&&obj instanceof Blob}}).call(this,require("buffer").Buffer)},{bencode:43,"block-stream":41,buffer:6,"filestream/read":58,flatten:46,fs:1,"git-sha1":59,multistream:62,once:64,path:12,"piece-length":47,"run-parallel":74,stream:30}],43:[function(require,module,exports){module.exports={encode:require("./lib/encode"),decode:require("./lib/decode")}},{"./lib/decode":44,"./lib/encode":45}],44:[function(require,module,exports){(function(Buffer){function decode(data,encoding){decode.position=0;decode.encoding=encoding||null;decode.data=!Buffer.isBuffer(data)?new Buffer(data):data;return decode.next()}decode.position=0;decode.data=null;decode.encoding=null;decode.next=function(){switch(decode.data[decode.position]){case 100:return decode.dictionary();break;case 108:return decode.list();break;case 105:return decode.integer();break;default:return decode.bytes();break}};decode.find=function(chr){var i=decode.position;var c=decode.data.length;var d=decode.data;while(i<c){if(d[i]===chr)return i;i++}throw new Error('Invalid data: Missing delimiter "'+String.fromCharCode(chr)+'" [0x'+chr.toString(16)+"]")};decode.dictionary=function(){decode.position++;var dict={};while(decode.data[decode.position]!==101){dict[decode.bytes()]=decode.next()}decode.position++;return dict};decode.list=function(){decode.position++;var lst=[];while(decode.data[decode.position]!==101){lst.push(decode.next())}decode.position++;return lst};decode.integer=function(){var end=decode.find(101);var number=decode.data.toString("ascii",decode.position+1,end);decode.position+=end+1-decode.position;return parseInt(number,10)};decode.bytes=function(){var sep=decode.find(58);var length=parseInt(decode.data.toString("ascii",decode.position,sep),10);var end=++sep+length;decode.position=end;return decode.encoding?decode.data.toString(decode.encoding,sep,end):decode.data.slice(sep,end)};module.exports=decode}).call(this,require("buffer").Buffer)},{buffer:6}],45:[function(require,module,exports){(function(Buffer){function encode(data){var buffers=[];encode._encode(buffers,data);return Buffer.concat(buffers)}encode._floatConversionDetected=false;encode._encode=function(buffers,data){if(Buffer.isBuffer(data)){buffers.push(new Buffer(data.length+":"));buffers.push(data);return}switch(typeof data){case"string":encode.bytes(buffers,data);break;case"number":encode.number(buffers,data);break;case"object":data.constructor===Array?encode.list(buffers,data):encode.dict(buffers,data);break}};var buff_e=new Buffer("e"),buff_d=new Buffer("d"),buff_l=new Buffer("l");encode.bytes=function(buffers,data){buffers.push(new Buffer(Buffer.byteLength(data)+":"+data))};encode.number=function(buffers,data){var maxLo=2147483648;var hi=data/maxLo<<0;var lo=data%maxLo<<0;var val=hi*maxLo+lo;buffers.push(new Buffer("i"+val+"e"));if(val!==data&&!encode._floatConversionDetected){encode._floatConversionDetected=true;console.warn('WARNING: Possible data corruption detected with value "'+data+'":','Bencoding only defines support for integers, value was converted to "'+val+'"');console.trace()}};encode.dict=function(buffers,data){buffers.push(buff_d);var j=0;var k;var keys=Object.keys(data).sort();var kl=keys.length;for(;j<kl;j++){k=keys[j];encode.bytes(buffers,k);encode._encode(buffers,data[k])}buffers.push(buff_e)};encode.list=function(buffers,data){var i=0,j=1;var c=data.length;buffers.push(buff_l);for(;i<c;i++){encode._encode(buffers,data[i])}buffers.push(buff_e)};module.exports=encode}).call(this,require("buffer").Buffer)},{buffer:6}],46:[function(require,module,exports){module.exports=function flatten(list,depth){depth=typeof depth=="number"?depth:Infinity;return _flatten(list,1);function _flatten(list,d){return list.reduce(function(acc,item){if(Array.isArray(item)&&d<depth){return acc.concat(_flatten(item,d+1))}else{return acc.concat(item)}},[])}}},{}],47:[function(require,module,exports){var closest=require("closest-to");var sizes=[];for(var i=14;i<=22;i++){sizes.push(Math.pow(2,i))}module.exports=function(size){return closest(size/Math.pow(2,10),sizes)}},{"closest-to":48}],48:[function(require,module,exports){module.exports=function(target,numbers){var closest=Infinity;var difference=0;var winner=null;numbers.sort(function(a,b){return a-b});for(var i=0,l=numbers.length;i<l;i++){difference=Math.abs(target-numbers[i]);if(difference>=closest){break}closest=difference;winner=numbers[i]}return winner}},{}],49:[function(require,module,exports){exports=module.exports=require("./debug");exports.log=log;exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"];function useColors(){return"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)||navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31}exports.formatters.j=function(v){return JSON.stringify(v)};function formatArgs(){var args=arguments;var useColors=this.useColors;args[0]=(useColors?"%c":"")+this.namespace+(useColors?" %c":" ")+args[0]+(useColors?"%c ":" ")+"+"+exports.humanize(this.diff);if(!useColors)return args;var c="color: "+this.color;args=[args[0],c,"color: inherit"].concat(Array.prototype.slice.call(args,1));var index=0;var lastC=0;args[0].replace(/%[a-z%]/g,function(match){if("%%"===match)return;index++;if("%c"===match){lastC=index}});args.splice(lastC,0,c);return args}function log(){return"object"==typeof console&&"function"==typeof console.log&&Function.prototype.apply.call(console.log,console,arguments)}function save(namespaces){try{if(null==namespaces){localStorage.removeItem("debug")}else{localStorage.debug=namespaces}}catch(e){}}function load(){var r;try{r=localStorage.debug}catch(e){}return r}exports.enable(load())},{"./debug":50}],50:[function(require,module,exports){exports=module.exports=debug;exports.coerce=coerce;exports.disable=disable;exports.enable=enable;exports.enabled=enabled;exports.humanize=require("ms");exports.names=[];exports.skips=[];exports.formatters={};var prevColor=0;var prevTime;function selectColor(){return exports.colors[prevColor++%exports.colors.length]}function debug(namespace){function disabled(){}disabled.enabled=false;function enabled(){var self=enabled;var curr=+new Date;var ms=curr-(prevTime||curr);self.diff=ms;self.prev=prevTime;self.curr=curr;prevTime=curr;if(null==self.useColors)self.useColors=exports.useColors();if(null==self.color&&self.useColors)self.color=selectColor();var args=Array.prototype.slice.call(arguments);args[0]=exports.coerce(args[0]);if("string"!==typeof args[0]){args=["%o"].concat(args)}var index=0;args[0]=args[0].replace(/%([a-z%])/g,function(match,format){if(match==="%%")return match;index++;var formatter=exports.formatters[format];if("function"===typeof formatter){var val=args[index];match=formatter.call(self,val);args.splice(index,1);index--}return match});if("function"===typeof exports.formatArgs){args=exports.formatArgs.apply(self,args)}var logFn=enabled.log||exports.log||console.log.bind(console);logFn.apply(self,args)}enabled.enabled=true;var fn=exports.enabled(namespace)?enabled:disabled;fn.namespace=namespace;return fn}function enable(namespaces){exports.save(namespaces);var split=(namespaces||"").split(/[\s,]+/);var len=split.length;for(var i=0;i<len;i++){if(!split[i])continue;namespaces=split[i].replace(/\*/g,".*?");if(namespaces[0]==="-"){exports.skips.push(new RegExp("^"+namespaces.substr(1)+"$"))}else{exports.names.push(new RegExp("^"+namespaces+"$"))}}}function disable(){exports.enable("")}function enabled(name){var i,len;for(i=0,len=exports.skips.length;i<len;i++){if(exports.skips[i].test(name)){return false}}for(i=0,len=exports.names.length;i<len;i++){if(exports.names[i].test(name)){return true}}return false}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{ms:51}],51:[function(require,module,exports){var s=1e3;var m=s*60;var h=m*60;var d=h*24;var y=d*365.25;module.exports=function(val,options){options=options||{};if("string"==typeof val)return parse(val);return options.long?long(val):short(val)};function parse(str){var match=/^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);if(!match)return;var n=parseFloat(match[1]);var type=(match[2]||"ms").toLowerCase();switch(type){case"years":case"year":case"y":return n*y;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"h":return n*h;case"minutes":case"minute":case"m":return n*m;case"seconds":case"second":case"s":return n*s;case"ms":return n}}function short(ms){if(ms>=d)return Math.round(ms/d)+"d";if(ms>=h)return Math.round(ms/h)+"h";if(ms>=m)return Math.round(ms/m)+"m";if(ms>=s)return Math.round(ms/s)+"s";return ms+"ms"}function long(ms){return plural(ms,d,"day")||plural(ms,h,"hour")||plural(ms,m,"minute")||plural(ms,s,"second")||ms+" ms"}function plural(ms,n,name){if(ms<n)return;if(ms<n*1.5)return Math.floor(ms/n)+" "+name;return Math.ceil(ms/n)+" "+name+"s"}},{}],52:[function(require,module,exports){var wrappy=require("wrappy");module.exports=wrappy(dezalgo);var asap=require("asap");function dezalgo(cb){var sync=true;asap(function(){sync=false});return function zalgoSafe(){var args=arguments;var me=this;if(sync)asap(function(){cb.apply(me,args)});else cb.apply(me,args)}}},{asap:53,wrappy:54}],53:[function(require,module,exports){(function(process){var head={task:void 0,next:null};var tail=head;var flushing=false;var requestFlush=void 0;var isNodeJS=false;function flush(){while(head.next){head=head.next;var task=head.task;head.task=void 0;var domain=head.domain;if(domain){head.domain=void 0;domain.enter()}try{task()}catch(e){if(isNodeJS){if(domain){domain.exit()}setTimeout(flush,0);if(domain){domain.enter()}throw e}else{setTimeout(function(){throw e},0)}}if(domain){domain.exit()}}flushing=false}if(typeof process!=="undefined"&&process.nextTick){isNodeJS=true;requestFlush=function(){process.nextTick(flush)}}else if(typeof setImmediate==="function"){if(typeof window!=="undefined"){requestFlush=setImmediate.bind(window,flush)}else{requestFlush=function(){setImmediate(flush)}}}else if(typeof MessageChannel!=="undefined"){var channel=new MessageChannel;channel.port1.onmessage=flush;requestFlush=function(){channel.port2.postMessage(0)}}else{requestFlush=function(){setTimeout(flush,0)}}function asap(task){tail=tail.next={task:task,domain:isNodeJS&&process.domain,next:null};if(!flushing){flushing=true;requestFlush()}}module.exports=asap}).call(this,require("_process"))},{_process:13}],54:[function(require,module,exports){module.exports=wrappy;function wrappy(fn,cb){if(fn&&cb)return wrappy(fn)(cb);if(typeof fn!=="function")throw new TypeError("need wrapper function");Object.keys(fn).forEach(function(k){wrapper[k]=fn[k]});return wrapper;function wrapper(){var args=new Array(arguments.length);for(var i=0;i<args.length;i++){args[i]=arguments[i]}var ret=fn.apply(this,args);var cb=args[args.length-1];if(typeof ret==="function"&&ret!==cb){Object.keys(cb).forEach(function(k){ret[k]=cb[k]})}return ret}}},{}],55:[function(require,module,exports){var once=require("once");var noop=function(){};var isRequest=function(stream){return stream.setHeader&&typeof stream.abort==="function"};var isChildProcess=function(stream){return stream.stdio&&Array.isArray(stream.stdio)&&stream.stdio.length===3};var eos=function(stream,opts,callback){if(typeof opts==="function")return eos(stream,null,opts);if(!opts)opts={};callback=once(callback||noop);var ws=stream._writableState;var rs=stream._readableState;var readable=opts.readable||opts.readable!==false&&stream.readable;var writable=opts.writable||opts.writable!==false&&stream.writable;var onlegacyfinish=function(){if(!stream.writable)onfinish()};var onfinish=function(){writable=false;if(!readable)callback()};var onend=function(){readable=false;if(!writable)callback()};var onexit=function(exitCode){callback(exitCode?new Error("exited with error code: "+exitCode):null)};var onclose=function(){if(readable&&!(rs&&rs.ended))return callback(new Error("premature close"));if(writable&&!(ws&&ws.ended))return callback(new Error("premature close"))};var onrequest=function(){stream.req.on("finish",onfinish)};if(isRequest(stream)){stream.on("complete",onfinish);stream.on("abort",onclose);if(stream.req)onrequest();else stream.on("request",onrequest)}else if(writable&&!ws){stream.on("end",onlegacyfinish);stream.on("close",onlegacyfinish)}if(isChildProcess(stream))stream.on("exit",onexit);stream.on("end",onend);stream.on("finish",onfinish);if(opts.error!==false)stream.on("error",callback);stream.on("close",onclose);return function(){stream.removeListener("complete",onfinish);stream.removeListener("abort",onclose);stream.removeListener("request",onrequest);if(stream.req)stream.req.removeListener("finish",onfinish);stream.removeListener("end",onlegacyfinish);stream.removeListener("close",onlegacyfinish);stream.removeListener("finish",onfinish);stream.removeListener("exit",onexit);stream.removeListener("end",onend);stream.removeListener("error",callback);stream.removeListener("close",onclose)}};module.exports=eos},{once:64}],56:[function(require,module,exports){module.exports=function(src){var objs=[].slice.call(arguments,1),obj;for(var i=0,len=objs.length;i<len;i++){obj=objs[i];for(var prop in obj){src[prop]=obj[prop]}}return src}},{}],57:[function(require,module,exports){(function(Buffer){module.exports=function(arr){if(typeof Buffer._augment==="function"&&Buffer.TYPED_ARRAY_SUPPORT){return Buffer._augment(arr)}else{return new Buffer(arr)}}}).call(this,require("buffer").Buffer)},{buffer:6}],58:[function(require,module,exports){"use strict";var Readable=require("stream").Readable;var util=require("util");var reExtension=/^.*\.(\w+)$/;var extend=require("extend.js");var toBuffer=require("typedarray-to-buffer");function FileReadStream(file,opts){if(!(this instanceof FileReadStream)){return new FileReadStream(file,opts)}opts=opts||{};Readable.call(this,extend({objectMode:true},opts));this._offset=0;this._eof=false;this._metasent=!opts.meta;this._metadata={name:file.name,size:file.size,extension:file.name.replace(reExtension,"$1")};if(opts.mime&&typeof opts.mime.lookup=="function"){this._metadata.type=opts.mime.lookup(this._metadata.extension)}this.reader=new FileReader;this.reader.onprogress=this._handleProgress.bind(this);this.reader.onload=this._handleLoad.bind(this);this.reader.readAsArrayBuffer(file)}util.inherits(FileReadStream,Readable);module.exports=FileReadStream;FileReadStream.prototype._read=function(bytes){var stream=this;var reader=this.reader;function checkBytes(){var startOffset=stream._offset;var endOffset=stream._offset+bytes;var availableBytes=reader.result&&reader.result.byteLength;var done=reader.readyState===2&&endOffset>availableBytes;var chunk;if(availableBytes&&(done||availableBytes>endOffset)){chunk=toBuffer(new Uint8Array(reader.result,startOffset,Math.min(bytes,reader.result.byteLength-startOffset)));stream._offset=startOffset+chunk.length;stream._eof=chunk.length===0;return stream.push(chunk.length>0?chunk:null)}stream.once("readable",checkBytes)}if(!this._metasent){this._metasent=true;return this.push("meta|"+JSON.stringify(this._metadata))}checkBytes()};FileReadStream.prototype._handleLoad=function(evt){this.emit("readable")};FileReadStream.prototype._handleProgress=function(evt){this.emit("readable")}},{"extend.js":56,stream:30,"typedarray-to-buffer":57,util:33}],59:[function(require,module,exports){(function(process){"use strict";var isNode=typeof process==="object"&&typeof process.versions==="object"&&process.versions.node&&process.__atom_type!=="renderer";var shared,create,crypto;if(isNode){var nodeRequire=require;crypto=nodeRequire("crypto");create=createNode}else{shared=new Uint32Array(80);create=createJs}module.exports=function sha1(buffer){if(buffer===undefined)return create(false);var shasum=create(true);shasum.update(buffer);return shasum.digest()};function createNode(){var shasum=crypto.createHash("sha1");return{update:function(buffer){return shasum.update(buffer)},digest:function(){return shasum.digest("hex")}}}function createJs(sync){var h0=1732584193;var h1=4023233417;var h2=2562383102;var h3=271733878;var h4=3285377520;var block,offset=0,shift=24;var totalLength=0;if(sync)block=shared;else block=new Uint32Array(80);return{update:update,digest:digest};function update(chunk){if(typeof chunk==="string")return updateString(chunk);var length=chunk.length;totalLength+=length*8;for(var i=0;i<length;i++){write(chunk[i])}}function updateString(string){var length=string.length;totalLength+=length*8;for(var i=0;i<length;i++){write(string.charCodeAt(i))}}function write(byte){block[offset]|=(byte&255)<<shift;if(shift){shift-=8}else{offset++;shift=24}if(offset===16)processBlock()}function digest(){write(128);if(offset>14||offset===14&&shift<24){processBlock()}offset=14;shift=24;write(0);write(0);write(totalLength>0xffffffffff?totalLength/1099511627776:0);write(totalLength>4294967295?totalLength/4294967296:0);for(var s=24;s>=0;s-=8){write(totalLength>>s)}return toHex(h0)+toHex(h1)+toHex(h2)+toHex(h3)+toHex(h4)}function processBlock(){for(var i=16;i<80;i++){var w=block[i-3]^block[i-8]^block[i-14]^block[i-16];block[i]=w<<1|w>>>31}var a=h0;var b=h1;var c=h2;var d=h3;var e=h4;var f,k;for(i=0;i<80;i++){if(i<20){f=d^b&(c^d);k=1518500249}else if(i<40){f=b^c^d;k=1859775393}else if(i<60){f=b&c|d&(b|c);k=2400959708}else{f=b^c^d;k=3395469782}var temp=(a<<5|a>>>27)+f+e+k+(block[i]|0);e=d;d=c;c=b<<30|b>>>2;b=a;a=temp}h0=h0+a|0;h1=h1+b|0;h2=h2+c|0;h3=h3+d|0;h4=h4+e|0;offset=0;for(i=0;i<16;i++){block[i]=0}}function toHex(word){var hex="";for(var i=28;i>=0;i-=4){hex+=(word>>i&15).toString(16)}return hex}}}).call(this,require("_process"))},{_process:13}],60:[function(require,module,exports){var hat=module.exports=function(bits,base){if(!base)base=16;if(bits===undefined)bits=128;if(bits<=0)return"0";var digits=Math.log(Math.pow(2,bits))/Math.log(base);for(var i=2;digits===Infinity;i*=2){digits=Math.log(Math.pow(2,bits/i))/Math.log(base)*i}var rem=digits-Math.floor(digits);var res="";for(var i=0;i<Math.floor(digits);i++){var x=Math.floor(Math.random()*base).toString(base);res=x+res}if(rem){var b=Math.pow(base,rem);var x=Math.floor(Math.random()*b).toString(base); | |
res=x+res}var parsed=parseInt(res,base);if(parsed!==Infinity&&parsed>=Math.pow(2,bits)){return hat(bits,base)}else return res};hat.rack=function(bits,base,expandBy){var fn=function(data){var iters=0;do{if(iters++>10){if(expandBy)bits+=expandBy;else throw new Error("too many ID collisions, use more bits")}var id=hat(bits,base)}while(Object.hasOwnProperty.call(hats,id));hats[id]=data;return id};var hats=fn.hats={};fn.get=function(id){return fn.hats[id]};fn.set=function(id,value){fn.hats[id]=value;return fn};fn.bits=bits||128;fn.base=base||16;return fn}},{}],61:[function(require,module,exports){module.exports=require(10)},{}],62:[function(require,module,exports){module.exports=MultiStream;var inherits=require("inherits");var stream=require("stream");inherits(MultiStream,stream.Readable);function MultiStream(streams,opts){if(!(this instanceof MultiStream))return new MultiStream(streams,opts);stream.Readable.call(this,opts);this.destroyed=false;this._drained=false;this._forwarding=false;this._current=null;this._queue=streams.map(toStreams2);this._next()}MultiStream.obj=function(streams){return new MultiStream(streams,{objectMode:true,highWaterMark:16})};MultiStream.prototype._read=function(){this._drained=true;this._forward()};MultiStream.prototype._forward=function(){if(this._forwarding||!this._drained)return;this._forwarding=true;var chunk;while((chunk=this._current.read())!==null){this._drained=this.push(chunk)}this._forwarding=false};MultiStream.prototype.destroy=function(err){if(this.destroyed)return;this.destroyed=true;if(this._current&&this._current.destroy)this._current.destroy();this._queue.forEach(function(stream){if(stream.destroy)stream.destroy()});if(err)this.emit("error",err);this.emit("close")};MultiStream.prototype._next=function(){var self=this;var stream=this._queue.shift();if(typeof stream==="function")stream=toStreams2(stream());if(!stream){this.push(null);return}this._current=stream;stream.on("readable",onReadable);stream.on("end",onEnd);stream.on("error",onError);stream.on("close",onClose);function onReadable(){self._forward()}function onClose(){if(!stream._readableState.ended){self.destroy()}}function onEnd(){self._current=null;stream.removeListener("readable",onReadable);stream.removeListener("end",onEnd);stream.removeListener("error",onError);stream.removeListener("close",onClose);self._next()}function onError(err){self.destroy(err)}};function toStreams2(s){if(!s||typeof s==="function"||s._readableState)return s;var wrap=(new stream.Readable).wrap(s);if(s.destroy){wrap.destroy=s.destroy.bind(s)}return wrap}},{inherits:61,stream:30}],63:[function(require,module,exports){module.exports=require(54)},{}],64:[function(require,module,exports){var wrappy=require("wrappy");module.exports=wrappy(once);once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:true})});function once(fn){var f=function(){if(f.called)return f.value;f.called=true;return f.value=fn.apply(this,arguments)};f.called=false;return f}},{wrappy:63}],65:[function(require,module,exports){(function(Buffer){var magnet=require("magnet-uri");var parseTorrentFile=require("parse-torrent-file");module.exports=function parseTorrent(torrentId){if(typeof torrentId==="string"&&/magnet:/.test(torrentId)){return magnet(torrentId)}else if(typeof torrentId==="string"&&(torrentId.length===40||torrentId.length===32)){var info=magnet("magnet:?xt=urn:btih:"+torrentId);if(info)return{infoHash:info.infoHash};else return null}else if(Buffer.isBuffer(torrentId)&&torrentId.length===20){return{infoHash:torrentId.toString("hex")}}else if(Buffer.isBuffer(torrentId)){try{return parseTorrentFile(torrentId)}catch(err){return null}}else if(torrentId&&torrentId.infoHash){return torrentId}else{return null}};module.exports.toBuffer=parseTorrentFile.toBuffer}).call(this,require("buffer").Buffer)},{buffer:6,"magnet-uri":66,"parse-torrent-file":69}],66:[function(require,module,exports){(function(Buffer){var base32=require("thirty-two");module.exports=function(uri){var result={};var data=uri.split("magnet:?")[1];if(!data||data.length===0)return result;var params=data.split("&");params.forEach(function(param){var keyval=param.split("=");if(keyval.length!==2)return;var key=keyval[0];var val=keyval[1];if(key==="dn")val=decodeURIComponent(val).replace(/\+/g," ");if(key==="tr")val=decodeURIComponent(val);if(key==="kt")val=decodeURIComponent(val).split("+");if(result[key]){if(Array.isArray(result[key])){result[key].push(val)}else{var old=result[key];result[key]=[old,val]}}else{result[key]=val}});var m;if(result.xt&&(m=result.xt.match(/^urn:btih:(.{40})/))){result.infoHash=new Buffer(m[1],"hex").toString("hex")}else if(result.xt&&(m=result.xt.match(/^urn:btih:(.{32})/))){var decodedStr=base32.decode(m[1]);result.infoHash=new Buffer(decodedStr,"binary").toString("hex")}if(result.dn)result.name=result.dn;if(result.kt)result.keywords=result.kt;if(typeof result.tr==="string")result.announce=[result.tr];else if(Array.isArray(result.tr))result.announce=result.tr;return result}}).call(this,require("buffer").Buffer)},{buffer:6,"thirty-two":67}],67:[function(require,module,exports){var base32=require("./thirty-two");exports.encode=base32.encode;exports.decode=base32.decode},{"./thirty-two":68}],68:[function(require,module,exports){(function(Buffer){var charTable="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";var byteTable=[255,255,26,27,28,29,30,31,255,255,255,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255];function quintetCount(buff){var quintets=Math.floor(buff.length/5);return buff.length%5==0?quintets:quintets+1}exports.encode=function(plain){var i=0;var j=0;var shiftIndex=0;var digit=0;var encoded=new Buffer(quintetCount(plain)*8);if(!Buffer.isBuffer(plain)){plain=new Buffer(plain)}while(i<plain.length){var current=plain[i];if(shiftIndex>3){digit=current&255>>shiftIndex;shiftIndex=(shiftIndex+5)%8;digit=digit<<shiftIndex|(i+1<plain.length?plain[i+1]:0)>>8-shiftIndex;i++}else{digit=current>>8-(shiftIndex+5)&31;shiftIndex=(shiftIndex+5)%8;if(shiftIndex==0)i++}encoded[j]=charTable.charCodeAt(digit);j++}for(i=j;i<encoded.length;i++)encoded[i]=61;return encoded};exports.decode=function(encoded){var shiftIndex=0;var plainDigit=0;var plainChar;var plainPos=0;if(!Buffer.isBuffer(encoded)){encoded=new Buffer(encoded)}var decoded=new Buffer(Math.ceil(encoded.length*5/8));for(var i=0;i<encoded.length;i++){if(encoded[i]==61){break}var encodedByte=encoded[i]-48;if(encodedByte<byteTable.length){plainDigit=byteTable[encodedByte];if(shiftIndex<=3){shiftIndex=(shiftIndex+5)%8;if(shiftIndex==0){plainChar|=plainDigit;decoded[plainPos]=plainChar;plainPos++;plainChar=0}else{plainChar|=255&plainDigit<<8-shiftIndex}}else{shiftIndex=(shiftIndex+5)%8;plainChar|=255&plainDigit>>>shiftIndex;decoded[plainPos]=plainChar;plainPos++;plainChar=255&plainDigit<<8-shiftIndex}}else{throw new Error("Invalid input - it is not base32 encoded string")}}return decoded.slice(0,plainPos)}}).call(this,require("buffer").Buffer)},{buffer:6}],69:[function(require,module,exports){(function(Buffer){module.exports=parseTorrent;module.exports.toBuffer=toBuffer;var bencode=require("bencode");var path=require("path");var sha1=require("git-sha1");function parseTorrent(torrent){if(Buffer.isBuffer(torrent)){torrent=bencode.decode(torrent)}ensure(torrent.info,"info");ensure(torrent.info.name,"info.name");ensure(torrent.info["piece length"],"info['piece length']");ensure(torrent.info.pieces,"info.pieces");if(torrent.info.files){torrent.info.files.forEach(function(file){ensure(typeof file.length==="number","info.files[0].length");ensure(file.path,"info.files[0].path")})}else{ensure(torrent.info.length,"info.length")}var result={};result.info=torrent.info;result.infoBuffer=bencode.encode(torrent.info);result.infoHash=sha1(result.infoBuffer);result.name=torrent.info.name.toString();result.private=!!torrent.info.private;if(torrent["creation date"])result.created=new Date(torrent["creation date"]*1e3);if(Buffer.isBuffer(torrent.comment))result.comment=torrent.comment.toString();var announce=torrent["announce-list"];if(!announce){if(torrent.announce){announce=[[torrent.announce]]}else{announce=[]}}result.announceList=announce.map(function(urls){return urls.map(function(url){return url.toString()})});result.announce=[].concat.apply([],result.announceList);result.urlList=(torrent["url-list"]||[]).map(function(url){return url.toString()});var files=torrent.info.files||[torrent.info];result.files=files.map(function(file,i){var parts=[].concat(file.name||result.name,file.path||[]).map(function(p){return p.toString()});return{path:path.join.apply(null,[path.sep].concat(parts)).slice(1),name:parts[parts.length-1],length:file.length,offset:files.slice(0,i).reduce(sumLength,0)}});result.length=files.reduce(sumLength,0);var lastFile=result.files[result.files.length-1];result.pieceLength=torrent.info["piece length"];result.lastPieceLength=(lastFile.offset+lastFile.length)%result.pieceLength||result.pieceLength;result.pieces=splitPieces(torrent.info.pieces);return result}function toBuffer(parsed){var torrent={info:parsed.info};if(parsed.announce&&parsed.announce[0]){torrent.announce=parsed.announce[0]}if(parsed.announceList){torrent["announce-list"]=parsed.announceList.map(function(urls){return urls.map(function(url){url=new Buffer(url,"utf8");if(!torrent.announce){torrent.announce=url}return url})})}if(parsed.created){torrent["creation date"]=parsed.created.getTime()/1e3|0}return bencode.encode(torrent)}function sumLength(sum,file){return sum+file.length}function splitPieces(buf){var pieces=[];for(var i=0;i<buf.length;i+=20){pieces.push(buf.slice(i,i+20).toString("hex"))}return pieces}function ensure(bool,fieldName){if(!bool)throw new Error("Torrent is missing required field: "+fieldName)}}).call(this,require("buffer").Buffer)},{bencode:70,buffer:6,"git-sha1":59,path:12}],70:[function(require,module,exports){module.exports=require(43)},{"./lib/decode":71,"./lib/encode":72}],71:[function(require,module,exports){module.exports=require(44)},{buffer:6}],72:[function(require,module,exports){module.exports=require(45)},{buffer:6}],73:[function(require,module,exports){module.exports=reemit;module.exports.filter=filter;var EventEmitter=require("events").EventEmitter;function reemit(source,target,events){if(!Array.isArray(events))events=[events];events.forEach(function(event){source.on(event,function(){var args=[].slice.call(arguments);args.unshift(event);target.emit.apply(target,args)})})}function filter(source,events){var emitter=new EventEmitter;reemit(source,emitter,events);return emitter}},{events:9}],74:[function(require,module,exports){module.exports=function(tasks,cb){var results,pending,keys;if(Array.isArray(tasks)){results=[];pending=tasks.length}else{keys=Object.keys(tasks);results={};pending=keys.length}function done(i,err,result){results[i]=result;if(--pending===0||err){cb&&cb(err,results);cb=null}}if(!pending){cb&&cb(null,results);cb=null}else if(keys){keys.forEach(function(key){tasks[key](done.bind(undefined,key))})}else{tasks.forEach(function(task,i){task(done.bind(undefined,i))})}}},{}],75:[function(require,module,exports){var tick=1;var maxTick=65535;var resolution=4;var inc=function(){tick=tick+1&maxTick};var timer=setInterval(inc,1e3/resolution|0);if(timer.unref)timer.unref();module.exports=function(seconds){var size=resolution*(seconds||5);var buffer=[0];var pointer=1;var last=tick-1&maxTick;return function(delta){var dist=tick-last&maxTick;if(dist>size)dist=size;last=tick;while(dist--){if(pointer===size)pointer=0;buffer[pointer]=buffer[pointer===0?size-1:pointer-1];pointer++}if(delta)buffer[pointer-1]+=delta;var top=buffer[pointer-1];var btm=buffer.length<size?0:buffer[pointer===size?0:pointer];return buffer.length<resolution?top:(top-btm)*resolution/buffer.length}}},{}],76:[function(require,module,exports){(function(process){module.exports=Discovery;var debug=require("debug")("torrent-discovery");var DHT=require("bittorrent-dht/client");var EventEmitter=require("events").EventEmitter;var extend=require("extend.js");var inherits=require("inherits");var reemit=require("re-emitter");var Tracker=require("bittorrent-tracker/client");inherits(Discovery,EventEmitter);function Discovery(opts){var self=this;if(!(self instanceof Discovery))return new Discovery(opts);EventEmitter.call(self);if(!opts)opts={};self._performedDHTLookup=false;extend(self,{announce:[],dht:typeof DHT==="function",externalDHT:false,tracker:true,port:null},opts);if(!self.peerId)throw new Error("peerId required");if(!self.port&&!process.browser)throw new Error("port required");self._createDHT(opts.dhtPort)}Discovery.prototype.setTorrent=function(torrent){var self=this;if(self.torrent)return;if(torrent&&torrent.infoHash){self.torrent=torrent;self.infoHash=torrent.infoHash}else{if(self.infoHash)return;self.infoHash=torrent}debug("setTorrent %s",torrent);if(self.tracker&&self.tracker!==true)self.tracker.torrentLength=torrent.length;else self._createTracker();if(self.dht){if(self.dht.ready)self._dhtLookupAndAnnounce();else self.dht.on("ready",self._dhtLookupAndAnnounce.bind(self))}};Discovery.prototype.stop=function(cb){var self=this;if(self.tracker&&self.tracker.stop)self.tracker.stop();if(!self.externalDHT&&self.dht&&self.dht.destroy)self.dht.destroy(cb);else process.nextTick(function(){cb(null)})};Discovery.prototype._createDHT=function(port){var self=this;if(!self.dht)return;if(self.dht)self.externalDHT=true;else self.dht=new DHT;reemit(self.dht,self,["peer","error","warning"]);if(!self.externalDHT)self.dht.listen(port)};Discovery.prototype._createTracker=function(){var self=this;if(!self.tracker)return;var torrent=self.torrent||{infoHash:self.infoHash,announce:self.announce};self.tracker=process.browser?new Tracker(self.peerId,torrent):new Tracker(self.peerId,self.port,torrent);reemit(self.tracker,self,["peer","warning","error"]);self.tracker.start()};Discovery.prototype._dhtLookupAndAnnounce=function(){var self=this;if(self._performedDHTLookup)return;self._performedDHTLookup=true;debug("lookup");self.dht.lookup(self.infoHash,function(err){if(err||!self.port)return;debug("dhtAnnounce");self.dht.announce(self.infoHash,self.port,function(){self.emit("dhtAnnounce")})})}}).call(this,require("_process"))},{_process:13,"bittorrent-dht/client":5,"bittorrent-tracker/client":77,debug:49,events:9,"extend.js":56,inherits:61,"re-emitter":73}],77:[function(require,module,exports){(function(Buffer){module.exports=Client;var debug=require("debug")("webtorrent-tracker");var EventEmitter=require("events").EventEmitter;var extend=require("extend.js");var hat=require("hat");var inherits=require("inherits");var Peer=require("simple-peer");var Socket=require("simple-websocket");var DEFAULT_NUM_WANT=15;inherits(Client,EventEmitter);var sockets={};function Client(peerId,torrent,opts){var self=this;if(!(self instanceof Client))return new Client(peerId,torrent,opts);EventEmitter.call(self);self._opts=opts||{};self._peerId=Buffer.isBuffer(peerId)?peerId:new Buffer(peerId,"utf8");self._infoHash=Buffer.isBuffer(torrent.infoHash)?torrent.infoHash:new Buffer(torrent.infoHash,"hex");self.torrentLength=torrent.length;self._numWant=self._opts.numWant||DEFAULT_NUM_WANT;self._intervalMs=self._opts.interval||30*60*1e3;debug("new client %s",self._infoHash.toString("hex"));if(typeof torrent.announce==="string")torrent.announce=[torrent.announce];self._trackers=(torrent.announce||[]).filter(function(announceUrl){return announceUrl.indexOf("ws://")===0||announceUrl.indexOf("wss://")===0}).map(function(announceUrl){return new Tracker(self,announceUrl,self._opts)})}Client.prototype.start=function(opts){var self=this;self._trackers.forEach(function(tracker){tracker.start(opts)})};Client.prototype.stop=function(opts){var self=this;self._trackers.forEach(function(tracker){tracker.stop(opts)})};Client.prototype.complete=function(opts){var self=this;self._trackers.forEach(function(tracker){tracker.complete(opts)})};Client.prototype.update=function(opts){var self=this;self._trackers.forEach(function(tracker){tracker.update(opts)})};Client.prototype.setInterval=function(intervalMs){var self=this;self._intervalMs=intervalMs;self._trackers.forEach(function(tracker){tracker.setInterval(intervalMs)})};inherits(Tracker,EventEmitter);function Tracker(client,announceUrl,opts){var self=this;EventEmitter.call(self);self._opts=opts||{};self._announceUrl=announceUrl;self._peers={};debug("new tracker %s",announceUrl);self.client=client;self.ready=false;self._socket=null;self._intervalMs=self.client._intervalMs;self._interval=null}Tracker.prototype.start=function(opts){var self=this;opts=opts||{};opts.event="started";debug("sent `start` %s %s",self._announceUrl,JSON.stringify(opts));self._announce(opts);self.setInterval(self._intervalMs)};Tracker.prototype.stop=function(opts){var self=this;opts=opts||{};opts.event="stopped";debug("sent `stop` %s %s",self._announceUrl,JSON.stringify(opts));self._announce(opts);self.setInterval(0)};Tracker.prototype.complete=function(opts){var self=this;opts=opts||{};opts.event="completed";opts.downloaded=opts.downloaded||self.torrentLength||0;debug("sent `complete` %s %s",self._announceUrl,JSON.stringify(opts));self._announce(opts)};Tracker.prototype.update=function(opts){var self=this;opts=opts||{};debug("sent `update` %s %s",self._announceUrl,JSON.stringify(opts));self._announce(opts)};Tracker.prototype._init=function(onready){var self=this;if(onready)self.once("ready",onready);if(self._socket)return;if(sockets[self._announceUrl]){self._socket=sockets[self._announceUrl];self._onSocketReady()}else{self._socket=sockets[self._announceUrl]=new Socket(self._announceUrl);self._socket.on("ready",self._onSocketReady.bind(self))}self._socket.on("warning",self._onSocketWarning.bind(self));self._socket.on("error",self._onSocketWarning.bind(self));self._socket.on("message",self._onSocketMessage.bind(self))};Tracker.prototype._onSocketReady=function(){var self=this;self.ready=true;self.emit("ready")};Tracker.prototype._onSocketWarning=function(err){debug("tracker warning %s",err.message)};Tracker.prototype._onSocketMessage=function(data){var self=this;if(!(typeof data==="object"&&data!==null))return self.client.emit("warning",new Error("Invalid tracker response"));if(data.info_hash!==self.client._infoHash.toString("binary"))return;debug("received %s from %s",JSON.stringify(data),self._announceUrl);var failure=data["failure reason"];if(failure)return self.client.emit("warning",new Error(failure));var warning=data["warning message"];if(warning)self.client.emit("warning",new Error(warning));var interval=data.interval||data["min interval"];if(interval&&!self._opts.interval&&self._intervalMs!==0){self.setInterval(interval*1e3)}var trackerId=data["tracker id"];if(trackerId){self._trackerId=trackerId}if(data.complete){self.client.emit("update",{announce:self._announceUrl,complete:data.complete,incomplete:data.incomplete})}var peer;if(data.offer){peer=new Peer({trickle:false});peer.id=binaryToHex(data.peer_id);peer.once("signal",function(answer){var opts={info_hash:self.client._infoHash.toString("binary"),peer_id:self.client._peerId.toString("binary"),to_peer_id:data.peer_id};if(self._trackerId)opts.trackerid=self._trackerId;self._send(extend({answer:answer,offer_id:data.offer_id},opts))});peer.signal(data.offer);self.client.emit("peer",peer)}if(data.answer){peer=self._peers[data.offer_id];if(peer){peer.signal(data.answer);self.client.emit("peer",peer)}}};Tracker.prototype._announce=function(opts){var self=this;if(!self.ready)return self._init(self._announce.bind(self,opts));self._generateOffers(function(offers){opts=extend({uploaded:0,downloaded:0,info_hash:self.client._infoHash.toString("binary"),peer_id:self.client._peerId.toString("binary"),offers:offers},opts);if(self.client.torrentLength!=null&&opts.left==null){opts.left=self.client.torrentLength-(opts.downloaded||0)}if(self._trackerId){opts.trackerid=self._trackerId}self._send(opts)})};Tracker.prototype._send=function(opts){var self=this;debug("send %s",JSON.stringify(opts));self._socket.send(opts)};Tracker.prototype._generateOffers=function(cb){var self=this;var offers=[];debug("generating %s offers",self.client._numWant);for(var i=0;i<self.client._numWant;++i){generateOffer()}function generateOffer(){var offerId=hat(160);var peer=self._peers[offerId]=new Peer({initiator:true,trickle:false});peer.once("signal",function(offer){offers.push({offer:offer,offer_id:offerId});checkDone()})}function checkDone(){if(offers.length===self.client._numWant){debug("generated %s offers",self.client._numWant);cb(offers)}}};Tracker.prototype.setInterval=function(intervalMs){var self=this;clearInterval(self._interval);self._intervalMs=intervalMs;if(intervalMs){self._interval=setInterval(self.update.bind(self),self._intervalMs)}};function binaryToHex(id){return new Buffer(id,"binary").toString("hex")}}).call(this,require("buffer").Buffer)},{buffer:6,debug:49,events:9,"extend.js":56,hat:60,inherits:61,"simple-peer":78,"simple-websocket":81}],78:[function(require,module,exports){module.exports=Peer;var debug=require("debug")("simple-peer");var EventEmitter=require("events").EventEmitter;var extend=require("extend.js");var hat=require("hat");var inherits=require("inherits");var isTypedArray=require("is-typedarray");var once=require("once");var stream=require("stream");var toBuffer=require("typedarray-to-buffer");var RTCPeerConnection=typeof window!=="undefined"&&(window.mozRTCPeerConnection||window.RTCPeerConnection||window.webkitRTCPeerConnection);var RTCSessionDescription=typeof window!=="undefined"&&(window.mozRTCSessionDescription||window.RTCSessionDescription||window.webkitRTCSessionDescription);var RTCIceCandidate=typeof window!=="undefined"&&(window.mozRTCIceCandidate||window.RTCIceCandidate||window.webkitRTCIceCandidate);inherits(Peer,EventEmitter);function Peer(opts){if(!(this instanceof Peer))return new Peer(opts);EventEmitter.call(this);opts=extend({initiator:false,stream:false,config:Peer.config,constraints:Peer.constraints,channelName:opts&&opts.initiator?hat(160):null,trickle:true},opts);extend(this,opts);debug("new peer initiator: %s channelName: %s",this.initiator,this.channelName);this.destroyed=false;this.ready=false;this._pcReady=false;this._channelReady=false;this._dataStreams=[];this._iceComplete=false;this._pc=new RTCPeerConnection(this.config,this.constraints);this._pc.oniceconnectionstatechange=this._onIceConnectionStateChange.bind(this);this._pc.onsignalingstatechange=this._onSignalingStateChange.bind(this);this._pc.onicecandidate=this._onIceCandidate.bind(this);this._channel=null;if(this.stream)this._setupVideo(this.stream);if(this.initiator){this._setupData({channel:this._pc.createDataChannel(this.channelName)});this._pc.onnegotiationneeded=once(function(){this._pc.createOffer(function(offer){this._pc.setLocalDescription(offer);var sendOffer=function(){this.emit("signal",this._pc.localDescription||offer)}.bind(this);if(this.trickle||this._iceComplete)sendOffer();else this.once("_iceComplete",sendOffer)}.bind(this),this._onError.bind(this))}.bind(this));if(window.mozRTCPeerConnection){setTimeout(this._pc.onnegotiationneeded.bind(this._pc),0)}}else{this._pc.ondatachannel=this._setupData.bind(this)}}Peer.config={iceServers:[{url:"stun:23.21.150.121"}]};Peer.constraints={};Peer.prototype.send=function(data,cb){if(!this._channelReady)return this.once("ready",this.send.bind(this,data,cb));debug("send %s",data);if(isTypedArray.strict(data)||data instanceof ArrayBuffer||data instanceof Blob||typeof data==="string"){this._channel.send(data)}else{this._channel.send(JSON.stringify(data))}if(cb)cb(null)};Peer.prototype.signal=function(data){if(this.destroyed)return;if(typeof data==="string"){try{data=JSON.parse(data)}catch(err){data={}}}debug("signal %s",JSON.stringify(data));if(data.sdp){this._pc.setRemoteDescription(new RTCSessionDescription(data),function(){var needsAnswer=this._pc.remoteDescription.type==="offer";if(needsAnswer){this._pc.createAnswer(function(answer){this._pc.setLocalDescription(answer);var sendAnswer=function(){this.emit("signal",this._pc.localDescription||answer)}.bind(this);if(this.trickle||this._iceComplete)sendAnswer();else this.once("_iceComplete",sendAnswer)}.bind(this),this._onError.bind(this))}}.bind(this),this._onError.bind(this))}if(data.candidate){try{this._pc.addIceCandidate(new RTCIceCandidate(data.candidate))}catch(err){this.destroy(new Error("error adding candidate, "+err.message))}}if(!data.sdp&&!data.candidate)this.destroy(new Error("signal() called with invalid signal data"))};Peer.prototype.destroy=function(err,onclose){if(this.destroyed)return;debug("destroy (error: %s)",err&&err.message);this.destroyed=true;this.ready=false;if(typeof err==="function"){onclose=err;err=null}if(onclose)this.once("close",onclose);if(this._pc){try{this._pc.close()}catch(err){}this._pc.oniceconnectionstatechange=null;this._pc.onsignalingstatechange=null;this._pc.onicecandidate=null}if(this._channel){try{this._channel.close()}catch(err){}this._channel.onmessage=null;this._channel.onopen=null;this._channel.onclose=null}this._pc=null;this._channel=null;this._dataStreams.forEach(function(stream){if(err)stream.emit("error",err);if(!stream._readableState.ended)stream.push(null);if(!stream._writableState.finished)stream.end()});this._dataStreams=[];if(err)this.emit("error",err);this.emit("close")};Peer.prototype.getDataStream=function(opts){if(this.destroyed)throw new Error("peer is destroyed");var dataStream=new DataStream(extend({_peer:this},opts));this._dataStreams.push(dataStream);return dataStream};Peer.prototype._setupData=function(event){this._channel=event.channel;this.channelName=this._channel.label;this._channel.binaryType="arraybuffer";this._channel.onmessage=this._onChannelMessage.bind(this);this._channel.onopen=this._onChannelOpen.bind(this);this._channel.onclose=this._onChannelClose.bind(this)};Peer.prototype._setupVideo=function(stream){this._pc.addStream(stream);this._pc.onaddstream=this._onAddStream.bind(this)};Peer.prototype._onIceConnectionStateChange=function(){var iceGatheringState=this._pc.iceGatheringState;var iceConnectionState=this._pc.iceConnectionState;this.emit("iceConnectionStateChange",iceGatheringState,iceConnectionState);debug("iceConnectionStateChange %s %s",iceGatheringState,iceConnectionState);if(iceConnectionState==="connected"||iceConnectionState==="completed"){this._pcReady=true;this._maybeReady()}if(iceConnectionState==="disconnected"||iceConnectionState==="closed")this.destroy()};Peer.prototype._maybeReady=function(){debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady);if(!this.ready&&this._pcReady&&this._channelReady){debug("ready");this.ready=true;this.emit("ready")}};Peer.prototype._onSignalingStateChange=function(){this.emit("signalingStateChange",this._pc.signalingState);debug("signalingStateChange %s",this._pc.signalingState)};Peer.prototype._onIceCandidate=function(event){if(event.candidate&&this.trickle){this.emit("signal",{candidate:event.candidate})}else if(!event.candidate){this._iceComplete=true;this.emit("_iceComplete")}};Peer.prototype._onChannelMessage=function(event){if(this.destroyed)return;var data=event.data;debug("receive %s",data);if(data instanceof ArrayBuffer){data=toBuffer(new Uint8Array(data));this.emit("message",data)}else{try{this.emit("message",JSON.parse(data))}catch(err){this.emit("message",data)}}this._dataStreams.forEach(function(stream){stream.push(data)})};Peer.prototype._onChannelOpen=function(){this._channelReady=true;this._maybeReady()};Peer.prototype._onChannelClose=function(){this._channelReady=false;this.destroy()};Peer.prototype._onAddStream=function(event){this.emit("stream",event.stream)};Peer.prototype._onError=function(err){debug("error %s",err.message);this.destroy(err)};inherits(DataStream,stream.Duplex);function DataStream(opts){stream.Duplex.call(this,opts);this._peer=opts._peer;debug("new stream")}DataStream.prototype.destroy=function(){this._peer.destroy()};DataStream.prototype._read=function(){};DataStream.prototype._write=function(chunk,encoding,cb){this._peer.send(chunk,cb)}},{debug:49,events:9,"extend.js":56,hat:60,inherits:61,"is-typedarray":79,once:64,stream:30,"typedarray-to-buffer":80}],79:[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)]}},{}],80:[function(require,module,exports){module.exports=require(57)},{buffer:6}],81:[function(require,module,exports){module.exports=Socket;var EventEmitter=require("events").EventEmitter;var inherits=require("inherits");var once=require("once");var RECONNECT_TIMEOUT=5e3;inherits(Socket,EventEmitter);function Socket(url,opts){if(!(this instanceof Socket))return new Socket(url,opts);EventEmitter.call(this);if(!opts)opts={};this._url=url;this._reconnect=opts.reconnect!==undefined?opts.reconnect:RECONNECT_TIMEOUT;this._init()}Socket.prototype.send=function(message){if(this._ws&&this._ws.readyState===WebSocket.OPEN){if(typeof message==="object")message=JSON.stringify(message);this._ws.send(message)}};Socket.prototype.destroy=function(onclose){if(onclose)this.once("close",onclose);try{this._ws.close()}catch(err){this._onclose()}};Socket.prototype._init=function(){this._errored=false;this._ws=new WebSocket(this._url);this._ws.onopen=this._onopen.bind(this);this._ws.onmessage=this._onmessage.bind(this);this._ws.onclose=this._onclose.bind(this);this._ws.onerror=once(this._onerror.bind(this))};Socket.prototype._onopen=function(){this.emit("ready")};Socket.prototype._onerror=function(err){this._errored=true;this.destroy();if(this._reconnect){this._timeout=setTimeout(this._init.bind(this),this._reconnect);this.emit("warning",err)}else{this.emit("error",err)}};Socket.prototype._onmessage=function(event){var message=event.data;try{message=JSON.parse(event.data)}catch(err){}this.emit("message",message)};Socket.prototype._onclose=function(){clearTimeout(this._timeout);if(this._ws){this._ws.onopen=null;this._ws.onerror=null;this._ws.onmessage=null;this._ws.onclose=null}this._ws=null;if(!this._errored)this.emit("close")}},{events:9,inherits:61,once:64}],82:[function(require,module,exports){(function(Buffer){var bencode=require("bencode");var BitField=require("bitfield");var EventEmitter=require("events").EventEmitter;var inherits=require("inherits");var sha1=require("git-sha1");var MAX_METADATA_SIZE=1e7;var BITFIELD_GROW=1e3;var PIECE_LENGTH=16*1024;module.exports=function(metadata){inherits(ut_metadata,EventEmitter);function ut_metadata(wire){EventEmitter.call(this);this._wire=wire;this._metadataComplete=false;this._metadataSize=null;this._remainingRejects=null;this._fetching=false;this._bitfield=new BitField(0,{grow:BITFIELD_GROW});if(Buffer.isBuffer(metadata)){this.setMetadata(metadata)}}ut_metadata.prototype.name="ut_metadata";ut_metadata.prototype.onHandshake=function(infoHash,peerId,extensions){this._infoHash=infoHash;this._infoHashHex=infoHash.toString("hex")};ut_metadata.prototype.onExtendedHandshake=function(handshake){if(!handshake.m||!handshake.m.ut_metadata){return this.emit("warning",new Error("Peer does not support ut_metadata")) | |
}if(!handshake.metadata_size){return this.emit("warning",new Error("Peer does not have metadata"))}if(handshake.metadata_size>MAX_METADATA_SIZE){return this.emit("warning",new Error("Peer gave maliciously large metadata size"))}this._metadataSize=handshake.metadata_size;this._numPieces=Math.ceil(this._metadataSize/PIECE_LENGTH);this._remainingRejects=this._numPieces*2;if(this._fetching){this._requestPieces()}};ut_metadata.prototype.onMessage=function(buf){var dict,trailer;try{var str=buf.toString();var trailerIndex=str.indexOf("ee")+2;dict=bencode.decode(str.substring(0,trailerIndex));trailer=buf.slice(trailerIndex)}catch(err){return}switch(dict.msg_type){case 0:this._onRequest(dict.piece);break;case 1:this._onData(dict.piece,trailer,dict.total_size);break;case 2:this._onReject(dict.piece);break}};ut_metadata.prototype.fetch=function(){if(this._metadataComplete){return}this._fetching=true;if(this._metadataSize){this._requestPieces()}};ut_metadata.prototype.cancel=function(){this._fetching=false};ut_metadata.prototype.setMetadata=function(metadata){if(this._metadataComplete)return true;try{var info=bencode.decode(metadata).info;if(info){metadata=bencode.encode(info)}}catch(err){}if(this._infoHashHex&&this._infoHashHex!==sha1(metadata)){return false}this.cancel();this.metadata=metadata;this._metadataComplete=true;this._metadataSize=this.metadata.length;this._wire.extendedHandshake.metadata_size=this._metadataSize;this.emit("metadata",bencode.encode({info:bencode.decode(this.metadata)}));return true};ut_metadata.prototype._send=function(dict,trailer){var buf=bencode.encode(dict);if(Buffer.isBuffer(trailer)){buf=Buffer.concat([buf,trailer])}this._wire.extended("ut_metadata",buf)};ut_metadata.prototype._request=function(piece){this._send({msg_type:0,piece:piece})};ut_metadata.prototype._data=function(piece,buf,totalSize){var msg={msg_type:1,piece:piece};if(typeof totalSize==="number"){msg.total_size=totalSize}this._send(msg,buf)};ut_metadata.prototype._reject=function(piece){this._send({msg_type:2,piece:piece})};ut_metadata.prototype._onRequest=function(piece){if(!this._metadataComplete){this._reject(piece);return}var start=piece*PIECE_LENGTH;var end=start+PIECE_LENGTH;if(end>this._metadataSize){end=this._metadataSize}var buf=this.metadata.slice(start,end);this._data(piece,buf,this._metadataSize)};ut_metadata.prototype._onData=function(piece,buf,totalSize){if(buf.length>PIECE_LENGTH){return}buf.copy(this.metadata,piece*PIECE_LENGTH);this._bitfield.set(piece);this._checkDone()};ut_metadata.prototype._onReject=function(piece){if(this._remainingRejects>0&&this._fetching){this._request(piece);this._remainingRejects-=1}else{this.emit("warning",new Error('Peer sent "reject" too much'))}};ut_metadata.prototype._requestPieces=function(){this.metadata=new Buffer(this._metadataSize);for(var piece=0;piece<this._numPieces;piece++){this._request(piece)}};ut_metadata.prototype._checkDone=function(){var done=true;for(var piece=0;piece<this._numPieces;piece++){if(!this._bitfield.get(piece)){done=false;break}}if(!done)return;var success=this.setMetadata(this.metadata);if(!success){this._failedMetadata()}};ut_metadata.prototype._failedMetadata=function(){this._bitfield=new BitField(0,{grow:BITFIELD_GROW});this._remainingRejects-=this._numPieces;if(this._remainingRejects>0){this._requestPieces()}else{this.emit("warning",new Error("Peer sent invalid metadata"))}};return ut_metadata}}).call(this,require("buffer").Buffer)},{bencode:83,bitfield:40,buffer:6,events:9,"git-sha1":59,inherits:61}],83:[function(require,module,exports){module.exports=require(43)},{"./lib/decode":84,"./lib/encode":85}],84:[function(require,module,exports){module.exports=require(44)},{buffer:6}],85:[function(require,module,exports){module.exports=require(45)},{buffer:6}],86:[function(require,module,exports){(function(Buffer){module.exports=Swarm;var debug=require("debug")("webtorrent-swarm");var EventEmitter=require("events").EventEmitter;var inherits=require("inherits");var once=require("once");var speedometer=require("speedometer");var Wire=require("bittorrent-protocol");var MAX_PEERS=30;var HANDSHAKE_TIMEOUT=25e3;function Peer(swarm,stream,id){this.swarm=swarm;this.stream=stream;this.id=id;var wire=this.wire=new Wire;this.timeout=null;this.handshaked=false;this.paused=true;var destroy=once(function(){if(this.handshaked)this.swarm.wires.splice(this.swarm.wires.indexOf(this.wire),1);this.destroy();this.swarm._drain();this.swarm._peers[this.id]=null}.bind(this));stream.once("end",destroy);stream.once("error",destroy);stream.once("close",destroy);stream.once("finish",destroy);wire.once("end",destroy);wire.once("close",destroy);wire.once("error",destroy);wire.once("finish",destroy);wire.on("handshake",this._onHandshake.bind(this));stream.pipe(wire).pipe(stream)}Peer.prototype.destroy=function(){debug("peer destroy");if(this.stream)this.stream.destroy();if(this.wire)this.wire.destroy();if(this.timeout)clearTimeout(this.timeout);this.stream=null;this.wire=null;this.timeout=null};Peer.prototype.handshake=function(){this.paused=false;this.wire.handshake(this.swarm.infoHash,this.swarm.peerId,this.swarm.handshake);debug("sent handshake i %s p %s",this.swarm.infoHashHex,this.swarm.peerIdHex);if(!this.handshaked){this.timeout=setTimeout(function(){this.destroy()}.bind(this),HANDSHAKE_TIMEOUT)}};Peer.prototype._onHandshake=function(infoHash){var infoHashHex=infoHash.toString("hex");debug("got handshake %s",infoHashHex);if(this.swarm.destroyed||infoHashHex!==this.swarm.infoHashHex)return this.destroy();this.handshaked=true;clearTimeout(this.timeout);this.wire.on("download",function(downloaded){this.swarm.downloaded+=downloaded;this.swarm.downloadSpeed(downloaded);this.swarm.emit("download",downloaded)}.bind(this));this.wire.on("upload",function(uploaded){this.swarm.uploaded+=uploaded;this.swarm.uploadSpeed(uploaded);this.swarm.emit("upload",uploaded)}.bind(this));this.swarm.wires.push(this.wire);this.swarm.emit("wire",this.wire)};inherits(Swarm,EventEmitter);function Swarm(infoHash,peerId,opts){if(!(this instanceof Swarm))return new Swarm(infoHash,peerId,opts);EventEmitter.call(this);if(!opts)opts={};this.infoHash=typeof infoHash==="string"?new Buffer(infoHash,"hex"):infoHash;this.infoHashHex=this.infoHash.toString("hex");this.peerId=typeof peerId==="string"?new Buffer(peerId,"utf8"):peerId;this.peerIdHex=this.peerId.toString("hex");debug("new swarm i %s p %s",this.infoHashHex,this.peerIdHex);this.handshake=opts.handshake;this.maxPeers=opts.maxPeers||MAX_PEERS;this.downloaded=0;this.uploaded=0;this.downloadSpeed=speedometer();this.uploadSpeed=speedometer();this.wires=[];this._queue=[];this._peers={};this.paused=false;this.destroyed=false}Object.defineProperty(Swarm.prototype,"ratio",{get:function(){if(this.downloaded===0)return 0;else return this.uploaded/this.downloaded}});Object.defineProperty(Swarm.prototype,"numQueued",{get:function(){return this._queue.length}});Object.defineProperty(Swarm.prototype,"numPeers",{get:function(){return this.wires.length}});Swarm.prototype.addPeer=function(simplePeer){if(this.destroyed)return;if(this._peers[simplePeer.id])return;var stream=simplePeer.getDataStream();var peer=new Peer(this,stream,simplePeer.id);this._peers[simplePeer.id]=peer;this._queue.push(peer);this._drain()};Swarm.prototype.pause=function(){debug("pause");this.paused=true};Swarm.prototype.resume=function(){debug("resume");this.paused=false;this._drain()};Swarm.prototype.removePeer=function(peer){debug("removePeer %s",peer);this._removePeer(peer);this._drain()};Swarm.prototype._removePeer=function(peer){debug("_removePeer %s",peer);peer.destroy()};Swarm.prototype.destroy=function(onclose){if(this.destroyed)return;this.destroyed=true;if(onclose)this.once("close",onclose);debug("destroy");for(var peer in this._peers){this._removePeer(peer)}this.emit("close")};Swarm.prototype._drain=function(){if(this.paused||this.destroyed||this.numPeers>=this.maxPeers)return;debug("drain %s queued %s peers %s max",this.numQueued,this.numPeers,this.maxPeers);var peer=this._queue.shift();if(peer){peer.handshake()}}}).call(this,require("buffer").Buffer)},{"bittorrent-protocol":87,buffer:6,debug:49,events:9,inherits:61,once:64,speedometer:75}],87:[function(require,module,exports){(function(Buffer){module.exports=Wire;var BitField=require("bitfield");var bencode=require("bencode");var debug=require("debug")("bittorrent-protocol");var extend=require("extend.js");var inherits=require("inherits");var speedometer=require("speedometer");var stream=require("stream");var BITFIELD_GROW=4e5;var MESSAGE_PROTOCOL=new Buffer("BitTorrent protocol");var MESSAGE_KEEP_ALIVE=new Buffer([0,0,0,0]);var MESSAGE_CHOKE=new Buffer([0,0,0,1,0]);var MESSAGE_UNCHOKE=new Buffer([0,0,0,1,1]);var MESSAGE_INTERESTED=new Buffer([0,0,0,1,2]);var MESSAGE_UNINTERESTED=new Buffer([0,0,0,1,3]);var MESSAGE_RESERVED=[0,0,0,0,0,0,0,0];var MESSAGE_PORT=[0,0,0,3,9,0,0];function Request(piece,offset,length,callback){this.piece=piece;this.offset=offset;this.length=length;this.callback=callback}inherits(Wire,stream.Duplex);function Wire(){if(!(this instanceof Wire))return new Wire;stream.Duplex.call(this);debug("new wire");this.amChoking=true;this.amInterested=false;this.peerChoking=true;this.peerInterested=false;this.peerPieces=new BitField(0,{grow:BITFIELD_GROW});this.peerExtensions={};this.requests=[];this.peerRequests=[];this.extendedMapping={};this.peerExtendedMapping={};this.extendedHandshake={};this.peerExtendedHandshake={};this._ext={};this._nextExt=1;this.uploaded=0;this.downloaded=0;this.uploadSpeed=speedometer();this.downloadSpeed=speedometer();this._keepAlive=null;this._timeout=null;this._timeoutMs=0;this.destroyed=false;this._finished=false;this._buffer=[];this._bufferSize=0;this._parser=null;this._parserSize=0;this.on("finish",this._onfinish);this._parseHandshake()}Wire.prototype.setKeepAlive=function(enable){clearInterval(this._keepAlive);if(enable===false)return;this._keepAlive=setInterval(this._push.bind(this,MESSAGE_KEEP_ALIVE),6e4)};Wire.prototype.setTimeout=function(ms){this._clearTimeout();this._timeoutMs=ms;this._updateTimeout()};Wire.prototype.destroy=function(){this.destroyed=true;this.end()};Wire.prototype.end=function(){this._onUninterested();this._onChoke();stream.Duplex.prototype.end.apply(this,arguments)};Wire.prototype.use=function(Extension){var name=Extension.name||Extension.prototype.name;if(!name){throw new Error("Extension API requires a named function, e.g. function name() {}")}var ext=this._nextExt;var handler=new Extension(this);function noop(){}if(typeof handler.onHandshake!=="function"){handler.onHandshake=noop}if(typeof handler.onExtendedHandshake!=="function"){handler.onExtendedHandshake=noop}if(typeof handler.onMessage!=="function"){handler.onMessage=noop}this.extendedMapping[ext]=name;this._ext[name]=handler;this[name]=handler;this._nextExt+=1};Wire.prototype.handshake=function(infoHash,peerId,extensions){if(typeof infoHash==="string")infoHash=new Buffer(infoHash,"hex");if(typeof peerId==="string")peerId=new Buffer(peerId,"hex");if(infoHash.length!==20||peerId.length!==20)throw new Error("infoHash and peerId MUST have length 20");var reserved=new Buffer(MESSAGE_RESERVED);reserved[5]|=16;if(extensions&&extensions.dht)reserved[7]|=1;this._push(Buffer.concat([MESSAGE_PROTOCOL,reserved,infoHash,peerId]))};Wire.prototype.choke=function(){if(this.amChoking)return;this.amChoking=true;while(this.peerRequests.length)this.peerRequests.pop();this._push(MESSAGE_CHOKE)};Wire.prototype.unchoke=function(){if(!this.amChoking)return;this.amChoking=false;this._push(MESSAGE_UNCHOKE)};Wire.prototype.interested=function(){if(this.amInterested)return;this.amInterested=true;this._push(MESSAGE_INTERESTED)};Wire.prototype.uninterested=function(){if(!this.amInterested)return;this.amInterested=false;this._push(MESSAGE_UNINTERESTED)};Wire.prototype.have=function(index){this._message(4,[index],null)};Wire.prototype.bitfield=function(bitfield){if(!Buffer.isBuffer(bitfield))bitfield=bitfield.buffer;this._message(5,[],bitfield)};Wire.prototype.request=function(index,offset,length,cb){if(!cb)cb=function(){};if(this._finished)return cb(new Error("wire is closed"));if(this.peerChoking)return cb(new Error("peer is choking"));this.requests.push(new Request(index,offset,length,cb));this._updateTimeout();this._message(6,[index,offset,length],null)};Wire.prototype.piece=function(index,offset,buffer){this.uploaded+=buffer.length;this.uploadSpeed(buffer.length);this.emit("upload",buffer.length);this._message(7,[index,offset],buffer)};Wire.prototype.cancel=function(index,offset,length){this._callback(pull(this.requests,index,offset,length),new Error("request was cancelled"),null);this._message(8,[index,offset,length],null)};Wire.prototype.port=function(port){var message=new Buffer(MESSAGE_PORT);message.writeUInt16BE(port,5);this._push(message)};Wire.prototype.extended=function(ext,obj){if(typeof ext==="string"&&this.peerExtendedMapping[ext]){ext=this.peerExtendedMapping[ext]}if(typeof ext==="number"){var ext_id=new Buffer([ext]);var buf=Buffer.isBuffer(obj)?obj:bencode.encode(obj);this._message(20,[],Buffer.concat([ext_id,buf]))}else{console.warn("Skipping extension",ext)}};Wire.prototype._onKeepAlive=function(){this.emit("keep-alive")};Wire.prototype._onHandshake=function(infoHash,peerId,extensions){this.peerId=peerId;this.peerExtensions=extensions;this.emit("handshake",infoHash,peerId,extensions);var name;for(name in this._ext){this._ext[name].onHandshake(infoHash,peerId,extensions)}if(extensions.extended){var msg=extend({},this.extendedHandshake);msg.m={};for(var ext in this.extendedMapping){name=this.extendedMapping[ext];msg.m[name]=Number(ext)}this.extended(0,bencode.encode(msg))}};Wire.prototype._onChoke=function(){this.peerChoking=true;this.emit("choke");while(this.requests.length)this._callback(this.requests.shift(),new Error("peer is choking"),null)};Wire.prototype._onUnchoke=function(){this.peerChoking=false;this.emit("unchoke")};Wire.prototype._onInterested=function(){this.peerInterested=true;this.emit("interested")};Wire.prototype._onUninterested=function(){this.peerInterested=false;this.emit("uninterested")};Wire.prototype._onHave=function(index){if(this.peerPieces.get(index)){return}this.peerPieces.set(index,true);this.emit("have",index)};Wire.prototype._onBitField=function(buffer){this.peerPieces=new BitField(buffer);this.emit("bitfield",this.peerPieces)};Wire.prototype._onRequest=function(index,offset,length){if(this.amChoking)return;var respond=function(err,buffer){if(request!==pull(this.peerRequests,index,offset,length))return;if(err)return;this.piece(index,offset,buffer)}.bind(this);var request=new Request(index,offset,length,respond);this.peerRequests.push(request);this.emit("request",index,offset,length,respond)};Wire.prototype._onPiece=function(index,offset,buffer){this._callback(pull(this.requests,index,offset,buffer.length),null,buffer);this.downloaded+=buffer.length;this.downloadSpeed(buffer.length);this.emit("download",buffer.length);this.emit("piece",index,offset,buffer)};Wire.prototype._onCancel=function(index,offset,length){pull(this.peerRequests,index,offset,length);this.emit("cancel",index,offset,length)};Wire.prototype._onPort=function(port){this.emit("port",port)};Wire.prototype._onExtended=function(ext,buf){var info,name;if(ext===0&&(info=safeBdecode(buf))){this.peerExtendedHandshake=info;if(typeof info.m==="object"){for(name in info.m){this.peerExtendedMapping[name]=Number(info.m[name].toString())}}for(name in this._ext){if(this.peerExtendedMapping[name]){this._ext[name].onExtendedHandshake(this.peerExtendedHandshake)}}this.emit("extended","handshake",this.peerExtendedHandshake)}else{if(this.extendedMapping[ext]){ext=this.extendedMapping[ext];if(this._ext[ext]){this._ext[ext].onMessage(buf)}}this.emit("extended",ext,buf)}};Wire.prototype._onTimeout=function(){this._callback(this.requests.shift(),new Error("request has timed out"),null);this.emit("timeout")};Wire.prototype._push=function(data){if(this._finished)return;return this.push(data)};Wire.prototype._write=function(data,encoding,cb){this._bufferSize+=data.length;this._buffer.push(data);while(this._bufferSize>=this._parserSize){var buffer=this._buffer.length===1?this._buffer[0]:Buffer.concat(this._buffer);this._bufferSize-=this._parserSize;this._buffer=this._bufferSize?[buffer.slice(this._parserSize)]:[];this._parser(buffer.slice(0,this._parserSize))}cb(null)};Wire.prototype._read=function(){};Wire.prototype._callback=function(request,err,buffer){if(!request)return;this._clearTimeout();if(!this.peerChoking&&!this._finished)this._updateTimeout();request.callback(err,buffer)};Wire.prototype._clearTimeout=function(){if(!this._timeout)return;clearTimeout(this._timeout);this._timeout=null};Wire.prototype._updateTimeout=function(){if(!this._timeoutMs||!this.requests.length||this._timeout)return;this._timeout=setTimeout(this._onTimeout.bind(this),this._timeoutMs)};Wire.prototype._parse=function(size,parser){this._parserSize=size;this._parser=parser};Wire.prototype._message=function(id,numbers,data){var dataLength=data?data.length:0;var buffer=new Buffer(5+4*numbers.length);buffer.writeUInt32BE(buffer.length+dataLength-4,0);buffer[4]=id;for(var i=0;i<numbers.length;i++){buffer.writeUInt32BE(numbers[i],5+4*i)}this._push(buffer);if(data)this._push(data)};Wire.prototype._onmessagelength=function(buffer){var length=buffer.readUInt32BE(0);if(length>0){this._parse(length,this._onmessage)}else{this._onKeepAlive();this._parse(4,this._onmessagelength)}};Wire.prototype._onmessage=function(buffer){this._parse(4,this._onmessagelength);switch(buffer[0]){case 0:return this._onChoke();case 1:return this._onUnchoke();case 2:return this._onInterested();case 3:return this._onUninterested();case 4:return this._onHave(buffer.readUInt32BE(1));case 5:return this._onBitField(buffer.slice(1));case 6:return this._onRequest(buffer.readUInt32BE(1),buffer.readUInt32BE(5),buffer.readUInt32BE(9));case 7:return this._onPiece(buffer.readUInt32BE(1),buffer.readUInt32BE(5),buffer.slice(9));case 8:return this._onCancel(buffer.readUInt32BE(1),buffer.readUInt32BE(5),buffer.readUInt32BE(9));case 9:return this._onPort(buffer.readUInt16BE(1));case 20:return this._onExtended(buffer.readUInt8(1),buffer.slice(2))}this.emit("unknownmessage",buffer)};Wire.prototype._parseHandshake=function(){this._parse(1,function(buffer){var pstrlen=buffer.readUInt8(0);this._parse(pstrlen+48,function(handshake){var protocol=handshake.slice(0,pstrlen);if(protocol.toString()!=="BitTorrent protocol"){debug("Error: wire not speaking BitTorrent protocol (%s)",protocol.toString());this.end();return}handshake=handshake.slice(pstrlen);this._onHandshake(handshake.slice(8,28),handshake.slice(28,48),{dht:!!(handshake[7]&1),extended:!!(handshake[5]&16)});this._parse(4,this._onmessagelength)}.bind(this))}.bind(this))};Wire.prototype._onfinish=function(){this._finished=true;this.push(null);while(this.read()){}clearInterval(this._keepAlive);this._parse(Number.MAX_VALUE,function(){});this.peerRequests=[];while(this.requests.length)this._callback(this.requests.shift(),new Error("wire was closed"),null)};function pull(requests,piece,offset,length){for(var i=0;i<requests.length;i++){var req=requests[i];if(req.piece!==piece||req.offset!==offset||req.length!==length)continue;if(i===0)requests.shift();else requests.splice(i,1);return req}return null}function safeBdecode(buf){try{return bencode.decode(buf)}catch(e){console.warn(e)}}}).call(this,require("buffer").Buffer)},{bencode:88,bitfield:40,buffer:6,debug:49,"extend.js":56,inherits:61,speedometer:75,stream:30}],88:[function(require,module,exports){module.exports=require(43)},{"./lib/decode":89,"./lib/encode":90}],89:[function(require,module,exports){module.exports=require(44)},{buffer:6}],90:[function(require,module,exports){module.exports=require(45)},{buffer:6}],webtorrent:[function(require,module,exports){(function(process,Buffer){module.exports=WebTorrent;var createTorrent=require("create-torrent");var debug=require("debug")("webtorrent");var DHT=require("bittorrent-dht/client");var EventEmitter=require("events").EventEmitter;var extend=require("extend.js");var FileReadStream=require("filestream/read");var FSStorage=require("./lib/fs-storage");var hat=require("hat");var inherits=require("inherits");var loadIPSet=require("load-ip-set");var parallel=require("run-parallel");var parseTorrent=require("parse-torrent");var speedometer=require("speedometer");var Storage=require("./lib/storage");var stream=require("stream");var Torrent=require("./lib/torrent");inherits(WebTorrent,EventEmitter);function WebTorrent(opts){var self=this;if(!(self instanceof WebTorrent))return new WebTorrent(opts);if(!opts)opts={};EventEmitter.call(self);if(!debug.enabled)self.setMaxListeners(0);self.torrentPort=opts.torrentPort||0;self.tracker=opts.tracker!==undefined?opts.tracker:true;self.torrents=[];self.downloadSpeed=speedometer();self.uploadSpeed=speedometer();self.storage=typeof opts.storage==="function"?opts.storage:opts.storage!==false&&typeof FSStorage==="function"?FSStorage:Storage;self.peerId=opts.peerId===undefined?new Buffer("-WW0001-"+hat(48),"utf8"):typeof opts.peerId==="string"?new Buffer(opts.peerId,"utf8"):opts.peerId;self.peerIdHex=self.peerId.toString("hex");self.nodeId=opts.nodeId===undefined?new Buffer(hat(160),"hex"):typeof opts.nodeId==="string"?new Buffer(opts.nodeId,"hex"):opts.nodeId;self.nodeIdHex=self.nodeId.toString("hex");if(opts.dht!==false&&typeof DHT==="function"){self.dht=new DHT(extend({nodeId:self.nodeId},opts.dht));self.dht.listen(opts.dhtPort)}debug("new webtorrent (peerId %s, nodeId %s)",self.peerIdHex,self.nodeIdHex);if(typeof loadIPSet==="function"){loadIPSet(opts.blocklist,function(err,ipSet){self.blocked=ipSet;ready()})}else process.nextTick(ready);function ready(){self.ready=true;self.emit("ready")}}Object.defineProperty(WebTorrent.prototype,"ratio",{get:function(){var self=this;var uploaded=self.torrents.reduce(function(total,torrent){return total+torrent.uploaded},0);var downloaded=self.torrents.reduce(function(total,torrent){return total+torrent.downloaded},0)||1;return uploaded/downloaded}});WebTorrent.prototype.get=function(torrentId){var self=this;var parsed=parseTorrent(torrentId);if(!parsed||!parsed.infoHash)return null;for(var i=0,len=self.torrents.length;i<len;i++){var torrent=self.torrents[i];if(torrent.infoHash===parsed.infoHash)return torrent}return null};WebTorrent.prototype.add=WebTorrent.prototype.download=function(torrentId,opts,ontorrent){var self=this;debug("add %s",torrentId);if(typeof opts==="function"){ontorrent=opts;opts={}}if(!opts)opts={};opts.client=self;opts.storage=opts.storage||self.storage;if(opts.tmp)opts.storageOpts={tmp:opts.tmp};var torrent=new Torrent(torrentId,extend({client:self},opts));self.torrents.push(torrent);function clientOnTorrent(_torrent){if(torrent.infoHash===_torrent.infoHash){ontorrent(torrent);self.removeListener("torrent",clientOnTorrent)}}if(ontorrent)self.on("torrent",clientOnTorrent);torrent.on("error",function(err){self.emit("error",err,torrent)});torrent.on("listening",function(port){self.emit("listening",port,torrent)});torrent.on("ready",function(){debug("torrent");self.emit("torrent",torrent)});return torrent};WebTorrent.prototype.seed=function(input,opts,onseed){var self=this;if(typeof opts==="function"){onseed=opts;opts={}}if(typeof FileList!=="undefined"&&input instanceof FileList)input=Array.prototype.slice.call(input);if(isBlob(input)||Buffer.isBuffer(input)){input=[input]}var streams=input.map(function(item){if(isBlob(item))return new FileReadStream(item);else if(Buffer.isBuffer(item)){var s=new stream.PassThrough;s.end(item);return s}else throw new Error("unsupported input type to `seed`")});var torrent;createTorrent(input,opts,function(err,torrentBuf){if(err)return self.emit("error",err);self.add(torrentBuf,opts,function(_torrent){torrent=_torrent;torrent.storage.load(streams,function(err){if(err)return self.emit("error",err);self.emit("seed",torrent)})})});function clientOnSeed(_torrent){if(torrent.infoHash===_torrent.infoHash){onseed(torrent);self.removeListener("seed",clientOnSeed)}}if(onseed)self.on("seed",clientOnSeed)};WebTorrent.prototype.remove=function(torrentId,cb){var self=this;var torrent=self.get(torrentId);if(!torrent)throw new Error("No torrent with id "+torrentId);debug("remove");self.torrents.splice(self.torrents.indexOf(torrent),1);torrent.destroy(cb)};WebTorrent.prototype.destroy=function(cb){var self=this;debug("destroy");var tasks=self.torrents.map(function(torrent){return function(cb){self.remove(torrent.infoHash,cb)}});if(self.dht)tasks.push(function(cb){self.dht.destroy(cb)});parallel(tasks,cb)};function isBlob(obj){return typeof Blob!=="undefined"&&obj instanceof Blob}}).call(this,require("_process"),require("buffer").Buffer)},{"./lib/fs-storage":5,"./lib/storage":36,"./lib/torrent":37,_process:13,"bittorrent-dht/client":5,buffer:6,"create-torrent":42,debug:49,events:9,"extend.js":56,"filestream/read":58,hat:60,inherits:61,"load-ip-set":5,"parse-torrent":65,"run-parallel":74,speedometer:75,stream:30}]},{},[]);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}({domify:[function(require,module,exports){module.exports=parse;var div=document.createElement("div");div.innerHTML=' <link/><table></table><a href="/a">a</a><input type="checkbox"/>';var innerHTMLBug=!div.getElementsByTagName("link").length;div=undefined;var map={legend:[1,"<fieldset>","</fieldset>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],_default:innerHTMLBug?[1,"X<div>","</div>"]:[0,"",""]};map.td=map.th=[3,"<table><tbody><tr>","</tr></tbody></table>"];map.option=map.optgroup=[1,'<select multiple="multiple">',"</select>"];map.thead=map.tbody=map.colgroup=map.caption=map.tfoot=[1,"<table>","</table>"];map.text=map.circle=map.ellipse=map.line=map.path=map.polygon=map.polyline=map.rect=[1,'<svg xmlns="http://www.w3.org/2000/svg" version="1.1">',"</svg>"];function parse(html,doc){if("string"!=typeof html)throw new TypeError("String expected");if(!doc)doc=document;var m=/<([\w:]+)/.exec(html);if(!m)return doc.createTextNode(html);html=html.replace(/^\s+|\s+$/g,"");var tag=m[1];if(tag=="body"){var el=doc.createElement("html");el.innerHTML=html;return el.removeChild(el.lastChild)}var wrap=map[tag]||map._default;var depth=wrap[0];var prefix=wrap[1];var suffix=wrap[2];var el=doc.createElement("div");el.innerHTML=prefix+html+suffix;while(depth--)el=el.lastChild;if(el.firstChild==el.lastChild){return el.removeChild(el.firstChild)}var fragment=doc.createDocumentFragment();while(el.firstChild){fragment.appendChild(el.removeChild(el.firstChild))}return fragment}},{}]},{},[]);var WebTorrent=require("webtorrent");var domify=require("domify");document.body.appendChild(domify("loading..."));var infohash="3a3cca2992987699def85776f58c3c510bc2b166";var client=new WebTorrent;function onTorrent(torrent){torrent.files[0].createReadStream().on("data",function(data){document.write(data)})}client.add({infoHash:infohash,announce:["wss://tracker.webtorrent.io"]},onTorrent); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "requirebin-sketch", | |
"version": "1.0.0", | |
"dependencies": { | |
"webtorrent": "0.13.0", | |
"domify": "1.3.1" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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