@faulpeltz/dertunnel 0.7.11 → 0.7.13
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 +73 -73
- package/index.js +6 -6
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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=(
|
|
2
|
-
`);for(let
|
|
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=(e,n)=>{for(var r in n)Y(e,r,{get:n[r],enumerable:!0})},he=(e,n,r,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of ot(n))!it.call(e,o)&&o!==r&&Y(e,o,{get:()=>n[o],enumerable:!(t=rt(n,o))||t.enumerable});return e};var W=(e,n,r)=>(r=e!=null?nt(st(e)):{},he(n||!e||!e.__esModule?Y(r,"default",{value:e,enumerable:!0}):r,e)),ct=e=>he(Y({},"__esModule",{value:!0}),e);var wt={};at(wt,{connectTunnel:()=>kt});module.exports=ct(wt);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(e){return{name:Object.keys(K).find(n=>K[n]===e)??"UNKNOWN",isBinary:!!(e&64)}}var me=1;var lt="service";var ne=lt+".",ge=5e3;var ut=1*1024*1024,$=12,be=70,Te=80,xe=0,ve=1,Ee=2,ye=4,Ce=8,Se=!!process.env.DERTUNNEL_DEBUG,z=class{constructor(n){this.onMessage=n}onMessage;buffer=void 0;async receive(n){let r=this.buffer?Buffer.concat([this.buffer,n]):n,t=0;for(;t<r.length;){if(r.length<t+$)return this.buffer=r.subarray(t),!0;if(r[t+xe]!=be||r[t+ve]!=Te)return this.reset(),!1;let o=r.readUint16LE(t+Ee),s=r.readUint32LE(t+ye),i=r.readUint32LE(t+Ce),d=i+$+t;if(i>ut)return this.reset(),!1;if(r.length>=d)try{let p=r.subarray(t+$,d);Se&&Re(o,s,p,!1),await this.onMessage(o,s,p)}catch{return this.reset(),!1}else break;t=d}return this.buffer=r.length>t?r.subarray(t):void 0,!0}reset(){this.buffer=void 0}};function w(e,n,r,t){let o=Buffer.isBuffer(t)?t:t?Buffer.from(JSON.stringify(t)):void 0,s=Buffer.allocUnsafe($+(o?o.length:0));s.writeUint8(be,xe),s.writeUint8(Te,ve),s.writeUint16LE(n,Ee),s.writeUint32LE(r,ye),s.writeUint32LE(o?o.length:0,Ce),o?.copy(s,$,0);let i=e.write(s);return Se&&Re(n,r,o,!0),i}function j(e){return JSON.parse(e.toString("utf8"))}function Re(e,n,r,t){let{name:o,isBinary:s}=pe(e);console.debug(`[msg-${t?"out":"in"} ${o} ${n>0?n:""}] ${r?s?`- ${r.length} payload bytes`:r.toString("utf8"):"- empty"}`)}var re=require("node:crypto");var ft=128,B,N;function dt(e){if(e<0||e>1024)throw new RangeError("Wrong ID size");!B||B.length<e?(B=Buffer.allocUnsafe(e*ft),re.webcrypto.getRandomValues(B),N=0):N+e>B.length&&(re.webcrypto.getRandomValues(B),N=0),N+=e}function ht(e){return dt(e|=0),B.subarray(N-e,N)}function pt(e,n,r){let t=256-256%e.length;if(t===256){let s=e.length-1;return(i=n)=>{if(!i)return"";let l="";for(;;){let d=r(i),p=i;for(;p--;)if(l+=e[d[p]&s],l.length>=i)return l}}}let o=Math.ceil(1.6*256*n/t);return(s=n)=>{if(!s)return"";let i="";for(;;){let l=r(o),d=o;for(;d--;)if(l[d]<t&&(i+=e[l[d]%e.length],i.length>=s))return i}}}function oe(e,n=21){return pt(e,n,ht)}var J=oe("0123456789abcdef",8),qt=oe("0123456789abcdefghijklmnopqrstuvwxyz",24);function Oe(){let e,n,r=new Promise((t,o)=>{e=t,n=o});return r.resolve=e,r.reject=n,r}var _=class{constructor(n,r){this.interval=n;this.func=r}interval;func;lastUpdated=0;updateTimer;update(n,r){let t=new Date().valueOf();r||t-this.lastUpdated>this.interval?(clearTimeout(this.updateTimer),this.func(n),this.lastUpdated=t):this.updateTimer=setTimeout(()=>{this.func(n),this.updateTimer=void 0},this.interval-t+this.lastUpdated).unref()}};function Ae(e){return e.toLocaleString("en-US",{useGrouping:!0})}function Pe(e){if(e.length<=24)return{service:"",user:"",token:e};let n=Buffer.from(mt(e),"base64").toString("utf8").split("#");return{service:n[0]??"",user:n[1]??"",token:n[2]??""}}function mt(e){let n="",r=e.length;for(let t=0;t<2;t++,r--)for(let o=r-1;o>=0;o-=2)n+=e[o];return n}var we=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,Ne=5,q=class{constructor(n){this.onParsed=n}onParsed;state=se;id="";contentData;headers=[];expectedBodyLen=0;isRequest=!1;method="";path="";status=0;statusText="";startAt=0;onData(n){let t=0,o=0;for(;t<n.length&&t!==-1&&o++<100;)if(this.state===se||this.state===X||this.state===Q){this.contentData=void 0;let s=t;if((t=n.indexOf(Le,s))>=0)for(let i=0;i<1;i++){let l=t+Le.length;for(;t>0&&n[t-1]!==H&&n[t-1]!==M;)t--;let d=n.subarray(t,l).toString("ascii").split(" ");if(d.length!==3){t=l;break}let p=Ie(n,l);if(p){t=l+p.length,this.headers=ke(p);let{nextState:a,len:b}=Be(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((t=n.indexOf(gt,s))>=0){let i=t,l=n.length;for(;t<l&&!(n[t+1]===M&&n[t+2]===H);)t++;for(let d=0;d<1;d++){let p=n.subarray(i,t+1).toString("ascii").split(" ");if(p.length<3)break;let a=Ie(n,i);if(a){t=i+a.length,this.headers=ke(a);let{nextState:O,len:R}=Be(this.headers,!1);this.state=O,this.expectedBodyLen=R}else break;let b=Number.parseInt(p[1]);if(!Number.isFinite(b)||b<100||b>999)break;this.isRequest=!1,this.status=b,this.statusText=p.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:l}=bt(n,t);t=i,l>0?(this.expectedBodyLen=l,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()}),t+=2,this.state=this.isRequest?Q:X)}else if(this.state===De){let s=Math.min(n.length-t,this.expectedBodyLen),i=n.slice(t,t+this.expectedBodyLen);this.contentData=this.contentData?Buffer.concat([this.contentData,i]):Buffer.from(i),this.expectedBodyLen-=s,t+=s,this.expectedBodyLen===0&&(t+=2,this.state=ie)}else if(this.state===Ne){let s=Math.min(n.length-t,this.expectedBodyLen),i=n.slice(t,t+this.expectedBodyLen);this.contentData=this.contentData?Buffer.concat([this.contentData,i]):Buffer.from(i),this.expectedBodyLen-=s,t+=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 Be(e,n){let r=Number.parseInt(e.find(t=>t.name==="content-length")?.value??"0");return e.find(t=>t.name==="transfer-encoding")?.value.includes("chunked")?{nextState:ie,isChunked:!0,len:0}:r>0?{nextState:Ne,isChunked:!1,len:r}:{nextState:n?Q:X,isChunked:!1,len:0}}function Ie(e,n){let r=n,t=Math.min(e.length-3,n+we);for(;r<t&&!(e[r]===M&&e[r+1]===H&&e[r+2]===M&&e[r+3]===H);)r++;return r<t?e.slice(n,r+4):void 0}function ke(e){let n=[],r=e.toString("ascii").split(`\r
|
|
2
|
+
`);for(let t of r){let o=t.indexOf(":");if(o<0)continue;let s=t.substring(0,o).toLowerCase().trim(),i=t.substring(o+1).trim();s.length>0&&i.length>0&&n.push({name:s,value:i})}return n}function bt(e,n){let r=0,t=n,o=!1,s=Tt(e,n);return s!==void 0&&(r=Number.parseInt(s,16))>=0&&Number.isFinite(r)&&(t=n+s.length+2,o=!0),{ok:o,p:t,size:r}}function Tt(e,n){let r=n,t=Math.min(e.length-1,n+we);for(;r<t&&!(e[r]===M&&e[r+1]===H);)r++;return r<t?e.slice(n,r).toString("ascii"):void 0}var _e=(e=0)=>n=>`\x1B[${n+e}m`,Me=(e=0)=>n=>`\x1B[${38+e};5;${n}m`,He=(e=0)=>(n,r,t)=>`\x1B[${38+e};2;${n};${r};${t}m`,u={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(u.modifier),xt=Object.keys(u.color),vt=Object.keys(u.bgColor),zt=[...xt,...vt];function Et(){let e=new Map;for(let[n,r]of Object.entries(u)){for(let[t,o]of Object.entries(r))u[t]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},r[t]=u[t],e.set(o[0],o[1]);Object.defineProperty(u,n,{value:r,enumerable:!1})}return Object.defineProperty(u,"codes",{value:e,enumerable:!1}),u.color.close="\x1B[39m",u.bgColor.close="\x1B[49m",u.color.ansi=_e(),u.color.ansi256=Me(),u.color.ansi16m=He(),u.bgColor.ansi=_e(10),u.bgColor.ansi256=Me(10),u.bgColor.ansi16m=He(10),Object.defineProperties(u,{rgbToAnsi256:{value(n,r,t){return n===r&&r===t?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(t/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[t]=r;t.length===3&&(t=[...t].map(s=>s+s).join(""));let o=Number.parseInt(t,16);return[o>>16&255,o>>8&255,o&255]},enumerable:!1},hexToAnsi256:{value:n=>u.rgbToAnsi256(...u.hexToRgb(n)),enumerable:!1},ansi256ToAnsi:{value(n){if(n<8)return 30+n;if(n<16)return 90+(n-8);let r,t,o;if(n>=232)r=((n-232)*10+8)/255,t=r,o=r;else{n-=16;let l=n%36;r=Math.floor(n/36)/5,t=Math.floor(l/6)/5,o=l%6/5}let s=Math.max(r,t,o)*2;if(s===0)return 30;let i=30+(Math.round(o)<<2|Math.round(t)<<1|Math.round(r));return s===2&&(i+=60),i},enumerable:!1},rgbToAnsi:{value:(n,r,t)=>u.ansi256ToAnsi(u.rgbToAnsi256(n,r,t)),enumerable:!1},hexToAnsi:{value:n=>u.ansi256ToAnsi(u.hexToAnsi256(n)),enumerable:!1}}),u}var yt=Et(),x=yt;var ee=W(require("node:process"),1),Fe=W(require("node:os"),1),ae=W(require("node:tty"),1);function T(e,n=globalThis.Deno?globalThis.Deno.args:ee.default.argv){let r=e.startsWith("-")?"":e.length===1?"-":"--",t=n.indexOf(r+e),o=n.indexOf("--");return t!==-1&&(o===-1||t<o)}var{env:f}=ee.default,Z;T("no-color")||T("no-colors")||T("color=false")||T("color=never")?Z=0:(T("color")||T("colors")||T("color=true")||T("color=always"))&&(Z=1);function Ct(){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 St(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function Rt(e,{streamIsTTY:n,sniffFlags:r=!0}={}){let t=Ct();t!==void 0&&(Z=t);let o=r?Z:t;if(o===0)return 0;if(r){if(T("color=16m")||T("color=full")||T("color=truecolor"))return 3;if(T("color=256"))return 2}if("TF_BUILD"in f&&"AGENT_NAME"in f)return 1;if(e&&!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"||f.TERM==="xterm-ghostty"||f.TERM==="wezterm")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(e,n={}){let r=Rt(e,{streamIsTTY:e&&e.isTTY,...n});return St(r)}var Ot={stdout:Ue({isTTY:ae.default.isatty(1)}),stderr:Ue({isTTY:ae.default.isatty(2)})},$e=Ot;function je(e,n,r){let t=e.indexOf(n);if(t===-1)return e;let o=n.length,s=0,i="";do i+=e.slice(s,t)+n+r,s=t+o,t=e.indexOf(n,s);while(t!==-1);return i+=e.slice(s),i}function qe(e,n,r,t){let o=0,s="";do{let i=e[t-1]==="\r";s+=e.slice(o,i?t-1:t)+n+(i?`\r
|
|
3
3
|
`:`
|
|
4
|
-
`)+r,o=
|
|
5
|
-
`,o)}while(
|
|
6
|
-
`);return s!==-1&&(n=qe(n,o,
|
|
7
|
-
`)})}function ze(
|
|
4
|
+
`)+r,o=t+1,t=e.indexOf(`
|
|
5
|
+
`,o)}while(t!==-1);return s+=e.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=(e,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;e.level=n.level===void 0?r:n.level};var Pt=e=>{let n=(...r)=>r.join(" ");return At(n,e),Object.setPrototypeOf(n,V.prototype),n};function V(e){return Pt(e)}Object.setPrototypeOf(V.prototype,Function.prototype);for(let[e,n]of Object.entries(x))F[e]={get(){let r=te(this,ue(n.open,n.close,this[U]),this[G]);return Object.defineProperty(this,e,{value:r}),r}};F.visible={get(){let e=te(this,this[U],!0);return Object.defineProperty(this,"visible",{value:e}),e}};var le=(e,n,r,...t)=>e==="rgb"?n==="ansi16m"?x[r].ansi16m(...t):n==="ansi256"?x[r].ansi256(x.rgbToAnsi256(...t)):x[r].ansi(x.rgbToAnsi(...t)):e==="hex"?le("rgb",n,r,...x.hexToRgb(...t)):x[r][e](...t),Lt=["rgb","hex","ansi256"];for(let e of Lt){F[e]={get(){let{level:r}=this;return function(...t){let o=ue(le(e,Ye[r],"color",...t),x.color.close,this[U]);return te(this,o,this[G])}}};let n="bg"+e[0].toUpperCase()+e.slice(1);F[n]={get(){let{level:r}=this;return function(...t){let o=ue(le(e,Ye[r],"bgColor",...t),x.bgColor.close,this[U]);return te(this,o,this[G])}}}}var Dt=Object.defineProperties(()=>{},{...F,level:{enumerable:!0,get(){return this[ce].level},set(e){this[ce].level=e}}}),ue=(e,n,r)=>{let t,o;return r===void 0?(t=e,o=n):(t=r.openAll+e,o=n+r.closeAll),{open:e,close:n,openAll:t,closeAll:o,parent:r}},te=(e,n,r)=>{let t=(...o)=>Bt(t,o.length===1?""+o[0]:o.join(" "));return Object.setPrototypeOf(t,Dt),t[ce]=e,t[U]=n,t[G]=r,t},Bt=(e,n)=>{if(e.level<=0||!n)return e[G]?"":n;let r=e[U];if(r===void 0)return n;let{openAll:t,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,t,s)),t+n+o};Object.defineProperties(V.prototype,F);var It=V(),nn=V({level:Ve?Ve.level:0});var y=It;var We="0.7.13";var g={headerLines:[`/__\\ DERTUNNEL v${We} /__\\`,""],logLines:[],inspectedRequests:[],statusLines:[]};function Ke(){let e=process.stdout,[n,r]=e.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 t=g.inspectedRequests.map(s=>{let i;s.status===0?i="...":s.status<400?i=y.blue(s.status):s.status<500?i=y.yellow(s.status):i=y.redBright(s.status);let l=new Date(s.startAt).toISOString(),d=s.endAt?`${s.endAt-s.startAt}ms`:"",p=l.slice(0,10)+" "+l.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=y.white(s.content?" "+Ae(s.content.length)+"b ":"");return`${y.cyan(`${p} -`)} ${i} ${y.green(s.method)} ${y.white(O)} ${s.content?y.gray(b):""} ${R} ${y.cyanBright(d)}`});for(;g.headerLines.length+g.statusLines.length+t.length+g.logLines.length+2>r&&g.logLines.length>2;)g.logLines.splice(0,1);let o=[...g.headerLines,"",...g.statusLines,...t,"",...g.logLines];e.cursorTo(0,0),e.clearScreenDown(),o.forEach(s=>{e.write(s??""),e.write(`
|
|
7
|
+
`)})}function ze(e){process.stdout.isTTY?(g.logLines.push(e),g.logLines.length>20&&g.logLines.splice(0,1),Ke()):console.log(e)}var ln=new _(200,()=>Ke());async function kt(e){let n=!1,r=!1,t,o=300,s=1.4,i=1e4,l={reconnectTime:o};if(!e.endpoint&&!e.endpointPrefix)throw new Error("Must either define 'endpoint' or 'endpointPrefix'");if(!e.clientToken||!e.localPort&&!e.localUrl)throw new Error("Missing required options");let d=Pe(e.clientToken);e.serviceHost??=d.service;let p=d.user,a=d.token,b,O;if(e.localPort)b=e.localServer??"127.0.0.1",O=e.localPort;else{let v=new URL(e.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=e.serviceHost;A.startsWith(ne)||(A=ne+A);let fe=()=>{let v=new _(200,()=>I("data")),E={bytesReceived:0,bytesSent:0,chunksReceived:0,chunksSent:0,currentConnections:0,totalConnections:0,connectionErrors:0};function I(m,D){try{e.onEndpoint?.(m,E,D??"")}catch{}}t?.destroy(),e.ignoreCertErrors&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0"),t=Xe.default.connect({timeout:1e4,host:A,port:e.servicePort||443,servername:A,...e.ignoreCertErrors?{checkServerIdentity:()=>{}}:{}},()=>{t&&(t.setKeepAlive(!0,ge),w(t,1,0,{version:me,user:p,token:a,endpoint:e.endpoint,endpointPrefix:e.endpointPrefix}))}),t.setMaxListeners(0);let k=new Map,P,L,Qe=new z(async(m,D,C)=>{if(!n&&m===2){let h=j(C);if(!h.success){t?.destroy();let c="Server connection error: "+(h.error??"Unknown error");R.reject(new Error(c)),e.onError?.(c);return}e.onConnected?.(h.endpoint||""),v.update(void 0,!0),R.resolve(),n=!0,l.reconnectTime=o,P=setInterval(()=>{if(!t){P&&clearInterval(P),L&&clearTimeout(L);return}try{w(t,7,0)}catch{P&&clearInterval(P)}L=setTimeout(()=>{e.onError?.("Server pong timeout"),t?.destroy()},7e3).unref()},15e3).unref()}if(m===3){t?.destroy();let h=j(C);h.error&&e.onError?.(h.error);return}if(n){if(m===7)w(t,8,0);else if(m===8)L&&clearTimeout(L);else if(m===65){let h=k.get(D);if(h){if(E.bytesSent+=C.length,E.chunksSent++,h.bytesSent+=C.length,h.parserOut)try{h.parserOut.onData(C)}catch(c){I("error",c?.message)}h.write(C),v.update(void 0,!1)}}else if(m===4){let h=j(C),c=(0,Je.createConnection)({host:b,port:O,allowHalfOpen:!1});c.channelId=h.channelId,c.wasConnected=!1;let Ze=J(),de=S=>{try{e.onProtocolData?.(S.type,Ze,S)}catch{}};e.protocols?.inspect&&(c.parserIn=new q(de),c.parserOut=new q(de)),c.bytesReceived=c.bytesSent=0,k.set(h.channelId,c),c.on("connect",()=>{c.wasConnected=!0,E.currentConnections++,E.totalConnections++,I("connect"),v.update(void 0,!0)}),c.on("close",()=>{c.wasConnected&&(E.currentConnections=Math.max(0,E.currentConnections-1)),k.delete(h.channelId),w(t,6,0,{channelId:c.channelId}),I("disconnect"),v.update(void 0,!0)}),c.on("data",S=>{if(c.bytesReceived+=S.length,E.bytesReceived+=S.length,E.chunksReceived++,c.parserIn)try{c.parserIn.onData(S)}catch(tt){I("error",tt?.message)}!w(t,66,c.channelId,S)&&!c.isPaused()&&(c.pause(),t.once("drain",()=>{c.resume()})),v.update(void 0,!1)}),c.on("error",S=>{E.connectionErrors++,I("error",S?.message),v.update(void 0,!0)})}else if(m===5){let h=j(C),c=k.get(h.channelId);c&&(k.delete(h.channelId),c.end(()=>c.destroy()))}}});t.on("error",m=>{n=!1,!r&&(R.reject(m),e.onError?.("Server connection error: "+m.message))}),t.on("close",()=>{n=!1,P&&clearInterval(P),L&&clearTimeout(L),k.forEach(m=>m.destroy()),!r&&(setTimeout(fe,l.reconnectTime),l.reconnectTime=Math.min(i,l.reconnectTime*s))}),t.on("data",m=>{r||!t||(t.pause(),Qe.receive(m).then(D=>{D||t?.destroy(),t?.resume()}).catch(D=>ze(`Unexpected parser error: ${D.message}`)))})};return fe(),e.waitForInitialConnection!==!1&&await R,()=>{r=!0,t?.destroy()}}0&&(module.exports={connectTunnel});
|