@faulpeltz/dertunnel 0.7.0 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dertunnel-client.js +71 -71
- package/index.js +7 -2
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -1,2 +1,7 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`);for(let e of r){let o=e.indexOf(":");if(o<0)continue;let s=e.substring(0,o).toLowerCase().trim(),
|
|
1
|
+
"use strict";var nt=Object.create;var Y=Object.defineProperty;var rt=Object.getOwnPropertyDescriptor;var ot=Object.getOwnPropertyNames;var st=Object.getPrototypeOf,it=Object.prototype.hasOwnProperty;var at=(t,n)=>{for(var r in n)Y(t,r,{get:n[r],enumerable:!0})},he=(t,n,r,e)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of ot(n))!it.call(t,o)&&o!==r&&Y(t,o,{get:()=>n[o],enumerable:!(e=rt(n,o))||e.enumerable});return t};var W=(t,n,r)=>(r=t!=null?nt(st(t)):{},he(n||!t||!t.__esModule?Y(r,"default",{value:t,enumerable:!0}):r,t)),ct=t=>he(Y({},"__esModule",{value:!0}),t);var Nt={};at(Nt,{connectTunnel:()=>It});module.exports=ct(Nt);var Je=require("net"),Xe=W(require("tls"));var K=(a=>(a[a.HELLO_REQ=1]="HELLO_REQ",a[a.HELLO_RESP=2]="HELLO_RESP",a[a.END=3]="END",a[a.SERVER_OPEN=4]="SERVER_OPEN",a[a.SERVER_CLOSE=5]="SERVER_CLOSE",a[a.CLIENT_CLOSE=6]="CLIENT_CLOSE",a[a.PING=7]="PING",a[a.PONG=8]="PONG",a[a.SERVER_DATA=65]="SERVER_DATA",a[a.CLIENT_DATA=66]="CLIENT_DATA",a))(K||{});function pe(t){return{name:Object.keys(K).find(n=>K[n]===t)??"UNKNOWN",isBinary:!!(t&64)}}var me=1;var lt="service";var ne=lt+".",ge=5e3;var ut=1*1024*1024,$=12,be=70,xe=80,Te=0,ve=1,ye=2,Ee=4,Se=8,Ce=!!process.env.DERTUNNEL_DEBUG,z=class{constructor(n){this.onMessage=n}buffer=void 0;async receive(n){let r=this.buffer?Buffer.concat([this.buffer,n]):n,e=0;for(;e<r.length;){if(r.length<e+$)return this.buffer=r.subarray(e),!0;if(r[e+Te]!=be||r[e+ve]!=xe)return this.reset(),!1;let o=r.readUint16LE(e+ye),s=r.readUint32LE(e+Ee),i=r.readUint32LE(e+Se),d=i+$+e;if(i>ut)return this.reset(),!1;if(r.length>=d)try{let m=r.subarray(e+$,d);Ce&&Re(o,s,m,!1),await this.onMessage(o,s,m)}catch{return this.reset(),!1}else break;e=d}return this.buffer=r.length>e?r.subarray(e):void 0,!0}reset(){this.buffer=void 0}};function N(t,n,r,e){let o=Buffer.isBuffer(e)?e:e?Buffer.from(JSON.stringify(e)):void 0,s=Buffer.allocUnsafe($+(o?o.length:0));s.writeUint8(be,Te),s.writeUint8(xe,ve),s.writeUint16LE(n,ye),s.writeUint32LE(r,Ee),s.writeUint32LE(o?o.length:0,Se),o?.copy(s,$,0);let i=t.write(s);return Ce&&Re(n,r,o,!0),i}function j(t){return JSON.parse(t.toString("utf8"))}function Re(t,n,r,e){let{name:o,isBinary:s}=pe(t);console.debug(`[msg-${e?"out":"in"} ${o} ${n>0?n:""}] ${r?s?`- ${r.length} payload bytes`:r.toString("utf8"):"- empty"}`)}var re=require("node:crypto");var ft=128,k,w;function dt(t){!k||k.length<t?(k=Buffer.allocUnsafe(t*ft),re.webcrypto.getRandomValues(k),w=0):w+t>k.length&&(re.webcrypto.getRandomValues(k),w=0),w+=t}function ht(t){return dt(t|=0),k.subarray(w-t,w)}function pt(t,n,r){let e=(2<<31-Math.clz32(t.length-1|1))-1,o=Math.ceil(1.6*e*n/t.length);return(s=n)=>{let i="";for(;;){let u=r(o),d=o;for(;d--;)if(i+=t[u[d]&e]||"",i.length>=s)return i}}}function oe(t,n=21){return pt(t,n,ht)}var J=oe("0123456789abcdef",8),qt=oe("0123456789abcdefghijklmnopqrstuvwxyz",24);function Oe(){let t,n,r=new Promise((e,o)=>{t=e,n=o});return r.resolve=t,r.reject=n,r}var _=class{constructor(n,r){this.interval=n;this.func=r}lastUpdated=0;updateTimer;update(n,r){let e=new Date().valueOf();r||e-this.lastUpdated>this.interval?(clearTimeout(this.updateTimer),this.func(n),this.lastUpdated=e):this.updateTimer=setTimeout(()=>{this.func(n),this.updateTimer=void 0},this.interval-e+this.lastUpdated).unref()}};function Ae(t){return t.toLocaleString("en-US",{useGrouping:!0})}function Pe(t){if(t.length<=24)return{service:"",user:"",token:t};let n=Buffer.from(mt(t),"base64").toString("utf8").split("#");return{service:n[0]??"",user:n[1]??"",token:n[2]??""}}function mt(t){let n="",r=t.length;for(let e=0;e<2;e++,r--)for(let o=r-1;o>=0;o-=2)n+=t[o];return n}var Ne=4096,M=13,H=10,Le=new Uint8Array([72,84,84,80,47,49,46,49,M,H]),gt=new Uint8Array([72,84,84,80,47,49,46,49,32]),se=0,X=1,Q=2,ie=3,De=4,we=5,q=class{constructor(n){this.onParsed=n}state=se;id="";contentData;headers=[];expectedBodyLen=0;isRequest=!1;method="";path="";status=0;statusText="";startAt=0;onData(n){let e=0,o=0;for(;e<n.length&&e!==-1&&o++<100;)if(this.state===se||this.state===X||this.state===Q){this.contentData=void 0;let s=e;if((e=n.indexOf(Le,s))>=0)for(let i=0;i<1;i++){let u=e+Le.length;for(;e>0&&n[e-1]!==H&&n[e-1]!==M;)e--;let d=n.subarray(e,u).toString("ascii").split(" ");if(d.length!==3){e=u;break}let m=Be(n,u);if(m){e=u+m.length,this.headers=Ie(m);let{nextState:a,len:b}=ke(this.headers,!0);this.state=a,this.expectedBodyLen=b}else break;this.isRequest=!0,this.id=J(12),this.method=d[0].toUpperCase(),this.path=decodeURI(d[1]),this.onParsed?.({id:this.id,type:"http-request-header",headers:this.headers,method:this.method,path:this.path,status:0,statusText:"",startAt:this.startAt=new Date().valueOf()})}else if((e=n.indexOf(gt,s))>=0){let i=e,u=n.length;for(;e<u&&!(n[e+1]===M&&n[e+2]===H);)e++;for(let d=0;d<1;d++){let m=n.subarray(i,e+1).toString("ascii").split(" ");if(m.length<3)break;let a=Be(n,i);if(a){e=i+a.length,this.headers=Ie(a);let{nextState:O,len:R}=ke(this.headers,!1);this.state=O,this.expectedBodyLen=R}else break;let b=Number.parseInt(m[1]);if(!Number.isFinite(b)||b<100||b>999)break;this.isRequest=!1,this.status=b,this.statusText=m.slice(2).join(" "),this.onParsed?.({id:this.id,type:"http-response-header",headers:this.headers,status:this.status,statusText:this.statusText,method:this.method,path:this.path,endAt:new Date().valueOf()})}}}else if(this.state===ie){let{ok:s,p:i,size:u}=bt(n,e);e=i,u>0?(this.expectedBodyLen=u,this.state=s?De:se):s&&(this.isRequest?this.onParsed?.({id:this.id,type:"http-request-body",headers:this.headers,method:this.method,path:this.path,status:this.status,statusText:this.statusText,content:this.contentData,startAt:this.startAt,endAt:new Date().valueOf()}):this.onParsed?.({id:this.id,type:"http-response-body",headers:this.headers,method:this.method,path:this.path,status:this.status,statusText:this.statusText,content:this.contentData,startAt:this.startAt,endAt:new Date().valueOf()}),e+=2,this.state=this.isRequest?Q:X)}else if(this.state===De){let s=Math.min(n.length-e,this.expectedBodyLen),i=n.slice(e,e+this.expectedBodyLen);this.contentData=this.contentData?Buffer.concat([this.contentData,i]):Buffer.from(i),this.expectedBodyLen-=s,e+=s,this.expectedBodyLen===0&&(e+=2,this.state=ie)}else if(this.state===we){let s=Math.min(n.length-e,this.expectedBodyLen),i=n.slice(e,e+this.expectedBodyLen);this.contentData=this.contentData?Buffer.concat([this.contentData,i]):Buffer.from(i),this.expectedBodyLen-=s,e+=s,this.expectedBodyLen===0&&(this.isRequest?this.onParsed?.({id:this.id,type:"http-request-body",headers:this.headers,method:this.method,path:this.path,status:this.status,statusText:this.statusText,content:this.contentData,startAt:this.startAt,endAt:new Date().valueOf()}):this.onParsed?.({id:this.id,type:"http-response-body",headers:this.headers,method:this.method,path:this.path,status:this.status,statusText:this.statusText,content:this.contentData,startAt:this.startAt,endAt:new Date().valueOf()}),this.state=this.isRequest?Q:X)}if(o>=100)throw new Error("Internal parser error: "+this.state)}};function ke(t,n){let r=Number.parseInt(t.find(e=>e.name==="content-length")?.value??"0");return t.find(e=>e.name==="transfer-encoding")?.value.includes("chunked")?{nextState:ie,isChunked:!0,len:0}:r>0?{nextState:we,isChunked:!1,len:r}:{nextState:n?Q:X,isChunked:!1,len:0}}function Be(t,n){let r=n,e=Math.min(t.length-3,n+Ne);for(;r<e&&!(t[r]===M&&t[r+1]===H&&t[r+2]===M&&t[r+3]===H);)r++;return r<e?t.slice(n,r+4):void 0}function Ie(t){let n=[],r=t.toString("ascii").split(`\r
|
|
2
|
+
`);for(let e of r){let o=e.indexOf(":");if(o<0)continue;let s=e.substring(0,o).toLowerCase().trim(),i=e.substring(o+1).trim();s.length>0&&i.length>0&&n.push({name:s,value:i})}return n}function bt(t,n){let r=0,e=n,o=!1,s=xt(t,n);return s!==void 0&&(r=Number.parseInt(s,16))>=0&&Number.isFinite(r)&&(e=n+s.length+2,o=!0),{ok:o,p:e,size:r}}function xt(t,n){let r=n,e=Math.min(t.length-1,n+Ne);for(;r<e&&!(t[r]===M&&t[r+1]===H);)r++;return r<e?t.slice(n,r).toString("ascii"):void 0}var _e=(t=0)=>n=>`\x1B[${n+t}m`,Me=(t=0)=>n=>`\x1B[${38+t};5;${n}m`,He=(t=0)=>(n,r,e)=>`\x1B[${38+t};2;${n};${r};${e}m`,l={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},Kt=Object.keys(l.modifier),Tt=Object.keys(l.color),vt=Object.keys(l.bgColor),zt=[...Tt,...vt];function yt(){let t=new Map;for(let[n,r]of Object.entries(l)){for(let[e,o]of Object.entries(r))l[e]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},r[e]=l[e],t.set(o[0],o[1]);Object.defineProperty(l,n,{value:r,enumerable:!1})}return Object.defineProperty(l,"codes",{value:t,enumerable:!1}),l.color.close="\x1B[39m",l.bgColor.close="\x1B[49m",l.color.ansi=_e(),l.color.ansi256=Me(),l.color.ansi16m=He(),l.bgColor.ansi=_e(10),l.bgColor.ansi256=Me(10),l.bgColor.ansi16m=He(10),Object.defineProperties(l,{rgbToAnsi256:{value(n,r,e){return n===r&&r===e?n<8?16:n>248?231:Math.round((n-8)/247*24)+232:16+36*Math.round(n/255*5)+6*Math.round(r/255*5)+Math.round(e/255*5)},enumerable:!1},hexToRgb:{value(n){let r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(n.toString(16));if(!r)return[0,0,0];let[e]=r;e.length===3&&(e=[...e].map(s=>s+s).join(""));let o=Number.parseInt(e,16);return[o>>16&255,o>>8&255,o&255]},enumerable:!1},hexToAnsi256:{value:n=>l.rgbToAnsi256(...l.hexToRgb(n)),enumerable:!1},ansi256ToAnsi:{value(n){if(n<8)return 30+n;if(n<16)return 90+(n-8);let r,e,o;if(n>=232)r=((n-232)*10+8)/255,e=r,o=r;else{n-=16;let u=n%36;r=Math.floor(n/36)/5,e=Math.floor(u/6)/5,o=u%6/5}let s=Math.max(r,e,o)*2;if(s===0)return 30;let i=30+(Math.round(o)<<2|Math.round(e)<<1|Math.round(r));return s===2&&(i+=60),i},enumerable:!1},rgbToAnsi:{value:(n,r,e)=>l.ansi256ToAnsi(l.rgbToAnsi256(n,r,e)),enumerable:!1},hexToAnsi:{value:n=>l.ansi256ToAnsi(l.hexToAnsi256(n)),enumerable:!1}}),l}var Et=yt(),T=Et;var ee=W(require("node:process"),1),Fe=W(require("node:os"),1),ae=W(require("node:tty"),1);function x(t,n=globalThis.Deno?globalThis.Deno.args:ee.default.argv){let r=t.startsWith("-")?"":t.length===1?"-":"--",e=n.indexOf(r+t),o=n.indexOf("--");return e!==-1&&(o===-1||e<o)}var{env:f}=ee.default,Z;x("no-color")||x("no-colors")||x("color=false")||x("color=never")?Z=0:(x("color")||x("colors")||x("color=true")||x("color=always"))&&(Z=1);function St(){if("FORCE_COLOR"in f)return f.FORCE_COLOR==="true"?1:f.FORCE_COLOR==="false"?0:f.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(f.FORCE_COLOR,10),3)}function Ct(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function Rt(t,{streamIsTTY:n,sniffFlags:r=!0}={}){let e=St();e!==void 0&&(Z=e);let o=r?Z:e;if(o===0)return 0;if(r){if(x("color=16m")||x("color=full")||x("color=truecolor"))return 3;if(x("color=256"))return 2}if("TF_BUILD"in f&&"AGENT_NAME"in f)return 1;if(t&&!n&&o===void 0)return 0;let s=o||0;if(f.TERM==="dumb")return s;if(ee.default.platform==="win32"){let i=Fe.default.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in f)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(i=>i in f)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(i=>i in f)||f.CI_NAME==="codeship"?1:s;if("TEAMCITY_VERSION"in f)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(f.TEAMCITY_VERSION)?1:0;if(f.COLORTERM==="truecolor"||f.TERM==="xterm-kitty")return 3;if("TERM_PROGRAM"in f){let i=Number.parseInt((f.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(f.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(f.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(f.TERM)||"COLORTERM"in f?1:s}function Ue(t,n={}){let r=Rt(t,{streamIsTTY:t&&t.isTTY,...n});return Ct(r)}var Ot={stdout:Ue({isTTY:ae.default.isatty(1)}),stderr:Ue({isTTY:ae.default.isatty(2)})},$e=Ot;function je(t,n,r){let e=t.indexOf(n);if(e===-1)return t;let o=n.length,s=0,i="";do i+=t.slice(s,e)+n+r,s=e+o,e=t.indexOf(n,s);while(e!==-1);return i+=t.slice(s),i}function qe(t,n,r,e){let o=0,s="";do{let i=t[e-1]==="\r";s+=t.slice(o,i?e-1:e)+n+(i?`\r
|
|
3
|
+
`:`
|
|
4
|
+
`)+r,o=e+1,e=t.indexOf(`
|
|
5
|
+
`,o)}while(e!==-1);return s+=t.slice(o),s}var{stdout:Ge,stderr:Ve}=$e,ce=Symbol("GENERATOR"),U=Symbol("STYLER"),G=Symbol("IS_EMPTY"),Ye=["ansi","ansi","ansi256","ansi16m"],F=Object.create(null),At=(t,n={})=>{if(n.level&&!(Number.isInteger(n.level)&&n.level>=0&&n.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let r=Ge?Ge.level:0;t.level=n.level===void 0?r:n.level};var Pt=t=>{let n=(...r)=>r.join(" ");return At(n,t),Object.setPrototypeOf(n,V.prototype),n};function V(t){return Pt(t)}Object.setPrototypeOf(V.prototype,Function.prototype);for(let[t,n]of Object.entries(T))F[t]={get(){let r=te(this,ue(n.open,n.close,this[U]),this[G]);return Object.defineProperty(this,t,{value:r}),r}};F.visible={get(){let t=te(this,this[U],!0);return Object.defineProperty(this,"visible",{value:t}),t}};var le=(t,n,r,...e)=>t==="rgb"?n==="ansi16m"?T[r].ansi16m(...e):n==="ansi256"?T[r].ansi256(T.rgbToAnsi256(...e)):T[r].ansi(T.rgbToAnsi(...e)):t==="hex"?le("rgb",n,r,...T.hexToRgb(...e)):T[r][t](...e),Lt=["rgb","hex","ansi256"];for(let t of Lt){F[t]={get(){let{level:r}=this;return function(...e){let o=ue(le(t,Ye[r],"color",...e),T.color.close,this[U]);return te(this,o,this[G])}}};let n="bg"+t[0].toUpperCase()+t.slice(1);F[n]={get(){let{level:r}=this;return function(...e){let o=ue(le(t,Ye[r],"bgColor",...e),T.bgColor.close,this[U]);return te(this,o,this[G])}}}}var Dt=Object.defineProperties(()=>{},{...F,level:{enumerable:!0,get(){return this[ce].level},set(t){this[ce].level=t}}}),ue=(t,n,r)=>{let e,o;return r===void 0?(e=t,o=n):(e=r.openAll+t,o=n+r.closeAll),{open:t,close:n,openAll:e,closeAll:o,parent:r}},te=(t,n,r)=>{let e=(...o)=>kt(e,o.length===1?""+o[0]:o.join(" "));return Object.setPrototypeOf(e,Dt),e[ce]=t,e[U]=n,e[G]=r,e},kt=(t,n)=>{if(t.level<=0||!n)return t[G]?"":n;let r=t[U];if(r===void 0)return n;let{openAll:e,closeAll:o}=r;if(n.includes("\x1B"))for(;r!==void 0;)n=je(n,r.close,r.open),r=r.parent;let s=n.indexOf(`
|
|
6
|
+
`);return s!==-1&&(n=qe(n,o,e,s)),e+n+o};Object.defineProperties(V.prototype,F);var Bt=V(),nn=V({level:Ve?Ve.level:0});var E=Bt;var We="0.7.2";var g={headerLines:[`/__\\ DERTUNNEL v${We} /__\\`,""],logLines:[],inspectedRequests:[],statusLines:[]};function Ke(){let t=process.stdout,[n,r]=t.getWindowSize();if(g.inspectedRequests.length>r-15){let s=g.inspectedRequests.findIndex(i=>i.type==="http-response-body"||i.type==="http-response-header");g.inspectedRequests.splice(s>=0?s:0,1)}let e=g.inspectedRequests.map(s=>{let i;s.status===0?i="...":s.status<400?i=E.blue(s.status):s.status<500?i=E.yellow(s.status):i=E.redBright(s.status);let u=new Date(s.startAt).toISOString(),d=s.endAt?`${s.endAt-s.startAt}ms`:"",m=u.slice(0,10)+" "+u.slice(11,19),a=s.headers.find(A=>A.name==="content-type")?.value??"(none)",b=a.split(";")[0],O=s.path.slice(0,Math.min(n-45-(a?a.length:2),s.path.length)),R=E.white(s.content?" "+Ae(s.content.length)+"b ":"");return`${E.cyan(`${m} -`)} ${i} ${E.green(s.method)} ${E.white(O)} ${s.content?E.gray(b):""} ${R} ${E.cyanBright(d)}`});for(;g.headerLines.length+g.statusLines.length+e.length+g.logLines.length+2>r&&g.logLines.length>2;)g.logLines.splice(0,1);let o=[...g.headerLines,"",...g.statusLines,...e,"",...g.logLines];t.cursorTo(0,0),t.clearScreenDown(),o.forEach(s=>{t.write(s??""),t.write(`
|
|
7
|
+
`)})}function ze(t){process.stdout.isTTY?(g.logLines.push(t),g.logLines.length>20&&g.logLines.splice(0,1),Ke()):console.log(t)}var ln=new _(200,()=>Ke());async function It(t){let n=!1,r=!1,e,o=300,s=1.4,i=1e4,u={reconnectTime:o};if(!t.endpoint&&!t.endpointPrefix)throw new Error("Must either define 'endpoint' or 'endpointPrefix'");if(!t.clientToken||!t.localPort&&!t.localUrl)throw new Error("Missing required options");let d=Pe(t.clientToken);t.serviceHost??=d.service;let m=d.user,a=d.token,b,O;if(t.localPort)b=t.localServer??"127.0.0.1",O=t.localPort;else{let v=new URL(t.localUrl||"http://localhost");if(v.protocol!=="http:")throw new Error("Local endpoints only support http protocol");b=v.hostname,O=Number.parseInt(v.port??"80")}let R=Oe(),A=t.serviceHost;A.startsWith(ne)||(A=ne+A);let fe=()=>{let v=new _(200,()=>B("data")),y={bytesReceived:0,bytesSent:0,chunksReceived:0,chunksSent:0,currentConnections:0,totalConnections:0,connectionErrors:0};function B(p,D){try{t.onEndpoint?.(p,y,D??"")}catch{}}e?.destroy(),t.ignoreCertErrors&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0"),e=Xe.default.connect({timeout:1e4,host:A,port:t.servicePort||443,servername:A,...t.ignoreCertErrors?{checkServerIdentity:()=>{}}:{}},()=>{e&&(e.setKeepAlive(!0,ge),N(e,1,0,{version:me,user:m,token:a,endpoint:t.endpoint,endpointPrefix:t.endpointPrefix}))}),e.setMaxListeners(0);let I=new Map,P,L,Qe=new z(async(p,D,S)=>{if(!n&&p===2){let h=j(S);if(!h.success){e?.destroy();let c="Server connection error: "+(h.error??"Unknown error");R.reject(new Error(c)),t.onError?.(c);return}t.onConnected?.(h.endpoint||""),v.update(void 0,!0),R.resolve(),n=!0,u.reconnectTime=o,P=setInterval(()=>{if(!e){P&&clearInterval(P),L&&clearTimeout(L);return}try{N(e,7,0)}catch{P&&clearInterval(P)}L=setTimeout(()=>{t.onError?.("Server pong timeout"),e?.destroy()},7e3).unref()},15e3).unref()}if(p===3){e?.destroy();let h=j(S);h.error&&t.onError?.(h.error);return}if(n){if(p===7)N(e,8,0);else if(p===8)L&&clearTimeout(L);else if(p===65){let h=I.get(D);if(h){if(y.bytesSent+=S.length,y.chunksSent++,h.bytesSent+=S.length,h.parserOut)try{h.parserOut.onData(S)}catch(c){B("error",c?.message)}h.write(S),v.update(void 0,!1)}}else if(p===4){let h=j(S),c=(0,Je.createConnection)({host:b,port:O,allowHalfOpen:!1});c.channelId=h.channelId,c.wasConnected=!1;let Ze=J(),de=C=>{try{t.onProtocolData?.(C.type,Ze,C)}catch{}};t.protocols?.inspect&&(c.parserIn=new q(de),c.parserOut=new q(de)),c.bytesReceived=c.bytesSent=0,I.set(h.channelId,c),c.on("connect",()=>{c.wasConnected=!0,y.currentConnections++,y.totalConnections++,B("connect"),v.update(void 0,!0)}),c.on("close",()=>{c.wasConnected&&(y.currentConnections=Math.max(0,y.currentConnections-1)),I.delete(h.channelId),N(e,6,0,{channelId:c.channelId}),B("disconnect"),v.update(void 0,!0)}),c.on("data",C=>{if(c.bytesReceived+=C.length,y.bytesReceived+=C.length,y.chunksReceived++,c.parserIn)try{c.parserIn.onData(C)}catch(tt){B("error",tt?.message)}!N(e,66,c.channelId,C)&&!c.isPaused()&&(c.pause(),e.once("drain",()=>{c.resume()})),v.update(void 0,!1)}),c.on("error",C=>{y.connectionErrors++,B("error",C?.message),v.update(void 0,!0)})}else if(p===5){let h=j(S),c=I.get(h.channelId);c&&(I.delete(h.channelId),c.end(()=>c.destroy()))}}});e.on("error",p=>{n=!1,!r&&(R.reject(p),t.onError?.("Server connection error: "+p.message))}),e.on("close",()=>{n=!1,P&&clearInterval(P),L&&clearTimeout(L),I.forEach(p=>p.destroy()),!r&&(setTimeout(fe,u.reconnectTime),u.reconnectTime=Math.min(i,u.reconnectTime*s))}),e.on("data",p=>{r||!e||(e.pause(),Qe.receive(p).then(D=>{D||e?.destroy(),e?.resume()}).catch(D=>ze(`Unexpected parser error: ${D.message}`)))})};return fe(),t.waitForInitialConnection!==!1&&await R,()=>{r=!0,e?.destroy()}}0&&(module.exports={connectTunnel});
|