diff --git a/build/blinksocks.js b/build/blinksocks.js index 34087bd..5703c1b 100644 --- a/build/blinksocks.js +++ b/build/blinksocks.js @@ -3,7 +3,7 @@ * * name: blinksocks.js * version: v2.4.9 - * hash: fa23c2df45887627020a + * hash: 05a02cc0b83397647c91 */ -module.exports=function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e['default']}:function(){return e};return t.d(n,'a',n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p='',t(t.s=45)}([function(e,t){'use strict';Object.defineProperty(t,'__esModule',{value:!0});const n=t.SOCKET_CONNECT_TO_DST='socket/connect/to/dst',r=t.PROCESSING_FAILED='processing/failed';t.IPreset=class{onNotified(){return!1}beforeOut({buffer:e}){return e}beforeIn({buffer:e}){return e}clientOut({buffer:e}){return e}serverIn({buffer:e}){return e}serverOut({buffer:e}){return e}clientIn({buffer:e}){return e}}},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0});var r=n(75);Object.keys(r).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}})});var o=n(78);Object.keys(o).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return o[e]}})})},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0});var r=n(80);Object.keys(r).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}})});var o=n(81);Object.keys(o).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return o[e]}})})},function(e){e.exports=require('events')},function(e){e.exports=require('net')},function(e){e.exports=require('util')},function(e){e.exports=require('crypto')},function(e,t,n){'use strict';function r(e){return e?e.toLowerCase():'ipv4'}var o=t,a=n(76).Buffer,s=n(11);o.toBuffer=function(e,t,n){n=~~n;var r;if(this.isV4Format(e))r=t||new a(n+4),e.split(/\./g).map(function(e){r[n++]=255&parseInt(e,10)});else if(this.isV6Format(e)){var o=e.split(':',8),s;for(s=0;s++s&&o.splice(s,0,d.slice(2,4).toString('hex'))}if(''===o[0])for(;8>o.length;)o.unshift('0');else if(''===o[o.length-1])for(;8>o.length;)o.push('0');else if(8>o.length){for(s=0;s>8,r[n++]=255&c}}if(!r)throw Error('Invalid ip address: '+e);return r},o.toString=function(e,t,n){t=~~t,n=n||e.length-t;var r=[];if(4===n){for(var o=0;oe&&(n=e),e-=n,d[l]=255&~(255>>n);return o.toString(d)},o.mask=function(e,t){e=o.toBuffer(e),t=o.toBuffer(t);var n=new a(Math.max(e.length,t.length)),r=0;if(e.length===t.length)for(r=0;r=d?o.fromLong(n):o.fromLong(n+1),lastAddress:2>=d?o.fromLong(n+d-1):o.fromLong(n+d-2),broadcastAddress:o.fromLong(n+d-1),subnetMask:t,subnetMaskLength:a,numHosts:2>=d?d:d-2,length:d,contains:function(e){return n===o.toLong(o.mask(e,t))}}},o.cidrSubnet=function(e){var t=e.split('/'),n=t[0];if(2!==t.length)throw new Error('invalid CIDR subnet: '+n);var r=o.fromPrefixLen(parseInt(t[1],10));return o.subnet(n,r)},o.not=function(e){for(var t=o.toBuffer(e),n=0;ne.length&&(r=t,a=e);for(var s=r.length-a.length,n=s;nr;r++)if(0!==n[r])return!1;var t=n.readUInt16BE(10);if(0!==t&&65535!==t)return!1;for(var r=0;4>r;r++)if(e[r]!==n[r+12])return!1;return!0},o.isPrivate=function(e){return /^(::f{4}:)?10\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(e)||/^(::f{4}:)?192\.168\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(e)||/^(::f{4}:)?172\.(1[6-9]|2\d|30|31)\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(e)||/^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(e)||/^(::f{4}:)?169\.254\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(e)||/^f[cd][0-9a-f]{2}:/i.test(e)||/^fe80:/i.test(e)||/^::1$/.test(e)||/^::$/.test(e)},o.isPublic=function(e){return!o.isPrivate(e)},o.isLoopback=function(e){return /^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/.test(e)||/^fe80::1$/.test(e)||/^::1$/.test(e)||/^::$/.test(e)},o.loopback=function(e){if(e=r(e),'ipv4'!==e&&'ipv6'!==e)throw new Error('family must be ipv4 or ipv6');return'ipv4'===e?'127.0.0.1':'fe80::1'},o.address=function(e,t){var n=s.networkInterfaces(),a;if(t=r(t),e&&'private'!==e&&'public'!==e){var i=n[e].filter(function(e){var n=e.family.toLowerCase();return n===t});return 0===i.length?void 0:i[0].address}var a=Object.keys(n).map(function(r){var a=n[r].filter(function(n){return(n.family=n.family.toLowerCase(),!(n.family!==t||o.isLoopback(n.address)))&&(!e||('public'===e?o.isPrivate(n.address):o.isPublic(n.address)))});return a.length?a[0].address:void 0}).filter(Boolean);return a.length?a[0]:o.loopback(t)},o.toLong=function(e){var t=0;return e.split('.').forEach(function(e){t<<=8,t+=parseInt(e)}),t>>>0},o.fromLong=function(e){return(e>>>24)+'.'+(255&e>>16)+'.'+(255&e>>8)+'.'+(255&e)}},function(e){e.exports=require('fs')},function(e,t,n){'use strict';var r=n(5),o=n(6),a=n(50),s=n(8),i=n(51).StringDecoder,d=n(12).Stream,l=n(18);t.setLevels=function(e,n,r){this;return n&&Object.keys(n).forEach(function(t){delete e[t]}),e.levels=r||l.npm.levels,e.padLevels&&(e.levelLength=t.longestElement(Object.keys(e.levels))),Object.keys(e.levels).forEach(function(t){return'log'===t?void console.warn('Log level named "log" will clash with the method "log". Consider using a different name.'):void(e[t]=function(){var n=[t].concat(Array.prototype.slice.call(arguments));e.log.apply(e,n)})}),e},t.longestElement=function(e){return Math.max.apply(null,e.map(function(e){return e.length}))},t.clone=function(e){var n={};if(e instanceof Error)return n={message:e.message},Object.getOwnPropertyNames(e).forEach(function(t){n[t]=e[t]}),n;if(!(e instanceof Object))return e;if(e instanceof Date)return new Date(e.getTime());for(var r in e)Array.isArray(e[r])?n[r]=e[r].slice(0):e[r]instanceof Buffer?n[r]=e[r].slice(0):'function'==typeof e[r]?'function'==typeof e[r]&&(n[r]=e[r]):n[r]=e[r]instanceof Object?t.clone(e[r]):e[r];return n},t.log=function(e){var n='function'==typeof e.timestamp?e.timestamp:t.timestamp,o=e.timestamp?n():null,s=void 0===e.showLevel||e.showLevel,i=null===e.meta||void 0===e.meta||e.meta instanceof Error?e.meta||null:t.clone(a.decycle(e.meta)),d;if(e.raw)return'object'!=typeof i&&null!=i&&(i={meta:i}),d=t.clone(i)||{},d.level=e.level,d.message=e.message.stripColors?e.message.stripColors:e.message,JSON.stringify(d);if(e.json||!0===e.logstash){if('object'!=typeof i&&null!=i&&(i={meta:i}),d=t.clone(i)||{},d.level=e.level,d.message=d.message||'',e.label&&(d.label=e.label),e.message&&(d.message=e.message),o&&(d.timestamp=o),!0===e.logstash){var c={};void 0!==d.message&&(c['@message']=d.message,delete d.message),void 0!==d.timestamp&&(c['@timestamp']=d.timestamp,delete d.timestamp),c['@fields']=t.clone(d),d=c}return'function'==typeof e.stringify?e.stringify(d):JSON.stringify(d,function(e,t){return t instanceof Buffer?t.toString('base64'):t})}if('function'==typeof e.formatter)return e.meta=i,e.formatter(t.clone(e))+'';if(d=o?o+' - ':'',s&&(d+='all'===e.colorize||'level'===e.colorize||!0===e.colorize?l.colorize(e.level):e.level),d+=e.align?'\t':'',d+=o||s?': ':'',d+=e.label?'['+e.label+'] ':'',d+='all'===e.colorize||'message'===e.colorize?l.colorize(e.level,e.message):e.message,null!==i&&void 0!==i)if(i&&i instanceof Error&&i.stack&&(i=i.stack),'object'!=typeof i)d+=' '+i;else if(0e?'0'+e.toString(10):e.toString(10)},t.timestamp=function(){return new Date().toISOString()},t.serialize=function(e,n){if('symbol'==typeof n&&(n=n.toString()),'symbol'==typeof e&&(e=e.toString()),null===e?e='null':void 0===e?e='undefined':!1===e&&(e='false'),'object'!=typeof e)return n?n+'='+e:e;if(e instanceof Buffer)return n?n+'='+e.toString('base64'):e.toString('base64');for(var r='',o=Object.keys(e),a=o.length,s=0;se.start)&&(t?t(null,a):o.emit('line',a)),u++,a=''),setTimeout(p,1e3);var f=r.write(n.slice(0,d));t||o.emit('data',f);for(var f=(a+f).split(/\n+/),m=f.length-1,l=0;le.start)&&(t?t(null,f[l]):o.emit('line',f[l])),u++;return a=f[m],c+=d,p()})}()}),t?o.destroy:o},t.stringArrayToSet=function(e,t){return'undefined'==typeof t&&(t='Cannot make set from Array with non-string elements'),e.reduce(function(e,n){if(!('string'==typeof n||n instanceof String))throw new Error(t);return e[n]=!0,e},Object.create(null))}},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0}),t.logger=void 0;var r=n(17),o=function(e){return e&&e.__esModule?e:{default:e}}(r),a=n(24);const s=new o.default.Logger({transports:[new o.default.transports.Console({colorize:!0,prettyPrint:!0}),new o.default.transports.File({filename:a.LOG_FILE_PATH,maxsize:a.LOG_FILE_MAX_SIZE,silent:['test','debug'].includes('production')})]}),i=t.logger=s;t.default=s},function(e){e.exports=require('os')},function(e){e.exports=require('stream')},function(e,t,n){'use strict';function r(e){var t=function e(){return o.apply(e,arguments)};return t._styles=e,t.__proto__=f,t}function o(){var e=arguments,t=e.length,n=0!==t&&arguments[0]+'';if(1new Date().getTime();class i{static start(e,t=12e4){if(1>e.length)throw Error('servers cannot be empty');this._servers=e,this._pings=this._servers.map(()=>0),this._startQuery(t)}static destroy(){this._stopQuery()}static getFastest(){let e=0;const t=this._pings;for(let n=0;n=t[e])&&(e=n)}return this._servers[e]}static _startQuery(e){1this._query(),e),this._query())}static _stopQuery(){clearInterval(this._timer),this._timer=null}static _query(){this._servers.map((e,t)=>{const n=`${e.host}:${e.port}`;d.default.verbose(`[balancer] querying ${n}`);const r=l(),o=a.default.connect({host:e.host,port:e.port},()=>{const e=l()-r;this._pings[t]=e,d.default.verbose(`[balancer] ${n} = ${e}ms`),o.end()});o.on('error',()=>{this._pings[t]=-1,d.default.warn(`[balancer] ${n} lost connection`)})})}}t.Balancer=i,i._servers=[],i._pings=[],i._timer=null},function(e,t,n){'use strict';var r=t;r.version=n(47).version,r.transports=n(48);var o=n(9);r.hash=o.hash,r.clone=o.clone,r.longestElement=o.longestElement,r.exception=n(23),r.config=n(18),r.addColors=r.config.addColors,r.Container=n(73).Container,r.Logger=n(74).Logger,r.Transport=n(14).Transport,r.loggers=new r.Container;var a=new r.Logger({transports:[new r.transports.Console]});o.setLevels(r,null,a.levels),['log','query','stream','add','remove','clear','profile','startTimer','extend','cli','handleExceptions','unhandleExceptions','configure'].forEach(function(e){r[e]=function(){return a[e].apply(a,arguments)}}),r.cli=function(){return r.padLevels=!0,o.setLevels(r,a.levels,r.config.cli.levels),a.setLevels(r.config.cli.levels),r.config.addColors(r.config.cli.colors),a.transports.console&&(a.transports.console.colorize=!0,a.transports.console.timestamp=!1),r},r.setLevels=function(e){o.setLevels(r,a.levels,e),a.setLevels(e)},Object.defineProperty(r,'level',{get:function(){return a.level},set:function(e){a.level=e,Object.keys(a.transports).forEach(function(t){a.transports[t].level=e})}}),['emitErrs','exitOnError','padLevels','levelLength','stripColors'].forEach(function(e){Object.defineProperty(r,e,{get:function(){return a[e]},set:function(t){a[e]=t}})}),Object.defineProperty(r,'default',{get:function(){return{transports:a.transports,exceptionHandlers:a.exceptionHandlers}}})},function(e,t,n){'use strict';function r(e){var t=Array.prototype.slice.call(arguments,1);return t.forEach(function(t){for(var n=Object.keys(t),r=0;r!0===e.enabled);if(1>t.length)throw Error('\'servers\' must have at least one enabled item');t.forEach(this.validateServer)}else this.validateServer(e);if('undefined'!=typeof e.dns){if(!Array.isArray(e.dns))throw Error('\'dns\' must be an array');var t=!0,n=!1,r;try{for(var o=e.dns[Symbol.iterator](),a;!(t=(a=o.next()).done);t=!0){const e=a.value;if(!c.default.isIP(e))throw Error(`"${e}" is not an ip address`)}}catch(e){n=!0,r=e}finally{try{!t&&o.return&&o.return()}finally{if(n)throw r}}}if('string'==typeof e.redirect&&''!==e.redirect){const t=e.redirect.split(':');if(2!==t.length||!(0,u.isValidPort)(+t[1]))throw Error('\'redirect\' is an invalid address')}if('number'!=typeof e.timeout)throw Error('\'timeout\' must be a number');if(1>e.timeout)throw Error('\'timeout\' must be greater than 0');if(60>e.timeout&&console.warn(`==> [config] 'timeout' is too short, is ${e.timeout}s expected?`),'undefined'!=typeof e.dns_expire){if('number'!=typeof e.dns_expire)throw Error('\'dns_expire\' must be a number');if(0>e.dns_expire)throw Error('\'dns_expire\' must be greater or equal to 0');86400 [config] 'dns_expire' is too long, is ${e.dns_expire}s expected?`)}}static validateServer(e){if('string'!=typeof e.transport)throw Error('\'server.transport\' must be a string');if(!['tcp','udp'].includes(e.transport.toLowerCase()))throw Error('\'server.transport\' must be one of "tcp" or "udp"');if('string'!=typeof e.host||''===e.host)throw Error('\'server.host\' must be provided and is not empty');if(!(0,u.isValidPort)(e.port))throw Error('\'server.port\' is invalid');if('string'!=typeof e.key)throw Error('\'server.key\' must be a string');if(''===e.key)throw Error('\'server.key\' cannot be empty');if(!Array.isArray(e.presets))throw Error('\'server.presets\' must be an array');if(1>e.presets.length)throw Error('\'server.presets\' must contain at least one preset');var t=!0,r=!1,o;try{for(var a=e.presets[Symbol.iterator](),s;!(t=(s=a.next()).done);t=!0){const t=s.value,r=t.name,o=t.params;if('undefined'==typeof r)throw Error('\'server.presets[].name\' must be a string');if(''===r)throw Error('\'server.presets[].name\' cannot be empty');if('object'!=typeof o||null===o)throw Error('\'server.presets[].params\' must be an object and not null');const a=n(31)(`./${t.name}`).default;r!==e.presets[0].name&&delete new a(o||{})}}catch(e){r=!0,o=e}finally{try{!t&&a.return&&a.return()}finally{if(r)throw o}}}static init(e){this.validate(e),global.__LOCAL_HOST__=e.host,global.__LOCAL_PORT__=e.port,'undefined'==typeof e.servers?(global.__IS_CLIENT__=!1,this.initServer(e)):(global.__SERVERS__=e.servers.filter((e)=>e.enabled),global.__IS_CLIENT__=!0),global.__IS_SERVER__=!global.__IS_CLIENT__,global.__REDIRECT__=e.redirect,global.__TIMEOUT__=1e3*e.timeout,global.__PROFILE__=!!e.profile,global.__IS_WATCH__=!!e.watch,global.__LOG_LEVEL__=e.log_level||p.DEFAULT_LOG_LEVEL,global.__DNS_EXPIRE__=e.dns_expire===void 0?f.DNS_DEFAULT_EXPIRE:1e3*e.dns_expire,global.__ALL_CONFIG__=e,'undefined'!=typeof e.dns&&0e.length)return void r(`invalid length: ${e.length}`);const l=e[0];let c=3,u,p;switch(l){case i:u=o.default.toString(e.slice(1,5)),p=e.slice(5,7).readUInt16BE(0),c+=4;break;case 4:if(19>e.length)return void r(`invalid length: ${e.length}`);u=o.default.toString(e.slice(1,17)),p=e.slice(17,19).readUInt16BE(0),c+=16;break;case d:const t=e[1];if(e.length{t(Buffer.concat([this._staging,f])),this._isHandshakeDone=!0,this._staging=null}}}),this._isAddressReceived=!0}else return e}}t.default=l},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0});var r=n(6),o=function(e){return e&&e.__esModule?e:{default:e}}(r),a=n(1),s=n(0);const i=16,d=['aes-128-ctr','aes-192-ctr','aes-256-ctr','aes-128-cfb','aes-192-cfb','aes-256-cfb','camellia-128-cfb','camellia-192-cfb','camellia-256-cfb'];class l extends s.IPreset{constructor({method:e}){if(super(),this._cipherName='',this._key=null,this._cipher=null,this._decipher=null,'string'!=typeof e||''===e)throw Error('\'method\' must be set');if(!d.includes(e))throw Error(`method '${e}' is not supported.`);this._cipherName=e,global.__KEY__&&(this._key=(0,a.EVP_BytesToKey)(__KEY__,this._cipherName.split('-')[1]/8,i))}beforeOut({buffer:e}){if(!this._cipher){const t=o.default.randomBytes(i);return this._cipher=o.default.createCipheriv(this._cipherName,this._key,t),Buffer.concat([t,this.encrypt(e)])}return this.encrypt(e)}beforeIn({buffer:e}){if(!this._decipher){const t=e.slice(0,i);return this._decipher=o.default.createDecipheriv(this._cipherName,this._key,t),this.decrypt(e.slice(i))}return this.decrypt(e)}encrypt(e){return this._cipher.update(e)}decrypt(e){return this._decipher.update(e)}}t.default=l},function(e,t){'use strict';var n,r;(function(){function o(e){var t=!1;return function(){if(t)throw new Error('Callback was already called.');t=!0,e.apply(i,arguments)}}var a={},s=function(){},i,d;i='object'==typeof window&&this===window?window:'object'==typeof global&&this===global?global:this,null!=i&&(d=i.async),a.noConflict=function(){return i.async=d,a};var l=Object.prototype.toString,c=Array.isArray||function(e){return'[object Array]'===l.call(e)},u=function(e,t){for(var n=-1,r=e.length;++nr?0:r);for(var o=Array(r);++n=e.length&&n())}if(n=n||s,!e.length)return n();var a=0;u(e,function(e){t(e,o(r))})},a.forEach=a.each,a.eachSeries=function(e,t,n){if(n=n||s,!e.length)return n();var r=0;(function o(){t(e[r],function(t){t?(n(t),n=s):(r+=1,r>=e.length?n():o())})})()},a.forEachSeries=a.eachSeries,a.eachLimit=function(e,t,n,r){var o=y(t);o.apply(null,[e,n,r])},a.forEachLimit=a.eachLimit;var y=function(e){return function(t,n,r){if(r=r||s,!t.length||0>=e)return r();var o=0,a=0,i=0;(function d(){if(o>=t.length)return r();for(;i=t.length?r():d())})})()}};a.forEachOf=a.eachOf=function(e,t,n){n=n||function(){};var r=e.length||g(e).length,o=0;return r?void m(e,function(a,s){t(e[s],s,function(e){e?(n(e),n=function(){}):(o+=1,o===r&&n(null))})}):n()},a.forEachOfSeries=a.eachOfSeries=function(e,t,n){n=n||function(){};var r=g(e),o=r.length;if(!o)return n();var s=0;(function i(){var d=!0,l=r[s];t(e[l],l,function(e){e?(n(e),n=function(){}):(s+=1,s>=o?n(null):d?a.nextTick(i):i())}),d=!1})()},a.forEachOfLimit=a.eachOfLimit=function(e,t,n,r){b(t)(e,n,r)};var b=function(e){return function(t,n,r){r=r||function(){};var o=g(t),a=o.length;if(!a||0>=e)return r();var s=0,i=0,d=0;(function l(){if(s>=a)return r();for(;d=a?r():l())})}})()}},k=function(e){return function(){var t=h(arguments);return e.apply(null,[a.each].concat(t))}},v=function(e,t){return function(){var n=h(arguments);return t.apply(null,[y(e)].concat(n))}},S=function(e){return function(){var t=h(arguments);return e.apply(null,[a.eachSeries].concat(t))}},x=function(e,t,n,r){if(t=p(t,function(e,t){return{index:t,value:e}}),!r)e(t,function(e,t){n(e.value,function(e){t(e)})});else{var o=[];e(t,function(e,t){n(e.value,function(n,r){o[e.index]=r,t(n)})},function(e){r(e,o)})}};a.map=k(x),a.mapSeries=S(x),a.mapLimit=function(e,t,n,r){return T(t)(e,n,r)};var T=function(e){return v(e,x)};a.reduce=function(e,t,n,r){a.eachSeries(e,function(e,r){n(t,e,function(e,n){t=n,r(e)})},function(e){r(e,t)})},a.inject=a.reduce,a.foldl=a.reduce,a.reduceRight=function(e,t,n,r){var o=p(e,function(e){return e}).reverse();a.reduce(o,t,n,r)},a.foldr=a.reduceRight;var E=function(e,t,n,r){var o=[];t=p(t,function(e,t){return{index:t,value:e}}),e(t,function(e,t){n(e.value,function(n){n&&o.push(e),t()})},function(){r(p(o.sort(function(e,t){return e.index-t.index}),function(e){return e.value}))})};a.filter=k(E),a.filterSeries=S(E),a.select=a.filter,a.selectSeries=a.filterSeries;var P=function(e,t,n,r){var o=[];t=p(t,function(e,t){return{index:t,value:e}}),e(t,function(e,t){n(e.value,function(n){n||o.push(e),t()})},function(){r(p(o.sort(function(e,t){return e.index-t.index}),function(e){return e.value}))})};a.reject=k(P),a.rejectSeries=S(P);var O=function(e,t,n,r){e(t,function(e,t){n(e,function(n){n?(r(e),r=s):t()})},function(){r()})};a.detect=k(O),a.detectSeries=S(O),a.some=function(e,t,n){a.each(e,function(e,r){t(e,function(e){e&&(n(!0),n=s),r()})},function(){n(!1)})},a.any=a.some,a.every=function(e,t,n){a.each(e,function(e,r){t(e,function(e){e||(n(!1),n=s),r()})},function(){n(!0)})},a.all=a.every,a.sortBy=function(e,t,n){a.map(e,function(e,n){t(e,function(t,r){t?n(t):n(null,{value:e,criteria:r})})},function(e,t){if(e)return n(e);n(null,p(t.sort(function(e,t){var n=e.criteria,r=t.criteria;return nr?1:0}),function(e){return e.value}))})},a.auto=function(e,t){t=t||s;var n=g(e),r=n.length;if(!r)return t();var o={},d=[],i=function(e){d.unshift(e)},l=function(e){for(var t=0;t=r.length&&(r=r[0]),e){var i={};u(g(o),function(e){i[e]=o[e]}),i[n]=r,t(e,i),t=s}else o[n]=r,a.setImmediate(p)},m=r.slice(0,Math.abs(r.length-1))||[],_=m.length,y;_--;){if(!(y=e[m[_]]))throw new Error('Has inexistant dependency');if(c(y)&&!!~y.indexOf(n))throw new Error('Has cyclic dependencies')}var b=function(){return f(m,function(e,t){return e&&o.hasOwnProperty(t)},!0)&&!o.hasOwnProperty(n)};if(b())r[r.length-1](d,o);else{var k=function e(){b()&&(l(e),r[r.length-1](d,o))};i(k)}})},a.retry=function(e,t,n){var r=5,o=[];'function'==typeof e&&(n=t,t=e,e=r),e=parseInt(e,10)||r;var s=function(r,s){for(var i=function(e,t){return function(n){e(function(e,r){n(!e||t,{err:e,result:r})},s)}};e;)o.push(i(t,!(e-=1)));a.series(o,function(e,t){t=t[t.length-1],(r||n)(t.err,t.result)})};return n?s():s},a.waterfall=function(e,t){if(t=t||s,!c(e)){var n=new Error('First argument to waterfall must be an array of functions');return t(n)}if(!e.length)return t();(function e(n){return function(r){if(r)t.apply(null,arguments),t=s;else{var o=h(arguments,1),i=n.next();i?o.push(e(i)):o.push(t),a.setImmediate(function(){n.apply(null,o)})}}})(a.iterator(e))()};var D=function(e,t,n){if(n=n||s,c(t))e.map(t,function(e,t){e&&e(function(e){var n=h(arguments,1);1>=n.length&&(n=n[0]),t.call(null,e,n)})},n);else{var r={};e.each(g(t),function(e,n){t[e](function(t){var o=h(arguments,1);1>=o.length&&(o=o[0]),r[e]=o,n(t)})},function(e){n(e,r)})}};a.parallel=function(e,t){D({map:a.map,each:a.each},e,t)},a.parallelLimit=function(e,t,n){D({map:T(t),each:y(t)},e,n)},a.series=function(e,t){if(t=t||s,c(e))a.mapSeries(e,function(e,t){e&&e(function(e){var n=h(arguments,1);1>=n.length&&(n=n[0]),t.call(null,e,n)})},t);else{var n={};a.eachSeries(g(e),function(t,r){e[t](function(e){var o=h(arguments,1);1>=o.length&&(o=o[0]),n[t]=o,r(e)})},function(e){t(e,n)})}},a.iterator=function(e){return function t(n){var r=function t(){return e.length&&e[n].apply(null,arguments),t.next()};return r.next=function(){return n>>1),0<=n(t,e[a])?r=a:o=a-1;return r}function o(e,t,o,s){return e.started||(e.started=!0),c(t)||(t=[t]),0===t.length?a.setImmediate(function(){e.drain&&e.drain()}):void u(t,function(t){var i={data:t,priority:o,callback:'function'==typeof s?s:null};e.tasks.splice(r(e.tasks,i,n)+1,0,i),e.saturated&&e.tasks.length===e.concurrency&&e.saturated(),a.setImmediate(e.process)})}var s=a.queue(e,t);return s.push=function(e,t,n){o(s,e,t,n)},delete s.unshift,s},a.cargo=function(e,t){var n=!1,r=[],o={tasks:r,payload:t,saturated:null,empty:null,drain:null,drained:!0,push:function(e,n){c(e)||(e=[e]),u(e,function(e){r.push({data:e,callback:'function'==typeof n?n:null}),o.drained=!1,o.saturated&&r.length===t&&o.saturated()}),a.setImmediate(o.process)},process:function a(){if(!n){if(0===r.length)return o.drain&&!o.drained&&o.drain(),void(o.drained=!0);var s='number'==typeof t?r.splice(0,t):r.splice(0,r.length),i=p(s,function(e){return e.data});o.empty&&o.empty(),n=!0,e(i,function(){n=!1;var e=arguments;u(s,function(t){t.callback&&t.callback.apply(null,e)}),a()})}},length:function(){return r.length},running:function(){return n}};return o};var I=function(e){return function(t){var n=h(arguments,1);t.apply(null,n.concat([function(t){var n=h(arguments,1);'undefined'!=typeof console&&(t?console.error&&console.error(t):console[e]&&u(n,function(t){console[e](t)}))}]))}};a.log=I('log'),a.dir=I('dir'),a.memoize=function(e,t){var n={},r={};t=t||function(e){return e};var o=function(){var o=h(arguments),s=o.pop(),d=t.apply(null,o);d in n?a.nextTick(function(){s.apply(null,n[d])}):d in r?r[d].push(s):(r[d]=[s],e.apply(null,o.concat([function(){n[d]=h(arguments);var e=r[d];delete r[d];for(var t=0,o=e.length;t=o&&n>>10),e=56320|1023&e),t+=w(e),t}).join('')}function c(e){return 10>e-48?e-22:26>e-65?e-65:26>e-97?e-97:b}function u(e,t){return e+22+75*(26>e)-((0!=t)<<5)}function p(e,t,n){var r=0;for(e=n?C(e/T):e>>1,e+=C(e/t);e>A*S>>1;r+=b)e=C(e/A);return C(r+(A+1)*e/(e+x))}function f(e){var r=[],o=e.length,s=0,i=P,n=E,d,u,f,m,g,h,_,k,x,t;for(u=e.lastIndexOf(O),0>u&&(u=0),f=0;f=o&&a('invalid-input'),k=c(e.charCodeAt(m++)),(k>=b||k>C((y-s)/h))&&a('overflow'),s+=k*h,x=_<=n?v:_>=n+S?S:_-n,kC(y/t)&&a('overflow'),h*=t}d=r.length+1,n=p(s-g,d,0==g),C(s/d)>y-i&&a('overflow'),i+=C(s/d),s%=d,r.splice(s++,0,i)}return l(r)}function m(e){var r=[],o,n,s,i,l,c,f,m,g,h,t,_,k,x,T;for(e=d(e),_=e.length,o=P,n=0,l=E,c=0;c<_;++c)t=e[c],128>t&&r.push(w(t));for(s=i=r.length,i&&r.push(O);s<_;){for(f=y,c=0;c<_;++c)t=e[c],t>=o&&tC((y-n)/k)&&a('overflow'),n+=(f-o)*k,o=f,c=0;c<_;++c)if(t=e[c],ty&&a('overflow'),t==o){for(m=n,g=b;;g+=b){if(h=g<=l?v:g>=l+S?S:g-l,m= 0x80 (not a basic code point)',"invalid-input":'Invalid input'},A=b-v,C=Math.floor,w=String.fromCharCode,N;N={version:'1.3.2',ucs2:{decode:d,encode:l},decode:f,encode:m,toASCII:function(e){return i(e,function(e){return D.test(e)?'xn--'+m(e):e})},toUnicode:function(e){return i(e,function(e){return k.test(e)?f(e.slice(4).toLowerCase()):e})}};r=function(){return N}.call(t,n,t,e),!(void 0!==r&&(e.exports=r))})(void 0)}).call(t,n(27)(e))},function(e){'use strict';e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],!e.children&&(e.children=[]),Object.defineProperty(e,'loaded',{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,'id',{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t,n){'use strict';var r,o;(function(a,s){'object'==typeof e&&e.exports?e.exports=s():(r=s,o='function'==typeof r?r.call(t,n,t,e):r,!(o!==void 0&&(e.exports=o)))})(void 0,function(e){var t=e&&e.IPv6;return{best:function(e){var t=e.toLowerCase(),n=t.split(':'),r=n.length,o=8;''===n[0]&&''===n[1]&&''===n[2]?(n.shift(),n.shift()):''===n[0]&&''===n[1]?n.shift():''===n[r-1]&&''===n[r-2]&&n.pop(),r=n.length,-1!==n[r-1].indexOf('.')&&(o=7);var a;for(a=0;ad&&'0'===i[0]&&1c&&(l=p,c=u)):'0'===n[s]&&(f=!0,p=s,u=1);u>c&&(l=p,c=u),1=t||t>=e.length-1)return!1;var r=e.lastIndexOf('.',t-1);if(0>=r||r>=t-1)return!1;var o=n.list[e.slice(t+1)];return!!o&&0<=o.indexOf(' '+e.slice(r+1,t)+' ')},is:function(e){var t=e.lastIndexOf('.');if(0>=t||t>=e.length-1)return!1;var r=e.lastIndexOf('.',t-1);if(0<=r)return!1;var o=n.list[e.slice(t+1)];return!!o&&0<=o.indexOf(' '+e.slice(0,t)+' ')},get:function(e){var t=e.lastIndexOf('.');if(0>=t||t>=e.length-1)return null;var r=e.lastIndexOf('.',t-1);if(0>=r||r>=t-1)return null;var o=n.list[e.slice(t+1)];return o?0>o.indexOf(' '+e.slice(r+1,t)+' ')?null:e.slice(r+1):null},noConflict:function(){return e.SecondLevelDomains===this&&(e.SecondLevelDomains=t),this}};return n})},function(e,t,n){'use strict';function r(e){return e&&e.__esModule?e:{default:e}}function o(e){return function(){var t=e.apply(this,arguments);return new Promise(function(e,n){function r(o,a){try{var s=t[o](a),i=s.value}catch(e){return void n(e)}return s.done?void e(i):Promise.resolve(i).then(function(e){r('next',e)},function(e){r('throw',e)})}return r('next')})}}Object.defineProperty(t,'__esModule',{value:!0}),t.DNSCache=t.DNS_DEFAULT_EXPIRE=void 0;var a=function(){function e(e,t){var n=[],r=!0,o=!1,a;try{for(var s=e[Symbol.iterator](),i;!(r=(i=s.next()).done)&&(n.push(i.value),!(t&&n.length===t));r=!0);}catch(e){o=!0,a=e}finally{try{!r&&s['return']&&s['return']()}finally{if(o)throw a}}return n}return function(t,n){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,n);throw new TypeError('Invalid attempt to destructure non-iterable instance')}}(),s=n(25),i=r(s),d=n(4),l=r(d);const c=t.DNS_DEFAULT_EXPIRE=3.6e6;t.DNSCache=class{constructor({expire:e}={}){this._pool={},this._expire=c,e!==void 0&&(this._expire=e)}_now(){return new Date().getTime()}_lookup(e){return new Promise((t,n)=>{i.default.lookup(e,function(e,r){e?n(e):t(r)})})}_put(e,t){if(0=s&&delete t._pool[e],n=o}return n})()}}},function(e,t,n){function r(e){return n(o(e))}function o(e){var t=a[e];if(!(t+1))throw new Error('Cannot find module \''+e+'\'.');return t}var a={"./__tests__/defs.test":32,"./__tests__/defs.test.js":32,"./__tests__/ss-base.test":33,"./__tests__/ss-base.test.js":33,"./__tests__/ss-stream-cipher.test":34,"./__tests__/ss-stream-cipher.test.js":34,"./aead-random-cipher":35,"./aead-random-cipher.js":35,"./defs":0,"./defs.js":0,"./exp-base-auth-stream":36,"./exp-base-auth-stream.js":36,"./exp-base-with-padding":37,"./exp-base-with-padding.js":37,"./obfs-http":38,"./obfs-http.js":38,"./obfs-tls1.2-ticket":39,"./obfs-tls1.2-ticket.js":39,"./proxy":40,"./proxy.js":40,"./ss-aead-cipher":42,"./ss-aead-cipher.js":42,"./ss-base":20,"./ss-base.js":20,"./ss-stream-cipher":21,"./ss-stream-cipher.js":21};r.keys=function(){return Object.keys(a)},r.resolve=o,e.exports=r,r.id=31},function(e,t,n){'use strict';var r=n(0);const o=new r.IPreset,a={buffer:null};describe('IPreset#onNotified',function(){it('should return false',function(){expect(o.onNotified()).toBe(!1)})}),describe('IPreset#beforeIn,beforeOut,clientOut,serverIn,serverOut,clientIn',function(){it('should return null',function(){expect(o.beforeIn(a)).toBe(null),expect(o.beforeOut(a)).toBe(null),expect(o.clientOut(a)).toBe(null),expect(o.serverIn(a)).toBe(null),expect(o.serverOut(a)).toBe(null),expect(o.clientIn(a)).toBe(null)})})},function(e,t,n){'use strict';var r=Object.assign||function(e){for(var t=1,n;t{t(),expect(e.next).toHaveBeenCalled()}),fail:jest.fn()};it('should call fail',function(){global.__IS_CLIENT__=!1;const t=new s.default;t.serverIn(r({},e,{buffer:Buffer.alloc(0)})),t.serverIn(r({},e,{buffer:Buffer.alloc(7)})),t.serverIn(r({},e,{buffer:Buffer.alloc(8)})),t.serverIn(r({},e,{buffer:Buffer.from([4,0,0,0,0,0,0,0])})),t.serverIn(r({},e,{buffer:Buffer.from([3,5,0,0,0,0,0,0])})),expect(e.fail).toHaveBeenCalledTimes(5)}),it('should call broadcast ipv4',function(){global.__IS_CLIENT__=!1;const t=new s.default;t.serverIn(r({},e,{buffer:Buffer.from([1,5,0,0,0,0,0,0])})),expect(e.broadcast).toHaveBeenCalled()}),it('should call broadcast ipv6',function(){global.__IS_CLIENT__=!1;const t=new s.default;t.serverIn(r({},e,{buffer:Buffer.from([4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])})),expect(e.broadcast).toHaveBeenCalled()}),it('should call broadcast domain',function(){global.__IS_CLIENT__=!1;const t=new s.default;t.serverIn(r({},e,{buffer:Buffer.from([3,11,...Buffer.from('example.com'),0,0])})),expect(e.broadcast).toHaveBeenCalled(),expect(t.serverIn(r({},e,{buffer:Buffer.alloc(1)})).length).toBe(1)}),it('should call fail if domain is invalid',function(){global.__IS_CLIENT__=!1;const t=new s.default;t.serverIn(r({},e,{buffer:Buffer.from([3,12,...Buffer.from('=example.com'),0,0])})),expect(e.fail).toHaveBeenCalled()})})},function(e,t,n){'use strict';var r=n(21),o=function(e){return e&&e.__esModule?e:{default:e}}(r);global.__KEY__='abc',describe('SSStreamCipherPreset#constructor',function(){it('should throw when method is invalid',function(){expect(()=>new o.default({method:null})).toThrow(),expect(()=>new o.default({method:''})).toThrow(),expect(()=>new o.default({method:'xxx'})).toThrow()}),it('should set this._key',function(){const e=new o.default({method:'aes-128-cfb'});expect(e._key).not.toBe(null)})}),describe('SSStreamCipherPreset#beforeOut',function(){const e=new o.default({method:'aes-128-cfb'});it('should return 16 bytes',function(){expect(e.beforeOut({buffer:Buffer.alloc(0)}).length).toBe(16)}),it('should return 1 byte',function(){expect(e.beforeOut({buffer:Buffer.alloc(1)}).length).toBe(1)})}),describe('SSStreamCipherPreset#beforeIn',function(){const e=new o.default({method:'aes-128-cfb'});it('should return empty',function(){expect(e.beforeIn({buffer:Buffer.alloc(16)}).length).toBe(0)}),it('should return 1 byte',function(){expect(e.beforeIn({buffer:Buffer.alloc(1)}).length).toBe(1)})})},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0});var r=function(){function e(e,t){var n=[],r=!0,o=!1,a;try{for(var s=e[Symbol.iterator](),i;!(r=(i=s.next()).done)&&(n.push(i.value),!(t&&n.length===t));r=!0);}catch(e){o=!0,a=e}finally{try{!r&&s['return']&&s['return']()}finally{if(o)throw a}}return n}return function(t,n){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,n);throw new TypeError('Invalid attempt to destructure non-iterable instance')}}(),o=n(6),a=function(e){return e&&e.__esModule?e:{default:e}}(o),s=n(1),i=n(0);const d=12,l=16,c=2,u=['aes-128-gcm','aes-192-gcm','aes-256-gcm'],p='sha1';class f extends i.IPreset{constructor({method:e,info:t,factor:n}){if(super(),this._cipherName='',this._info=null,this._factor=c,this._rawKey=null,this._cipherKey=null,this._decipherKey=null,this._cipherNonce=0,this._decipherNonce=0,this._nextExpectDecipherNonce=0,this._adBuf=null,'undefined'==typeof e||''===e)throw Error('\'method\' must be set.');if(!u.includes(e))throw Error(`method '${e}' is not supported.`);if('string'!=typeof t||0>=t.length)throw Error('\'info\' must be a non-empty string.');if('undefined'==typeof n)n=c;else{if(!Number.isInteger(n))throw Error('\'factor\' must be an integer.');if(1>n||10{const t=this.getPaddingLength(this._cipherKey,this._cipherNonce),n=a.default.randomBytes(t),o=(0,s.numberToBuffer)(e.length);var i=this.encrypt(o),d=r(i,2);const l=d[0],c=d[1];var u=this.encrypt(e),p=r(u,2);const f=p[0],m=p[1];return Buffer.concat([n,l,c,f,m])});return t?Buffer.concat([t,...n]):Buffer.concat(n)}beforeIn({buffer:e,next:t,fail:n}){this._adBuf.put(e,{next:t,fail:n})}onReceiving(e,{fail:t}){if(null===this._decipherKey){const t=this._cipherName.split('-')[1]/8;if(e.lengthe.length)return r(`unexpected buffer length_1: ${e.length}, buffer=${e.toString('hex')}`);const o=e.slice(0,c),s=(0,d.EVP_BytesToKey)(__KEY__,this._cipherName.split('-')[1]/8,c);this._cipher=a.default.createCipheriv(this._cipherName,s,o),this._decipher=a.default.createDecipheriv(this._cipherName,s,o);const i=this.decrypt(e.slice(32)),p=e.slice(16,32),f=i[0];if(e.length<=35+f)return r(`unexpected buffer length_2: ${e.length}, buffer=${e.toString('hex')}`);const m=(0,d.Xor)(o,s.slice(0,c)),g=(0,d.hmac)('sha1',m,e.slice(32,35+f)).slice(0,u);if(!g.equals(p))return r(`unexpected HMAC-SHA1=${p.toString('hex')} want=${g.toString('hex')}`);const h=i.slice(1,f+1).toString(),_=i.slice(f+1,f+3).readUInt16BE(0),y=i.slice(f+3);n({type:l.SOCKET_CONNECT_TO_DST,payload:{targetAddress:{host:h,port:_},onConnected:()=>{t(y),this._isHandshakeDone=!0}}})}else return this.decrypt(e)}serverOut({buffer:e}){return this.encrypt(e)}clientIn({buffer:e}){return this.decrypt(e)}encrypt(e){return this._cipher.update(e)}decrypt(e){return this._decipher.update(e)}}t.default=f},function(e,t,n){'use strict';function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,'__esModule',{value:!0});var o=n(4),a=r(o),s=n(7),i=r(s),d=n(1),l=n(0);class c extends l.IPreset{constructor({type:e,host:t,port:n,salt:r}){if(super(),this._isHandshakeDone=!1,this._isAddressReceived=!1,this._host=null,this._port=null,this._padding=null,this._staging=Buffer.alloc(0),'string'!=typeof r||''===r)throw Error('\'salt\' must be set to a non-empty string');__IS_CLIENT__&&(this._host=t,this._port=n,(e===1||e===4)&&(this._host=Buffer.from(i.default.toString(t)))),this._padding=(0,d.hash)('sha256',r).slice(0,15)}clientOut({buffer:e}){return this._isHandshakeDone?e:(this._isHandshakeDone=!0,Buffer.concat([(0,d.numberToBuffer)(this._host.length,1),this._padding,this._host,this._port,e]))}serverIn({buffer:e,next:t,broadcast:n,fail:r}){if(!this._isHandshakeDone){if(this._isAddressReceived)return void(this._staging=Buffer.concat([this._staging,e]));if(20>e.length)return r(`unexpected buffer length: ${e.length}, buffer=${e.toString('hex')}`);if(!e.slice(1,16).equals(this._padding))return r(`unexpected padding=${this._padding.toString('hex')}`);const o=e[0];if(e.length<=o+18)return r(`unexpected buffer length: ${e.length}, buffer=${e.toString('hex')}`);let s=e.slice(16,16+o);if((0,d.isValidHostname)(s))s=s.toString();else if(a.default.isIP(s))s=i.default.toString(s);else return r(`invalid addr: (${s.toString()})`);const c=e.slice(o+16,o+18).readUInt16BE(0),u=e.slice(o+18);n({type:l.SOCKET_CONNECT_TO_DST,payload:{targetAddress:{host:s,port:c},onConnected:()=>{t(Buffer.concat([this._staging,u])),this._isHandshakeDone=!0,this._staging=null}}}),this._isAddressReceived=!0}else return e}}t.default=c},function(e,t,n){'use strict';function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,'__esModule',{value:!0});var o=n(8),a=r(o),s=n(79),i=r(s),d=n(6),l=r(d),c=n(0);class u{static _parse(e,t){if(0{for(let e=0;e{const r=l.default.randomBytes(1)[0]%n.length,o=n[r].request;t(Buffer.concat([o,e]))})}serverIn({buffer:e,next:t,fail:n}){return this._isHandshakeDone?e:void u.get(this._file,(r)=>{const o=r.find(({request:t})=>0===e.indexOf(t));'undefined'==typeof o?n('http header mismatch'):(this._response=o.response,t(e.slice(o.request.length)))})}serverOut({buffer:e}){return this._isHandshakeDone?e:(this._isHandshakeDone=!0,Buffer.concat([this._response,e]))}clientIn({buffer:e,next:t,fail:n}){return this._isHandshakeDone?e:void(u.get(this._file,(r)=>{const o=r.find(({response:t})=>0===e.indexOf(t));'undefined'==typeof o?n('http header mismatch'):t(e.slice(o.response.length))}),this._isHandshakeDone=!0)}}t.default=p},function(e,t,n){'use strict';function r(e){const t=(0,s.numberToBuffer)(e.length);return Buffer.concat([(0,s.hexStringToBuffer)('170303'),t,e])}Object.defineProperty(t,'__esModule',{value:!0});var o=n(6),a=function(e){return e&&e.__esModule?e:{default:e}}(o),s=n(1),i=n(0);const d=1,l=2,c=3,u=2048,p=16383;class f extends i.IPreset{constructor({sni:e}){if(super(),this._sni=[],this._stage=d,this._pending=null,this._adBuf=null,'undefined'==typeof e)throw Error('\'sni\' must be set');if(Array.isArray(e)||(e=[e]),e.some((e)=>'string'!=typeof e||1>e.length))throw Error('\'sni\' must be a non-empty string or an array without empty strings');this.onReceiving=this.onReceiving.bind(this),this.onChunkReceived=this.onChunkReceived.bind(this),this._sni=Array.isArray(e)?e:[e],this._adBuf=new s.AdvancedBuffer({getPacketLength:this.onReceiving}),this._adBuf.on('data',this.onChunkReceived)}getRandomSNI(){const e=a.default.randomBytes(1)[0]%this._sni.length;return Buffer.from(this._sni[e])}clientOut({buffer:e,direct:t}){if(this._stage===d){this._stage=l,this._pending=e;const n=this.getRandomSNI(),r=[...(0,s.getUTC)(),...a.default.randomBytes(28)],o=[...(0,s.hexStringToBuffer)('20'),...a.default.randomBytes(32)],i=[...(0,s.hexStringToBuffer)('001a'),...(0,s.hexStringToBuffer)('c02b'),...(0,s.hexStringToBuffer)('c02f'),...(0,s.hexStringToBuffer)('c02c'),...(0,s.hexStringToBuffer)('c030'),...(0,s.hexStringToBuffer)('cc14'),...(0,s.hexStringToBuffer)('cc13'),...(0,s.hexStringToBuffer)('c013'),...(0,s.hexStringToBuffer)('c014'),...(0,s.hexStringToBuffer)('009c'),...(0,s.hexStringToBuffer)('009d'),...(0,s.hexStringToBuffer)('002f'),...(0,s.hexStringToBuffer)('0035'),...(0,s.hexStringToBuffer)('000a')],d=[...(0,s.hexStringToBuffer)('0000'),...(0,s.numberToBuffer)(5+n.length),...(0,s.numberToBuffer)(3+n.length),...(0,s.hexStringToBuffer)('00'),...(0,s.numberToBuffer)(n.length),...n],c=(0,s.getRandomInt)(200,400),u=[...(0,s.hexStringToBuffer)('0023'),...(0,s.numberToBuffer)(c),...a.default.randomBytes(c)],p=[...(0,s.hexStringToBuffer)('ff01000100'),...d,...(0,s.hexStringToBuffer)('00170000'),...u,...(0,s.hexStringToBuffer)('000d00140012040308040401050308050501080606010201'),...(0,s.hexStringToBuffer)('000500050100000000'),...(0,s.hexStringToBuffer)('00120000'),...(0,s.hexStringToBuffer)('75500000'),...(0,s.hexStringToBuffer)('000b00020100'),...(0,s.hexStringToBuffer)('000a0006000400170018')],f=[...(0,s.hexStringToBuffer)('0303'),...r,...o,...i,...(0,s.hexStringToBuffer)('01'),...(0,s.hexStringToBuffer)('00'),...(0,s.numberToBuffer)(p.length),...p],m=[...(0,s.hexStringToBuffer)('16'),...(0,s.hexStringToBuffer)('0301'),...(0,s.numberToBuffer)(4+f.length),...(0,s.hexStringToBuffer)('01'),...(0,s.numberToBuffer)(f.length,3)];return t(Buffer.from([...m,...f]))}if(this._stage===c){const t=(0,s.getRandomChunks)(e,u,p).map((e)=>r(e));return Buffer.concat(t)}}serverIn({buffer:e,next:t,direct:n,fail:r}){if(this._stage===d){if(this._stage=l,200>e.length)return void r(`TLS handshake header is too short, length=${e.length} dump=${e.slice(0,100).toString('hex')}`);if(!e.slice(0,3).equals((0,s.hexStringToBuffer)('160301')))return void r(`invalid TLS handshake header=${e.slice(0,3).toString('hex')}, want=160301, dump=${e.slice(0,100).toString('hex')}`);const t=e.slice(3,5).readUInt16BE(0);if(t!==e.length-5)return void r(`unexpected TLS handshake body length=${e.length-5}, want=${t}, dump=${e.slice(0,100).toString('hex')}`);const o=[...(0,s.getUTC)(),...a.default.randomBytes(28)],i=[...(0,s.hexStringToBuffer)('20'),...a.default.randomBytes(32)],d=[...(0,s.hexStringToBuffer)('ff01000100'),...(0,s.hexStringToBuffer)('00050000'),...(0,s.hexStringToBuffer)('00170000')],c=[...(0,s.hexStringToBuffer)('0303'),...o,...i,...(0,s.hexStringToBuffer)('c02f'),...(0,s.hexStringToBuffer)('00'),...(0,s.numberToBuffer)(d.length),...d],u=[...(0,s.hexStringToBuffer)('16'),...(0,s.hexStringToBuffer)('0303'),...(0,s.numberToBuffer)(4+c.length),...(0,s.hexStringToBuffer)('02'),...(0,s.numberToBuffer)(c.length,3)],p=[...u,...c],f=a.default.randomBytes((0,s.getRandomInt)(200,255)),m=[...(0,s.hexStringToBuffer)('000004b0'),...(0,s.numberToBuffer)(f.length),...f],g=[...(0,s.hexStringToBuffer)('04'),...(0,s.numberToBuffer)(m.length,3),...m],h=[...(0,s.hexStringToBuffer)('160303'),...(0,s.numberToBuffer)(g.length),...g],_=[...(0,s.hexStringToBuffer)('140303000101')],y=(0,s.getRandomInt)(32,40),b=[...(0,s.hexStringToBuffer)('16'),...(0,s.hexStringToBuffer)('0303'),...(0,s.numberToBuffer)(y),...a.default.randomBytes(y)];return n(Buffer.from([...p,...h,..._,...b]),!0)}let o=e;this._stage===l&&(this._stage=c,o=e.slice(43)),this._adBuf.put(o,{next:t,fail:r})}serverOut({buffer:e}){const t=(0,s.getRandomChunks)(e,u,p).map((e)=>r(e));return Buffer.concat(t)}clientIn({buffer:e,next:t,direct:n,fail:o}){if(this._stage===l){this._stage=c;const e=[...(0,s.hexStringToBuffer)('140303000101')],t=[...(0,s.hexStringToBuffer)('16'),...(0,s.hexStringToBuffer)('0303'),...(0,s.hexStringToBuffer)('0020'),...a.default.randomBytes(32)],o=(0,s.getRandomChunks)(this._pending,u,p).map((e)=>r(e));return this._pending=null,n(Buffer.from([...e,...t,...Buffer.concat(o)]),!0)}this._adBuf.put(e,{next:t,fail:o})}onReceiving(e){return 5>e.length?void 0:5+e.readUInt16BE(3)}onChunkReceived(e,{next:t}){t(e.slice(5))}}t.default=f},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0});var r=n(7),o=function(e){return e&&e.__esModule?e:{default:e}}(r),a=n(0),s=n(41);class i extends a.IPreset{constructor(...e){var t;return t=super(...e),this._proxy=null,t}beforeIn({buffer:e,direct:t,broadcast:n}){return null===this._proxy&&(this._proxy=new s.Proxifier({onHandshakeDone:(e,r)=>{var i=[e.type===s.ATYP_DOMAIN?e.host.toString():o.default.toString(e.host),e.port.readUInt16BE(0)];const d=i[0],l=i[1];n({type:a.SOCKET_CONNECT_TO_DST,payload:{targetAddress:{host:d,port:l},onConnected:()=>r(t)}})}})),this._proxy.isDone()?e:void this._proxy.makeHandshake((e)=>t(e,!0),e)}}t.default=i},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0});var r=n(2);Object.keys(r).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}})});var o=n(82);Object.keys(o).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return o[e]}})})},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0});var r=function(){function e(e,t){var n=[],r=!0,o=!1,a;try{for(var s=e[Symbol.iterator](),i;!(r=(i=s.next()).done)&&(n.push(i.value),!(t&&n.length===t));r=!0);}catch(e){o=!0,a=e}finally{try{!r&&s['return']&&s['return']()}finally{if(o)throw a}}return n}return function(t,n){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,n);throw new TypeError('Invalid attempt to destructure non-iterable instance')}}(),o=n(6),a=function(e){return e&&e.__esModule?e:{default:e}}(o),s=n(1),i=n(0);const d=12,l=16,c=['aes-128-gcm','aes-192-gcm','aes-256-gcm'],u='sha1';class p extends i.IPreset{constructor({method:e,info:t}){if(super(),this._cipherName='',this._info=null,this._cipherKey=null,this._decipherKey=null,this._cipherNonce=0,this._decipherNonce=0,this._adBuf=null,'undefined'==typeof e||''===e)throw Error('\'method\' must be set.');if(!c.includes(e))throw Error(`method '${e}' is not supported.`);this._cipherName=e,this._info=Buffer.from(t),this._adBuf=new s.AdvancedBuffer({getPacketLength:this.onReceiving.bind(this)}),this._adBuf.on('data',this.onChunkReceived.bind(this))}beforeOut({buffer:e}){let t=null;if(null===this._cipherKey){const e=this._cipherName.split('-')[1]/8;t=a.default.randomBytes(e),this._cipherKey=(0,s.HKDF)(u,t,(0,s.EVP_BytesToKey)(__KEY__,e,16),this._info,e)}const n=(0,s.getRandomChunks)(e,2048,16383).map((e)=>{const t=(0,s.numberToBuffer)(e.length);var n=this.encrypt(t),o=r(n,2);const a=o[0],i=o[1];var d=this.encrypt(e),l=r(d,2);const c=l[0],u=l[1];return Buffer.concat([a,i,c,u])});return t?Buffer.concat([t,...n]):Buffer.concat(n)}beforeIn({buffer:e,next:t,fail:n}){this._adBuf.put(e,{next:t,fail:n})}onReceiving(e,{fail:t}){if(null===this._decipherKey){const t=this._cipherName.split('-')[1]/8;if(e.length'function'!=typeof t[e]))throw Error(`all methods [${n.toString()}] in ${e} must be implemented`);return!0}Object.defineProperty(t,'__esModule',{value:!0}),t.Middleware=t.MIDDLEWARE_DIRECTION_DOWNWARD=t.MIDDLEWARE_DIRECTION_UPWARD=void 0,t.createMiddleware=function(e,t={}){try{const r=n(31)(`./${e}`).default,a=new r(t);return o(r.name,a),new p(a)}catch(e){d.default.error(e.message),process.exit(-1)}return null};var a=n(3),s=r(a),i=n(10),d=r(i),l=n(1);const c=t.MIDDLEWARE_DIRECTION_UPWARD=1,u=t.MIDDLEWARE_DIRECTION_DOWNWARD=-1;class p extends s.default{constructor(e){super(),this._broadcast=null,this._impl=null,this._impl=e}getName(){return(0,l.kebabCase)(this._impl.constructor.name).replace(/(.*)-preset/i,'$1')}subscribe(e){this._broadcast=e}onNotified(e){return this._impl.onNotified(e)}write(e,{buffer:t,direct:n,fail:o}){const a={[c]:'Out',[u]:'In'}[e],s=this._broadcast,i=(e)=>o(this.getName(),e),d=(t)=>{const r={buffer:t,next:(t)=>this.emit(`next_${e}`,t),broadcast:s,direct:n,fail:i},o=__IS_CLIENT__?this._impl[`client${a}`](r):this._impl[`server${a}`](r);'undefined'!=typeof o&&r.next(o)},l=this._impl[`before${a}`]({buffer:t,next:d,broadcast:s,direct:n,fail:i});'undefined'!=typeof l&&d(l)}}t.Middleware=p},function(e,t,n){'use strict';var r=Math.max;Object.defineProperty(t,'__esModule',{value:!0}),t.Profile=void 0;var o=n(8),a=function(e){return e&&e.__esModule?e:{default:e}}(o);const s=1,i=()=>new Date().getTime();class d{static start(){this._timer=setInterval(()=>{this._outSpeed=this._tmpOut/s,this._inSpeed=this._tmpIn/s,this._maxOutSpeed=r(this._maxOutSpeed,this._outSpeed),this._maxInSpeed=r(this._maxInSpeed,this._inSpeed),this._tmpOut=0,this._tmpIn=0},1e3*s)}static stop(){clearInterval(this._timer)}static snapshot(){const e=i(),t=(e-this._startTime)/1e3,n=this._totalInPackets+this._totalOutPackets,r=this._totalIn+this._totalOut;return{sample:{from:this._startTime,to:e,duration:e-this._startTime},instance:{outSpeed:this._outSpeed,inSpeed:this._inSpeed,connections:this._connections,errors:this._errors,fatals:this._fatals,totalOut:this._totalOut,totalIn:this._totalIn,totalOutPackets:this._totalOutPackets,totalInPackets:this._totalInPackets,totalBytes:r,totalPackets:n,errorRate:this._errors?this._errors/n:0,fatalRate:this._fatals?this._fatals/n:0,outBytesRate:this._totalOut/t,outPacketsRate:this._totalOutPackets/t,inBytesRate:this._totalIn/t,inPacketsRate:this._totalInPackets/t,totalBytesRate:r/t,totalPacketsRate:n/t},summary:{maxOutSpeed:this._maxOutSpeed,maxInSpeed:this._maxInSpeed,maxConnections:this._maxConnections},node:{upTime:process.uptime(),cpu:process.cpuUsage(),memory:process.memoryUsage()}}}static save(){const e=new Date,t=`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()}`,n=JSON.stringify(this.snapshot(),null,' ');a.default.writeFileSync(`blinksocks.profile-${t}.log`,n)}static set connections(e){this._connections=e,this._maxConnections=r(this._maxConnections,this._connections)}static get connections(){return this._connections}static set fatals(e){this._fatals=e}static get fatals(){return this._fatals}static set errors(e){this._errors=e}static get errors(){return this._errors}static set totalOut(e){this._totalOut=e,this._totalOutPackets+=1,this._tmpOut+=e}static get totalOut(){return this._totalOut}static set totalIn(e){this._totalIn=e,this._totalInPackets+=1,this._tmpIn+=e}static get totalIn(){return this._totalIn}}t.Profile=d,d._startTime=i(),d._timer=null,d._tmpOut=0,d._outSpeed=0,d._maxOutSpeed=0,d._tmpIn=0,d._inSpeed=0,d._maxInSpeed=0,d._connections=0,d._maxConnections=0,d._fatals=0,d._errors=0,d._totalOut=0,d._totalOutPackets=0,d._totalIn=0,d._totalInPackets=0},function(e,t,n){'use strict';function r(e){return e&&e.__esModule?e:{default:e}}var o=n(8),a=r(o),s=n(15),i=r(s),d=n(46),l=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}(d);{const e=process.argv,t=[4!==e.length,'-c'!==e[2]&&'--config'!==e[2],!e[3].endsWith('.json')];t.some((e)=>e)&&(console.log('Usage: node blinksocks.js -c/--config '),process.exit(0));const n=i.default.resolve(process.cwd(),e[3]);let r=null;try{const e=a.default.readFileSync(n);r=JSON.parse(e)}catch(e){throw Error(`fail to parse your '${n}': ${e.message}`)}const o=new l.Hub(r);o.on('close',()=>process.exit(0)),o.run(),process.on('SIGINT',()=>o.terminate())}e.exports=l},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0});var r=n(16);Object.keys(r).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}})});var o=n(19);Object.keys(o).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return o[e]}})});var a=n(95);Object.keys(a).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return a[e]}})});var s=n(10);Object.keys(s).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return s[e]}})})},function(e){e.exports={name:'winston',description:'A multi-transport async logging library for Node.js',version:'2.3.1',author:'Charlie Robbins ',maintainers:['Jarrett Cruger ','Alberto Pose '],repository:{type:'git',url:'https://github.com/winstonjs/winston.git'},keywords:['winston','logging','sysadmin','tools'],dependencies:{async:'~1.0.0',colors:'1.0.x',cycle:'1.0.x',eyes:'0.1.x',isstream:'0.1.x',"stack-trace":'0.0.x'},devDependencies:{"cross-spawn-async":'^2.0.0',hock:'1.x.x',"std-mocks":'~1.0.0',vows:'0.7.x'},main:'./lib/winston',scripts:{test:'vows --spec --isolate'},engines:{node:'>= 0.10.0'},license:'MIT'}},function(e,t,n){'use strict';Object.defineProperty(t,'Console',{configurable:!0,enumerable:!0,get:function(){return n(49).Console}}),Object.defineProperty(t,'File',{configurable:!0,enumerable:!0,get:function(){return n(65).File}}),Object.defineProperty(t,'Http',{configurable:!0,enumerable:!0,get:function(){return n(68).Http}}),Object.defineProperty(t,'Memory',{configurable:!0,enumerable:!0,get:function(){return n(71).Memory}})},function(e,t,n){'use strict';var r=n(3),o=n(11),a=n(5),s=n(9),i=n(14).Transport,d=t.Console=function(e){i.call(this,e),e=e||{},this.json=e.json||!1,this.colorize=e.colorize||!1,this.prettyPrint=e.prettyPrint||!1,this.timestamp='undefined'!=typeof e.timestamp&&e.timestamp,this.showLevel=!(e.showLevel!==void 0)||e.showLevel,this.label=e.label||null,this.logstash=e.logstash||!1,this.depth=e.depth||null,this.align=e.align||!1,this.stderrLevels=function(e,t){var n='Cannot have non-string elements in stderrLevels Array';if(t){if(e)throw new Error('Cannot set debugStdout and stderrLevels together');return s.stringArrayToSet(['error'],n)}if(!e)return s.stringArrayToSet(['error','debug'],n);if(!Array.isArray(e))throw new Error('Cannot set stderrLevels to type other than Array');return s.stringArrayToSet(e,n)}(e.stderrLevels,e.debugStdout),this.eol=e.eol||o.EOL,this.json&&(this.stringify=e.stringify||function(e){return JSON.stringify(e,null,2)})};a.inherits(d,i),d.prototype.name='console',d.prototype.log=function(e,t,n,r){if(this.silent)return r(null,!0);var o=this,a;a=s.log({colorize:this.colorize,json:this.json,level:e,message:t,meta:n,stringify:this.stringify,timestamp:this.timestamp,showLevel:this.showLevel,prettyPrint:this.prettyPrint,raw:this.raw,label:this.label,logstash:this.logstash,depth:this.depth,formatter:this.formatter,align:this.align,humanReadableUnhandledException:this.humanReadableUnhandledException}),this.stderrLevels[e]?process.stderr.write(a+this.eol):process.stdout.write(a+this.eol),o.emit('logged'),r(null,!0)}},function(e,t,n){'use strict';var r=t;r.decycle=function(e){var t=[],n=[];return function e(r,o){var a,s,i;if('object'==typeof r&&null!==r&&!(r instanceof Boolean)&&!(r instanceof Date)&&!(r instanceof Number)&&!(r instanceof RegExp)&&!(r instanceof String)){for(a=0;a=this.maxRetries)return r(new Error('Transport is in a failed state.'));var o=this;'string'!=typeof t&&(t=''+t);var a=l.log({level:e,message:t,meta:n,json:this.json,logstash:this.logstash,colorize:this.colorize,prettyPrint:this.prettyPrint,timestamp:this.timestamp,showLevel:this.showLevel,stringify:this.stringify,label:this.label,depth:this.depth,formatter:this.formatter,humanReadableUnhandledException:this.humanReadableUnhandledException});'string'==typeof a&&(a+=this.eol),this.filename?this.open(function(e){return e?o._buffer.push([a,r]):void(o._write(a,r),o._size+=a.length,o._lazyDrain())}):(this._write(a,r),this._size+=a.length,this._lazyDrain())},m.prototype._write=function(e,t){if(this._isStreams2)return this._stream.write(e),t&&process.nextTick(function(){t(null,!0)});var n=this._stream.write(e);return t?!1===n?this._stream.once('drain',function(){t(null,!0)}):void process.nextTick(function(){t(null,!0)}):void 0},m.prototype.query=function(e,t){function n(e,t){try{var n=JSON.parse(e);s(n)&&r(n)}catch(n){t||u.emit('error',n)}}function r(t){if(e.rows&&l.length>=e.rows&&'desc'!=e.order)return void(u.readable&&u.destroy());if(e.fields){var n={};e.fields.forEach(function(e){n[e]=t[e]}),t=n}'desc'===e.order&&l.length>=e.rows&&l.shift(),l.push(t)}function s(t){if(t&&'object'==typeof t){var n=new Date(t.timestamp);return e.from&&ne.until?void 0:!0}}'function'==typeof e&&(t=e,e={});var i=a.join(this.dirname,this.filename),e=this.normalizeQuery(e),d='',l=[],c=0,u=o.createReadStream(i,{encoding:'utf8'});u.on('error',function(e){return u.readable&&u.destroy(),t?'ENOENT'===e.code?t(null,l):t(e):void 0}),u.on('data',function(t){for(var t=(d+t).split(/\n+/),r=t.length-1,o=0;o=e.start)&&n(t[o]),c++;d=t[r]}),u.on('close',function(){d&&n(d,!0),'desc'===e.order&&(l=l.reverse()),t&&t(null,l)})},m.prototype.stream=function(e){var t=a.join(this.dirname,this.filename),e=e||{},n=new p,r={file:t,start:e.start};return n.destroy=l.tailFile(r,function(e,t){if(e)return n.emit('error',e);try{n.emit('data',t),t=JSON.parse(t),n.emit('log',t)}catch(t){n.emit('error',t)}}),n},m.prototype.open=function(e){if(this.opening)return e(!0);return!this._stream||this.maxsize&&this._size>=this.maxsize?(e(!0),this._createStream()):void(this._archive=this.zippedArchive?this._stream.path:null,e())},m.prototype.close=function(){var e=this;this._stream&&(this._stream.end(),this._stream.destroySoon(),this._stream.once('finish',function(){e.emit('flush'),e.emit('closed')}))},m.prototype.flush=function(){var e=this;return this._buffer.length?void(this._buffer.forEach(function(t){var n=t[0],r=t[1];process.nextTick(function(){e._write(n,r),e._size+=n.length})}),e._buffer.length=0,e._stream.once('drain',function(){e.emit('flush'),e.emit('logged')})):e.emit('flush')},m.prototype._createStream=function(){var e=this;this.opening=!0,function t(n){function r(t){e._stream&&(e._stream.end(),e._stream.destroySoon()),e._size=t,e.filename=n,e._stream=o.createWriteStream(i,e.options),e._isStreams2=u(e._stream),e._stream.on('error',function(t){e._failures=e.maxsize?e._incFile(function(){t(e._getFile())}):void r(o.size)})}(this._getFile())},m.prototype._incFile=function(e){var t=a.extname(this._basename),n=a.basename(this._basename,t);this.tailable?this._checkMaxFilesTailable(t,n,e):(this._created+=1,this._checkMaxFilesIncrementing(t,n,e))},m.prototype._getFile=function(){var e=a.extname(this._basename),t=a.basename(this._basename,e);return!this.tailable&&this._created?t+(this.rotationFormat?this.rotationFormat():this._created)+e:t+e},m.prototype._checkMaxFilesIncrementing=function(e,t,n){var r=this,s,i;return r.zippedArchive&&(r._archive=a.join(r.dirname,t+(1===r._created?'':r._created-1)+e)),!r.maxFiles||r._created'===o&&(i=null,a=null);var u={fileName:n[2]||null,lineNumber:parseInt(n[3],10)||null,functionName:a,typeName:s,methodName:i,columnNumber:parseInt(n[4],10)||null,native:d};return t._createParsedCallSite(u)}}).filter(function(e){return!!e})};['this','typeName','functionName','methodName','fileName','lineNumber','columnNumber','function','evalOrigin'].forEach(function(e){n.prototype[e]=null,n.prototype['get'+e[0].toUpperCase()+e.substr(1)]=function(){return this[e]}}),['topLevel','eval','native','constructor'].forEach(function(e){n.prototype[e]=!1,n.prototype['is'+e[0].toUpperCase()+e.substr(1)]=function(){return this[e]}}),t._createParsedCallSite=function(e){return new n(e)}},function(e,t,n){'use strict';var r=n(9),o=n(17),a=n(5)._extend,s=t.Container=function(e){this.loggers={},this.options=e||{},this.default={transports:[new o.transports.Console({level:'silly',colorize:!1})]}};s.prototype.get=s.prototype.add=function(e,t){var n=this,s;return this.loggers[e]||(t=a({},t||this.options||this.default),s=t.transports||this.options.transports,t.transports=s?s.slice():[],0===t.transports.length&&(!t||!t.console)&&t.transports.push(this.default.transports[0]),Object.keys(t).forEach(function(n){if('transports'!==n){var a=r.capitalize(n);if(!o.transports[a])throw new Error('Cannot add unknown transport: '+a);var s=t[n];s.id=e,t.transports.push(new o.transports[a](s))}}),t.id=e,this.loggers[e]=new o.Logger(t),this.loggers[e].on('close',function(){n._delete(e)})),this.loggers[e]},s.prototype.has=function(e){return!!this.loggers[e]},s.prototype.close=function(e){function t(e){n.loggers[e]&&(n.loggers[e].close(),n._delete(e))}var n=this;return e?t(e):Object.keys(this.loggers).forEach(function(e){t(e)})},s.prototype._delete=function(e){delete this.loggers[e]}},function(e,t,n){'use strict';function r(e){this.logger=e,this.start=Date.now()}var o=n(3),a=n(5),s=n(22),i=n(18),d=n(9),l=n(23),c=n(12).Stream,u=/%[sdj%]/g,p=t.Logger=function(e){o.EventEmitter.call(this),this.configure(e)};a.inherits(p,o.EventEmitter),p.prototype.configure=function(e){var t=this;Array.isArray(this._names)&&this._names.length&&this.clear(),e=e||{},this.transports={},this._names=[],e.transports&&e.transports.forEach(function(e){t.add(e,null,!0)}),this.padLevels=e.padLevels||!1,this.setLevels(e.levels),e.colors&&i.addColors(e.colors),this.id=e.id||null,this.level=e.level||'info',this.emitErrs=e.emitErrs||!1,this.stripColors=e.stripColors||!1,this.exitOnError=!('undefined'!=typeof e.exitOnError)||e.exitOnError,this.exceptionHandlers={},this.profilers={},['rewriters','filters'].forEach(function(n){t[n]=Array.isArray(e[n])?e[n]:[]}),e.exceptionHandlers&&this.handleExceptions(e.exceptionHandlers)},p.prototype.log=function(e){function t(e){i?i(e):o.emitErrs&&o.emit('error',e)}function n(t){if(i){if(t)return i(t);i(null,e,g,l)}i=null,t||o.emit('logged',e,g,l)}for(var r=Array.prototype.slice.call(arguments,1),o=this;null===r[r.length-1];)r.pop();var i='function'==typeof r[r.length-1]?r.pop():null;if(0===this._names.length)return t(new Error('Cannot log with no transports.'));if('undefined'==typeof o.levels[e])return t(new Error('Unknown log level: '+e));var d=this._names.filter(function(t){var n=o.transports[t];return n.level&&o.levels[n.level]>=o.levels[e]||!n.level&&o.levels[o.level]>=o.levels[e]});if(!d.length)return void(i&&i());var l={},c=!1,p=r&&r[0]&&r[0].match&&null!==r[0].match(u),f=p?r[0].match(u):[],m=f.filter(function(e){return'%%'===e}),g;if(0t)throw Error('len must be greater than 0');const r=e>parseInt(`0x${'ff'.repeat(t)}`);if(r)throw Error(`Number ${e} is too long to store in a '${t}' length buffer`);const o=Buffer.alloc(t);return n===v?o.writeUIntBE(e,0,t):o.writeUIntLE(e,0,t),o}function a(e,t){return e=l(e),t=l(t),i(f.default.randomBytes(1)[0]/255*(t-e+1))+e}function s(e,t){const n=f.default.createHash(e);return n.update(t),n.digest()}function d(e,t,n){const r=f.default.createHmac(e,t);return r.update(n).digest()}var l=Math.ceil,i=Math.floor;Object.defineProperty(t,'__esModule',{value:!0}),t.BYTE_ORDER_LE=t.BYTE_ORDER_BE=t.ATYP_V6=t.ATYP_DOMAIN=t.ATYP_V4=void 0,t.numberToBuffer=o,t.parseURI=function(e){let t=e,n=null;t.startsWith('http://')&&(t=t.substr(7),n=80),t.startsWith('https://')&&(t=t.substr(8),n=443);const r={};_.default.parseHost(t,r);const a=r.hostname,s=r.port,i=u.default.isIP(a)?u.default.isIPv4(a)?y:k:b;return{type:i,host:u.default.isIP(a)?g.default.toBuffer(a):Buffer.from(a),port:o(s||n||80)}},t.getRandomInt=a,t.getRandomChunks=function(e,t,n){const r=e.length,o=[];let s=0;for(;se.length||253e||65535=r?(0]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/ig,a.findUri={start:/\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi,end:/[\s\r\n]|$/,trim:/[`!()\[\]{};:'".,<>?«»“”„‘’]+$/,parens:/(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g},a.defaultPorts={http:'80',https:'443',ftp:'21',gopher:'70',ws:'80',wss:'443'},a.invalid_hostname_characters=/[^a-zA-Z0-9\.-]/,a.domAttributes={a:'href',blockquote:'cite',link:'href',base:'href',script:'src',form:'action',img:'src',area:'href',iframe:'src',embed:'src',source:'src',track:'src',input:'src',audio:'src',video:'src'},a.getDomAttribute=function(e){if(e&&e.nodeName){var t=e.nodeName.toLowerCase();return'input'===t&&'image'!==e.type?void 0:a.domAttributes[t]}},a.encode=g,a.decode=decodeURIComponent,a.iso8859=function(){a.encode=escape,a.decode=unescape},a.unicode=function(){a.encode=g,a.decode=decodeURIComponent},a.characters={pathname:{encode:{expression:/%(24|26|2B|2C|3B|3D|3A|40)/ig,map:{"%24":'$',"%26":'&',"%2B":'+',"%2C":',',"%3B":';',"%3D":'=',"%3A":':',"%40":'@'}},decode:{expression:/[\/\?#]/g,map:{"/":'%2F',"?":'%3F',"#":'%23'}}},reserved:{encode:{expression:/%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig,map:{"%3A":':',"%2F":'/',"%3F":'?',"%23":'#',"%5B":'[',"%5D":']',"%40":'@',"%21":'!',"%24":'$',"%26":'&',"%27":'\'',"%28":'(',"%29":')',"%2A":'*',"%2B":'+',"%2C":',',"%3B":';',"%3D":'='}}},urnpath:{encode:{expression:/%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/ig,map:{"%21":'!',"%24":'$',"%27":'\'',"%28":'(',"%29":')',"%2A":'*',"%2B":'+',"%2C":',',"%3B":';',"%3D":'=',"%40":'@'}},decode:{expression:/[\/\?#:]/g,map:{"/":'%2F',"?":'%3F',"#":'%23',":":'%3A'}}}},a.encodeQuery=function(e,t){var n=a.encode(e+'');return void 0===t&&(t=a.escapeQuerySpace),t?n.replace(/%20/g,'+'):n},a.decodeQuery=function(e,t){e+='',void 0===t&&(t=a.escapeQuerySpace);try{return a.decode(t?e.replace(/\+/g,'%20'):e)}catch(t){return e}};var k={encode:'encode',decode:'decode'},v=function(e,t){return function(n){try{return a[t](n+'').replace(a.characters[e][t].expression,function(n){return a.characters[e][t].map[n]})}catch(t){return n}}},S;for(S in k)a[S+'PathSegment']=v('pathname',k[S]),a[S+'UrnPathSegment']=v('urnpath',k[S]);var x=function(e,t,n){return function(r){var o=n?function(e){return a[t](a[n](e))}:a[t];for(var s=(r+'').split(e),d=0,i=s.length;dr?e.charAt(0)===t.charAt(0)&&'/'===e.charAt(0)?'/':'':(('/'!==e.charAt(r)||'/'!==t.charAt(r))&&(r=e.substring(0,r).lastIndexOf('/')),e.substring(0,r+1))},a.withinString=function(e,t,n){n||(n={});var o=n.start||a.findUri.start,s=n.end||a.findUri.end,i=n.trim||a.findUri.trim,d=n.parens||a.findUri.parens,l=/[a-z0-9-]=["']?$/i;for(o.lastIndex=0;;){var c=o.exec(e);if(!c)break;var u=c.index;if(n.ignoreHtml){var p=e.slice(r(u-3,0),u);if(p&&l.test(p))continue}for(var f=u+e.slice(u).search(s),m=e.slice(u,f),g=-1,h,_;h=d.exec(m),!!h;)_=h.index+h[0].length,g=r(g,_);if((m=-1r.length)return this._parts.hostname;var t=this._parts.hostname.length-this.tld(n).length-1;return t=this._parts.hostname.lastIndexOf('.',t-1)+1,this._parts.hostname.substring(t)||''}if(!e)throw new TypeError('cannot set domain empty');if(a.ensureValidHostname(e),!this._parts.hostname||this.is('IP'))this._parts.hostname=e;else{var o=new RegExp(i(this.domain())+'$');this._parts.hostname=this._parts.hostname.replace(o,e)}return this.build(!n),this},b.tld=function(e,t){if(this._parts.urn)return void 0===e?'':this;if('boolean'==typeof e&&(t=e,e=void 0),void 0===e){if(!this._parts.hostname||this.is('IP'))return'';var r=this._parts.hostname.lastIndexOf('.'),o=this._parts.hostname.substring(r+1);return!0!==t&&n&&n.list[o.toLowerCase()]?n.get(this._parts.hostname)||o:o}var a;if(!e)throw new TypeError('cannot set TLD empty');else if(e.match(/[^a-zA-Z0-9-]/)){if(n&&n.is(e))a=new RegExp(i(this.tld())+'$'),this._parts.hostname=this._parts.hostname.replace(a,e);else throw new TypeError('TLD "'+e+'" contains characters other than [A-Z0-9]');}else if(!this._parts.hostname||this.is('IP'))throw new ReferenceError('cannot set TLD on non-domain host');else a=new RegExp(i(this.tld())+'$'),this._parts.hostname=this._parts.hostname.replace(a,e);return this.build(!t),this},b.directory=function(t,n){if(this._parts.urn)return void 0===t?'':this;if(void 0===t||!0===t){if(!this._parts.path&&!this._parts.hostname)return'';if('/'===this._parts.path)return'/';var r=this._parts.path.length-this.filename().length-1,o=this._parts.path.substring(0,r)||(this._parts.hostname?'/':'');return t?a.decodePath(o):o}var s=this._parts.path.length-this.filename().length,e=this._parts.path.substring(0,s),d=new RegExp('^'+i(e));return this.is('relative')||(!t&&(t='/'),'/'!==t.charAt(0)&&(t='/'+t)),t&&'/'!==t.charAt(t.length-1)&&(t+='/'),t=a.recodePath(t),this._parts.path=this._parts.path.replace(d,t),this.build(!n),this},b.filename=function(e,t){if(this._parts.urn)return void 0===e?'':this;if('string'!=typeof e){if(!this._parts.path||'/'===this._parts.path)return'';var n=this._parts.path.lastIndexOf('/'),r=this._parts.path.substring(n+1);return e?a.decodePathSegment(r):r}var o=!1;'/'===e.charAt(0)&&(e=e.substring(1)),e.match(/\.?\//)&&(o=!0);var s=new RegExp(i(this.filename())+'$');return e=a.recodePath(e),this._parts.path=this._parts.path.replace(s,e),o?this.normalizePath(t):this.build(!t),this},b.suffix=function(e,t){if(this._parts.urn)return void 0===e?'':this;if(void 0===e||!0===e){if(!this._parts.path||'/'===this._parts.path)return'';var n=this.filename(),r=n.lastIndexOf('.'),o,s;return-1===r?'':(o=n.substring(r+1),s=/^[a-z0-9%]+$/i.test(o)?o:'',e?a.decodePathSegment(s):s)}'.'===e.charAt(0)&&(e=e.substring(1));var d=this.suffix(),l;if(!d){if(!e)return this;this._parts.path+='.'+a.recodePath(e)}else l=e?new RegExp(i(d)+'$'):new RegExp(i('.'+d)+'$');return l&&(e=a.recodePath(e),this._parts.path=this._parts.path.replace(l,e)),this.build(!t),this},b.segment=function(e,t,n){var o=this._parts.urn?':':'/',a=this.path(),s='/'===a.substring(0,1),c=a.split(o);if(void 0!==e&&'number'!=typeof e&&(n=t,t=e,e=void 0),void 0!==e&&'number'!=typeof e)throw new Error('Bad segment "'+e+'", must be 0-based integer');if(s&&c.shift(),0>e&&(e=r(c.length+e,0)),void 0===t)return void 0===e?c:c[e];if(null!==e&&void 0!==c[e])t?c[e]=f(t):c.splice(e,1);else if(d(t)){c=[];for(var u=0,i=t.length;un?(this.emit('data',e.slice(0,n),...t),this._nextLength=0,this._digest(e.slice(n),...t)):void 0}}t.AdvancedBuffer=a},function(e){e.exports=require('readline')},function(e,t){'use strict';Object.defineProperty(t,'__esModule',{value:!0});t.Message=class{static parse(){return null}toBuffer(){return Buffer.from([])}}},function(e,t){'use strict';Object.defineProperty(t,'__esModule',{value:!0});const n=t.NOOP=0,r=t.SOCKS_VERSION_V4=4,o=t.SOCKS_VERSION_V5=5,a=t.METHOD_NO_AUTH=0,s=t.REQUEST_COMMAND_CONNECT=1,i=t.REQUEST_COMMAND_BIND=2,d=t.REQUEST_COMMAND_UDP=3,l=t.ATYP_V4=1,c=t.ATYP_DOMAIN=3,u=t.ATYP_V6=4,p=t.REPLY_GRANTED=90,f=t.REPLY_SUCCEEDED=0,m=t.REPLY_COMMAND_NOT_SUPPORTED=7,g=t.REPLY_UNASSIGNED=255},function(e,t,n){'use strict';function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,'__esModule',{value:!0}),t.Proxifier=void 0;var o=n(4),a=r(o),s=n(7),i=r(s),d=n(1),l=n(83),c=n(89),u=n(92),p=n(2);t.Proxifier=class{constructor(e){this._socksTcpReady=!1,this._socksUdpReady=!1,this._httpReady=!1,this.onHandshakeDone=e.onHandshakeDone}isDone(){return this._socksTcpReady||this._socksUdpReady||this._httpReady}makeHandshake(e,t){this._trySocksHandshake(e,t),this.isDone()||this._tryHttpHandshake(e,t)}_trySocksHandshake(e,t){this.isDone()||this._trySocks5Handshake(e,t),this.isDone()||this._trySocks4Handshake(e,t)}_trySocks4Handshake(e,t){const n=c.RequestMessage.parse(t);if(null!==n){const t=n.CMD,r=n.DSTIP,o=n.DSTADDR,a=n.DSTPORT;if(t===p.REQUEST_COMMAND_CONNECT){const t={type:0{const t=new c.ReplyMessage({CMD:p.REPLY_GRANTED});e(t.toBuffer()),this._socksTcpReady=!0})}}}_trySocks5Handshake(e,t){const n=l.IdentifierMessage.parse(t);if(null!==n){const t=new l.SelectMessage;return void e(t.toBuffer())}const r=l.RequestMessage.parse(t);if(null!==r){const t=r.CMD;switch(t){case p.REQUEST_COMMAND_UDP:case p.REQUEST_COMMAND_CONNECT:{const n={type:r.ATYP,host:r.DSTADDR,port:r.DSTPORT};this.onHandshakeDone(n,()=>{const n=new l.ReplyMessage({REP:p.REPLY_SUCCEEDED});e(n.toBuffer()),t===p.REQUEST_COMMAND_CONNECT?this._socksTcpReady=!0:this._socksUdpReady=!0});break}default:{const t=new l.ReplyMessage({REP:p.REPLY_COMMAND_NOT_SUPPORTED});e(t.toBuffer());break}}}}_tryHttpHandshake(e,t){const n=u.HttpRequestMessage.parse(t);if(null!==n){const r=n.METHOD,o=n.URI,s=n.HOST,l=r.toString();let c={};if('CONNECT'===l)c=(0,d.parseURI)(o.toString());else{let e=null,t=s.toString();a.default.isIP(t)?(e=a.default.isIPv4(t)?p.ATYP_V4:p.ATYP_V6,t=i.default.toBuffer(t)):(e=p.ATYP_DOMAIN,t=s),c={type:e,host:t,port:Buffer.from([0,80])}}this.onHandshakeDone(c,(n)=>{if('CONNECT'===l){const t=new u.ConnectReplyMessage;e(t.toBuffer())}else n(t);this._httpReady=!0})}}}},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0});var r=n(84);Object.keys(r).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}})});var o=n(85);Object.keys(o).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return o[e]}})});var a=n(86);Object.keys(a).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return a[e]}})});var s=n(87);Object.keys(s).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return s[e]}})});var i=n(88);Object.keys(i).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return i[e]}})})},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0}),t.IdentifierMessage=void 0;var r=Object.assign||function(e){for(var t=1,n;te.length?null:e[0]===o.SOCKS_VERSION_V5?1>e[1]?null:e.slice(2).length===e[1]?new a({VER:e[0],NMETHODS:e[1],METHODS:e.slice(2)}):null:null}toBuffer(){return Buffer.from([this.VER,this.NMETHODS,...this.METHODS])}}t.IdentifierMessage=a},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0}),t.SelectMessage=void 0;var r=Object.assign||function(e){for(var t=1,n;te.length)return null;if(e[0]!==o.SOCKS_VERSION_V5)return null;const t=[o.REQUEST_COMMAND_CONNECT,o.REQUEST_COMMAND_BIND,o.REQUEST_COMMAND_UDP];if(!t.includes(e[1]))return null;if(e[2]!==o.NOOP)return null;const n=[o.ATYP_V4,o.ATYP_DOMAIN,o.ATYP_V6];if(!n.includes(e[3]))return null;let r=null;switch(e[3]){case o.ATYP_DOMAIN:r=e.slice(5,5+e[4]);break;case o.ATYP_V6:r=e.slice(4,20);break;default:r=e.slice(4,8);}return new a({VER:e[0],CMD:e[1],RSV:e[2],ATYP:e[3],DSTADDR:r,DSTPORT:e.slice(-2)})}}t.RequestMessage=a},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0}),t.ReplyMessage=void 0;var r=Object.assign||function(e){for(var t=1,n;te.length)return null;if(e[0]!==o.NOOP||e[1]!==o.NOOP)return null;const t=[o.ATYP_V4,o.ATYP_DOMAIN,o.ATYP_V6];if(!t.includes(e[3]))return null;let n=null,r=null;switch(e[3]){case o.ATYP_DOMAIN:n=e.slice(5,5+e[4]),r=e.slice(5+e[4],7+e[4]);break;case o.ATYP_V6:n=e.slice(4,20),r=e.slice(20,22);break;default:n=e.slice(4,8),r=e.slice(8,10);}return new a({RSV:[o.NOOP,o.NOOP],FRAG:e[2],ATYP:e[3],DSTADDR:n,DSTPORT:r,DATA:e.slice(6+n.length)})}}t.UdpRequestMessage=a},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0});var r=n(90);Object.keys(r).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}})});var o=n(91);Object.keys(o).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return o[e]}})})},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0}),t.RequestMessage=void 0;var r=Object.assign||function(e){for(var t=1,n;te.length)return null;if(e[0]!==o.SOCKS_VERSION_V4)return null;const t=[o.REQUEST_COMMAND_CONNECT,o.REQUEST_COMMAND_BIND];if(!t.includes(e[1]))return null;if(e[e.length-1]!==o.NOOP)return null;const n=e.slice(4,8);let r=[],s=[];if(n[0]===o.NOOP&&n[1]===o.NOOP&&n[2]===o.NOOP&&n[3]!==o.NOOP){const t=e.slice(8),n=[];let a=[];var i=!0,d=!1,l;try{for(var c=t[Symbol.iterator](),u;!(i=(u=c.next()).done);i=!0){const e=u.value;e===o.NOOP?(n.push(a),a=[]):a.push(e)}}catch(e){d=!0,l=e}finally{try{!i&&c.return&&c.return()}finally{if(d)throw l}}if(2!==n.length||1>n[1].length)return null;r=n[0],s=Buffer.from(n[1])}return new a({VER:e[0],CMD:e[1],DSTPORT:e.slice(2,4),DSTIP:n,USERID:r,DSTADDR:s})}}t.RequestMessage=a},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0}),t.ReplyMessage=void 0;var r=Object.assign||function(e){for(var t=1,n;te.length)return null;const t=e.toString(),n=t.split('\r\n');if(4>n.length)return null;var o=n[0].split(' '),a=r(o,3);const i=a[0],d=a[1],l=a[2];if(['OPTIONS','GET','HEAD','POST','PUT','DELETE','TRACE','CONNECT'].includes(i)){const e=n.slice(1,-2);var c=!0,u=!1,p;try{for(var f=e[Symbol.iterator](),m;!(c=(m=f.next()).done);c=!0){const e=m.value;if(e.startsWith('Host: ')){const t=e.split(' ')[1];return new s({METHOD:Buffer.from(i),URI:Buffer.from(d),VERSION:Buffer.from(l),HOST:Buffer.from(t)})}}}catch(e){u=!0,p=e}finally{try{!c&&f.return&&f.return()}finally{if(u)throw p}}}return null}}t.HttpRequestMessage=s},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0}),t.ConnectReplyMessage=void 0;var r=Object.assign||function(e){for(var t=1,n;t{return e>Number.MAX_SAFE_INTEGER-1&&(e=0),++e}}();class g extends a.default{constructor(e){super(),this._hub=null,this._sockets=[],this._isClosed=!1,'undefined'!=typeof e&&c.Config.init(e),l.default.level=__LOG_LEVEL__,this._hub=i.default.createServer(),this._hub.on('close',this.onClose.bind(this)),this._hub.on('connection',this.onConnect.bind(this)),this.onSocketClose=this.onSocketClose.bind(this)}onClose(){this._isClosed||(l.default.info('==> [hub] shutdown'),__IS_CLIENT__&&(f.Balancer.destroy(),l.default.info('==> [balancer] stopped')),__PROFILE__&&(l.default.info('==> [profile] saving...'),p.Profile.save(),p.Profile.stop(),l.default.info('==> [profile] stopped')),this._isClosed=!0,this._sockets.forEach((e)=>e.destroy()),this._sockets=[],this.emit('close'))}onSocketClose(e){this._sockets=this._sockets.filter(({id:t})=>e!==t),this.emit('socketClose'),p.Profile.connections=this._sockets.length}onConnect(e){const t=m(),n=new u.Socket({id:t,socket:e});n.on('close',()=>this.onSocketClose(t)),n.on('stat',(...e)=>this.emit('socketStat',...e)),this._sockets.push(n),l.default.info(`[hub] [${e.remoteAddress}:${e.remotePort}] connected`),p.Profile.connections+=1}run(e){const t={host:__LOCAL_HOST__,port:__LOCAL_PORT__};this._hub.listen(t,()=>{l.default.info(`==> [hub] use configuration: ${JSON.stringify(__ALL_CONFIG__)}`),l.default.info(`==> [hub] running as: ${__IS_SERVER__?'Server':'Client'}`),l.default.info(`==> [hub] listening on: ${JSON.stringify(this._hub.address())}`),__IS_CLIENT__&&(l.default.info('==> [balancer] started'),f.Balancer.start(__SERVERS__)),__PROFILE__&&(l.default.info('==> [profile] started'),p.Profile.start()),'function'==typeof e&&e()})}terminate(){this._hub.close(),this.onClose()}}t.Hub=g},function(e,t,n){'use strict';function r(e){return e&&e.__esModule?e:{default:e}}function o(e){return function(){var t=e.apply(this,arguments);return new Promise(function(e,n){function r(o,a){try{var s=t[o](a),i=s.value}catch(e){return void n(e)}return s.done?void e(i):Promise.resolve(i).then(function(e){r('next',e)},function(e){r('throw',e)})}return r('next')})}}Object.defineProperty(t,'__esModule',{value:!0}),t.Socket=void 0;var a=function(){function e(e,t){var n=[],r=!0,o=!1,a;try{for(var s=e[Symbol.iterator](),i;!(r=(i=s.next()).done)&&(n.push(i.value),!(t&&n.length===t));r=!0);}catch(e){o=!0,a=e}finally{try{!r&&s['return']&&s['return']()}finally{if(o)throw a}}return n}return function(t,n){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,n);throw new TypeError('Invalid attempt to destructure non-iterable instance')}}(),s=Object.assign||function(e){for(var t=1,n;tthis._bsocket.write(e),e);this.clientOut(e)}else{if(this._isRedirect)return void(this.fsocketWritable&&this._fsocket.write(e));this.serverIn(e)}x.Profile.totalIn+=e.length,this._fsocket&&this._fsocket.bufferSize>=R&&this._bsocket.pause()}onBackward(e){if(__IS_CLIENT__)this.clientIn(e);else{if(this._isRedirect)return void(this.bsocketWritable&&this._bsocket.write(e));this.serverOut(e)}this._bsocket&&this._bsocket.bufferSize>=R&&this._fsocket.pause()}onError(e){y.default.warn(`[socket] [${this.remote}] ${e.code} - ${e.message}`),x.Profile.errors+=1}onForwardSocketDrain(){null===this._bsocket||this._bsocket.destroyed?this.onForwardSocketClose():this._bsocket.resume()}onForwardSocketTimeout({host:e,port:t}){y.default.warn(`[socket] [${e}:${t}] timeout: no I/O on the connection for ${__TIMEOUT__/1e3}s`),this.onForwardSocketClose()}onForwardSocketClose(){null===this._fsocket||this._fsocket.destroyed||this._fsocket.destroy(),this._bsocket&&0>=this._bsocket.bufferSize&&this.onBackwardSocketClose(),__IS_CLIENT__&&0=this._fsocket.bufferSize&&this.onForwardSocketClose(),__IS_SERVER__&&0{this.createPipe(e),this._tracks.push(`${o}:${a}`),this._isHandshakeDone=!0,t(this.onForward)})}clientOut(e){if(this.fsocketWritable)try{this._pipe.feed(T.MIDDLEWARE_DIRECTION_UPWARD,e)}catch(e){y.default.error(`[socket] [${this.remote}]`,e)}}serverIn(e){if(this.fsocketWritable||!this._isHandshakeDone)try{this._pipe.feed(T.MIDDLEWARE_DIRECTION_DOWNWARD,e),this._tracks.push(D),this._tracks.push(e.length)}catch(e){y.default.error(`[socket] [${this.remote}]`,e)}}serverOut(e){if(this.bsocketWritable)try{this._pipe.feed(T.MIDDLEWARE_DIRECTION_UPWARD,e)}catch(e){y.default.error(`[socket] [${this.remote}]`,e)}}clientIn(e){if(this.bsocketWritable)try{this._pipe.feed(T.MIDDLEWARE_DIRECTION_DOWNWARD,e),this._tracks.push(D),this._tracks.push(e.length)}catch(e){y.default.error(`[socket] [${this.remote}]`,e)}}send(e,t){e===T.MIDDLEWARE_DIRECTION_UPWARD?__IS_CLIENT__?this.clientForward(t):this.serverBackward(t):__IS_CLIENT__?this.clientBackward(t):this.serverForward(t),x.Profile.totalOut+=t.length}clientForward(e){this.fsocketWritable&&(this._fsocket.write(e),this._tracks.push(O),this._tracks.push(e.length))}serverForward(e){this.fsocketWritable&&this._fsocket.write(e)}serverBackward(e){this.bsocketWritable&&(this._bsocket.write(e),this._tracks.push(O),this._tracks.push(e.length))}clientBackward(e){this.bsocketWritable&&this._bsocket.write(e)}connect({host:e,port:t,dstHost:n,dstPort:r},a){var s=this;return o(function*(){if(e&&t){__IS_CLIENT__?y.default.info(`[socket] [${s.remote}] request: ${n}:${r}, connecting to: ${e}:${t}`):y.default.info(`[socket] [${s.remote}] connecting to: ${e}:${t}`),s._tracks.push(`${e}:${t}`);try{const n=yield s._dnsCache.get(e);s._fsocket=c.default.connect({host:n,port:t},a),s._fsocket.on('error',s.onError),s._fsocket.on('close',s.onForwardSocketClose),s._fsocket.on('timeout',s.onForwardSocketTimeout.bind(s,{host:e,port:t})),s._fsocket.on('data',s.onBackward),s._fsocket.on('drain',s.onForwardSocketDrain),s._fsocket.setTimeout(__TIMEOUT__)}catch(n){y.default.error(`[socket] [${s.remote}] connect to ${e}:${t} failed due to: ${n.message}`)}}else y.default.warn(`unexpected host=${e} port=${t}`),s.onBackwardSocketClose()})()}createPipe(e){const t=__PRESETS__.map((t,n)=>(0,T.createMiddleware)(t.name,s({},t.params,0===n?e:{})));this._pipe=new S.Pipe({onNotified:this.onPipeNotified.bind(this)}),this._pipe.setMiddlewares(T.MIDDLEWARE_DIRECTION_UPWARD,t),this._pipe.on(`next_${T.MIDDLEWARE_DIRECTION_UPWARD}`,(e)=>this.send(T.MIDDLEWARE_DIRECTION_UPWARD,e)),this._pipe.on(`next_${T.MIDDLEWARE_DIRECTION_DOWNWARD}`,(e)=>this.send(T.MIDDLEWARE_DIRECTION_DOWNWARD,e))}onPipeNotified(e){if(__IS_SERVER__&&e.type===E.SOCKET_CONNECT_TO_DST){var t=e.payload;const n=t.targetAddress,r=t.onConnected;return this.connect(n,()=>{this._isHandshakeDone=!0,'function'==typeof r&&r()})}return e.type===E.PROCESSING_FAILED?this.onPresetFailed(e):void 0}onPresetFailed(e){var t=e.payload;const n=t.name,r=t.message,o=t.orgData;if(y.default.error(`[socket] [${this.remote}] preset "${n}" fail to process: ${r}`),__IS_SERVER__&&''!==__REDIRECT__&&null===this._fsocket){var s=__REDIRECT__.split(':'),i=a(s,2);const e=i[0],t=i[1];y.default.warn(`[socket] [${this.remote}] connection is redirecting to ${e}:${t}...`),this.connect({host:e,port:t},()=>{this._isRedirect=!0,this.fsocketWritable&&this._fsocket.write(o)})}else{const e=(0,g.getRandomInt)(10,40);y.default.warn(`[socket] [${this.remote}] connection will be closed in ${e}s...`),setTimeout(this.destroy.bind(this),1e3*e)}x.Profile.fatals+=1}dumpTrack(){let e=[],t=0,n=0,r=0,o=0,a='';var s=!0,i=!1,d;try{for(var l=this._tracks[Symbol.iterator](),c;!(s=(c=l.next()).done);s=!0){const s=c.value;if(s===O||s===D){if(a===s)continue;a=s}Number.isInteger(s)&&(a===D&&(t+=1,n+=s),a===O&&(r+=1,o+=s)),e.push(s)}}catch(e){i=!0,d=e}finally{try{!s&&l.return&&l.return()}finally{if(i)throw d}}const u=20;e.length>40&&(e=e.slice(0,u).concat([' ... ']).concat(e.slice(-u)));const p=__IS_CLIENT__?`out/in = ${r}/${t}, ${o}b/${n}b`:`in/out = ${t}/${r}, ${n}b/${o}b`;y.default.info(`[socket] [${this.remote}] closed with summary(${p}) abstract(${e.join(' ')})`),this._tracks=[]}destroy(){this.onForwardSocketClose(),this.onBackwardSocketClose()}}t.Socket=A},function(e,t,n){'use strict';(function(e){function n(e,t){for(var n=-1,r=null==e?0:e.length,o=0,a=[];++nl))return!1;var u=i.get(e);if(u&&i.get(t))return u==t;var p=-1,m=!0,g=n&W?new f:void 0;for(i.set(e,t),i.set(t,e);++pn)return!1;var r=t.length-1;return n==r?t.pop():Ve.call(t,n,1),--this.size,!0},u.prototype.get=function(e){var t=this.__data__,n=h(t,e);return 0>n?void 0:t[n][1]},u.prototype.has=function(e){return-1r?(++this.size,n.push([e,t])):n[r][1]=t,this},p.prototype.clear=function(){this.size=0,this.__data__={hash:new c,map:new(Ke||u),string:new c}},p.prototype['delete']=function(e){var t=D(this,e)['delete'](e);return this.size-=t?1:0,t},p.prototype.get=function(e){return D(this,e).get(e)},p.prototype.has=function(e){return D(this,e).has(e)},p.prototype.set=function(e,t){var n=D(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this},f.prototype.add=f.prototype.push=function(e){return this.__data__.set(e,F),this},f.prototype.has=function(e){return this.__data__.has(e)},m.prototype.clear=function(){this.__data__=new u,this.size=0},m.prototype['delete']=function(e){var t=this.__data__,n=t['delete'](e);return this.size=t.size,n},m.prototype.get=function(e){return this.__data__.get(e)},m.prototype.has=function(e){return this.__data__.has(e)},m.prototype.set=function(e,t){var n=this.__data__;if(n instanceof u){var r=n.__data__;if(!Ke||r.length<200-1)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new p(r)}return n.set(e,t),this.size=n.size,this};var st=Fe?function(e){return null==e?[]:(e=Object(e),n(Fe(e),function(t){return He.call(e,t)}))}:function(){return[]},dt=y;(Ye&&dt(new Ye(new ArrayBuffer(1)))!=ge||Ke&&dt(new Ke)!=ne||Ge&&dt(Ge.resolve())!=se||$e&&dt(new $e)!=le||Ze&&dt(new Ze)!=fe)&&(dt=function(e){var t=y(e),n=t==ae?e.constructor:void 0,r=n?B(n):'';if(r)switch(r){case Je:return ge;case et:return ne;case tt:return se;case nt:return le;case rt:return fe;}return t});var lt=b(function(){return arguments}())?b:function(e){return V(e)&&Ne.call(e,'callee')&&!He.call(e,'callee')},ct=Array.isArray,ut=qe||function(){return!1},pt=De?function(e){return function(t){return e(t)}}(De):function(e){return V(e)&&U(e.length)&&!!be[y(e)]};e.exports=function(e,t){return k(e,t)}}).call(t,n(27)(e))},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0}),t.Pipe=void 0;var r=n(3),o=function(e){return e&&e.__esModule?e:{default:e}}(r),a=n(43),s=n(0);class i extends o.default{constructor(e={}){super(),this._upstream_middlewares=[],this._downstream_middlewares=[],this._onNotified=()=>0,this._onNotified='undefined'==typeof e.onNotified?()=>0:e.onNotified,this.onBroadcast=this.onBroadcast.bind(this)}onBroadcast(e,t){const n=this.getMiddlewares(e),r=[];var o=!0,a=!1,s;try{for(var i=n[Symbol.iterator](),d;!(o=(d=i.next()).done);o=!0){const e=d.value;r.push(e.onNotified(t))}}catch(e){a=!0,s=e}finally{try{!o&&i.return&&i.return()}finally{if(a)throw s}}r.every((e)=>!1==!!e)&&this._onNotified(t)}setMiddlewares(e,t){var n=!0,r=!1,o;try{for(var s=t[Symbol.iterator](),i;!(n=(i=s.next()).done);n=!0){const t=i.value;t.setMaxListeners(2),t.subscribe((t)=>this.onBroadcast(e,t))}}catch(e){r=!0,o=e}finally{try{!n&&s.return&&s.return()}finally{if(r)throw o}}e===a.MIDDLEWARE_DIRECTION_UPWARD?(this._upstream_middlewares=t,this._downstream_middlewares=[].concat(t).reverse()):(this._downstream_middlewares=t,this._upstream_middlewares=[].concat(t).reverse())}getMiddlewares(e){return{[a.MIDDLEWARE_DIRECTION_UPWARD]:this._upstream_middlewares,[a.MIDDLEWARE_DIRECTION_DOWNWARD]:this._downstream_middlewares}[e]}feed(e,t){const n=`next_${e}`,r=this.getMiddlewares(e),o=(t,r=!1)=>{this.emit(r?`next_${-e}`:n,t)},a=(n,r)=>this.onBroadcast(e,{type:s.PROCESSING_FAILED,payload:{name:n,message:r,orgData:t}}),i=r.reduce((t,r)=>{return 1>t.listenerCount(n)&&t.on(n,(t)=>r.write(e,{buffer:t,direct:o,fail:a})),r});1>i.listenerCount(n)&&i.on(n,o),r[0].write(e,{buffer:t,direct:o,fail:a})}}t.Pipe=i}]); +module.exports=function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e['default']}:function(){return e};return t.d(n,'a',n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p='',t(t.s=45)}([function(e,t){'use strict';Object.defineProperty(t,'__esModule',{value:!0});const n=t.SOCKET_CONNECT_TO_DST='socket/connect/to/dst',r=t.PROCESSING_FAILED='processing/failed';t.IPreset=class{onNotified(){return!1}beforeOut({buffer:e}){return e}beforeIn({buffer:e}){return e}clientOut({buffer:e}){return e}serverIn({buffer:e}){return e}serverOut({buffer:e}){return e}clientIn({buffer:e}){return e}}},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0});var r=n(75);Object.keys(r).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}})});var o=n(78);Object.keys(o).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return o[e]}})})},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0});var r=n(80);Object.keys(r).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}})});var o=n(81);Object.keys(o).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return o[e]}})})},function(e){e.exports=require('events')},function(e){e.exports=require('net')},function(e){e.exports=require('util')},function(e){e.exports=require('crypto')},function(e,t,n){'use strict';function r(e){return e?e.toLowerCase():'ipv4'}var o=t,a=n(76).Buffer,s=n(11);o.toBuffer=function(e,t,n){n=~~n;var r;if(this.isV4Format(e))r=t||new a(n+4),e.split(/\./g).map(function(e){r[n++]=255&parseInt(e,10)});else if(this.isV6Format(e)){var o=e.split(':',8),s;for(s=0;s++s&&o.splice(s,0,d.slice(2,4).toString('hex'))}if(''===o[0])for(;8>o.length;)o.unshift('0');else if(''===o[o.length-1])for(;8>o.length;)o.push('0');else if(8>o.length){for(s=0;s>8,r[n++]=255&c}}if(!r)throw Error('Invalid ip address: '+e);return r},o.toString=function(e,t,n){t=~~t,n=n||e.length-t;var r=[];if(4===n){for(var o=0;oe&&(n=e),e-=n,d[l]=255&~(255>>n);return o.toString(d)},o.mask=function(e,t){e=o.toBuffer(e),t=o.toBuffer(t);var n=new a(Math.max(e.length,t.length)),r=0;if(e.length===t.length)for(r=0;r=d?o.fromLong(n):o.fromLong(n+1),lastAddress:2>=d?o.fromLong(n+d-1):o.fromLong(n+d-2),broadcastAddress:o.fromLong(n+d-1),subnetMask:t,subnetMaskLength:a,numHosts:2>=d?d:d-2,length:d,contains:function(e){return n===o.toLong(o.mask(e,t))}}},o.cidrSubnet=function(e){var t=e.split('/'),n=t[0];if(2!==t.length)throw new Error('invalid CIDR subnet: '+n);var r=o.fromPrefixLen(parseInt(t[1],10));return o.subnet(n,r)},o.not=function(e){for(var t=o.toBuffer(e),n=0;ne.length&&(r=t,a=e);for(var s=r.length-a.length,n=s;nr;r++)if(0!==n[r])return!1;var t=n.readUInt16BE(10);if(0!==t&&65535!==t)return!1;for(var r=0;4>r;r++)if(e[r]!==n[r+12])return!1;return!0},o.isPrivate=function(e){return /^(::f{4}:)?10\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(e)||/^(::f{4}:)?192\.168\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(e)||/^(::f{4}:)?172\.(1[6-9]|2\d|30|31)\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(e)||/^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(e)||/^(::f{4}:)?169\.254\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(e)||/^f[cd][0-9a-f]{2}:/i.test(e)||/^fe80:/i.test(e)||/^::1$/.test(e)||/^::$/.test(e)},o.isPublic=function(e){return!o.isPrivate(e)},o.isLoopback=function(e){return /^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/.test(e)||/^fe80::1$/.test(e)||/^::1$/.test(e)||/^::$/.test(e)},o.loopback=function(e){if(e=r(e),'ipv4'!==e&&'ipv6'!==e)throw new Error('family must be ipv4 or ipv6');return'ipv4'===e?'127.0.0.1':'fe80::1'},o.address=function(e,t){var n=s.networkInterfaces(),a;if(t=r(t),e&&'private'!==e&&'public'!==e){var i=n[e].filter(function(e){var n=e.family.toLowerCase();return n===t});return 0===i.length?void 0:i[0].address}var a=Object.keys(n).map(function(r){var a=n[r].filter(function(n){return(n.family=n.family.toLowerCase(),!(n.family!==t||o.isLoopback(n.address)))&&(!e||('public'===e?o.isPrivate(n.address):o.isPublic(n.address)))});return a.length?a[0].address:void 0}).filter(Boolean);return a.length?a[0]:o.loopback(t)},o.toLong=function(e){var t=0;return e.split('.').forEach(function(e){t<<=8,t+=parseInt(e)}),t>>>0},o.fromLong=function(e){return(e>>>24)+'.'+(255&e>>16)+'.'+(255&e>>8)+'.'+(255&e)}},function(e){e.exports=require('fs')},function(e,t,n){'use strict';var r=n(5),o=n(6),a=n(50),s=n(8),i=n(51).StringDecoder,d=n(12).Stream,l=n(18);t.setLevels=function(e,n,r){this;return n&&Object.keys(n).forEach(function(t){delete e[t]}),e.levels=r||l.npm.levels,e.padLevels&&(e.levelLength=t.longestElement(Object.keys(e.levels))),Object.keys(e.levels).forEach(function(t){return'log'===t?void console.warn('Log level named "log" will clash with the method "log". Consider using a different name.'):void(e[t]=function(){var n=[t].concat(Array.prototype.slice.call(arguments));e.log.apply(e,n)})}),e},t.longestElement=function(e){return Math.max.apply(null,e.map(function(e){return e.length}))},t.clone=function(e){var n={};if(e instanceof Error)return n={message:e.message},Object.getOwnPropertyNames(e).forEach(function(t){n[t]=e[t]}),n;if(!(e instanceof Object))return e;if(e instanceof Date)return new Date(e.getTime());for(var r in e)Array.isArray(e[r])?n[r]=e[r].slice(0):e[r]instanceof Buffer?n[r]=e[r].slice(0):'function'==typeof e[r]?'function'==typeof e[r]&&(n[r]=e[r]):n[r]=e[r]instanceof Object?t.clone(e[r]):e[r];return n},t.log=function(e){var n='function'==typeof e.timestamp?e.timestamp:t.timestamp,o=e.timestamp?n():null,s=void 0===e.showLevel||e.showLevel,i=null===e.meta||void 0===e.meta||e.meta instanceof Error?e.meta||null:t.clone(a.decycle(e.meta)),d;if(e.raw)return'object'!=typeof i&&null!=i&&(i={meta:i}),d=t.clone(i)||{},d.level=e.level,d.message=e.message.stripColors?e.message.stripColors:e.message,JSON.stringify(d);if(e.json||!0===e.logstash){if('object'!=typeof i&&null!=i&&(i={meta:i}),d=t.clone(i)||{},d.level=e.level,d.message=d.message||'',e.label&&(d.label=e.label),e.message&&(d.message=e.message),o&&(d.timestamp=o),!0===e.logstash){var c={};void 0!==d.message&&(c['@message']=d.message,delete d.message),void 0!==d.timestamp&&(c['@timestamp']=d.timestamp,delete d.timestamp),c['@fields']=t.clone(d),d=c}return'function'==typeof e.stringify?e.stringify(d):JSON.stringify(d,function(e,t){return t instanceof Buffer?t.toString('base64'):t})}if('function'==typeof e.formatter)return e.meta=i,e.formatter(t.clone(e))+'';if(d=o?o+' - ':'',s&&(d+='all'===e.colorize||'level'===e.colorize||!0===e.colorize?l.colorize(e.level):e.level),d+=e.align?'\t':'',d+=o||s?': ':'',d+=e.label?'['+e.label+'] ':'',d+='all'===e.colorize||'message'===e.colorize?l.colorize(e.level,e.message):e.message,null!==i&&void 0!==i)if(i&&i instanceof Error&&i.stack&&(i=i.stack),'object'!=typeof i)d+=' '+i;else if(0e?'0'+e.toString(10):e.toString(10)},t.timestamp=function(){return new Date().toISOString()},t.serialize=function(e,n){if('symbol'==typeof n&&(n=n.toString()),'symbol'==typeof e&&(e=e.toString()),null===e?e='null':void 0===e?e='undefined':!1===e&&(e='false'),'object'!=typeof e)return n?n+'='+e:e;if(e instanceof Buffer)return n?n+'='+e.toString('base64'):e.toString('base64');for(var r='',o=Object.keys(e),a=o.length,s=0;se.start)&&(t?t(null,a):o.emit('line',a)),u++,a=''),setTimeout(p,1e3);var f=r.write(n.slice(0,d));t||o.emit('data',f);for(var f=(a+f).split(/\n+/),m=f.length-1,l=0;le.start)&&(t?t(null,f[l]):o.emit('line',f[l])),u++;return a=f[m],c+=d,p()})}()}),t?o.destroy:o},t.stringArrayToSet=function(e,t){return'undefined'==typeof t&&(t='Cannot make set from Array with non-string elements'),e.reduce(function(e,n){if(!('string'==typeof n||n instanceof String))throw new Error(t);return e[n]=!0,e},Object.create(null))}},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0}),t.logger=void 0;var r=n(17),o=function(e){return e&&e.__esModule?e:{default:e}}(r),a=n(24);const s=new o.default.Logger({transports:[new o.default.transports.Console({colorize:!0,prettyPrint:!0}),new o.default.transports.File({filename:a.LOG_FILE_PATH,maxsize:a.LOG_FILE_MAX_SIZE,silent:['test','debug'].includes('production')})]}),i=t.logger=s;t.default=s},function(e){e.exports=require('os')},function(e){e.exports=require('stream')},function(e,t,n){'use strict';function r(e){var t=function e(){return o.apply(e,arguments)};return t._styles=e,t.__proto__=f,t}function o(){var e=arguments,t=e.length,n=0!==t&&arguments[0]+'';if(1new Date().getTime();class i{static start(e,t=12e4){if(1>e.length)throw Error('servers cannot be empty');this._servers=e,this._pings=this._servers.map(()=>0),this._startQuery(t)}static destroy(){this._stopQuery()}static getFastest(){let e=0;const t=this._pings;for(let n=0;n=t[e])&&(e=n)}return this._servers[e]}static _startQuery(e){1this._query(),e),this._query())}static _stopQuery(){clearInterval(this._timer),this._timer=null}static _query(){this._servers.map((e,t)=>{const n=`${e.host}:${e.port}`;d.default.verbose(`[balancer] querying ${n}`);const r=l(),o=a.default.connect({host:e.host,port:e.port},()=>{const e=l()-r;this._pings[t]=e,d.default.verbose(`[balancer] ${n} = ${e}ms`),o.end()});o.on('error',()=>{this._pings[t]=-1,d.default.warn(`[balancer] ${n} lost connection`)})})}}t.Balancer=i,i._servers=[],i._pings=[],i._timer=null},function(e,t,n){'use strict';var r=t;r.version=n(47).version,r.transports=n(48);var o=n(9);r.hash=o.hash,r.clone=o.clone,r.longestElement=o.longestElement,r.exception=n(23),r.config=n(18),r.addColors=r.config.addColors,r.Container=n(73).Container,r.Logger=n(74).Logger,r.Transport=n(14).Transport,r.loggers=new r.Container;var a=new r.Logger({transports:[new r.transports.Console]});o.setLevels(r,null,a.levels),['log','query','stream','add','remove','clear','profile','startTimer','extend','cli','handleExceptions','unhandleExceptions','configure'].forEach(function(e){r[e]=function(){return a[e].apply(a,arguments)}}),r.cli=function(){return r.padLevels=!0,o.setLevels(r,a.levels,r.config.cli.levels),a.setLevels(r.config.cli.levels),r.config.addColors(r.config.cli.colors),a.transports.console&&(a.transports.console.colorize=!0,a.transports.console.timestamp=!1),r},r.setLevels=function(e){o.setLevels(r,a.levels,e),a.setLevels(e)},Object.defineProperty(r,'level',{get:function(){return a.level},set:function(e){a.level=e,Object.keys(a.transports).forEach(function(t){a.transports[t].level=e})}}),['emitErrs','exitOnError','padLevels','levelLength','stripColors'].forEach(function(e){Object.defineProperty(r,e,{get:function(){return a[e]},set:function(t){a[e]=t}})}),Object.defineProperty(r,'default',{get:function(){return{transports:a.transports,exceptionHandlers:a.exceptionHandlers}}})},function(e,t,n){'use strict';function r(e){var t=Array.prototype.slice.call(arguments,1);return t.forEach(function(t){for(var n=Object.keys(t),r=0;r!0===e.enabled);if(1>t.length)throw Error('\'servers\' must have at least one enabled item');t.forEach(this.validateServer)}else this.validateServer(e);if('undefined'!=typeof e.dns){if(!Array.isArray(e.dns))throw Error('\'dns\' must be an array');var t=!0,n=!1,r;try{for(var o=e.dns[Symbol.iterator](),a;!(t=(a=o.next()).done);t=!0){const e=a.value;if(!c.default.isIP(e))throw Error(`"${e}" is not an ip address`)}}catch(e){n=!0,r=e}finally{try{!t&&o.return&&o.return()}finally{if(n)throw r}}}if('string'==typeof e.redirect&&''!==e.redirect){const t=e.redirect.split(':');if(2!==t.length||!(0,u.isValidPort)(+t[1]))throw Error('\'redirect\' is an invalid address')}if('number'!=typeof e.timeout)throw Error('\'timeout\' must be a number');if(1>e.timeout)throw Error('\'timeout\' must be greater than 0');if(60>e.timeout&&console.warn(`==> [config] 'timeout' is too short, is ${e.timeout}s expected?`),'undefined'!=typeof e.dns_expire){if('number'!=typeof e.dns_expire)throw Error('\'dns_expire\' must be a number');if(0>e.dns_expire)throw Error('\'dns_expire\' must be greater or equal to 0');86400 [config] 'dns_expire' is too long, is ${e.dns_expire}s expected?`)}}static validateServer(e){if('string'!=typeof e.transport)throw Error('\'server.transport\' must be a string');if(!['tcp','udp'].includes(e.transport.toLowerCase()))throw Error('\'server.transport\' must be one of "tcp" or "udp"');if('string'!=typeof e.host||''===e.host)throw Error('\'server.host\' must be provided and is not empty');if(!(0,u.isValidPort)(e.port))throw Error('\'server.port\' is invalid');if('string'!=typeof e.key)throw Error('\'server.key\' must be a string');if(''===e.key)throw Error('\'server.key\' cannot be empty');if(!Array.isArray(e.presets))throw Error('\'server.presets\' must be an array');if(1>e.presets.length)throw Error('\'server.presets\' must contain at least one preset');var t=!0,r=!1,o;try{for(var a=e.presets[Symbol.iterator](),s;!(t=(s=a.next()).done);t=!0){const t=s.value,r=t.name,o=t.params;if('undefined'==typeof r)throw Error('\'server.presets[].name\' must be a string');if(''===r)throw Error('\'server.presets[].name\' cannot be empty');if('object'!=typeof o||null===o)throw Error('\'server.presets[].params\' must be an object and not null');const a=n(31)(`./${t.name}`).default;r!==e.presets[0].name&&delete new a(o||{})}}catch(e){r=!0,o=e}finally{try{!t&&a.return&&a.return()}finally{if(r)throw o}}}static init(e){this.validate(e),global.__LOCAL_HOST__=e.host,global.__LOCAL_PORT__=e.port,'undefined'==typeof e.servers?(global.__IS_CLIENT__=!1,this.initServer(e)):(global.__SERVERS__=e.servers.filter((e)=>e.enabled),global.__IS_CLIENT__=!0),global.__IS_SERVER__=!global.__IS_CLIENT__,global.__REDIRECT__=e.redirect,global.__TIMEOUT__=1e3*e.timeout,global.__PROFILE__=!!e.profile,global.__IS_WATCH__=!!e.watch,global.__LOG_LEVEL__=e.log_level||p.DEFAULT_LOG_LEVEL,global.__DNS_EXPIRE__=e.dns_expire===void 0?f.DNS_DEFAULT_EXPIRE:1e3*e.dns_expire,global.__ALL_CONFIG__=e,'undefined'!=typeof e.dns&&0e.length)return void r(`invalid length: ${e.length}`);const l=e[0];let c=3,u,p;switch(l){case i:u=o.default.toString(e.slice(1,5)),p=e.slice(5,7).readUInt16BE(0),c+=4;break;case 4:if(19>e.length)return void r(`invalid length: ${e.length}`);u=o.default.toString(e.slice(1,17)),p=e.slice(17,19).readUInt16BE(0),c+=16;break;case d:const t=e[1];if(e.length{t(Buffer.concat([this._staging,f])),this._isHandshakeDone=!0,this._staging=null}}}),this._isAddressReceived=!0}else return e}}t.default=l},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0});var r=n(6),o=function(e){return e&&e.__esModule?e:{default:e}}(r),a=n(1),s=n(0);const i=16,d=['aes-128-ctr','aes-192-ctr','aes-256-ctr','aes-128-cfb','aes-192-cfb','aes-256-cfb','camellia-128-cfb','camellia-192-cfb','camellia-256-cfb'];class l extends s.IPreset{constructor({method:e}){if(super(),this._cipherName='',this._key=null,this._cipher=null,this._decipher=null,'string'!=typeof e||''===e)throw Error('\'method\' must be set');if(!d.includes(e))throw Error(`method '${e}' is not supported.`);this._cipherName=e,global.__KEY__&&(this._key=(0,a.EVP_BytesToKey)(__KEY__,this._cipherName.split('-')[1]/8,i))}beforeOut({buffer:e}){if(!this._cipher){const t=o.default.randomBytes(i);return this._cipher=o.default.createCipheriv(this._cipherName,this._key,t),Buffer.concat([t,this.encrypt(e)])}return this.encrypt(e)}beforeIn({buffer:e}){if(!this._decipher){const t=e.slice(0,i);return this._decipher=o.default.createDecipheriv(this._cipherName,this._key,t),this.decrypt(e.slice(i))}return this.decrypt(e)}encrypt(e){return this._cipher.update(e)}decrypt(e){return this._decipher.update(e)}}t.default=l},function(e,t){'use strict';var n,r;(function(){function o(e){var t=!1;return function(){if(t)throw new Error('Callback was already called.');t=!0,e.apply(i,arguments)}}var a={},s=function(){},i,d;i='object'==typeof window&&this===window?window:'object'==typeof global&&this===global?global:this,null!=i&&(d=i.async),a.noConflict=function(){return i.async=d,a};var l=Object.prototype.toString,c=Array.isArray||function(e){return'[object Array]'===l.call(e)},u=function(e,t){for(var n=-1,r=e.length;++nr?0:r);for(var o=Array(r);++n=e.length&&n())}if(n=n||s,!e.length)return n();var a=0;u(e,function(e){t(e,o(r))})},a.forEach=a.each,a.eachSeries=function(e,t,n){if(n=n||s,!e.length)return n();var r=0;(function o(){t(e[r],function(t){t?(n(t),n=s):(r+=1,r>=e.length?n():o())})})()},a.forEachSeries=a.eachSeries,a.eachLimit=function(e,t,n,r){var o=y(t);o.apply(null,[e,n,r])},a.forEachLimit=a.eachLimit;var y=function(e){return function(t,n,r){if(r=r||s,!t.length||0>=e)return r();var o=0,a=0,i=0;(function d(){if(o>=t.length)return r();for(;i=t.length?r():d())})})()}};a.forEachOf=a.eachOf=function(e,t,n){n=n||function(){};var r=e.length||g(e).length,o=0;return r?void m(e,function(a,s){t(e[s],s,function(e){e?(n(e),n=function(){}):(o+=1,o===r&&n(null))})}):n()},a.forEachOfSeries=a.eachOfSeries=function(e,t,n){n=n||function(){};var r=g(e),o=r.length;if(!o)return n();var s=0;(function i(){var d=!0,l=r[s];t(e[l],l,function(e){e?(n(e),n=function(){}):(s+=1,s>=o?n(null):d?a.nextTick(i):i())}),d=!1})()},a.forEachOfLimit=a.eachOfLimit=function(e,t,n,r){b(t)(e,n,r)};var b=function(e){return function(t,n,r){r=r||function(){};var o=g(t),a=o.length;if(!a||0>=e)return r();var s=0,i=0,d=0;(function l(){if(s>=a)return r();for(;d=a?r():l())})}})()}},k=function(e){return function(){var t=h(arguments);return e.apply(null,[a.each].concat(t))}},v=function(e,t){return function(){var n=h(arguments);return t.apply(null,[y(e)].concat(n))}},S=function(e){return function(){var t=h(arguments);return e.apply(null,[a.eachSeries].concat(t))}},x=function(e,t,n,r){if(t=p(t,function(e,t){return{index:t,value:e}}),!r)e(t,function(e,t){n(e.value,function(e){t(e)})});else{var o=[];e(t,function(e,t){n(e.value,function(n,r){o[e.index]=r,t(n)})},function(e){r(e,o)})}};a.map=k(x),a.mapSeries=S(x),a.mapLimit=function(e,t,n,r){return T(t)(e,n,r)};var T=function(e){return v(e,x)};a.reduce=function(e,t,n,r){a.eachSeries(e,function(e,r){n(t,e,function(e,n){t=n,r(e)})},function(e){r(e,t)})},a.inject=a.reduce,a.foldl=a.reduce,a.reduceRight=function(e,t,n,r){var o=p(e,function(e){return e}).reverse();a.reduce(o,t,n,r)},a.foldr=a.reduceRight;var E=function(e,t,n,r){var o=[];t=p(t,function(e,t){return{index:t,value:e}}),e(t,function(e,t){n(e.value,function(n){n&&o.push(e),t()})},function(){r(p(o.sort(function(e,t){return e.index-t.index}),function(e){return e.value}))})};a.filter=k(E),a.filterSeries=S(E),a.select=a.filter,a.selectSeries=a.filterSeries;var P=function(e,t,n,r){var o=[];t=p(t,function(e,t){return{index:t,value:e}}),e(t,function(e,t){n(e.value,function(n){n||o.push(e),t()})},function(){r(p(o.sort(function(e,t){return e.index-t.index}),function(e){return e.value}))})};a.reject=k(P),a.rejectSeries=S(P);var O=function(e,t,n,r){e(t,function(e,t){n(e,function(n){n?(r(e),r=s):t()})},function(){r()})};a.detect=k(O),a.detectSeries=S(O),a.some=function(e,t,n){a.each(e,function(e,r){t(e,function(e){e&&(n(!0),n=s),r()})},function(){n(!1)})},a.any=a.some,a.every=function(e,t,n){a.each(e,function(e,r){t(e,function(e){e||(n(!1),n=s),r()})},function(){n(!0)})},a.all=a.every,a.sortBy=function(e,t,n){a.map(e,function(e,n){t(e,function(t,r){t?n(t):n(null,{value:e,criteria:r})})},function(e,t){if(e)return n(e);n(null,p(t.sort(function(e,t){var n=e.criteria,r=t.criteria;return nr?1:0}),function(e){return e.value}))})},a.auto=function(e,t){t=t||s;var n=g(e),r=n.length;if(!r)return t();var o={},d=[],i=function(e){d.unshift(e)},l=function(e){for(var t=0;t=r.length&&(r=r[0]),e){var i={};u(g(o),function(e){i[e]=o[e]}),i[n]=r,t(e,i),t=s}else o[n]=r,a.setImmediate(p)},m=r.slice(0,Math.abs(r.length-1))||[],_=m.length,y;_--;){if(!(y=e[m[_]]))throw new Error('Has inexistant dependency');if(c(y)&&!!~y.indexOf(n))throw new Error('Has cyclic dependencies')}var b=function(){return f(m,function(e,t){return e&&o.hasOwnProperty(t)},!0)&&!o.hasOwnProperty(n)};if(b())r[r.length-1](d,o);else{var k=function e(){b()&&(l(e),r[r.length-1](d,o))};i(k)}})},a.retry=function(e,t,n){var r=5,o=[];'function'==typeof e&&(n=t,t=e,e=r),e=parseInt(e,10)||r;var s=function(r,s){for(var i=function(e,t){return function(n){e(function(e,r){n(!e||t,{err:e,result:r})},s)}};e;)o.push(i(t,!(e-=1)));a.series(o,function(e,t){t=t[t.length-1],(r||n)(t.err,t.result)})};return n?s():s},a.waterfall=function(e,t){if(t=t||s,!c(e)){var n=new Error('First argument to waterfall must be an array of functions');return t(n)}if(!e.length)return t();(function e(n){return function(r){if(r)t.apply(null,arguments),t=s;else{var o=h(arguments,1),i=n.next();i?o.push(e(i)):o.push(t),a.setImmediate(function(){n.apply(null,o)})}}})(a.iterator(e))()};var D=function(e,t,n){if(n=n||s,c(t))e.map(t,function(e,t){e&&e(function(e){var n=h(arguments,1);1>=n.length&&(n=n[0]),t.call(null,e,n)})},n);else{var r={};e.each(g(t),function(e,n){t[e](function(t){var o=h(arguments,1);1>=o.length&&(o=o[0]),r[e]=o,n(t)})},function(e){n(e,r)})}};a.parallel=function(e,t){D({map:a.map,each:a.each},e,t)},a.parallelLimit=function(e,t,n){D({map:T(t),each:y(t)},e,n)},a.series=function(e,t){if(t=t||s,c(e))a.mapSeries(e,function(e,t){e&&e(function(e){var n=h(arguments,1);1>=n.length&&(n=n[0]),t.call(null,e,n)})},t);else{var n={};a.eachSeries(g(e),function(t,r){e[t](function(e){var o=h(arguments,1);1>=o.length&&(o=o[0]),n[t]=o,r(e)})},function(e){t(e,n)})}},a.iterator=function(e){return function t(n){var r=function t(){return e.length&&e[n].apply(null,arguments),t.next()};return r.next=function(){return n>>1),0<=n(t,e[a])?r=a:o=a-1;return r}function o(e,t,o,s){return e.started||(e.started=!0),c(t)||(t=[t]),0===t.length?a.setImmediate(function(){e.drain&&e.drain()}):void u(t,function(t){var i={data:t,priority:o,callback:'function'==typeof s?s:null};e.tasks.splice(r(e.tasks,i,n)+1,0,i),e.saturated&&e.tasks.length===e.concurrency&&e.saturated(),a.setImmediate(e.process)})}var s=a.queue(e,t);return s.push=function(e,t,n){o(s,e,t,n)},delete s.unshift,s},a.cargo=function(e,t){var n=!1,r=[],o={tasks:r,payload:t,saturated:null,empty:null,drain:null,drained:!0,push:function(e,n){c(e)||(e=[e]),u(e,function(e){r.push({data:e,callback:'function'==typeof n?n:null}),o.drained=!1,o.saturated&&r.length===t&&o.saturated()}),a.setImmediate(o.process)},process:function a(){if(!n){if(0===r.length)return o.drain&&!o.drained&&o.drain(),void(o.drained=!0);var s='number'==typeof t?r.splice(0,t):r.splice(0,r.length),i=p(s,function(e){return e.data});o.empty&&o.empty(),n=!0,e(i,function(){n=!1;var e=arguments;u(s,function(t){t.callback&&t.callback.apply(null,e)}),a()})}},length:function(){return r.length},running:function(){return n}};return o};var I=function(e){return function(t){var n=h(arguments,1);t.apply(null,n.concat([function(t){var n=h(arguments,1);'undefined'!=typeof console&&(t?console.error&&console.error(t):console[e]&&u(n,function(t){console[e](t)}))}]))}};a.log=I('log'),a.dir=I('dir'),a.memoize=function(e,t){var n={},r={};t=t||function(e){return e};var o=function(){var o=h(arguments),s=o.pop(),d=t.apply(null,o);d in n?a.nextTick(function(){s.apply(null,n[d])}):d in r?r[d].push(s):(r[d]=[s],e.apply(null,o.concat([function(){n[d]=h(arguments);var e=r[d];delete r[d];for(var t=0,o=e.length;t=o&&n>>10),e=56320|1023&e),t+=w(e),t}).join('')}function c(e){return 10>e-48?e-22:26>e-65?e-65:26>e-97?e-97:b}function u(e,t){return e+22+75*(26>e)-((0!=t)<<5)}function p(e,t,n){var r=0;for(e=n?C(e/T):e>>1,e+=C(e/t);e>A*S>>1;r+=b)e=C(e/A);return C(r+(A+1)*e/(e+x))}function f(e){var r=[],o=e.length,s=0,i=P,n=E,d,u,f,m,g,h,_,k,x,t;for(u=e.lastIndexOf(O),0>u&&(u=0),f=0;f=o&&a('invalid-input'),k=c(e.charCodeAt(m++)),(k>=b||k>C((y-s)/h))&&a('overflow'),s+=k*h,x=_<=n?v:_>=n+S?S:_-n,kC(y/t)&&a('overflow'),h*=t}d=r.length+1,n=p(s-g,d,0==g),C(s/d)>y-i&&a('overflow'),i+=C(s/d),s%=d,r.splice(s++,0,i)}return l(r)}function m(e){var r=[],o,n,s,i,l,c,f,m,g,h,t,_,k,x,T;for(e=d(e),_=e.length,o=P,n=0,l=E,c=0;c<_;++c)t=e[c],128>t&&r.push(w(t));for(s=i=r.length,i&&r.push(O);s<_;){for(f=y,c=0;c<_;++c)t=e[c],t>=o&&tC((y-n)/k)&&a('overflow'),n+=(f-o)*k,o=f,c=0;c<_;++c)if(t=e[c],ty&&a('overflow'),t==o){for(m=n,g=b;;g+=b){if(h=g<=l?v:g>=l+S?S:g-l,m= 0x80 (not a basic code point)',"invalid-input":'Invalid input'},A=b-v,C=Math.floor,w=String.fromCharCode,N;N={version:'1.3.2',ucs2:{decode:d,encode:l},decode:f,encode:m,toASCII:function(e){return i(e,function(e){return D.test(e)?'xn--'+m(e):e})},toUnicode:function(e){return i(e,function(e){return k.test(e)?f(e.slice(4).toLowerCase()):e})}};r=function(){return N}.call(t,n,t,e),!(void 0!==r&&(e.exports=r))})(void 0)}).call(t,n(27)(e))},function(e){'use strict';e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],!e.children&&(e.children=[]),Object.defineProperty(e,'loaded',{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,'id',{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t,n){'use strict';var r,o;(function(a,s){'object'==typeof e&&e.exports?e.exports=s():(r=s,o='function'==typeof r?r.call(t,n,t,e):r,!(o!==void 0&&(e.exports=o)))})(void 0,function(e){var t=e&&e.IPv6;return{best:function(e){var t=e.toLowerCase(),n=t.split(':'),r=n.length,o=8;''===n[0]&&''===n[1]&&''===n[2]?(n.shift(),n.shift()):''===n[0]&&''===n[1]?n.shift():''===n[r-1]&&''===n[r-2]&&n.pop(),r=n.length,-1!==n[r-1].indexOf('.')&&(o=7);var a;for(a=0;ad&&'0'===i[0]&&1c&&(l=p,c=u)):'0'===n[s]&&(f=!0,p=s,u=1);u>c&&(l=p,c=u),1=t||t>=e.length-1)return!1;var r=e.lastIndexOf('.',t-1);if(0>=r||r>=t-1)return!1;var o=n.list[e.slice(t+1)];return!!o&&0<=o.indexOf(' '+e.slice(r+1,t)+' ')},is:function(e){var t=e.lastIndexOf('.');if(0>=t||t>=e.length-1)return!1;var r=e.lastIndexOf('.',t-1);if(0<=r)return!1;var o=n.list[e.slice(t+1)];return!!o&&0<=o.indexOf(' '+e.slice(0,t)+' ')},get:function(e){var t=e.lastIndexOf('.');if(0>=t||t>=e.length-1)return null;var r=e.lastIndexOf('.',t-1);if(0>=r||r>=t-1)return null;var o=n.list[e.slice(t+1)];return o?0>o.indexOf(' '+e.slice(r+1,t)+' ')?null:e.slice(r+1):null},noConflict:function(){return e.SecondLevelDomains===this&&(e.SecondLevelDomains=t),this}};return n})},function(e,t,n){'use strict';function r(e){return e&&e.__esModule?e:{default:e}}function o(e){return function(){var t=e.apply(this,arguments);return new Promise(function(e,n){function r(o,a){try{var s=t[o](a),i=s.value}catch(e){return void n(e)}return s.done?void e(i):Promise.resolve(i).then(function(e){r('next',e)},function(e){r('throw',e)})}return r('next')})}}Object.defineProperty(t,'__esModule',{value:!0}),t.DNSCache=t.DNS_DEFAULT_EXPIRE=void 0;var a=function(){function e(e,t){var n=[],r=!0,o=!1,a;try{for(var s=e[Symbol.iterator](),i;!(r=(i=s.next()).done)&&(n.push(i.value),!(t&&n.length===t));r=!0);}catch(e){o=!0,a=e}finally{try{!r&&s['return']&&s['return']()}finally{if(o)throw a}}return n}return function(t,n){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,n);throw new TypeError('Invalid attempt to destructure non-iterable instance')}}(),s=n(25),i=r(s),d=n(4),l=r(d);const c=t.DNS_DEFAULT_EXPIRE=3.6e6;t.DNSCache=class{constructor({expire:e}={}){this._pool={},this._expire=c,e!==void 0&&(this._expire=e)}_now(){return new Date().getTime()}_lookup(e){return new Promise((t,n)=>{i.default.lookup(e,function(e,r){e?n(e):t(r)})})}_put(e,t){if(0=s&&delete t._pool[e],n=o}return n})()}}},function(e,t,n){function r(e){return n(o(e))}function o(e){var t=a[e];if(!(t+1))throw new Error('Cannot find module \''+e+'\'.');return t}var a={"./__tests__/defs.test":32,"./__tests__/defs.test.js":32,"./__tests__/ss-base.test":33,"./__tests__/ss-base.test.js":33,"./__tests__/ss-stream-cipher.test":34,"./__tests__/ss-stream-cipher.test.js":34,"./aead-random-cipher":35,"./aead-random-cipher.js":35,"./defs":0,"./defs.js":0,"./exp-base-auth-stream":36,"./exp-base-auth-stream.js":36,"./exp-base-with-padding":37,"./exp-base-with-padding.js":37,"./obfs-http":38,"./obfs-http.js":38,"./obfs-tls1.2-ticket":39,"./obfs-tls1.2-ticket.js":39,"./proxy":40,"./proxy.js":40,"./ss-aead-cipher":42,"./ss-aead-cipher.js":42,"./ss-base":20,"./ss-base.js":20,"./ss-stream-cipher":21,"./ss-stream-cipher.js":21};r.keys=function(){return Object.keys(a)},r.resolve=o,e.exports=r,r.id=31},function(e,t,n){'use strict';var r=n(0);const o=new r.IPreset,a={buffer:null};describe('IPreset#onNotified',function(){it('should return false',function(){expect(o.onNotified()).toBe(!1)})}),describe('IPreset#beforeIn,beforeOut,clientOut,serverIn,serverOut,clientIn',function(){it('should return null',function(){expect(o.beforeIn(a)).toBe(null),expect(o.beforeOut(a)).toBe(null),expect(o.clientOut(a)).toBe(null),expect(o.serverIn(a)).toBe(null),expect(o.serverOut(a)).toBe(null),expect(o.clientIn(a)).toBe(null)})})},function(e,t,n){'use strict';var r=Object.assign||function(e){for(var t=1,n;t{t(),expect(e.next).toHaveBeenCalled()}),fail:jest.fn()};it('should call fail',function(){global.__IS_CLIENT__=!1;const t=new s.default;t.serverIn(r({},e,{buffer:Buffer.alloc(0)})),t.serverIn(r({},e,{buffer:Buffer.alloc(7)})),t.serverIn(r({},e,{buffer:Buffer.alloc(8)})),t.serverIn(r({},e,{buffer:Buffer.from([4,0,0,0,0,0,0,0])})),t.serverIn(r({},e,{buffer:Buffer.from([3,5,0,0,0,0,0,0])})),expect(e.fail).toHaveBeenCalledTimes(5)}),it('should call broadcast ipv4',function(){global.__IS_CLIENT__=!1;const t=new s.default;t.serverIn(r({},e,{buffer:Buffer.from([1,5,0,0,0,0,0,0])})),expect(e.broadcast).toHaveBeenCalled()}),it('should call broadcast ipv6',function(){global.__IS_CLIENT__=!1;const t=new s.default;t.serverIn(r({},e,{buffer:Buffer.from([4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])})),expect(e.broadcast).toHaveBeenCalled()}),it('should call broadcast domain',function(){global.__IS_CLIENT__=!1;const t=new s.default;t.serverIn(r({},e,{buffer:Buffer.from([3,11,...Buffer.from('example.com'),0,0])})),expect(e.broadcast).toHaveBeenCalled(),expect(t.serverIn(r({},e,{buffer:Buffer.alloc(1)})).length).toBe(1)}),it('should call fail if domain is invalid',function(){global.__IS_CLIENT__=!1;const t=new s.default;t.serverIn(r({},e,{buffer:Buffer.from([3,12,...Buffer.from('=example.com'),0,0])})),expect(e.fail).toHaveBeenCalled()})})},function(e,t,n){'use strict';var r=n(21),o=function(e){return e&&e.__esModule?e:{default:e}}(r);global.__KEY__='abc',describe('SSStreamCipherPreset#constructor',function(){it('should throw when method is invalid',function(){expect(()=>new o.default({method:null})).toThrow(),expect(()=>new o.default({method:''})).toThrow(),expect(()=>new o.default({method:'xxx'})).toThrow()}),it('should set this._key',function(){const e=new o.default({method:'aes-128-cfb'});expect(e._key).not.toBe(null)})}),describe('SSStreamCipherPreset#beforeOut',function(){const e=new o.default({method:'aes-128-cfb'});it('should return 16 bytes',function(){expect(e.beforeOut({buffer:Buffer.alloc(0)}).length).toBe(16)}),it('should return 1 byte',function(){expect(e.beforeOut({buffer:Buffer.alloc(1)}).length).toBe(1)})}),describe('SSStreamCipherPreset#beforeIn',function(){const e=new o.default({method:'aes-128-cfb'});it('should return empty',function(){expect(e.beforeIn({buffer:Buffer.alloc(16)}).length).toBe(0)}),it('should return 1 byte',function(){expect(e.beforeIn({buffer:Buffer.alloc(1)}).length).toBe(1)})})},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0});var r=function(){function e(e,t){var n=[],r=!0,o=!1,a;try{for(var s=e[Symbol.iterator](),i;!(r=(i=s.next()).done)&&(n.push(i.value),!(t&&n.length===t));r=!0);}catch(e){o=!0,a=e}finally{try{!r&&s['return']&&s['return']()}finally{if(o)throw a}}return n}return function(t,n){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,n);throw new TypeError('Invalid attempt to destructure non-iterable instance')}}(),o=n(6),a=function(e){return e&&e.__esModule?e:{default:e}}(o),s=n(1),i=n(0);const d=12,l=16,c=2,u=['aes-128-gcm','aes-192-gcm','aes-256-gcm'],p='sha1';class f extends i.IPreset{constructor({method:e,info:t,factor:n}){if(super(),this._cipherName='',this._info=null,this._factor=c,this._rawKey=null,this._cipherKey=null,this._decipherKey=null,this._cipherNonce=0,this._decipherNonce=0,this._nextExpectDecipherNonce=0,this._adBuf=null,'undefined'==typeof e||''===e)throw Error('\'method\' must be set.');if(!u.includes(e))throw Error(`method '${e}' is not supported.`);if('string'!=typeof t||0>=t.length)throw Error('\'info\' must be a non-empty string.');if('undefined'==typeof n)n=c;else{if(!Number.isInteger(n))throw Error('\'factor\' must be an integer.');if(1>n||10{const t=this.getPaddingLength(this._cipherKey,this._cipherNonce),n=a.default.randomBytes(t),o=(0,s.numberToBuffer)(e.length);var i=this.encrypt(o),d=r(i,2);const l=d[0],c=d[1];var u=this.encrypt(e),p=r(u,2);const f=p[0],m=p[1];return Buffer.concat([n,l,c,f,m])});return t?Buffer.concat([t,...n]):Buffer.concat(n)}beforeIn({buffer:e,next:t,fail:n}){this._adBuf.put(e,{next:t,fail:n})}onReceiving(e,{fail:t}){if(null===this._decipherKey){const t=this._cipherName.split('-')[1]/8;if(e.lengthe.length)return r(`unexpected buffer length_1: ${e.length}, buffer=${e.toString('hex')}`);const o=e.slice(0,c),s=(0,d.EVP_BytesToKey)(__KEY__,this._cipherName.split('-')[1]/8,c);this._cipher=a.default.createCipheriv(this._cipherName,s,o),this._decipher=a.default.createDecipheriv(this._cipherName,s,o);const i=this.decrypt(e.slice(32)),p=e.slice(16,32),f=i[0];if(e.length<=35+f)return r(`unexpected buffer length_2: ${e.length}, buffer=${e.toString('hex')}`);const m=(0,d.Xor)(o,s.slice(0,c)),g=(0,d.hmac)('sha1',m,e.slice(32,35+f)).slice(0,u);if(!g.equals(p))return r(`unexpected HMAC-SHA1=${p.toString('hex')} want=${g.toString('hex')}`);const h=i.slice(1,f+1).toString(),_=i.slice(f+1,f+3).readUInt16BE(0),y=i.slice(f+3);n({type:l.SOCKET_CONNECT_TO_DST,payload:{targetAddress:{host:h,port:_},onConnected:()=>{t(y),this._isHandshakeDone=!0}}})}else return this.decrypt(e)}serverOut({buffer:e}){return this.encrypt(e)}clientIn({buffer:e}){return this.decrypt(e)}encrypt(e){return this._cipher.update(e)}decrypt(e){return this._decipher.update(e)}}t.default=f},function(e,t,n){'use strict';function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,'__esModule',{value:!0});var o=n(4),a=r(o),s=n(7),i=r(s),d=n(1),l=n(0);class c extends l.IPreset{constructor({type:e,host:t,port:n,salt:r}){if(super(),this._isHandshakeDone=!1,this._isAddressReceived=!1,this._host=null,this._port=null,this._padding=null,this._staging=Buffer.alloc(0),'string'!=typeof r||''===r)throw Error('\'salt\' must be set to a non-empty string');__IS_CLIENT__&&(this._host=t,this._port=n,(e===1||e===4)&&(this._host=Buffer.from(i.default.toString(t)))),this._padding=(0,d.hash)('sha256',r).slice(0,15)}clientOut({buffer:e}){return this._isHandshakeDone?e:(this._isHandshakeDone=!0,Buffer.concat([(0,d.numberToBuffer)(this._host.length,1),this._padding,this._host,this._port,e]))}serverIn({buffer:e,next:t,broadcast:n,fail:r}){if(!this._isHandshakeDone){if(this._isAddressReceived)return void(this._staging=Buffer.concat([this._staging,e]));if(20>e.length)return r(`unexpected buffer length: ${e.length}, buffer=${e.toString('hex')}`);if(!e.slice(1,16).equals(this._padding))return r(`unexpected padding=${this._padding.toString('hex')}`);const o=e[0];if(e.length<=o+18)return r(`unexpected buffer length: ${e.length}, buffer=${e.toString('hex')}`);let s=e.slice(16,16+o);if((0,d.isValidHostname)(s))s=s.toString();else if(a.default.isIP(s))s=i.default.toString(s);else return r(`invalid addr: (${s.toString()})`);const c=e.slice(o+16,o+18).readUInt16BE(0),u=e.slice(o+18);n({type:l.SOCKET_CONNECT_TO_DST,payload:{targetAddress:{host:s,port:c},onConnected:()=>{t(Buffer.concat([this._staging,u])),this._isHandshakeDone=!0,this._staging=null}}}),this._isAddressReceived=!0}else return e}}t.default=c},function(e,t,n){'use strict';function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,'__esModule',{value:!0});var o=n(8),a=r(o),s=n(79),i=r(s),d=n(6),l=r(d),c=n(0);class u{static _parse(e,t){if(0{for(let e=0;e{const r=l.default.randomBytes(1)[0]%n.length,o=n[r].request;t(Buffer.concat([o,e]))})}serverIn({buffer:e,next:t,fail:n}){return this._isHandshakeDone?e:void u.get(this._file,(r)=>{const o=r.find(({request:t})=>0===e.indexOf(t));'undefined'==typeof o?n('http header mismatch'):(this._response=o.response,t(e.slice(o.request.length)))})}serverOut({buffer:e}){return this._isHandshakeDone?e:(this._isHandshakeDone=!0,Buffer.concat([this._response,e]))}clientIn({buffer:e,next:t,fail:n}){return this._isHandshakeDone?e:void(u.get(this._file,(r)=>{const o=r.find(({response:t})=>0===e.indexOf(t));'undefined'==typeof o?n('http header mismatch'):t(e.slice(o.response.length))}),this._isHandshakeDone=!0)}}t.default=p},function(e,t,n){'use strict';function r(e){const t=(0,s.numberToBuffer)(e.length);return Buffer.concat([(0,s.hexStringToBuffer)('170303'),t,e])}Object.defineProperty(t,'__esModule',{value:!0});var o=n(6),a=function(e){return e&&e.__esModule?e:{default:e}}(o),s=n(1),i=n(0);const d=1,l=2,c=3,u=2048,p=16383;class f extends i.IPreset{constructor({sni:e}){if(super(),this._sni=[],this._stage=d,this._pending=null,this._adBuf=null,'undefined'==typeof e)throw Error('\'sni\' must be set');if(Array.isArray(e)||(e=[e]),e.some((e)=>'string'!=typeof e||1>e.length))throw Error('\'sni\' must be a non-empty string or an array without empty strings');this.onReceiving=this.onReceiving.bind(this),this.onChunkReceived=this.onChunkReceived.bind(this),this._sni=Array.isArray(e)?e:[e],this._adBuf=new s.AdvancedBuffer({getPacketLength:this.onReceiving}),this._adBuf.on('data',this.onChunkReceived)}getRandomSNI(){const e=a.default.randomBytes(1)[0]%this._sni.length;return Buffer.from(this._sni[e])}clientOut({buffer:e,direct:t}){if(this._stage===d){this._stage=l,this._pending=e;const n=this.getRandomSNI(),r=[...(0,s.getUTC)(),...a.default.randomBytes(28)],o=[...(0,s.hexStringToBuffer)('20'),...a.default.randomBytes(32)],i=[...(0,s.hexStringToBuffer)('001a'),...(0,s.hexStringToBuffer)('c02b'),...(0,s.hexStringToBuffer)('c02f'),...(0,s.hexStringToBuffer)('c02c'),...(0,s.hexStringToBuffer)('c030'),...(0,s.hexStringToBuffer)('cc14'),...(0,s.hexStringToBuffer)('cc13'),...(0,s.hexStringToBuffer)('c013'),...(0,s.hexStringToBuffer)('c014'),...(0,s.hexStringToBuffer)('009c'),...(0,s.hexStringToBuffer)('009d'),...(0,s.hexStringToBuffer)('002f'),...(0,s.hexStringToBuffer)('0035'),...(0,s.hexStringToBuffer)('000a')],d=[...(0,s.hexStringToBuffer)('0000'),...(0,s.numberToBuffer)(5+n.length),...(0,s.numberToBuffer)(3+n.length),...(0,s.hexStringToBuffer)('00'),...(0,s.numberToBuffer)(n.length),...n],c=(0,s.getRandomInt)(200,400),u=[...(0,s.hexStringToBuffer)('0023'),...(0,s.numberToBuffer)(c),...a.default.randomBytes(c)],p=[...(0,s.hexStringToBuffer)('ff01000100'),...d,...(0,s.hexStringToBuffer)('00170000'),...u,...(0,s.hexStringToBuffer)('000d00140012040308040401050308050501080606010201'),...(0,s.hexStringToBuffer)('000500050100000000'),...(0,s.hexStringToBuffer)('00120000'),...(0,s.hexStringToBuffer)('75500000'),...(0,s.hexStringToBuffer)('000b00020100'),...(0,s.hexStringToBuffer)('000a0006000400170018')],f=[...(0,s.hexStringToBuffer)('0303'),...r,...o,...i,...(0,s.hexStringToBuffer)('01'),...(0,s.hexStringToBuffer)('00'),...(0,s.numberToBuffer)(p.length),...p],m=[...(0,s.hexStringToBuffer)('16'),...(0,s.hexStringToBuffer)('0301'),...(0,s.numberToBuffer)(4+f.length),...(0,s.hexStringToBuffer)('01'),...(0,s.numberToBuffer)(f.length,3)];return t(Buffer.from([...m,...f]))}if(this._stage===c){const t=(0,s.getRandomChunks)(e,u,p).map((e)=>r(e));return Buffer.concat(t)}}serverIn({buffer:e,next:t,direct:n,fail:r}){if(this._stage===d){if(this._stage=l,200>e.length)return void r(`TLS handshake header is too short, length=${e.length} dump=${e.slice(0,100).toString('hex')}`);if(!e.slice(0,3).equals((0,s.hexStringToBuffer)('160301')))return void r(`invalid TLS handshake header=${e.slice(0,3).toString('hex')}, want=160301, dump=${e.slice(0,100).toString('hex')}`);const t=e.slice(3,5).readUInt16BE(0);if(t!==e.length-5)return void r(`unexpected TLS handshake body length=${e.length-5}, want=${t}, dump=${e.slice(0,100).toString('hex')}`);const o=[...(0,s.getUTC)(),...a.default.randomBytes(28)],i=[...(0,s.hexStringToBuffer)('20'),...a.default.randomBytes(32)],d=[...(0,s.hexStringToBuffer)('ff01000100'),...(0,s.hexStringToBuffer)('00050000'),...(0,s.hexStringToBuffer)('00170000')],c=[...(0,s.hexStringToBuffer)('0303'),...o,...i,...(0,s.hexStringToBuffer)('c02f'),...(0,s.hexStringToBuffer)('00'),...(0,s.numberToBuffer)(d.length),...d],u=[...(0,s.hexStringToBuffer)('16'),...(0,s.hexStringToBuffer)('0303'),...(0,s.numberToBuffer)(4+c.length),...(0,s.hexStringToBuffer)('02'),...(0,s.numberToBuffer)(c.length,3)],p=[...u,...c],f=a.default.randomBytes((0,s.getRandomInt)(200,255)),m=[...(0,s.hexStringToBuffer)('000004b0'),...(0,s.numberToBuffer)(f.length),...f],g=[...(0,s.hexStringToBuffer)('04'),...(0,s.numberToBuffer)(m.length,3),...m],h=[...(0,s.hexStringToBuffer)('160303'),...(0,s.numberToBuffer)(g.length),...g],_=[...(0,s.hexStringToBuffer)('140303000101')],y=(0,s.getRandomInt)(32,40),b=[...(0,s.hexStringToBuffer)('16'),...(0,s.hexStringToBuffer)('0303'),...(0,s.numberToBuffer)(y),...a.default.randomBytes(y)];return n(Buffer.from([...p,...h,..._,...b]),!0)}let o=e;this._stage===l&&(this._stage=c,o=e.slice(43)),this._adBuf.put(o,{next:t,fail:r})}serverOut({buffer:e}){const t=(0,s.getRandomChunks)(e,u,p).map((e)=>r(e));return Buffer.concat(t)}clientIn({buffer:e,next:t,direct:n,fail:o}){if(this._stage===l){this._stage=c;const e=[...(0,s.hexStringToBuffer)('140303000101')],t=[...(0,s.hexStringToBuffer)('16'),...(0,s.hexStringToBuffer)('0303'),...(0,s.hexStringToBuffer)('0020'),...a.default.randomBytes(32)],o=(0,s.getRandomChunks)(this._pending,u,p).map((e)=>r(e));return this._pending=null,n(Buffer.from([...e,...t,...Buffer.concat(o)]),!0)}this._adBuf.put(e,{next:t,fail:o})}onReceiving(e){return 5>e.length?void 0:5+e.readUInt16BE(3)}onChunkReceived(e,{next:t}){t(e.slice(5))}}t.default=f},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0});var r=n(7),o=function(e){return e&&e.__esModule?e:{default:e}}(r),a=n(0),s=n(41);class i extends a.IPreset{constructor(...e){var t;return t=super(...e),this._proxy=null,t}beforeIn({buffer:e,direct:t,broadcast:n}){return null===this._proxy&&(this._proxy=new s.Proxifier({onHandshakeDone:(e,r)=>{var i=[e.type===s.ATYP_DOMAIN?e.host.toString():o.default.toString(e.host),e.port.readUInt16BE(0)];const d=i[0],l=i[1];n({type:a.SOCKET_CONNECT_TO_DST,payload:{targetAddress:{host:d,port:l},onConnected:()=>r(t)}})}})),this._proxy.isDone()?e:void this._proxy.makeHandshake((e)=>t(e,!0),e)}}t.default=i},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0});var r=n(2);Object.keys(r).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}})});var o=n(82);Object.keys(o).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return o[e]}})})},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0});var r=function(){function e(e,t){var n=[],r=!0,o=!1,a;try{for(var s=e[Symbol.iterator](),i;!(r=(i=s.next()).done)&&(n.push(i.value),!(t&&n.length===t));r=!0);}catch(e){o=!0,a=e}finally{try{!r&&s['return']&&s['return']()}finally{if(o)throw a}}return n}return function(t,n){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,n);throw new TypeError('Invalid attempt to destructure non-iterable instance')}}(),o=n(6),a=function(e){return e&&e.__esModule?e:{default:e}}(o),s=n(1),i=n(0);const d=12,l=16,c=['aes-128-gcm','aes-192-gcm','aes-256-gcm'],u='sha1';class p extends i.IPreset{constructor({method:e,info:t}){if(super(),this._cipherName='',this._info=null,this._cipherKey=null,this._decipherKey=null,this._cipherNonce=0,this._decipherNonce=0,this._adBuf=null,'undefined'==typeof e||''===e)throw Error('\'method\' must be set.');if(!c.includes(e))throw Error(`method '${e}' is not supported.`);this._cipherName=e,this._info=Buffer.from(t),this._adBuf=new s.AdvancedBuffer({getPacketLength:this.onReceiving.bind(this)}),this._adBuf.on('data',this.onChunkReceived.bind(this))}beforeOut({buffer:e}){let t=null;if(null===this._cipherKey){const e=this._cipherName.split('-')[1]/8;t=a.default.randomBytes(e),this._cipherKey=(0,s.HKDF)(u,t,(0,s.EVP_BytesToKey)(__KEY__,e,16),this._info,e)}const n=(0,s.getRandomChunks)(e,2048,16383).map((e)=>{const t=(0,s.numberToBuffer)(e.length);var n=this.encrypt(t),o=r(n,2);const a=o[0],i=o[1];var d=this.encrypt(e),l=r(d,2);const c=l[0],u=l[1];return Buffer.concat([a,i,c,u])});return t?Buffer.concat([t,...n]):Buffer.concat(n)}beforeIn({buffer:e,next:t,fail:n}){this._adBuf.put(e,{next:t,fail:n})}onReceiving(e,{fail:t}){if(null===this._decipherKey){const t=this._cipherName.split('-')[1]/8;if(e.length'function'!=typeof t[e]))throw Error(`all methods [${n.toString()}] in ${e} must be implemented`);return!0}Object.defineProperty(t,'__esModule',{value:!0}),t.Middleware=t.MIDDLEWARE_DIRECTION_DOWNWARD=t.MIDDLEWARE_DIRECTION_UPWARD=void 0,t.createMiddleware=function(e,t={}){try{const r=n(31)(`./${e}`).default,a=new r(t);return o(r.name,a),new p(a)}catch(e){d.default.error(e.message),process.exit(-1)}return null};var a=n(3),s=r(a),i=n(10),d=r(i),l=n(1);const c=t.MIDDLEWARE_DIRECTION_UPWARD=1,u=t.MIDDLEWARE_DIRECTION_DOWNWARD=-1;class p extends s.default{constructor(e){super(),this._broadcast=null,this._impl=null,this._impl=e}getName(){return(0,l.kebabCase)(this._impl.constructor.name).replace(/(.*)-preset/i,'$1')}subscribe(e){this._broadcast=e}onNotified(e){return this._impl.onNotified(e)}write(e,{buffer:t,direct:n,fail:o}){const a={[c]:'Out',[u]:'In'}[e],s=this._broadcast,i=(e)=>o(this.getName(),e),d=(t)=>{const r={buffer:t,next:(t)=>this.emit(`next_${e}`,t),broadcast:s,direct:n,fail:i},o=__IS_CLIENT__?this._impl[`client${a}`](r):this._impl[`server${a}`](r);'undefined'!=typeof o&&r.next(o)},l=this._impl[`before${a}`]({buffer:t,next:d,broadcast:s,direct:n,fail:i});'undefined'!=typeof l&&d(l)}}t.Middleware=p},function(e,t,n){'use strict';var r=Math.max;Object.defineProperty(t,'__esModule',{value:!0}),t.Profile=void 0;var o=n(8),a=function(e){return e&&e.__esModule?e:{default:e}}(o);const s=1,i=()=>new Date().getTime();class d{static start(){this._timer=setInterval(()=>{this._outSpeed=this._tmpOut/s,this._inSpeed=this._tmpIn/s,this._maxOutSpeed=r(this._maxOutSpeed,this._outSpeed),this._maxInSpeed=r(this._maxInSpeed,this._inSpeed),this._tmpOut=0,this._tmpIn=0},1e3*s)}static stop(){clearInterval(this._timer)}static snapshot(){const e=i(),t=(e-this._startTime)/1e3,n=this._totalInPackets+this._totalOutPackets,r=this._totalIn+this._totalOut;return{sample:{from:this._startTime,to:e,duration:e-this._startTime},instance:{outSpeed:this._outSpeed,inSpeed:this._inSpeed,connections:this._connections,errors:this._errors,fatals:this._fatals,totalOut:this._totalOut,totalIn:this._totalIn,totalOutPackets:this._totalOutPackets,totalInPackets:this._totalInPackets,totalBytes:r,totalPackets:n,errorRate:this._errors?this._errors/n:0,fatalRate:this._fatals?this._fatals/n:0,outBytesRate:this._totalOut/t,outPacketsRate:this._totalOutPackets/t,inBytesRate:this._totalIn/t,inPacketsRate:this._totalInPackets/t,totalBytesRate:r/t,totalPacketsRate:n/t},summary:{maxOutSpeed:this._maxOutSpeed,maxInSpeed:this._maxInSpeed,maxConnections:this._maxConnections},node:{upTime:process.uptime(),cpu:process.cpuUsage(),memory:process.memoryUsage()}}}static save(){const e=new Date,t=`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()}`,n=JSON.stringify(this.snapshot(),null,' ');a.default.writeFileSync(`blinksocks.profile-${t}.log`,n)}static set connections(e){this._connections=e,this._maxConnections=r(this._maxConnections,this._connections)}static get connections(){return this._connections}static set fatals(e){this._fatals=e}static get fatals(){return this._fatals}static set errors(e){this._errors=e}static get errors(){return this._errors}static set totalOut(e){this._totalOut=e,this._totalOutPackets+=1,this._tmpOut+=e}static get totalOut(){return this._totalOut}static set totalIn(e){this._totalIn=e,this._totalInPackets+=1,this._tmpIn+=e}static get totalIn(){return this._totalIn}}t.Profile=d,d._startTime=i(),d._timer=null,d._tmpOut=0,d._outSpeed=0,d._maxOutSpeed=0,d._tmpIn=0,d._inSpeed=0,d._maxInSpeed=0,d._connections=0,d._maxConnections=0,d._fatals=0,d._errors=0,d._totalOut=0,d._totalOutPackets=0,d._totalIn=0,d._totalInPackets=0},function(e,t,n){'use strict';function r(e){return e&&e.__esModule?e:{default:e}}var o=n(8),a=r(o),s=n(15),i=r(s),d=n(46),l=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}(d);{const e=process.argv;4===e.length&&('-c'===e[2]||'--config'===e[2])&&e[3].endsWith('.json')||(console.log('Usage: node blinksocks.js -c/--config '),process.exit(0));const t=i.default.resolve(process.cwd(),e[3]);let n=null;try{const e=a.default.readFileSync(t);n=JSON.parse(e)}catch(e){throw Error(`fail to parse your '${t}': ${e.message}`)}const r=new l.Hub(n);r.on('close',()=>process.exit(0)),r.run(),process.on('SIGINT',()=>r.terminate())}e.exports=l},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0});var r=n(16);Object.keys(r).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}})});var o=n(19);Object.keys(o).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return o[e]}})});var a=n(95);Object.keys(a).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return a[e]}})});var s=n(10);Object.keys(s).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return s[e]}})})},function(e){e.exports={name:'winston',description:'A multi-transport async logging library for Node.js',version:'2.3.1',author:'Charlie Robbins ',maintainers:['Jarrett Cruger ','Alberto Pose '],repository:{type:'git',url:'https://github.com/winstonjs/winston.git'},keywords:['winston','logging','sysadmin','tools'],dependencies:{async:'~1.0.0',colors:'1.0.x',cycle:'1.0.x',eyes:'0.1.x',isstream:'0.1.x',"stack-trace":'0.0.x'},devDependencies:{"cross-spawn-async":'^2.0.0',hock:'1.x.x',"std-mocks":'~1.0.0',vows:'0.7.x'},main:'./lib/winston',scripts:{test:'vows --spec --isolate'},engines:{node:'>= 0.10.0'},license:'MIT'}},function(e,t,n){'use strict';Object.defineProperty(t,'Console',{configurable:!0,enumerable:!0,get:function(){return n(49).Console}}),Object.defineProperty(t,'File',{configurable:!0,enumerable:!0,get:function(){return n(65).File}}),Object.defineProperty(t,'Http',{configurable:!0,enumerable:!0,get:function(){return n(68).Http}}),Object.defineProperty(t,'Memory',{configurable:!0,enumerable:!0,get:function(){return n(71).Memory}})},function(e,t,n){'use strict';var r=n(3),o=n(11),a=n(5),s=n(9),i=n(14).Transport,d=t.Console=function(e){i.call(this,e),e=e||{},this.json=e.json||!1,this.colorize=e.colorize||!1,this.prettyPrint=e.prettyPrint||!1,this.timestamp='undefined'!=typeof e.timestamp&&e.timestamp,this.showLevel=!(e.showLevel!==void 0)||e.showLevel,this.label=e.label||null,this.logstash=e.logstash||!1,this.depth=e.depth||null,this.align=e.align||!1,this.stderrLevels=function(e,t){var n='Cannot have non-string elements in stderrLevels Array';if(t){if(e)throw new Error('Cannot set debugStdout and stderrLevels together');return s.stringArrayToSet(['error'],n)}if(!e)return s.stringArrayToSet(['error','debug'],n);if(!Array.isArray(e))throw new Error('Cannot set stderrLevels to type other than Array');return s.stringArrayToSet(e,n)}(e.stderrLevels,e.debugStdout),this.eol=e.eol||o.EOL,this.json&&(this.stringify=e.stringify||function(e){return JSON.stringify(e,null,2)})};a.inherits(d,i),d.prototype.name='console',d.prototype.log=function(e,t,n,r){if(this.silent)return r(null,!0);var o=this,a;a=s.log({colorize:this.colorize,json:this.json,level:e,message:t,meta:n,stringify:this.stringify,timestamp:this.timestamp,showLevel:this.showLevel,prettyPrint:this.prettyPrint,raw:this.raw,label:this.label,logstash:this.logstash,depth:this.depth,formatter:this.formatter,align:this.align,humanReadableUnhandledException:this.humanReadableUnhandledException}),this.stderrLevels[e]?process.stderr.write(a+this.eol):process.stdout.write(a+this.eol),o.emit('logged'),r(null,!0)}},function(e,t,n){'use strict';var r=t;r.decycle=function(e){var t=[],n=[];return function e(r,o){var a,s,i;if('object'==typeof r&&null!==r&&!(r instanceof Boolean)&&!(r instanceof Date)&&!(r instanceof Number)&&!(r instanceof RegExp)&&!(r instanceof String)){for(a=0;a=this.maxRetries)return r(new Error('Transport is in a failed state.'));var o=this;'string'!=typeof t&&(t=''+t);var a=l.log({level:e,message:t,meta:n,json:this.json,logstash:this.logstash,colorize:this.colorize,prettyPrint:this.prettyPrint,timestamp:this.timestamp,showLevel:this.showLevel,stringify:this.stringify,label:this.label,depth:this.depth,formatter:this.formatter,humanReadableUnhandledException:this.humanReadableUnhandledException});'string'==typeof a&&(a+=this.eol),this.filename?this.open(function(e){return e?o._buffer.push([a,r]):void(o._write(a,r),o._size+=a.length,o._lazyDrain())}):(this._write(a,r),this._size+=a.length,this._lazyDrain())},m.prototype._write=function(e,t){if(this._isStreams2)return this._stream.write(e),t&&process.nextTick(function(){t(null,!0)});var n=this._stream.write(e);return t?!1===n?this._stream.once('drain',function(){t(null,!0)}):void process.nextTick(function(){t(null,!0)}):void 0},m.prototype.query=function(e,t){function n(e,t){try{var n=JSON.parse(e);s(n)&&r(n)}catch(n){t||u.emit('error',n)}}function r(t){if(e.rows&&l.length>=e.rows&&'desc'!=e.order)return void(u.readable&&u.destroy());if(e.fields){var n={};e.fields.forEach(function(e){n[e]=t[e]}),t=n}'desc'===e.order&&l.length>=e.rows&&l.shift(),l.push(t)}function s(t){if(t&&'object'==typeof t){var n=new Date(t.timestamp);return e.from&&ne.until?void 0:!0}}'function'==typeof e&&(t=e,e={});var i=a.join(this.dirname,this.filename),e=this.normalizeQuery(e),d='',l=[],c=0,u=o.createReadStream(i,{encoding:'utf8'});u.on('error',function(e){return u.readable&&u.destroy(),t?'ENOENT'===e.code?t(null,l):t(e):void 0}),u.on('data',function(t){for(var t=(d+t).split(/\n+/),r=t.length-1,o=0;o=e.start)&&n(t[o]),c++;d=t[r]}),u.on('close',function(){d&&n(d,!0),'desc'===e.order&&(l=l.reverse()),t&&t(null,l)})},m.prototype.stream=function(e){var t=a.join(this.dirname,this.filename),e=e||{},n=new p,r={file:t,start:e.start};return n.destroy=l.tailFile(r,function(e,t){if(e)return n.emit('error',e);try{n.emit('data',t),t=JSON.parse(t),n.emit('log',t)}catch(t){n.emit('error',t)}}),n},m.prototype.open=function(e){if(this.opening)return e(!0);return!this._stream||this.maxsize&&this._size>=this.maxsize?(e(!0),this._createStream()):void(this._archive=this.zippedArchive?this._stream.path:null,e())},m.prototype.close=function(){var e=this;this._stream&&(this._stream.end(),this._stream.destroySoon(),this._stream.once('finish',function(){e.emit('flush'),e.emit('closed')}))},m.prototype.flush=function(){var e=this;return this._buffer.length?void(this._buffer.forEach(function(t){var n=t[0],r=t[1];process.nextTick(function(){e._write(n,r),e._size+=n.length})}),e._buffer.length=0,e._stream.once('drain',function(){e.emit('flush'),e.emit('logged')})):e.emit('flush')},m.prototype._createStream=function(){var e=this;this.opening=!0,function t(n){function r(t){e._stream&&(e._stream.end(),e._stream.destroySoon()),e._size=t,e.filename=n,e._stream=o.createWriteStream(i,e.options),e._isStreams2=u(e._stream),e._stream.on('error',function(t){e._failures=e.maxsize?e._incFile(function(){t(e._getFile())}):void r(o.size)})}(this._getFile())},m.prototype._incFile=function(e){var t=a.extname(this._basename),n=a.basename(this._basename,t);this.tailable?this._checkMaxFilesTailable(t,n,e):(this._created+=1,this._checkMaxFilesIncrementing(t,n,e))},m.prototype._getFile=function(){var e=a.extname(this._basename),t=a.basename(this._basename,e);return!this.tailable&&this._created?t+(this.rotationFormat?this.rotationFormat():this._created)+e:t+e},m.prototype._checkMaxFilesIncrementing=function(e,t,n){var r=this,s,i;return r.zippedArchive&&(r._archive=a.join(r.dirname,t+(1===r._created?'':r._created-1)+e)),!r.maxFiles||r._created'===o&&(i=null,a=null);var u={fileName:n[2]||null,lineNumber:parseInt(n[3],10)||null,functionName:a,typeName:s,methodName:i,columnNumber:parseInt(n[4],10)||null,native:d};return t._createParsedCallSite(u)}}).filter(function(e){return!!e})};['this','typeName','functionName','methodName','fileName','lineNumber','columnNumber','function','evalOrigin'].forEach(function(e){n.prototype[e]=null,n.prototype['get'+e[0].toUpperCase()+e.substr(1)]=function(){return this[e]}}),['topLevel','eval','native','constructor'].forEach(function(e){n.prototype[e]=!1,n.prototype['is'+e[0].toUpperCase()+e.substr(1)]=function(){return this[e]}}),t._createParsedCallSite=function(e){return new n(e)}},function(e,t,n){'use strict';var r=n(9),o=n(17),a=n(5)._extend,s=t.Container=function(e){this.loggers={},this.options=e||{},this.default={transports:[new o.transports.Console({level:'silly',colorize:!1})]}};s.prototype.get=s.prototype.add=function(e,t){var n=this,s;return this.loggers[e]||(t=a({},t||this.options||this.default),s=t.transports||this.options.transports,t.transports=s?s.slice():[],0===t.transports.length&&(!t||!t.console)&&t.transports.push(this.default.transports[0]),Object.keys(t).forEach(function(n){if('transports'!==n){var a=r.capitalize(n);if(!o.transports[a])throw new Error('Cannot add unknown transport: '+a);var s=t[n];s.id=e,t.transports.push(new o.transports[a](s))}}),t.id=e,this.loggers[e]=new o.Logger(t),this.loggers[e].on('close',function(){n._delete(e)})),this.loggers[e]},s.prototype.has=function(e){return!!this.loggers[e]},s.prototype.close=function(e){function t(e){n.loggers[e]&&(n.loggers[e].close(),n._delete(e))}var n=this;return e?t(e):Object.keys(this.loggers).forEach(function(e){t(e)})},s.prototype._delete=function(e){delete this.loggers[e]}},function(e,t,n){'use strict';function r(e){this.logger=e,this.start=Date.now()}var o=n(3),a=n(5),s=n(22),i=n(18),d=n(9),l=n(23),c=n(12).Stream,u=/%[sdj%]/g,p=t.Logger=function(e){o.EventEmitter.call(this),this.configure(e)};a.inherits(p,o.EventEmitter),p.prototype.configure=function(e){var t=this;Array.isArray(this._names)&&this._names.length&&this.clear(),e=e||{},this.transports={},this._names=[],e.transports&&e.transports.forEach(function(e){t.add(e,null,!0)}),this.padLevels=e.padLevels||!1,this.setLevels(e.levels),e.colors&&i.addColors(e.colors),this.id=e.id||null,this.level=e.level||'info',this.emitErrs=e.emitErrs||!1,this.stripColors=e.stripColors||!1,this.exitOnError=!('undefined'!=typeof e.exitOnError)||e.exitOnError,this.exceptionHandlers={},this.profilers={},['rewriters','filters'].forEach(function(n){t[n]=Array.isArray(e[n])?e[n]:[]}),e.exceptionHandlers&&this.handleExceptions(e.exceptionHandlers)},p.prototype.log=function(e){function t(e){i?i(e):o.emitErrs&&o.emit('error',e)}function n(t){if(i){if(t)return i(t);i(null,e,g,l)}i=null,t||o.emit('logged',e,g,l)}for(var r=Array.prototype.slice.call(arguments,1),o=this;null===r[r.length-1];)r.pop();var i='function'==typeof r[r.length-1]?r.pop():null;if(0===this._names.length)return t(new Error('Cannot log with no transports.'));if('undefined'==typeof o.levels[e])return t(new Error('Unknown log level: '+e));var d=this._names.filter(function(t){var n=o.transports[t];return n.level&&o.levels[n.level]>=o.levels[e]||!n.level&&o.levels[o.level]>=o.levels[e]});if(!d.length)return void(i&&i());var l={},c=!1,p=r&&r[0]&&r[0].match&&null!==r[0].match(u),f=p?r[0].match(u):[],m=f.filter(function(e){return'%%'===e}),g;if(0t)throw Error('len must be greater than 0');const r=e>parseInt(`0x${'ff'.repeat(t)}`);if(r)throw Error(`Number ${e} is too long to store in a '${t}' length buffer`);const o=Buffer.alloc(t);return n===v?o.writeUIntBE(e,0,t):o.writeUIntLE(e,0,t),o}function a(e,t){return e=l(e),t=l(t),i(f.default.randomBytes(1)[0]/255*(t-e+1))+e}function s(e,t){const n=f.default.createHash(e);return n.update(t),n.digest()}function d(e,t,n){const r=f.default.createHmac(e,t);return r.update(n).digest()}var l=Math.ceil,i=Math.floor;Object.defineProperty(t,'__esModule',{value:!0}),t.BYTE_ORDER_LE=t.BYTE_ORDER_BE=t.ATYP_V6=t.ATYP_DOMAIN=t.ATYP_V4=void 0,t.numberToBuffer=o,t.parseURI=function(e){let t=e,n=null;t.startsWith('http://')&&(t=t.substr(7),n=80),t.startsWith('https://')&&(t=t.substr(8),n=443);const r={};_.default.parseHost(t,r);const a=r.hostname,s=r.port,i=u.default.isIP(a)?u.default.isIPv4(a)?y:k:b;return{type:i,host:u.default.isIP(a)?g.default.toBuffer(a):Buffer.from(a),port:o(s||n||80)}},t.getRandomInt=a,t.getRandomChunks=function(e,t,n){const r=e.length,o=[];let s=0;for(;se.length||253e||65535=r?(0]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/ig,a.findUri={start:/\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi,end:/[\s\r\n]|$/,trim:/[`!()\[\]{};:'".,<>?«»“”„‘’]+$/,parens:/(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g},a.defaultPorts={http:'80',https:'443',ftp:'21',gopher:'70',ws:'80',wss:'443'},a.invalid_hostname_characters=/[^a-zA-Z0-9\.-]/,a.domAttributes={a:'href',blockquote:'cite',link:'href',base:'href',script:'src',form:'action',img:'src',area:'href',iframe:'src',embed:'src',source:'src',track:'src',input:'src',audio:'src',video:'src'},a.getDomAttribute=function(e){if(e&&e.nodeName){var t=e.nodeName.toLowerCase();return'input'===t&&'image'!==e.type?void 0:a.domAttributes[t]}},a.encode=g,a.decode=decodeURIComponent,a.iso8859=function(){a.encode=escape,a.decode=unescape},a.unicode=function(){a.encode=g,a.decode=decodeURIComponent},a.characters={pathname:{encode:{expression:/%(24|26|2B|2C|3B|3D|3A|40)/ig,map:{"%24":'$',"%26":'&',"%2B":'+',"%2C":',',"%3B":';',"%3D":'=',"%3A":':',"%40":'@'}},decode:{expression:/[\/\?#]/g,map:{"/":'%2F',"?":'%3F',"#":'%23'}}},reserved:{encode:{expression:/%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig,map:{"%3A":':',"%2F":'/',"%3F":'?',"%23":'#',"%5B":'[',"%5D":']',"%40":'@',"%21":'!',"%24":'$',"%26":'&',"%27":'\'',"%28":'(',"%29":')',"%2A":'*',"%2B":'+',"%2C":',',"%3B":';',"%3D":'='}}},urnpath:{encode:{expression:/%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/ig,map:{"%21":'!',"%24":'$',"%27":'\'',"%28":'(',"%29":')',"%2A":'*',"%2B":'+',"%2C":',',"%3B":';',"%3D":'=',"%40":'@'}},decode:{expression:/[\/\?#:]/g,map:{"/":'%2F',"?":'%3F',"#":'%23',":":'%3A'}}}},a.encodeQuery=function(e,t){var n=a.encode(e+'');return void 0===t&&(t=a.escapeQuerySpace),t?n.replace(/%20/g,'+'):n},a.decodeQuery=function(e,t){e+='',void 0===t&&(t=a.escapeQuerySpace);try{return a.decode(t?e.replace(/\+/g,'%20'):e)}catch(t){return e}};var k={encode:'encode',decode:'decode'},v=function(e,t){return function(n){try{return a[t](n+'').replace(a.characters[e][t].expression,function(n){return a.characters[e][t].map[n]})}catch(t){return n}}},S;for(S in k)a[S+'PathSegment']=v('pathname',k[S]),a[S+'UrnPathSegment']=v('urnpath',k[S]);var x=function(e,t,n){return function(r){var o=n?function(e){return a[t](a[n](e))}:a[t];for(var s=(r+'').split(e),d=0,i=s.length;dr?e.charAt(0)===t.charAt(0)&&'/'===e.charAt(0)?'/':'':(('/'!==e.charAt(r)||'/'!==t.charAt(r))&&(r=e.substring(0,r).lastIndexOf('/')),e.substring(0,r+1))},a.withinString=function(e,t,n){n||(n={});var o=n.start||a.findUri.start,s=n.end||a.findUri.end,i=n.trim||a.findUri.trim,d=n.parens||a.findUri.parens,l=/[a-z0-9-]=["']?$/i;for(o.lastIndex=0;;){var c=o.exec(e);if(!c)break;var u=c.index;if(n.ignoreHtml){var p=e.slice(r(u-3,0),u);if(p&&l.test(p))continue}for(var f=u+e.slice(u).search(s),m=e.slice(u,f),g=-1,h,_;h=d.exec(m),!!h;)_=h.index+h[0].length,g=r(g,_);if((m=-1r.length)return this._parts.hostname;var t=this._parts.hostname.length-this.tld(n).length-1;return t=this._parts.hostname.lastIndexOf('.',t-1)+1,this._parts.hostname.substring(t)||''}if(!e)throw new TypeError('cannot set domain empty');if(a.ensureValidHostname(e),!this._parts.hostname||this.is('IP'))this._parts.hostname=e;else{var o=new RegExp(i(this.domain())+'$');this._parts.hostname=this._parts.hostname.replace(o,e)}return this.build(!n),this},b.tld=function(e,t){if(this._parts.urn)return void 0===e?'':this;if('boolean'==typeof e&&(t=e,e=void 0),void 0===e){if(!this._parts.hostname||this.is('IP'))return'';var r=this._parts.hostname.lastIndexOf('.'),o=this._parts.hostname.substring(r+1);return!0!==t&&n&&n.list[o.toLowerCase()]?n.get(this._parts.hostname)||o:o}var a;if(!e)throw new TypeError('cannot set TLD empty');else if(e.match(/[^a-zA-Z0-9-]/)){if(n&&n.is(e))a=new RegExp(i(this.tld())+'$'),this._parts.hostname=this._parts.hostname.replace(a,e);else throw new TypeError('TLD "'+e+'" contains characters other than [A-Z0-9]');}else if(!this._parts.hostname||this.is('IP'))throw new ReferenceError('cannot set TLD on non-domain host');else a=new RegExp(i(this.tld())+'$'),this._parts.hostname=this._parts.hostname.replace(a,e);return this.build(!t),this},b.directory=function(t,n){if(this._parts.urn)return void 0===t?'':this;if(void 0===t||!0===t){if(!this._parts.path&&!this._parts.hostname)return'';if('/'===this._parts.path)return'/';var r=this._parts.path.length-this.filename().length-1,o=this._parts.path.substring(0,r)||(this._parts.hostname?'/':'');return t?a.decodePath(o):o}var s=this._parts.path.length-this.filename().length,e=this._parts.path.substring(0,s),d=new RegExp('^'+i(e));return this.is('relative')||(!t&&(t='/'),'/'!==t.charAt(0)&&(t='/'+t)),t&&'/'!==t.charAt(t.length-1)&&(t+='/'),t=a.recodePath(t),this._parts.path=this._parts.path.replace(d,t),this.build(!n),this},b.filename=function(e,t){if(this._parts.urn)return void 0===e?'':this;if('string'!=typeof e){if(!this._parts.path||'/'===this._parts.path)return'';var n=this._parts.path.lastIndexOf('/'),r=this._parts.path.substring(n+1);return e?a.decodePathSegment(r):r}var o=!1;'/'===e.charAt(0)&&(e=e.substring(1)),e.match(/\.?\//)&&(o=!0);var s=new RegExp(i(this.filename())+'$');return e=a.recodePath(e),this._parts.path=this._parts.path.replace(s,e),o?this.normalizePath(t):this.build(!t),this},b.suffix=function(e,t){if(this._parts.urn)return void 0===e?'':this;if(void 0===e||!0===e){if(!this._parts.path||'/'===this._parts.path)return'';var n=this.filename(),r=n.lastIndexOf('.'),o,s;return-1===r?'':(o=n.substring(r+1),s=/^[a-z0-9%]+$/i.test(o)?o:'',e?a.decodePathSegment(s):s)}'.'===e.charAt(0)&&(e=e.substring(1));var d=this.suffix(),l;if(!d){if(!e)return this;this._parts.path+='.'+a.recodePath(e)}else l=e?new RegExp(i(d)+'$'):new RegExp(i('.'+d)+'$');return l&&(e=a.recodePath(e),this._parts.path=this._parts.path.replace(l,e)),this.build(!t),this},b.segment=function(e,t,n){var o=this._parts.urn?':':'/',a=this.path(),s='/'===a.substring(0,1),c=a.split(o);if(void 0!==e&&'number'!=typeof e&&(n=t,t=e,e=void 0),void 0!==e&&'number'!=typeof e)throw new Error('Bad segment "'+e+'", must be 0-based integer');if(s&&c.shift(),0>e&&(e=r(c.length+e,0)),void 0===t)return void 0===e?c:c[e];if(null!==e&&void 0!==c[e])t?c[e]=f(t):c.splice(e,1);else if(d(t)){c=[];for(var u=0,i=t.length;un?(this.emit('data',e.slice(0,n),...t),this._nextLength=0,this._digest(e.slice(n),...t)):void 0}}t.AdvancedBuffer=a},function(e){e.exports=require('readline')},function(e,t){'use strict';Object.defineProperty(t,'__esModule',{value:!0});t.Message=class{static parse(){return null}toBuffer(){return Buffer.from([])}}},function(e,t){'use strict';Object.defineProperty(t,'__esModule',{value:!0});const n=t.NOOP=0,r=t.SOCKS_VERSION_V4=4,o=t.SOCKS_VERSION_V5=5,a=t.METHOD_NO_AUTH=0,s=t.REQUEST_COMMAND_CONNECT=1,i=t.REQUEST_COMMAND_BIND=2,d=t.REQUEST_COMMAND_UDP=3,l=t.ATYP_V4=1,c=t.ATYP_DOMAIN=3,u=t.ATYP_V6=4,p=t.REPLY_GRANTED=90,f=t.REPLY_SUCCEEDED=0,m=t.REPLY_COMMAND_NOT_SUPPORTED=7,g=t.REPLY_UNASSIGNED=255},function(e,t,n){'use strict';function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,'__esModule',{value:!0}),t.Proxifier=void 0;var o=n(4),a=r(o),s=n(7),i=r(s),d=n(1),l=n(83),c=n(89),u=n(92),p=n(2);t.Proxifier=class{constructor(e){this._socksTcpReady=!1,this._socksUdpReady=!1,this._httpReady=!1,this.onHandshakeDone=e.onHandshakeDone}isDone(){return this._socksTcpReady||this._socksUdpReady||this._httpReady}makeHandshake(e,t){this._trySocksHandshake(e,t),this.isDone()||this._tryHttpHandshake(e,t)}_trySocksHandshake(e,t){this.isDone()||this._trySocks5Handshake(e,t),this.isDone()||this._trySocks4Handshake(e,t)}_trySocks4Handshake(e,t){const n=c.RequestMessage.parse(t);if(null!==n){const t=n.CMD,r=n.DSTIP,o=n.DSTADDR,a=n.DSTPORT;if(t===p.REQUEST_COMMAND_CONNECT){const t={type:0{const t=new c.ReplyMessage({CMD:p.REPLY_GRANTED});e(t.toBuffer()),this._socksTcpReady=!0})}}}_trySocks5Handshake(e,t){const n=l.IdentifierMessage.parse(t);if(null!==n){const t=new l.SelectMessage;return void e(t.toBuffer())}const r=l.RequestMessage.parse(t);if(null!==r){const t=r.CMD;switch(t){case p.REQUEST_COMMAND_UDP:case p.REQUEST_COMMAND_CONNECT:{const n={type:r.ATYP,host:r.DSTADDR,port:r.DSTPORT};this.onHandshakeDone(n,()=>{const n=new l.ReplyMessage({REP:p.REPLY_SUCCEEDED});e(n.toBuffer()),t===p.REQUEST_COMMAND_CONNECT?this._socksTcpReady=!0:this._socksUdpReady=!0});break}default:{const t=new l.ReplyMessage({REP:p.REPLY_COMMAND_NOT_SUPPORTED});e(t.toBuffer());break}}}}_tryHttpHandshake(e,t){const n=u.HttpRequestMessage.parse(t);if(null!==n){const r=n.METHOD,o=n.URI,s=n.HOST,l=r.toString();let c={};if('CONNECT'===l)c=(0,d.parseURI)(o.toString());else{let e=null,t=s.toString();a.default.isIP(t)?(e=a.default.isIPv4(t)?p.ATYP_V4:p.ATYP_V6,t=i.default.toBuffer(t)):(e=p.ATYP_DOMAIN,t=s),c={type:e,host:t,port:Buffer.from([0,80])}}this.onHandshakeDone(c,(n)=>{if('CONNECT'===l){const t=new u.ConnectReplyMessage;e(t.toBuffer())}else n(t);this._httpReady=!0})}}}},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0});var r=n(84);Object.keys(r).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}})});var o=n(85);Object.keys(o).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return o[e]}})});var a=n(86);Object.keys(a).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return a[e]}})});var s=n(87);Object.keys(s).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return s[e]}})});var i=n(88);Object.keys(i).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return i[e]}})})},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0}),t.IdentifierMessage=void 0;var r=Object.assign||function(e){for(var t=1,n;te.length?null:e[0]===o.SOCKS_VERSION_V5?1>e[1]?null:e.slice(2).length===e[1]?new a({VER:e[0],NMETHODS:e[1],METHODS:e.slice(2)}):null:null}toBuffer(){return Buffer.from([this.VER,this.NMETHODS,...this.METHODS])}}t.IdentifierMessage=a},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0}),t.SelectMessage=void 0;var r=Object.assign||function(e){for(var t=1,n;te.length)return null;if(e[0]!==o.SOCKS_VERSION_V5)return null;const t=[o.REQUEST_COMMAND_CONNECT,o.REQUEST_COMMAND_BIND,o.REQUEST_COMMAND_UDP];if(!t.includes(e[1]))return null;if(e[2]!==o.NOOP)return null;const n=[o.ATYP_V4,o.ATYP_DOMAIN,o.ATYP_V6];if(!n.includes(e[3]))return null;let r=null;switch(e[3]){case o.ATYP_DOMAIN:r=e.slice(5,5+e[4]);break;case o.ATYP_V6:r=e.slice(4,20);break;default:r=e.slice(4,8);}return new a({VER:e[0],CMD:e[1],RSV:e[2],ATYP:e[3],DSTADDR:r,DSTPORT:e.slice(-2)})}}t.RequestMessage=a},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0}),t.ReplyMessage=void 0;var r=Object.assign||function(e){for(var t=1,n;te.length)return null;if(e[0]!==o.NOOP||e[1]!==o.NOOP)return null;const t=[o.ATYP_V4,o.ATYP_DOMAIN,o.ATYP_V6];if(!t.includes(e[3]))return null;let n=null,r=null;switch(e[3]){case o.ATYP_DOMAIN:n=e.slice(5,5+e[4]),r=e.slice(5+e[4],7+e[4]);break;case o.ATYP_V6:n=e.slice(4,20),r=e.slice(20,22);break;default:n=e.slice(4,8),r=e.slice(8,10);}return new a({RSV:[o.NOOP,o.NOOP],FRAG:e[2],ATYP:e[3],DSTADDR:n,DSTPORT:r,DATA:e.slice(6+n.length)})}}t.UdpRequestMessage=a},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0});var r=n(90);Object.keys(r).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}})});var o=n(91);Object.keys(o).forEach(function(e){'default'===e||'__esModule'===e||Object.defineProperty(t,e,{enumerable:!0,get:function(){return o[e]}})})},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0}),t.RequestMessage=void 0;var r=Object.assign||function(e){for(var t=1,n;te.length)return null;if(e[0]!==o.SOCKS_VERSION_V4)return null;const t=[o.REQUEST_COMMAND_CONNECT,o.REQUEST_COMMAND_BIND];if(!t.includes(e[1]))return null;if(e[e.length-1]!==o.NOOP)return null;const n=e.slice(4,8);let r=[],s=[];if(n[0]===o.NOOP&&n[1]===o.NOOP&&n[2]===o.NOOP&&n[3]!==o.NOOP){const t=e.slice(8),n=[];let a=[];var i=!0,d=!1,l;try{for(var c=t[Symbol.iterator](),u;!(i=(u=c.next()).done);i=!0){const e=u.value;e===o.NOOP?(n.push(a),a=[]):a.push(e)}}catch(e){d=!0,l=e}finally{try{!i&&c.return&&c.return()}finally{if(d)throw l}}if(2!==n.length||1>n[1].length)return null;r=n[0],s=Buffer.from(n[1])}return new a({VER:e[0],CMD:e[1],DSTPORT:e.slice(2,4),DSTIP:n,USERID:r,DSTADDR:s})}}t.RequestMessage=a},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0}),t.ReplyMessage=void 0;var r=Object.assign||function(e){for(var t=1,n;te.length)return null;const t=e.toString(),n=t.split('\r\n');if(4>n.length)return null;var o=n[0].split(' '),a=r(o,3);const i=a[0],d=a[1],l=a[2];if(['OPTIONS','GET','HEAD','POST','PUT','DELETE','TRACE','CONNECT'].includes(i)){const e=n.slice(1,-2);var c=!0,u=!1,p;try{for(var f=e[Symbol.iterator](),m;!(c=(m=f.next()).done);c=!0){const e=m.value;if(e.startsWith('Host: ')){const t=e.split(' ')[1];return new s({METHOD:Buffer.from(i),URI:Buffer.from(d),VERSION:Buffer.from(l),HOST:Buffer.from(t)})}}}catch(e){u=!0,p=e}finally{try{!c&&f.return&&f.return()}finally{if(u)throw p}}}return null}}t.HttpRequestMessage=s},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0}),t.ConnectReplyMessage=void 0;var r=Object.assign||function(e){for(var t=1,n;t{return e>Number.MAX_SAFE_INTEGER-1&&(e=0),++e}}();class g extends a.default{constructor(e){super(),this._hub=null,this._sockets=[],this._isClosed=!1,'undefined'!=typeof e&&c.Config.init(e),l.default.level=__LOG_LEVEL__,this._hub=i.default.createServer(),this._hub.on('close',this.onClose.bind(this)),this._hub.on('connection',this.onConnect.bind(this)),this.onSocketClose=this.onSocketClose.bind(this)}onClose(){this._isClosed||(l.default.info('==> [hub] shutdown'),__IS_CLIENT__&&(f.Balancer.destroy(),l.default.info('==> [balancer] stopped')),__PROFILE__&&(l.default.info('==> [profile] saving...'),p.Profile.save(),p.Profile.stop(),l.default.info('==> [profile] stopped')),this._isClosed=!0,this._sockets.forEach((e)=>e.destroy()),this._sockets=[],this.emit('close'))}onSocketClose(e){this._sockets=this._sockets.filter(({id:t})=>e!==t),this.emit('socketClose'),p.Profile.connections=this._sockets.length}onConnect(e){const t=m(),n=new u.Socket({id:t,socket:e});n.on('close',()=>this.onSocketClose(t)),n.on('stat',(...e)=>this.emit('socketStat',...e)),this._sockets.push(n),l.default.info(`[hub] [${e.remoteAddress}:${e.remotePort}] connected`),p.Profile.connections+=1}run(e){const t={host:__LOCAL_HOST__,port:__LOCAL_PORT__};this._hub.listen(t,()=>{l.default.info(`==> [hub] use configuration: ${JSON.stringify(__ALL_CONFIG__)}`),l.default.info(`==> [hub] running as: ${__IS_SERVER__?'Server':'Client'}`),l.default.info(`==> [hub] listening on: ${JSON.stringify(this._hub.address())}`),__IS_CLIENT__&&(l.default.info('==> [balancer] started'),f.Balancer.start(__SERVERS__)),__PROFILE__&&(l.default.info('==> [profile] started'),p.Profile.start()),'function'==typeof e&&e()})}terminate(){this._hub.close(),this.onClose()}}t.Hub=g},function(e,t,n){'use strict';function r(e){return e&&e.__esModule?e:{default:e}}function o(e){return function(){var t=e.apply(this,arguments);return new Promise(function(e,n){function r(o,a){try{var s=t[o](a),i=s.value}catch(e){return void n(e)}return s.done?void e(i):Promise.resolve(i).then(function(e){r('next',e)},function(e){r('throw',e)})}return r('next')})}}Object.defineProperty(t,'__esModule',{value:!0}),t.Socket=void 0;var a=function(){function e(e,t){var n=[],r=!0,o=!1,a;try{for(var s=e[Symbol.iterator](),i;!(r=(i=s.next()).done)&&(n.push(i.value),!(t&&n.length===t));r=!0);}catch(e){o=!0,a=e}finally{try{!r&&s['return']&&s['return']()}finally{if(o)throw a}}return n}return function(t,n){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,n);throw new TypeError('Invalid attempt to destructure non-iterable instance')}}(),s=Object.assign||function(e){for(var t=1,n;tthis._bsocket.write(e),e);this.clientOut(e)}else{if(this._isRedirect)return void(this.fsocketWritable&&this._fsocket.write(e));this.serverIn(e)}x.Profile.totalIn+=e.length,this._fsocket&&this._fsocket.bufferSize>=R&&this._bsocket.pause()}onBackward(e){if(__IS_CLIENT__)this.clientIn(e);else{if(this._isRedirect)return void(this.bsocketWritable&&this._bsocket.write(e));this.serverOut(e)}this._bsocket&&this._bsocket.bufferSize>=R&&this._fsocket.pause()}onError(e){y.default.warn(`[socket] [${this.remote}] ${e.code} - ${e.message}`),x.Profile.errors+=1}onForwardSocketDrain(){null===this._bsocket||this._bsocket.destroyed?this.onForwardSocketClose():this._bsocket.resume()}onForwardSocketTimeout({host:e,port:t}){y.default.warn(`[socket] [${e}:${t}] timeout: no I/O on the connection for ${__TIMEOUT__/1e3}s`),this.onForwardSocketClose()}onForwardSocketClose(){null===this._fsocket||this._fsocket.destroyed||this._fsocket.destroy(),this._bsocket&&0>=this._bsocket.bufferSize&&this.onBackwardSocketClose(),__IS_CLIENT__&&0=this._fsocket.bufferSize&&this.onForwardSocketClose(),__IS_SERVER__&&0{this.createPipe(e),this._tracks.push(`${o}:${a}`),this._isHandshakeDone=!0,t(this.onForward)})}clientOut(e){if(this.fsocketWritable)try{this._pipe.feed(T.MIDDLEWARE_DIRECTION_UPWARD,e)}catch(e){y.default.error(`[socket] [${this.remote}]`,e)}}serverIn(e){if(this.fsocketWritable||!this._isHandshakeDone)try{this._pipe.feed(T.MIDDLEWARE_DIRECTION_DOWNWARD,e),this._tracks.push(D),this._tracks.push(e.length)}catch(e){y.default.error(`[socket] [${this.remote}]`,e)}}serverOut(e){if(this.bsocketWritable)try{this._pipe.feed(T.MIDDLEWARE_DIRECTION_UPWARD,e)}catch(e){y.default.error(`[socket] [${this.remote}]`,e)}}clientIn(e){if(this.bsocketWritable)try{this._pipe.feed(T.MIDDLEWARE_DIRECTION_DOWNWARD,e),this._tracks.push(D),this._tracks.push(e.length)}catch(e){y.default.error(`[socket] [${this.remote}]`,e)}}send(e,t){e===T.MIDDLEWARE_DIRECTION_UPWARD?__IS_CLIENT__?this.clientForward(t):this.serverBackward(t):__IS_CLIENT__?this.clientBackward(t):this.serverForward(t),x.Profile.totalOut+=t.length}clientForward(e){this.fsocketWritable&&(this._fsocket.write(e),this._tracks.push(O),this._tracks.push(e.length))}serverForward(e){this.fsocketWritable&&this._fsocket.write(e)}serverBackward(e){this.bsocketWritable&&(this._bsocket.write(e),this._tracks.push(O),this._tracks.push(e.length))}clientBackward(e){this.bsocketWritable&&this._bsocket.write(e)}connect({host:e,port:t,dstHost:n,dstPort:r},a){var s=this;return o(function*(){if(e&&t){__IS_CLIENT__?y.default.info(`[socket] [${s.remote}] request: ${n}:${r}, connecting to: ${e}:${t}`):y.default.info(`[socket] [${s.remote}] connecting to: ${e}:${t}`),s._tracks.push(`${e}:${t}`);try{const n=yield s._dnsCache.get(e);s._fsocket=c.default.connect({host:n,port:t},a),s._fsocket.on('error',s.onError),s._fsocket.on('close',s.onForwardSocketClose),s._fsocket.on('timeout',s.onForwardSocketTimeout.bind(s,{host:e,port:t})),s._fsocket.on('data',s.onBackward),s._fsocket.on('drain',s.onForwardSocketDrain),s._fsocket.setTimeout(__TIMEOUT__)}catch(n){y.default.error(`[socket] [${s.remote}] connect to ${e}:${t} failed due to: ${n.message}`)}}else y.default.warn(`unexpected host=${e} port=${t}`),s.onBackwardSocketClose()})()}createPipe(e){const t=__PRESETS__.map((t,n)=>(0,T.createMiddleware)(t.name,s({},t.params,0===n?e:{})));this._pipe=new S.Pipe({onNotified:this.onPipeNotified.bind(this)}),this._pipe.setMiddlewares(T.MIDDLEWARE_DIRECTION_UPWARD,t),this._pipe.on(`next_${T.MIDDLEWARE_DIRECTION_UPWARD}`,(e)=>this.send(T.MIDDLEWARE_DIRECTION_UPWARD,e)),this._pipe.on(`next_${T.MIDDLEWARE_DIRECTION_DOWNWARD}`,(e)=>this.send(T.MIDDLEWARE_DIRECTION_DOWNWARD,e))}onPipeNotified(e){if(__IS_SERVER__&&e.type===E.SOCKET_CONNECT_TO_DST){var t=e.payload;const n=t.targetAddress,r=t.onConnected;return this.connect(n,()=>{this._isHandshakeDone=!0,'function'==typeof r&&r()})}return e.type===E.PROCESSING_FAILED?this.onPresetFailed(e):void 0}onPresetFailed(e){var t=e.payload;const n=t.name,r=t.message,o=t.orgData;if(y.default.error(`[socket] [${this.remote}] preset "${n}" fail to process: ${r}`),__IS_SERVER__&&''!==__REDIRECT__&&null===this._fsocket){var s=__REDIRECT__.split(':'),i=a(s,2);const e=i[0],t=i[1];y.default.warn(`[socket] [${this.remote}] connection is redirecting to ${e}:${t}...`),this.connect({host:e,port:t},()=>{this._isRedirect=!0,this.fsocketWritable&&this._fsocket.write(o)})}else{const e=(0,g.getRandomInt)(10,40);y.default.warn(`[socket] [${this.remote}] connection will be closed in ${e}s...`),setTimeout(this.destroy.bind(this),1e3*e)}x.Profile.fatals+=1}dumpTrack(){let e=[],t=0,n=0,r=0,o=0,a='';var s=!0,i=!1,d;try{for(var l=this._tracks[Symbol.iterator](),c;!(s=(c=l.next()).done);s=!0){const s=c.value;if(s===O||s===D){if(a===s)continue;a=s}Number.isInteger(s)&&(a===D&&(t+=1,n+=s),a===O&&(r+=1,o+=s)),e.push(s)}}catch(e){i=!0,d=e}finally{try{!s&&l.return&&l.return()}finally{if(i)throw d}}const u=20;e.length>40&&(e=e.slice(0,u).concat([' ... ']).concat(e.slice(-u)));const p=__IS_CLIENT__?`out/in = ${r}/${t}, ${o}b/${n}b`:`in/out = ${t}/${r}, ${n}b/${o}b`;y.default.info(`[socket] [${this.remote}] closed with summary(${p}) abstract(${e.join(' ')})`),this._tracks=[]}destroy(){this.onForwardSocketClose(),this.onBackwardSocketClose()}}t.Socket=A},function(e,t,n){'use strict';(function(e){function n(e,t){for(var n=-1,r=null==e?0:e.length,o=0,a=[];++nl))return!1;var u=i.get(e);if(u&&i.get(t))return u==t;var p=-1,m=!0,g=n&W?new f:void 0;for(i.set(e,t),i.set(t,e);++pn)return!1;var r=t.length-1;return n==r?t.pop():Ve.call(t,n,1),--this.size,!0},u.prototype.get=function(e){var t=this.__data__,n=h(t,e);return 0>n?void 0:t[n][1]},u.prototype.has=function(e){return-1r?(++this.size,n.push([e,t])):n[r][1]=t,this},p.prototype.clear=function(){this.size=0,this.__data__={hash:new c,map:new(Ke||u),string:new c}},p.prototype['delete']=function(e){var t=D(this,e)['delete'](e);return this.size-=t?1:0,t},p.prototype.get=function(e){return D(this,e).get(e)},p.prototype.has=function(e){return D(this,e).has(e)},p.prototype.set=function(e,t){var n=D(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this},f.prototype.add=f.prototype.push=function(e){return this.__data__.set(e,F),this},f.prototype.has=function(e){return this.__data__.has(e)},m.prototype.clear=function(){this.__data__=new u,this.size=0},m.prototype['delete']=function(e){var t=this.__data__,n=t['delete'](e);return this.size=t.size,n},m.prototype.get=function(e){return this.__data__.get(e)},m.prototype.has=function(e){return this.__data__.has(e)},m.prototype.set=function(e,t){var n=this.__data__;if(n instanceof u){var r=n.__data__;if(!Ke||r.length<200-1)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new p(r)}return n.set(e,t),this.size=n.size,this};var st=Fe?function(e){return null==e?[]:(e=Object(e),n(Fe(e),function(t){return He.call(e,t)}))}:function(){return[]},dt=y;(Ye&&dt(new Ye(new ArrayBuffer(1)))!=ge||Ke&&dt(new Ke)!=ne||Ge&&dt(Ge.resolve())!=se||$e&&dt(new $e)!=le||Ze&&dt(new Ze)!=fe)&&(dt=function(e){var t=y(e),n=t==ae?e.constructor:void 0,r=n?B(n):'';if(r)switch(r){case Je:return ge;case et:return ne;case tt:return se;case nt:return le;case rt:return fe;}return t});var lt=b(function(){return arguments}())?b:function(e){return V(e)&&Ne.call(e,'callee')&&!He.call(e,'callee')},ct=Array.isArray,ut=qe||function(){return!1},pt=De?function(e){return function(t){return e(t)}}(De):function(e){return V(e)&&U(e.length)&&!!be[y(e)]};e.exports=function(e,t){return k(e,t)}}).call(t,n(27)(e))},function(e,t,n){'use strict';Object.defineProperty(t,'__esModule',{value:!0}),t.Pipe=void 0;var r=n(3),o=function(e){return e&&e.__esModule?e:{default:e}}(r),a=n(43),s=n(0);class i extends o.default{constructor(e={}){super(),this._upstream_middlewares=[],this._downstream_middlewares=[],this._onNotified=()=>0,this._onNotified='undefined'==typeof e.onNotified?()=>0:e.onNotified,this.onBroadcast=this.onBroadcast.bind(this)}onBroadcast(e,t){const n=this.getMiddlewares(e),r=[];var o=!0,a=!1,s;try{for(var i=n[Symbol.iterator](),d;!(o=(d=i.next()).done);o=!0){const e=d.value;r.push(e.onNotified(t))}}catch(e){a=!0,s=e}finally{try{!o&&i.return&&i.return()}finally{if(a)throw s}}r.every((e)=>!1==!!e)&&this._onNotified(t)}setMiddlewares(e,t){var n=!0,r=!1,o;try{for(var s=t[Symbol.iterator](),i;!(n=(i=s.next()).done);n=!0){const t=i.value;t.setMaxListeners(2),t.subscribe((t)=>this.onBroadcast(e,t))}}catch(e){r=!0,o=e}finally{try{!n&&s.return&&s.return()}finally{if(r)throw o}}e===a.MIDDLEWARE_DIRECTION_UPWARD?(this._upstream_middlewares=t,this._downstream_middlewares=[].concat(t).reverse()):(this._downstream_middlewares=t,this._upstream_middlewares=[].concat(t).reverse())}getMiddlewares(e){return{[a.MIDDLEWARE_DIRECTION_UPWARD]:this._upstream_middlewares,[a.MIDDLEWARE_DIRECTION_DOWNWARD]:this._downstream_middlewares}[e]}feed(e,t){const n=`next_${e}`,r=this.getMiddlewares(e),o=(t,r=!1)=>{this.emit(r?`next_${-e}`:n,t)},a=(n,r)=>this.onBroadcast(e,{type:s.PROCESSING_FAILED,payload:{name:n,message:r,orgData:t}}),i=r.reduce((t,r)=>{return 1>t.listenerCount(n)&&t.on(n,(t)=>r.write(e,{buffer:t,direct:o,fail:a})),r});1>i.listenerCount(n)&&i.on(n,o),r[0].write(e,{buffer:t,direct:o,fail:a})}}t.Pipe=i}]); //# sourceMappingURL=blinksocks.js.map \ No newline at end of file diff --git a/build/index.js b/build/index.js index b16090f..d9ef254 100755 --- a/build/index.js +++ b/build/index.js @@ -1 +1 @@ -'use strict';var _fs=require('fs');var _fs2=_interopRequireDefault(_fs);var _path=require('path');var _path2=_interopRequireDefault(_path);var _core=require('./core');var __modules__=_interopRequireWildcard(_core);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}if(global.__WEBPACK__){const argv=process.argv;const usage='Usage: node blinksocks.js -c/--config ';const conditions=[argv.length!==4,argv[2]!=='-c'&&argv[2]!=='--config',!argv[3].endsWith('.json')];if(conditions.some(c=>c)){console.log(usage);process.exit(0)}const file=_path2.default.resolve(process.cwd(),argv[3]);let json=null;try{const jsonFile=_fs2.default.readFileSync(file);json=JSON.parse(jsonFile)}catch(err){throw Error(`fail to parse your '${file}': ${err.message}`)}const app=new __modules__.Hub(json);app.on('close',()=>process.exit(0));app.run();process.on('SIGINT',()=>app.terminate())}module.exports=__modules__; \ No newline at end of file +'use strict';var _fs=require('fs');var _fs2=_interopRequireDefault(_fs);var _path=require('path');var _path2=_interopRequireDefault(_path);var _core=require('./core');var __modules__=_interopRequireWildcard(_core);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}if(global.__WEBPACK__){const argv=process.argv;const usage='Usage: node blinksocks.js -c/--config ';if(argv.length!==4||argv[2]!=='-c'&&argv[2]!=='--config'||!argv[3].endsWith('.json')){console.log(usage);process.exit(0)}const file=_path2.default.resolve(process.cwd(),argv[3]);let json=null;try{const jsonFile=_fs2.default.readFileSync(file);json=JSON.parse(jsonFile)}catch(err){throw Error(`fail to parse your '${file}': ${err.message}`)}const app=new __modules__.Hub(json);app.on('close',()=>process.exit(0));app.run();process.on('SIGINT',()=>app.terminate())}module.exports=__modules__; \ No newline at end of file diff --git a/src/index.js b/src/index.js index 589aba4..f969720 100755 --- a/src/index.js +++ b/src/index.js @@ -7,13 +7,7 @@ if (global.__WEBPACK__) { const argv = process.argv; const usage = 'Usage: node blinksocks.js -c/--config '; - const conditions = [ - argv.length !== 4, - (argv[2] !== '-c' && argv[2] !== '--config'), - !argv[3].endsWith('.json') - ]; - - if (conditions.some((c) => c)) { + if (argv.length !== 4 || (argv[2] !== '-c' && argv[2] !== '--config') || !argv[3].endsWith('.json')) { console.log(usage); process.exit(0); }