@termiq/cli 1.6.0 → 1.8.0
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/dist/bin.js +36 -31
- package/package.json +6 -3
package/dist/bin.js
CHANGED
|
@@ -1,39 +1,39 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Ld=Object.create;var So=Object.defineProperty;var Nd=Object.getOwnPropertyDescriptor;var Dd=Object.getOwnPropertyNames;var Fd=Object.getPrototypeOf,Md=Object.prototype.hasOwnProperty;var Ft=(r,e)=>()=>(r&&(e=r(r=0)),e);var D=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Bd=(r,e)=>{for(var t in e)So(r,t,{get:e[t],enumerable:!0})},jd=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Dd(e))!Md.call(r,s)&&s!==t&&So(r,s,{get:()=>e[s],enumerable:!(n=Nd(e,s))||n.enumerable});return r};var me=(r,e,t)=>(t=r!=null?Ld(Fd(r)):{},jd(e||!r||!r.__esModule?So(t,"default",{value:r,enumerable:!0}):t,r));var Ws=D(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.generateCorrelationId=Wd;Qn.runWithCorrelation=Hd;Qn.getCurrentCorrelationId=Vd;var qd=require("async_hooks");function Wd(){let r=new Uint8Array(4),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(r);else for(let t=0;t<4;t++)r[t]=Math.floor(Math.random()*256);return"c-"+Array.from(r,t=>t.toString(16).padStart(2,"0")).join("")}var nf=new qd.AsyncLocalStorage;function Hd(r,e){return nf.run(r,e)}function Vd(){return nf.getStore()}});var of=D(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.LOG_LEVELS=void 0;yn.shouldLog=$d;yn.formatLogLine=zd;var Kd=Ws();yn.LOG_LEVELS=["silent","error","warn","info","debug"];var sf={silent:0,error:1,warn:2,info:3,debug:4};function $d(r,e){return sf[r]<=sf[e]}function zd(r,e,t,n){let s={ts:new Date().toISOString(),level:r,src:e,msg:t},i=(0,Kd.getCurrentCorrelationId)();i&&(s.cid=i);let a=n;a.length>0&&typeof a[0]=="object"&&a[0]!==null&&!(a[0]instanceof Error)&&!Array.isArray(a[0])&&(s.ctx=a[0],a=a.slice(1));let c=[...a].reverse().find(u=>u instanceof Error);c&&(s.err={message:c.message,stack:c.stack,name:c.name},a=a.filter(u=>u!==c)),a.length>0&&(s.args=a);try{return JSON.stringify(s)}catch{return JSON.stringify({ts:s.ts,level:r,src:e,msg:t,_unserializable:!0})}}});var af=D(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.formatLogLine=xr.shouldLog=xr.LOG_LEVELS=void 0;var To=of();Object.defineProperty(xr,"LOG_LEVELS",{enumerable:!0,get:function(){return To.LOG_LEVELS}});Object.defineProperty(xr,"shouldLog",{enumerable:!0,get:function(){return To.shouldLog}});Object.defineProperty(xr,"formatLogLine",{enumerable:!0,get:function(){return To.formatLogLine}})});var cf=D(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});Hs.CircularBuffer=void 0;var Co=class{buffer=[];totalSize=0;maxSize;constructor(e=100){this.maxSize=e*1024}append(e){for(this.buffer.push(e),this.totalSize+=e.length;this.totalSize>this.maxSize&&this.buffer.length>1;){let t=this.buffer.shift();t&&(this.totalSize-=t.length)}}getContent(){return this.buffer.join("")}getLastBytes(e){let t=this.getContent();return t.length<=e?t:t.slice(-e)}getSize(){return this.totalSize}clear(){this.buffer=[],this.totalSize=0}};Hs.CircularBuffer=Co});var Ks=D(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.getApiUrl=Gd;Vs.getWsUrl=Yd;function Gd(r){return`${r.getServerUrl()}/api`}function Yd(r){let e=r.getServerUrl();return e.startsWith("https://")?e.replace(/^https:\/\//,"wss://"):e.replace(/^http:\/\//,"ws://")}});var uf=D(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.getCurrentCorrelationId=pt.runWithCorrelation=pt.generateCorrelationId=pt.getWsUrl=pt.getApiUrl=pt.CircularBuffer=void 0;var Xd=cf();Object.defineProperty(pt,"CircularBuffer",{enumerable:!0,get:function(){return Xd.CircularBuffer}});var ff=Ks();Object.defineProperty(pt,"getApiUrl",{enumerable:!0,get:function(){return ff.getApiUrl}});Object.defineProperty(pt,"getWsUrl",{enumerable:!0,get:function(){return ff.getWsUrl}});var Oo=Ws();Object.defineProperty(pt,"generateCorrelationId",{enumerable:!0,get:function(){return Oo.generateCorrelationId}});Object.defineProperty(pt,"runWithCorrelation",{enumerable:!0,get:function(){return Oo.runWithCorrelation}});Object.defineProperty(pt,"getCurrentCorrelationId",{enumerable:!0,get:function(){return Oo.getCurrentCorrelationId}})});var hf=D(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0})});var pf=D(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0})});var gf=D($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});$s.PLAN_LIMITS=void 0;$s.PLAN_LIMITS={free:{maxAgents:1,maxTerminals:2,maxTeamMembers:1,historyDays:1},basic:{maxAgents:3,maxTerminals:10,maxTeamMembers:1,historyDays:7},pro:{maxAgents:10,maxTerminals:50,maxTeamMembers:5,historyDays:30}}});var mf=D(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0})});var yf=D(Kt=>{"use strict";var Jd=Kt&&Kt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),zs=Kt&&Kt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Jd(e,r,t)};Object.defineProperty(Kt,"__esModule",{value:!0});zs(hf(),Kt);zs(pf(),Kt);zs(gf(),Kt);zs(mf(),Kt)});var Ef=D(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.API_VERSION=Ct.WS_NAMESPACES=Ct.TIMEOUTS=Ct.STATUS_PATTERNS=Ct.TERMINAL_STATUSES=void 0;Ct.TERMINAL_STATUSES={idle:{label:"Idle",color:"gray",icon:"\u25CF"},working:{label:"Working",color:"blue",icon:"\u27F3"},waiting:{label:"Awaiting input",color:"orange",icon:"\u26A0"},completed:{label:"Completed",color:"green",icon:"\u2713"},error:{label:"Error",color:"red",icon:"\u2715"},offline:{label:"Offline",color:"black",icon:"\u26AB"}};Ct.STATUS_PATTERNS={idle:[/[❯$]\s*$/,/>\s*$/],waiting:[/\[Y\/n\]/i,/\(y\/N\)/i,/Continue\?/i,/proceed\?/i],completed:[/✓/,/Done/,/Completed/,/Success/],error:[/Error/,/Failed/,/✕/,/Exception/]};Ct.TIMEOUTS={HEARTBEAT_INTERVAL:3e4,OFFLINE_THRESHOLD:6e4,DEVICE_CODE_EXPIRY:9e5,DEVICE_CODE_POLL_INTERVAL:5e3};Ct.WS_NAMESPACES={AGENT:"/agent",CLIENT:"/client"};Ct.API_VERSION="v1"});var wf=D(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.isMultiRecipientPayload=Zd;Gs.isEncryptedPayload=Qd;function Zd(r){return typeof r=="object"&&r!==null&&"v"in r&&r.v===2&&"recipients"in r&&Array.isArray(r.recipients)}function Qd(r){if(typeof r!="object"||r===null||!("encrypted"in r))return!1;let e=r.encrypted;if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.v=="number"&&typeof t.sid=="string"&&typeof t.n=="string"&&typeof t.c=="string"}});var ko=D((HE,Ys)=>{(function(r){"use strict";var e=function(f){var h,l=new Float64Array(16);if(f)for(h=0;h<f.length;h++)l[h]=f[h];return l},t=function(){throw new Error("no PRNG")},n=new Uint8Array(16),s=new Uint8Array(32);s[0]=9;var i=e(),a=e([1]),c=e([56129,1]),u=e([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),d=e([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),g=e([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),_=e([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),y=e([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function v(f,h,l,o){f[h]=l>>24&255,f[h+1]=l>>16&255,f[h+2]=l>>8&255,f[h+3]=l&255,f[h+4]=o>>24&255,f[h+5]=o>>16&255,f[h+6]=o>>8&255,f[h+7]=o&255}function S(f,h,l,o,p){var E,w=0;for(E=0;E<p;E++)w|=f[h+E]^l[o+E];return(1&w-1>>>8)-1}function O(f,h,l,o){return S(f,h,l,o,16)}function H(f,h,l,o){return S(f,h,l,o,32)}function z(f,h,l,o){for(var p=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,E=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,w=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,k=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,F=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,Y=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,q=h[0]&255|(h[1]&255)<<8|(h[2]&255)<<16|(h[3]&255)<<24,Ce=h[4]&255|(h[5]&255)<<8|(h[6]&255)<<16|(h[7]&255)<<24,V=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,te=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,re=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,fe=l[16]&255|(l[17]&255)<<8|(l[18]&255)<<16|(l[19]&255)<<24,ce=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,ne=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,ae=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,se=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,K=p,Z=E,W=w,$=k,G=F,U=Y,b=q,x=Ce,R=V,C=te,P=re,N=fe,ee=ce,ue=ne,ge=ae,le=se,m,ye=0;ye<20;ye+=2)m=K+ee|0,G^=m<<7|m>>>25,m=G+K|0,R^=m<<9|m>>>23,m=R+G|0,ee^=m<<13|m>>>19,m=ee+R|0,K^=m<<18|m>>>14,m=U+Z|0,C^=m<<7|m>>>25,m=C+U|0,ue^=m<<9|m>>>23,m=ue+C|0,Z^=m<<13|m>>>19,m=Z+ue|0,U^=m<<18|m>>>14,m=P+b|0,ge^=m<<7|m>>>25,m=ge+P|0,W^=m<<9|m>>>23,m=W+ge|0,b^=m<<13|m>>>19,m=b+W|0,P^=m<<18|m>>>14,m=le+N|0,$^=m<<7|m>>>25,m=$+le|0,x^=m<<9|m>>>23,m=x+$|0,N^=m<<13|m>>>19,m=N+x|0,le^=m<<18|m>>>14,m=K+$|0,Z^=m<<7|m>>>25,m=Z+K|0,W^=m<<9|m>>>23,m=W+Z|0,$^=m<<13|m>>>19,m=$+W|0,K^=m<<18|m>>>14,m=U+G|0,b^=m<<7|m>>>25,m=b+U|0,x^=m<<9|m>>>23,m=x+b|0,G^=m<<13|m>>>19,m=G+x|0,U^=m<<18|m>>>14,m=P+C|0,N^=m<<7|m>>>25,m=N+P|0,R^=m<<9|m>>>23,m=R+N|0,C^=m<<13|m>>>19,m=C+R|0,P^=m<<18|m>>>14,m=le+ge|0,ee^=m<<7|m>>>25,m=ee+le|0,ue^=m<<9|m>>>23,m=ue+ee|0,ge^=m<<13|m>>>19,m=ge+ue|0,le^=m<<18|m>>>14;K=K+p|0,Z=Z+E|0,W=W+w|0,$=$+k|0,G=G+F|0,U=U+Y|0,b=b+q|0,x=x+Ce|0,R=R+V|0,C=C+te|0,P=P+re|0,N=N+fe|0,ee=ee+ce|0,ue=ue+ne|0,ge=ge+ae|0,le=le+se|0,f[0]=K>>>0&255,f[1]=K>>>8&255,f[2]=K>>>16&255,f[3]=K>>>24&255,f[4]=Z>>>0&255,f[5]=Z>>>8&255,f[6]=Z>>>16&255,f[7]=Z>>>24&255,f[8]=W>>>0&255,f[9]=W>>>8&255,f[10]=W>>>16&255,f[11]=W>>>24&255,f[12]=$>>>0&255,f[13]=$>>>8&255,f[14]=$>>>16&255,f[15]=$>>>24&255,f[16]=G>>>0&255,f[17]=G>>>8&255,f[18]=G>>>16&255,f[19]=G>>>24&255,f[20]=U>>>0&255,f[21]=U>>>8&255,f[22]=U>>>16&255,f[23]=U>>>24&255,f[24]=b>>>0&255,f[25]=b>>>8&255,f[26]=b>>>16&255,f[27]=b>>>24&255,f[28]=x>>>0&255,f[29]=x>>>8&255,f[30]=x>>>16&255,f[31]=x>>>24&255,f[32]=R>>>0&255,f[33]=R>>>8&255,f[34]=R>>>16&255,f[35]=R>>>24&255,f[36]=C>>>0&255,f[37]=C>>>8&255,f[38]=C>>>16&255,f[39]=C>>>24&255,f[40]=P>>>0&255,f[41]=P>>>8&255,f[42]=P>>>16&255,f[43]=P>>>24&255,f[44]=N>>>0&255,f[45]=N>>>8&255,f[46]=N>>>16&255,f[47]=N>>>24&255,f[48]=ee>>>0&255,f[49]=ee>>>8&255,f[50]=ee>>>16&255,f[51]=ee>>>24&255,f[52]=ue>>>0&255,f[53]=ue>>>8&255,f[54]=ue>>>16&255,f[55]=ue>>>24&255,f[56]=ge>>>0&255,f[57]=ge>>>8&255,f[58]=ge>>>16&255,f[59]=ge>>>24&255,f[60]=le>>>0&255,f[61]=le>>>8&255,f[62]=le>>>16&255,f[63]=le>>>24&255}function X(f,h,l,o){for(var p=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,E=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,w=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,k=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,F=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,Y=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,q=h[0]&255|(h[1]&255)<<8|(h[2]&255)<<16|(h[3]&255)<<24,Ce=h[4]&255|(h[5]&255)<<8|(h[6]&255)<<16|(h[7]&255)<<24,V=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,te=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,re=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,fe=l[16]&255|(l[17]&255)<<8|(l[18]&255)<<16|(l[19]&255)<<24,ce=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,ne=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,ae=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,se=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,K=p,Z=E,W=w,$=k,G=F,U=Y,b=q,x=Ce,R=V,C=te,P=re,N=fe,ee=ce,ue=ne,ge=ae,le=se,m,ye=0;ye<20;ye+=2)m=K+ee|0,G^=m<<7|m>>>25,m=G+K|0,R^=m<<9|m>>>23,m=R+G|0,ee^=m<<13|m>>>19,m=ee+R|0,K^=m<<18|m>>>14,m=U+Z|0,C^=m<<7|m>>>25,m=C+U|0,ue^=m<<9|m>>>23,m=ue+C|0,Z^=m<<13|m>>>19,m=Z+ue|0,U^=m<<18|m>>>14,m=P+b|0,ge^=m<<7|m>>>25,m=ge+P|0,W^=m<<9|m>>>23,m=W+ge|0,b^=m<<13|m>>>19,m=b+W|0,P^=m<<18|m>>>14,m=le+N|0,$^=m<<7|m>>>25,m=$+le|0,x^=m<<9|m>>>23,m=x+$|0,N^=m<<13|m>>>19,m=N+x|0,le^=m<<18|m>>>14,m=K+$|0,Z^=m<<7|m>>>25,m=Z+K|0,W^=m<<9|m>>>23,m=W+Z|0,$^=m<<13|m>>>19,m=$+W|0,K^=m<<18|m>>>14,m=U+G|0,b^=m<<7|m>>>25,m=b+U|0,x^=m<<9|m>>>23,m=x+b|0,G^=m<<13|m>>>19,m=G+x|0,U^=m<<18|m>>>14,m=P+C|0,N^=m<<7|m>>>25,m=N+P|0,R^=m<<9|m>>>23,m=R+N|0,C^=m<<13|m>>>19,m=C+R|0,P^=m<<18|m>>>14,m=le+ge|0,ee^=m<<7|m>>>25,m=ee+le|0,ue^=m<<9|m>>>23,m=ue+ee|0,ge^=m<<13|m>>>19,m=ge+ue|0,le^=m<<18|m>>>14;f[0]=K>>>0&255,f[1]=K>>>8&255,f[2]=K>>>16&255,f[3]=K>>>24&255,f[4]=U>>>0&255,f[5]=U>>>8&255,f[6]=U>>>16&255,f[7]=U>>>24&255,f[8]=P>>>0&255,f[9]=P>>>8&255,f[10]=P>>>16&255,f[11]=P>>>24&255,f[12]=le>>>0&255,f[13]=le>>>8&255,f[14]=le>>>16&255,f[15]=le>>>24&255,f[16]=b>>>0&255,f[17]=b>>>8&255,f[18]=b>>>16&255,f[19]=b>>>24&255,f[20]=x>>>0&255,f[21]=x>>>8&255,f[22]=x>>>16&255,f[23]=x>>>24&255,f[24]=R>>>0&255,f[25]=R>>>8&255,f[26]=R>>>16&255,f[27]=R>>>24&255,f[28]=C>>>0&255,f[29]=C>>>8&255,f[30]=C>>>16&255,f[31]=C>>>24&255}function T(f,h,l,o){z(f,h,l,o)}function M(f,h,l,o){X(f,h,l,o)}var Q=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function B(f,h,l,o,p,E,w){var k=new Uint8Array(16),F=new Uint8Array(64),Y,q;for(q=0;q<16;q++)k[q]=0;for(q=0;q<8;q++)k[q]=E[q];for(;p>=64;){for(T(F,k,w,Q),q=0;q<64;q++)f[h+q]=l[o+q]^F[q];for(Y=1,q=8;q<16;q++)Y=Y+(k[q]&255)|0,k[q]=Y&255,Y>>>=8;p-=64,h+=64,o+=64}if(p>0)for(T(F,k,w,Q),q=0;q<p;q++)f[h+q]=l[o+q]^F[q];return 0}function ie(f,h,l,o,p){var E=new Uint8Array(16),w=new Uint8Array(64),k,F;for(F=0;F<16;F++)E[F]=0;for(F=0;F<8;F++)E[F]=o[F];for(;l>=64;){for(T(w,E,p,Q),F=0;F<64;F++)f[h+F]=w[F];for(k=1,F=8;F<16;F++)k=k+(E[F]&255)|0,E[F]=k&255,k>>>=8;l-=64,h+=64}if(l>0)for(T(w,E,p,Q),F=0;F<l;F++)f[h+F]=w[F];return 0}function he(f,h,l,o,p){var E=new Uint8Array(32);M(E,o,p,Q);for(var w=new Uint8Array(8),k=0;k<8;k++)w[k]=o[k+16];return ie(f,h,l,w,E)}function de(f,h,l,o,p,E,w){var k=new Uint8Array(32);M(k,E,w,Q);for(var F=new Uint8Array(8),Y=0;Y<8;Y++)F[Y]=E[Y+16];return B(f,h,l,o,p,F,k)}var Re=function(f){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var h,l,o,p,E,w,k,F;h=f[0]&255|(f[1]&255)<<8,this.r[0]=h&8191,l=f[2]&255|(f[3]&255)<<8,this.r[1]=(h>>>13|l<<3)&8191,o=f[4]&255|(f[5]&255)<<8,this.r[2]=(l>>>10|o<<6)&7939,p=f[6]&255|(f[7]&255)<<8,this.r[3]=(o>>>7|p<<9)&8191,E=f[8]&255|(f[9]&255)<<8,this.r[4]=(p>>>4|E<<12)&255,this.r[5]=E>>>1&8190,w=f[10]&255|(f[11]&255)<<8,this.r[6]=(E>>>14|w<<2)&8191,k=f[12]&255|(f[13]&255)<<8,this.r[7]=(w>>>11|k<<5)&8065,F=f[14]&255|(f[15]&255)<<8,this.r[8]=(k>>>8|F<<8)&8191,this.r[9]=F>>>5&127,this.pad[0]=f[16]&255|(f[17]&255)<<8,this.pad[1]=f[18]&255|(f[19]&255)<<8,this.pad[2]=f[20]&255|(f[21]&255)<<8,this.pad[3]=f[22]&255|(f[23]&255)<<8,this.pad[4]=f[24]&255|(f[25]&255)<<8,this.pad[5]=f[26]&255|(f[27]&255)<<8,this.pad[6]=f[28]&255|(f[29]&255)<<8,this.pad[7]=f[30]&255|(f[31]&255)<<8};Re.prototype.blocks=function(f,h,l){for(var o=this.fin?0:2048,p,E,w,k,F,Y,q,Ce,V,te,re,fe,ce,ne,ae,se,K,Z,W,$=this.h[0],G=this.h[1],U=this.h[2],b=this.h[3],x=this.h[4],R=this.h[5],C=this.h[6],P=this.h[7],N=this.h[8],ee=this.h[9],ue=this.r[0],ge=this.r[1],le=this.r[2],m=this.r[3],ye=this.r[4],Oe=this.r[5],ke=this.r[6],_e=this.r[7],be=this.r[8],xe=this.r[9];l>=16;)p=f[h+0]&255|(f[h+1]&255)<<8,$+=p&8191,E=f[h+2]&255|(f[h+3]&255)<<8,G+=(p>>>13|E<<3)&8191,w=f[h+4]&255|(f[h+5]&255)<<8,U+=(E>>>10|w<<6)&8191,k=f[h+6]&255|(f[h+7]&255)<<8,b+=(w>>>7|k<<9)&8191,F=f[h+8]&255|(f[h+9]&255)<<8,x+=(k>>>4|F<<12)&8191,R+=F>>>1&8191,Y=f[h+10]&255|(f[h+11]&255)<<8,C+=(F>>>14|Y<<2)&8191,q=f[h+12]&255|(f[h+13]&255)<<8,P+=(Y>>>11|q<<5)&8191,Ce=f[h+14]&255|(f[h+15]&255)<<8,N+=(q>>>8|Ce<<8)&8191,ee+=Ce>>>5|o,V=0,te=V,te+=$*ue,te+=G*(5*xe),te+=U*(5*be),te+=b*(5*_e),te+=x*(5*ke),V=te>>>13,te&=8191,te+=R*(5*Oe),te+=C*(5*ye),te+=P*(5*m),te+=N*(5*le),te+=ee*(5*ge),V+=te>>>13,te&=8191,re=V,re+=$*ge,re+=G*ue,re+=U*(5*xe),re+=b*(5*be),re+=x*(5*_e),V=re>>>13,re&=8191,re+=R*(5*ke),re+=C*(5*Oe),re+=P*(5*ye),re+=N*(5*m),re+=ee*(5*le),V+=re>>>13,re&=8191,fe=V,fe+=$*le,fe+=G*ge,fe+=U*ue,fe+=b*(5*xe),fe+=x*(5*be),V=fe>>>13,fe&=8191,fe+=R*(5*_e),fe+=C*(5*ke),fe+=P*(5*Oe),fe+=N*(5*ye),fe+=ee*(5*m),V+=fe>>>13,fe&=8191,ce=V,ce+=$*m,ce+=G*le,ce+=U*ge,ce+=b*ue,ce+=x*(5*xe),V=ce>>>13,ce&=8191,ce+=R*(5*be),ce+=C*(5*_e),ce+=P*(5*ke),ce+=N*(5*Oe),ce+=ee*(5*ye),V+=ce>>>13,ce&=8191,ne=V,ne+=$*ye,ne+=G*m,ne+=U*le,ne+=b*ge,ne+=x*ue,V=ne>>>13,ne&=8191,ne+=R*(5*xe),ne+=C*(5*be),ne+=P*(5*_e),ne+=N*(5*ke),ne+=ee*(5*Oe),V+=ne>>>13,ne&=8191,ae=V,ae+=$*Oe,ae+=G*ye,ae+=U*m,ae+=b*le,ae+=x*ge,V=ae>>>13,ae&=8191,ae+=R*ue,ae+=C*(5*xe),ae+=P*(5*be),ae+=N*(5*_e),ae+=ee*(5*ke),V+=ae>>>13,ae&=8191,se=V,se+=$*ke,se+=G*Oe,se+=U*ye,se+=b*m,se+=x*le,V=se>>>13,se&=8191,se+=R*ge,se+=C*ue,se+=P*(5*xe),se+=N*(5*be),se+=ee*(5*_e),V+=se>>>13,se&=8191,K=V,K+=$*_e,K+=G*ke,K+=U*Oe,K+=b*ye,K+=x*m,V=K>>>13,K&=8191,K+=R*le,K+=C*ge,K+=P*ue,K+=N*(5*xe),K+=ee*(5*be),V+=K>>>13,K&=8191,Z=V,Z+=$*be,Z+=G*_e,Z+=U*ke,Z+=b*Oe,Z+=x*ye,V=Z>>>13,Z&=8191,Z+=R*m,Z+=C*le,Z+=P*ge,Z+=N*ue,Z+=ee*(5*xe),V+=Z>>>13,Z&=8191,W=V,W+=$*xe,W+=G*be,W+=U*_e,W+=b*ke,W+=x*Oe,V=W>>>13,W&=8191,W+=R*ye,W+=C*m,W+=P*le,W+=N*ge,W+=ee*ue,V+=W>>>13,W&=8191,V=(V<<2)+V|0,V=V+te|0,te=V&8191,V=V>>>13,re+=V,$=te,G=re,U=fe,b=ce,x=ne,R=ae,C=se,P=K,N=Z,ee=W,h+=16,l-=16;this.h[0]=$,this.h[1]=G,this.h[2]=U,this.h[3]=b,this.h[4]=x,this.h[5]=R,this.h[6]=C,this.h[7]=P,this.h[8]=N,this.h[9]=ee},Re.prototype.finish=function(f,h){var l=new Uint16Array(10),o,p,E,w;if(this.leftover){for(w=this.leftover,this.buffer[w++]=1;w<16;w++)this.buffer[w]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(o=this.h[1]>>>13,this.h[1]&=8191,w=2;w<10;w++)this.h[w]+=o,o=this.h[w]>>>13,this.h[w]&=8191;for(this.h[0]+=o*5,o=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=o,o=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=o,l[0]=this.h[0]+5,o=l[0]>>>13,l[0]&=8191,w=1;w<10;w++)l[w]=this.h[w]+o,o=l[w]>>>13,l[w]&=8191;for(l[9]-=8192,p=(o^1)-1,w=0;w<10;w++)l[w]&=p;for(p=~p,w=0;w<10;w++)this.h[w]=this.h[w]&p|l[w];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,E=this.h[0]+this.pad[0],this.h[0]=E&65535,w=1;w<8;w++)E=(this.h[w]+this.pad[w]|0)+(E>>>16)|0,this.h[w]=E&65535;f[h+0]=this.h[0]>>>0&255,f[h+1]=this.h[0]>>>8&255,f[h+2]=this.h[1]>>>0&255,f[h+3]=this.h[1]>>>8&255,f[h+4]=this.h[2]>>>0&255,f[h+5]=this.h[2]>>>8&255,f[h+6]=this.h[3]>>>0&255,f[h+7]=this.h[3]>>>8&255,f[h+8]=this.h[4]>>>0&255,f[h+9]=this.h[4]>>>8&255,f[h+10]=this.h[5]>>>0&255,f[h+11]=this.h[5]>>>8&255,f[h+12]=this.h[6]>>>0&255,f[h+13]=this.h[6]>>>8&255,f[h+14]=this.h[7]>>>0&255,f[h+15]=this.h[7]>>>8&255},Re.prototype.update=function(f,h,l){var o,p;if(this.leftover){for(p=16-this.leftover,p>l&&(p=l),o=0;o<p;o++)this.buffer[this.leftover+o]=f[h+o];if(l-=p,h+=p,this.leftover+=p,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(l>=16&&(p=l-l%16,this.blocks(f,h,p),h+=p,l-=p),l){for(o=0;o<l;o++)this.buffer[this.leftover+o]=f[h+o];this.leftover+=l}};function We(f,h,l,o,p,E){var w=new Re(E);return w.update(l,o,p),w.finish(f,h),0}function Ye(f,h,l,o,p,E){var w=new Uint8Array(16);return We(w,0,l,o,p,E),O(f,h,w,0)}function ve(f,h,l,o,p){var E;if(l<32)return-1;for(de(f,0,h,0,l,o,p),We(f,16,f,32,l-32,f),E=0;E<16;E++)f[E]=0;return 0}function Xe(f,h,l,o,p){var E,w=new Uint8Array(32);if(l<32||(he(w,0,32,o,p),Ye(h,16,h,32,l-32,w)!==0))return-1;for(de(f,0,h,0,l,o,p),E=0;E<32;E++)f[E]=0;return 0}function Fe(f,h){var l;for(l=0;l<16;l++)f[l]=h[l]|0}function J(f){var h,l,o=1;for(h=0;h<16;h++)l=f[h]+o+65535,o=Math.floor(l/65536),f[h]=l-o*65536;f[0]+=o-1+37*(o-1)}function Ee(f,h,l){for(var o,p=~(l-1),E=0;E<16;E++)o=p&(f[E]^h[E]),f[E]^=o,h[E]^=o}function pe(f,h){var l,o,p,E=e(),w=e();for(l=0;l<16;l++)w[l]=h[l];for(J(w),J(w),J(w),o=0;o<2;o++){for(E[0]=w[0]-65517,l=1;l<15;l++)E[l]=w[l]-65535-(E[l-1]>>16&1),E[l-1]&=65535;E[15]=w[15]-32767-(E[14]>>16&1),p=E[15]>>16&1,E[14]&=65535,Ee(w,E,1-p)}for(l=0;l<16;l++)f[2*l]=w[l]&255,f[2*l+1]=w[l]>>8}function nt(f,h){var l=new Uint8Array(32),o=new Uint8Array(32);return pe(l,f),pe(o,h),H(l,0,o,0)}function Qe(f){var h=new Uint8Array(32);return pe(h,f),h[0]&1}function Vt(f,h){var l;for(l=0;l<16;l++)f[l]=h[2*l]+(h[2*l+1]<<8);f[15]&=32767}function L(f,h,l){for(var o=0;o<16;o++)f[o]=h[o]+l[o]}function j(f,h,l){for(var o=0;o<16;o++)f[o]=h[o]-l[o]}function A(f,h,l){var o,p,E=0,w=0,k=0,F=0,Y=0,q=0,Ce=0,V=0,te=0,re=0,fe=0,ce=0,ne=0,ae=0,se=0,K=0,Z=0,W=0,$=0,G=0,U=0,b=0,x=0,R=0,C=0,P=0,N=0,ee=0,ue=0,ge=0,le=0,m=l[0],ye=l[1],Oe=l[2],ke=l[3],_e=l[4],be=l[5],xe=l[6],Ge=l[7],Ae=l[8],Ve=l[9],Ke=l[10],$e=l[11],Ze=l[12],it=l[13],ot=l[14],at=l[15];o=h[0],E+=o*m,w+=o*ye,k+=o*Oe,F+=o*ke,Y+=o*_e,q+=o*be,Ce+=o*xe,V+=o*Ge,te+=o*Ae,re+=o*Ve,fe+=o*Ke,ce+=o*$e,ne+=o*Ze,ae+=o*it,se+=o*ot,K+=o*at,o=h[1],w+=o*m,k+=o*ye,F+=o*Oe,Y+=o*ke,q+=o*_e,Ce+=o*be,V+=o*xe,te+=o*Ge,re+=o*Ae,fe+=o*Ve,ce+=o*Ke,ne+=o*$e,ae+=o*Ze,se+=o*it,K+=o*ot,Z+=o*at,o=h[2],k+=o*m,F+=o*ye,Y+=o*Oe,q+=o*ke,Ce+=o*_e,V+=o*be,te+=o*xe,re+=o*Ge,fe+=o*Ae,ce+=o*Ve,ne+=o*Ke,ae+=o*$e,se+=o*Ze,K+=o*it,Z+=o*ot,W+=o*at,o=h[3],F+=o*m,Y+=o*ye,q+=o*Oe,Ce+=o*ke,V+=o*_e,te+=o*be,re+=o*xe,fe+=o*Ge,ce+=o*Ae,ne+=o*Ve,ae+=o*Ke,se+=o*$e,K+=o*Ze,Z+=o*it,W+=o*ot,$+=o*at,o=h[4],Y+=o*m,q+=o*ye,Ce+=o*Oe,V+=o*ke,te+=o*_e,re+=o*be,fe+=o*xe,ce+=o*Ge,ne+=o*Ae,ae+=o*Ve,se+=o*Ke,K+=o*$e,Z+=o*Ze,W+=o*it,$+=o*ot,G+=o*at,o=h[5],q+=o*m,Ce+=o*ye,V+=o*Oe,te+=o*ke,re+=o*_e,fe+=o*be,ce+=o*xe,ne+=o*Ge,ae+=o*Ae,se+=o*Ve,K+=o*Ke,Z+=o*$e,W+=o*Ze,$+=o*it,G+=o*ot,U+=o*at,o=h[6],Ce+=o*m,V+=o*ye,te+=o*Oe,re+=o*ke,fe+=o*_e,ce+=o*be,ne+=o*xe,ae+=o*Ge,se+=o*Ae,K+=o*Ve,Z+=o*Ke,W+=o*$e,$+=o*Ze,G+=o*it,U+=o*ot,b+=o*at,o=h[7],V+=o*m,te+=o*ye,re+=o*Oe,fe+=o*ke,ce+=o*_e,ne+=o*be,ae+=o*xe,se+=o*Ge,K+=o*Ae,Z+=o*Ve,W+=o*Ke,$+=o*$e,G+=o*Ze,U+=o*it,b+=o*ot,x+=o*at,o=h[8],te+=o*m,re+=o*ye,fe+=o*Oe,ce+=o*ke,ne+=o*_e,ae+=o*be,se+=o*xe,K+=o*Ge,Z+=o*Ae,W+=o*Ve,$+=o*Ke,G+=o*$e,U+=o*Ze,b+=o*it,x+=o*ot,R+=o*at,o=h[9],re+=o*m,fe+=o*ye,ce+=o*Oe,ne+=o*ke,ae+=o*_e,se+=o*be,K+=o*xe,Z+=o*Ge,W+=o*Ae,$+=o*Ve,G+=o*Ke,U+=o*$e,b+=o*Ze,x+=o*it,R+=o*ot,C+=o*at,o=h[10],fe+=o*m,ce+=o*ye,ne+=o*Oe,ae+=o*ke,se+=o*_e,K+=o*be,Z+=o*xe,W+=o*Ge,$+=o*Ae,G+=o*Ve,U+=o*Ke,b+=o*$e,x+=o*Ze,R+=o*it,C+=o*ot,P+=o*at,o=h[11],ce+=o*m,ne+=o*ye,ae+=o*Oe,se+=o*ke,K+=o*_e,Z+=o*be,W+=o*xe,$+=o*Ge,G+=o*Ae,U+=o*Ve,b+=o*Ke,x+=o*$e,R+=o*Ze,C+=o*it,P+=o*ot,N+=o*at,o=h[12],ne+=o*m,ae+=o*ye,se+=o*Oe,K+=o*ke,Z+=o*_e,W+=o*be,$+=o*xe,G+=o*Ge,U+=o*Ae,b+=o*Ve,x+=o*Ke,R+=o*$e,C+=o*Ze,P+=o*it,N+=o*ot,ee+=o*at,o=h[13],ae+=o*m,se+=o*ye,K+=o*Oe,Z+=o*ke,W+=o*_e,$+=o*be,G+=o*xe,U+=o*Ge,b+=o*Ae,x+=o*Ve,R+=o*Ke,C+=o*$e,P+=o*Ze,N+=o*it,ee+=o*ot,ue+=o*at,o=h[14],se+=o*m,K+=o*ye,Z+=o*Oe,W+=o*ke,$+=o*_e,G+=o*be,U+=o*xe,b+=o*Ge,x+=o*Ae,R+=o*Ve,C+=o*Ke,P+=o*$e,N+=o*Ze,ee+=o*it,ue+=o*ot,ge+=o*at,o=h[15],K+=o*m,Z+=o*ye,W+=o*Oe,$+=o*ke,G+=o*_e,U+=o*be,b+=o*xe,x+=o*Ge,R+=o*Ae,C+=o*Ve,P+=o*Ke,N+=o*$e,ee+=o*Ze,ue+=o*it,ge+=o*ot,le+=o*at,E+=38*Z,w+=38*W,k+=38*$,F+=38*G,Y+=38*U,q+=38*b,Ce+=38*x,V+=38*R,te+=38*C,re+=38*P,fe+=38*N,ce+=38*ee,ne+=38*ue,ae+=38*ge,se+=38*le,p=1,o=E+p+65535,p=Math.floor(o/65536),E=o-p*65536,o=w+p+65535,p=Math.floor(o/65536),w=o-p*65536,o=k+p+65535,p=Math.floor(o/65536),k=o-p*65536,o=F+p+65535,p=Math.floor(o/65536),F=o-p*65536,o=Y+p+65535,p=Math.floor(o/65536),Y=o-p*65536,o=q+p+65535,p=Math.floor(o/65536),q=o-p*65536,o=Ce+p+65535,p=Math.floor(o/65536),Ce=o-p*65536,o=V+p+65535,p=Math.floor(o/65536),V=o-p*65536,o=te+p+65535,p=Math.floor(o/65536),te=o-p*65536,o=re+p+65535,p=Math.floor(o/65536),re=o-p*65536,o=fe+p+65535,p=Math.floor(o/65536),fe=o-p*65536,o=ce+p+65535,p=Math.floor(o/65536),ce=o-p*65536,o=ne+p+65535,p=Math.floor(o/65536),ne=o-p*65536,o=ae+p+65535,p=Math.floor(o/65536),ae=o-p*65536,o=se+p+65535,p=Math.floor(o/65536),se=o-p*65536,o=K+p+65535,p=Math.floor(o/65536),K=o-p*65536,E+=p-1+37*(p-1),p=1,o=E+p+65535,p=Math.floor(o/65536),E=o-p*65536,o=w+p+65535,p=Math.floor(o/65536),w=o-p*65536,o=k+p+65535,p=Math.floor(o/65536),k=o-p*65536,o=F+p+65535,p=Math.floor(o/65536),F=o-p*65536,o=Y+p+65535,p=Math.floor(o/65536),Y=o-p*65536,o=q+p+65535,p=Math.floor(o/65536),q=o-p*65536,o=Ce+p+65535,p=Math.floor(o/65536),Ce=o-p*65536,o=V+p+65535,p=Math.floor(o/65536),V=o-p*65536,o=te+p+65535,p=Math.floor(o/65536),te=o-p*65536,o=re+p+65535,p=Math.floor(o/65536),re=o-p*65536,o=fe+p+65535,p=Math.floor(o/65536),fe=o-p*65536,o=ce+p+65535,p=Math.floor(o/65536),ce=o-p*65536,o=ne+p+65535,p=Math.floor(o/65536),ne=o-p*65536,o=ae+p+65535,p=Math.floor(o/65536),ae=o-p*65536,o=se+p+65535,p=Math.floor(o/65536),se=o-p*65536,o=K+p+65535,p=Math.floor(o/65536),K=o-p*65536,E+=p-1+37*(p-1),f[0]=E,f[1]=w,f[2]=k,f[3]=F,f[4]=Y,f[5]=q,f[6]=Ce,f[7]=V,f[8]=te,f[9]=re,f[10]=fe,f[11]=ce,f[12]=ne,f[13]=ae,f[14]=se,f[15]=K}function oe(f,h){A(f,h,h)}function Ie(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=253;o>=0;o--)oe(l,l),o!==2&&o!==4&&A(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function ut(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=250;o>=0;o--)oe(l,l),o!==1&&A(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function yt(f,h,l){var o=new Uint8Array(32),p=new Float64Array(80),E,w,k=e(),F=e(),Y=e(),q=e(),Ce=e(),V=e();for(w=0;w<31;w++)o[w]=h[w];for(o[31]=h[31]&127|64,o[0]&=248,Vt(p,l),w=0;w<16;w++)F[w]=p[w],q[w]=k[w]=Y[w]=0;for(k[0]=q[0]=1,w=254;w>=0;--w)E=o[w>>>3]>>>(w&7)&1,Ee(k,F,E),Ee(Y,q,E),L(Ce,k,Y),j(k,k,Y),L(Y,F,q),j(F,F,q),oe(q,Ce),oe(V,k),A(k,Y,k),A(Y,F,Ce),L(Ce,k,Y),j(k,k,Y),oe(F,k),j(Y,q,V),A(k,Y,c),L(k,k,q),A(Y,Y,k),A(k,q,V),A(q,F,p),oe(F,Ce),Ee(k,F,E),Ee(Y,q,E);for(w=0;w<16;w++)p[w+16]=k[w],p[w+32]=Y[w],p[w+48]=F[w],p[w+64]=q[w];var te=p.subarray(32),re=p.subarray(16);return Ie(te,te),A(re,re,te),pe(f,re),0}function Et(f,h){return yt(f,h,s)}function wt(f,h){return t(h,32),Et(f,h)}function ir(f,h,l){var o=new Uint8Array(32);return yt(o,l,h),M(f,n,o,Q)}var vr=ve,qr=Xe;function br(f,h,l,o,p,E){var w=new Uint8Array(32);return ir(w,p,E),vr(f,h,l,o,w)}function gn(f,h,l,o,p,E){var w=new Uint8Array(32);return ir(w,p,E),qr(f,h,l,o,w)}var Is=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function Yc(f,h,l,o){for(var p=new Int32Array(16),E=new Int32Array(16),w,k,F,Y,q,Ce,V,te,re,fe,ce,ne,ae,se,K,Z,W,$,G,U,b,x,R,C,P,N,ee=f[0],ue=f[1],ge=f[2],le=f[3],m=f[4],ye=f[5],Oe=f[6],ke=f[7],_e=h[0],be=h[1],xe=h[2],Ge=h[3],Ae=h[4],Ve=h[5],Ke=h[6],$e=h[7],Ze=0;o>=128;){for(G=0;G<16;G++)U=8*G+Ze,p[G]=l[U+0]<<24|l[U+1]<<16|l[U+2]<<8|l[U+3],E[G]=l[U+4]<<24|l[U+5]<<16|l[U+6]<<8|l[U+7];for(G=0;G<80;G++)if(w=ee,k=ue,F=ge,Y=le,q=m,Ce=ye,V=Oe,te=ke,re=_e,fe=be,ce=xe,ne=Ge,ae=Ae,se=Ve,K=Ke,Z=$e,b=ke,x=$e,R=x&65535,C=x>>>16,P=b&65535,N=b>>>16,b=(m>>>14|Ae<<18)^(m>>>18|Ae<<14)^(Ae>>>9|m<<23),x=(Ae>>>14|m<<18)^(Ae>>>18|m<<14)^(m>>>9|Ae<<23),R+=x&65535,C+=x>>>16,P+=b&65535,N+=b>>>16,b=m&ye^~m&Oe,x=Ae&Ve^~Ae&Ke,R+=x&65535,C+=x>>>16,P+=b&65535,N+=b>>>16,b=Is[G*2],x=Is[G*2+1],R+=x&65535,C+=x>>>16,P+=b&65535,N+=b>>>16,b=p[G%16],x=E[G%16],R+=x&65535,C+=x>>>16,P+=b&65535,N+=b>>>16,C+=R>>>16,P+=C>>>16,N+=P>>>16,W=P&65535|N<<16,$=R&65535|C<<16,b=W,x=$,R=x&65535,C=x>>>16,P=b&65535,N=b>>>16,b=(ee>>>28|_e<<4)^(_e>>>2|ee<<30)^(_e>>>7|ee<<25),x=(_e>>>28|ee<<4)^(ee>>>2|_e<<30)^(ee>>>7|_e<<25),R+=x&65535,C+=x>>>16,P+=b&65535,N+=b>>>16,b=ee&ue^ee&ge^ue&ge,x=_e&be^_e&xe^be&xe,R+=x&65535,C+=x>>>16,P+=b&65535,N+=b>>>16,C+=R>>>16,P+=C>>>16,N+=P>>>16,te=P&65535|N<<16,Z=R&65535|C<<16,b=Y,x=ne,R=x&65535,C=x>>>16,P=b&65535,N=b>>>16,b=W,x=$,R+=x&65535,C+=x>>>16,P+=b&65535,N+=b>>>16,C+=R>>>16,P+=C>>>16,N+=P>>>16,Y=P&65535|N<<16,ne=R&65535|C<<16,ue=w,ge=k,le=F,m=Y,ye=q,Oe=Ce,ke=V,ee=te,be=re,xe=fe,Ge=ce,Ae=ne,Ve=ae,Ke=se,$e=K,_e=Z,G%16===15)for(U=0;U<16;U++)b=p[U],x=E[U],R=x&65535,C=x>>>16,P=b&65535,N=b>>>16,b=p[(U+9)%16],x=E[(U+9)%16],R+=x&65535,C+=x>>>16,P+=b&65535,N+=b>>>16,W=p[(U+1)%16],$=E[(U+1)%16],b=(W>>>1|$<<31)^(W>>>8|$<<24)^W>>>7,x=($>>>1|W<<31)^($>>>8|W<<24)^($>>>7|W<<25),R+=x&65535,C+=x>>>16,P+=b&65535,N+=b>>>16,W=p[(U+14)%16],$=E[(U+14)%16],b=(W>>>19|$<<13)^($>>>29|W<<3)^W>>>6,x=($>>>19|W<<13)^(W>>>29|$<<3)^($>>>6|W<<26),R+=x&65535,C+=x>>>16,P+=b&65535,N+=b>>>16,C+=R>>>16,P+=C>>>16,N+=P>>>16,p[U]=P&65535|N<<16,E[U]=R&65535|C<<16;b=ee,x=_e,R=x&65535,C=x>>>16,P=b&65535,N=b>>>16,b=f[0],x=h[0],R+=x&65535,C+=x>>>16,P+=b&65535,N+=b>>>16,C+=R>>>16,P+=C>>>16,N+=P>>>16,f[0]=ee=P&65535|N<<16,h[0]=_e=R&65535|C<<16,b=ue,x=be,R=x&65535,C=x>>>16,P=b&65535,N=b>>>16,b=f[1],x=h[1],R+=x&65535,C+=x>>>16,P+=b&65535,N+=b>>>16,C+=R>>>16,P+=C>>>16,N+=P>>>16,f[1]=ue=P&65535|N<<16,h[1]=be=R&65535|C<<16,b=ge,x=xe,R=x&65535,C=x>>>16,P=b&65535,N=b>>>16,b=f[2],x=h[2],R+=x&65535,C+=x>>>16,P+=b&65535,N+=b>>>16,C+=R>>>16,P+=C>>>16,N+=P>>>16,f[2]=ge=P&65535|N<<16,h[2]=xe=R&65535|C<<16,b=le,x=Ge,R=x&65535,C=x>>>16,P=b&65535,N=b>>>16,b=f[3],x=h[3],R+=x&65535,C+=x>>>16,P+=b&65535,N+=b>>>16,C+=R>>>16,P+=C>>>16,N+=P>>>16,f[3]=le=P&65535|N<<16,h[3]=Ge=R&65535|C<<16,b=m,x=Ae,R=x&65535,C=x>>>16,P=b&65535,N=b>>>16,b=f[4],x=h[4],R+=x&65535,C+=x>>>16,P+=b&65535,N+=b>>>16,C+=R>>>16,P+=C>>>16,N+=P>>>16,f[4]=m=P&65535|N<<16,h[4]=Ae=R&65535|C<<16,b=ye,x=Ve,R=x&65535,C=x>>>16,P=b&65535,N=b>>>16,b=f[5],x=h[5],R+=x&65535,C+=x>>>16,P+=b&65535,N+=b>>>16,C+=R>>>16,P+=C>>>16,N+=P>>>16,f[5]=ye=P&65535|N<<16,h[5]=Ve=R&65535|C<<16,b=Oe,x=Ke,R=x&65535,C=x>>>16,P=b&65535,N=b>>>16,b=f[6],x=h[6],R+=x&65535,C+=x>>>16,P+=b&65535,N+=b>>>16,C+=R>>>16,P+=C>>>16,N+=P>>>16,f[6]=Oe=P&65535|N<<16,h[6]=Ke=R&65535|C<<16,b=ke,x=$e,R=x&65535,C=x>>>16,P=b&65535,N=b>>>16,b=f[7],x=h[7],R+=x&65535,C+=x>>>16,P+=b&65535,N+=b>>>16,C+=R>>>16,P+=C>>>16,N+=P>>>16,f[7]=ke=P&65535|N<<16,h[7]=$e=R&65535|C<<16,Ze+=128,o-=128}return o}function Wr(f,h,l){var o=new Int32Array(8),p=new Int32Array(8),E=new Uint8Array(256),w,k=l;for(o[0]=1779033703,o[1]=3144134277,o[2]=1013904242,o[3]=2773480762,o[4]=1359893119,o[5]=2600822924,o[6]=528734635,o[7]=1541459225,p[0]=4089235720,p[1]=2227873595,p[2]=4271175723,p[3]=1595750129,p[4]=2917565137,p[5]=725511199,p[6]=4215389547,p[7]=327033209,Yc(o,p,h,l),l%=128,w=0;w<l;w++)E[w]=h[k-l+w];for(E[l]=128,l=256-128*(l<112?1:0),E[l-9]=0,v(E,l-8,k/536870912|0,k<<3),Yc(o,p,E,l),w=0;w<8;w++)v(f,8*w,o[w],p[w]);return 0}function Ls(f,h){var l=e(),o=e(),p=e(),E=e(),w=e(),k=e(),F=e(),Y=e(),q=e();j(l,f[1],f[0]),j(q,h[1],h[0]),A(l,l,q),L(o,f[0],f[1]),L(q,h[0],h[1]),A(o,o,q),A(p,f[3],h[3]),A(p,p,d),A(E,f[2],h[2]),L(E,E,E),j(w,o,l),j(k,E,p),L(F,E,p),L(Y,o,l),A(f[0],w,k),A(f[1],Y,F),A(f[2],F,k),A(f[3],w,Y)}function Xc(f,h,l){var o;for(o=0;o<4;o++)Ee(f[o],h[o],l)}function po(f,h){var l=e(),o=e(),p=e();Ie(p,h[2]),A(l,h[0],p),A(o,h[1],p),pe(f,o),f[31]^=Qe(l)<<7}function go(f,h,l){var o,p;for(Fe(f[0],i),Fe(f[1],a),Fe(f[2],a),Fe(f[3],i),p=255;p>=0;--p)o=l[p/8|0]>>(p&7)&1,Xc(f,h,o),Ls(h,f),Ls(f,f),Xc(f,h,o)}function Ns(f,h){var l=[e(),e(),e(),e()];Fe(l[0],g),Fe(l[1],_),Fe(l[2],a),A(l[3],g,_),go(f,l,h)}function _o(f,h,l){var o=new Uint8Array(64),p=[e(),e(),e(),e()],E;for(l||t(h,32),Wr(o,h,32),o[0]&=248,o[31]&=127,o[31]|=64,Ns(p,o),po(f,p),E=0;E<32;E++)h[E+32]=f[E];return 0}var Ds=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function mo(f,h){var l,o,p,E;for(o=63;o>=32;--o){for(l=0,p=o-32,E=o-12;p<E;++p)h[p]+=l-16*h[o]*Ds[p-(o-32)],l=Math.floor((h[p]+128)/256),h[p]-=l*256;h[p]+=l,h[o]=0}for(l=0,p=0;p<32;p++)h[p]+=l-(h[31]>>4)*Ds[p],l=h[p]>>8,h[p]&=255;for(p=0;p<32;p++)h[p]-=l*Ds[p];for(o=0;o<32;o++)h[o+1]+=h[o]>>8,f[o]=h[o]&255}function yo(f){var h=new Float64Array(64),l;for(l=0;l<64;l++)h[l]=f[l];for(l=0;l<64;l++)f[l]=0;mo(f,h)}function Jc(f,h,l,o){var p=new Uint8Array(64),E=new Uint8Array(64),w=new Uint8Array(64),k,F,Y=new Float64Array(64),q=[e(),e(),e(),e()];Wr(p,o,32),p[0]&=248,p[31]&=127,p[31]|=64;var Ce=l+64;for(k=0;k<l;k++)f[64+k]=h[k];for(k=0;k<32;k++)f[32+k]=p[32+k];for(Wr(w,f.subarray(32),l+32),yo(w),Ns(q,w),po(f,q),k=32;k<64;k++)f[k]=o[k];for(Wr(E,f,l+64),yo(E),k=0;k<64;k++)Y[k]=0;for(k=0;k<32;k++)Y[k]=w[k];for(k=0;k<32;k++)for(F=0;F<32;F++)Y[k+F]+=E[k]*p[F];return mo(f.subarray(32),Y),Ce}function Pd(f,h){var l=e(),o=e(),p=e(),E=e(),w=e(),k=e(),F=e();return Fe(f[2],a),Vt(f[1],h),oe(p,f[1]),A(E,p,u),j(p,p,f[2]),L(E,f[2],E),oe(w,E),oe(k,w),A(F,k,w),A(l,F,p),A(l,l,E),ut(l,l),A(l,l,p),A(l,l,E),A(l,l,E),A(f[0],l,E),oe(o,f[0]),A(o,o,E),nt(o,p)&&A(f[0],f[0],y),oe(o,f[0]),A(o,o,E),nt(o,p)?-1:(Qe(f[0])===h[31]>>7&&j(f[0],i,f[0]),A(f[3],f[0],f[1]),0)}function Eo(f,h,l,o){var p,E=new Uint8Array(32),w=new Uint8Array(64),k=[e(),e(),e(),e()],F=[e(),e(),e(),e()];if(l<64||Pd(F,o))return-1;for(p=0;p<l;p++)f[p]=h[p];for(p=0;p<32;p++)f[p+32]=o[p];if(Wr(w,f,l),yo(w),go(k,F,w),Ns(F,h.subarray(32)),Ls(k,F),po(E,k),l-=64,H(h,0,E,0)){for(p=0;p<l;p++)f[p]=0;return-1}for(p=0;p<l;p++)f[p]=h[p+64];return l}var wo=32,Fs=24,zn=32,_n=16,Gn=32,Ms=32,Yn=32,Xn=32,vo=32,Zc=Fs,Rd=zn,Ad=_n,or=64,Hr=32,mn=64,bo=32,xo=64;r.lowlevel={crypto_core_hsalsa20:M,crypto_stream_xor:de,crypto_stream:he,crypto_stream_salsa20_xor:B,crypto_stream_salsa20:ie,crypto_onetimeauth:We,crypto_onetimeauth_verify:Ye,crypto_verify_16:O,crypto_verify_32:H,crypto_secretbox:ve,crypto_secretbox_open:Xe,crypto_scalarmult:yt,crypto_scalarmult_base:Et,crypto_box_beforenm:ir,crypto_box_afternm:vr,crypto_box:br,crypto_box_open:gn,crypto_box_keypair:wt,crypto_hash:Wr,crypto_sign:Jc,crypto_sign_keypair:_o,crypto_sign_open:Eo,crypto_secretbox_KEYBYTES:wo,crypto_secretbox_NONCEBYTES:Fs,crypto_secretbox_ZEROBYTES:zn,crypto_secretbox_BOXZEROBYTES:_n,crypto_scalarmult_BYTES:Gn,crypto_scalarmult_SCALARBYTES:Ms,crypto_box_PUBLICKEYBYTES:Yn,crypto_box_SECRETKEYBYTES:Xn,crypto_box_BEFORENMBYTES:vo,crypto_box_NONCEBYTES:Zc,crypto_box_ZEROBYTES:Rd,crypto_box_BOXZEROBYTES:Ad,crypto_sign_BYTES:or,crypto_sign_PUBLICKEYBYTES:Hr,crypto_sign_SECRETKEYBYTES:mn,crypto_sign_SEEDBYTES:bo,crypto_hash_BYTES:xo,gf:e,D:u,L:Ds,pack25519:pe,unpack25519:Vt,M:A,A:L,S:oe,Z:j,pow2523:ut,add:Ls,set25519:Fe,modL:mo,scalarmult:go,scalarbase:Ns};function Qc(f,h){if(f.length!==wo)throw new Error("bad key size");if(h.length!==Fs)throw new Error("bad nonce size")}function Id(f,h){if(f.length!==Yn)throw new Error("bad public key size");if(h.length!==Xn)throw new Error("bad secret key size")}function vt(){for(var f=0;f<arguments.length;f++)if(!(arguments[f]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function ef(f){for(var h=0;h<f.length;h++)f[h]=0}r.randomBytes=function(f){var h=new Uint8Array(f);return t(h,f),h},r.secretbox=function(f,h,l){vt(f,h,l),Qc(l,h);for(var o=new Uint8Array(zn+f.length),p=new Uint8Array(o.length),E=0;E<f.length;E++)o[E+zn]=f[E];return ve(p,o,o.length,h,l),p.subarray(_n)},r.secretbox.open=function(f,h,l){vt(f,h,l),Qc(l,h);for(var o=new Uint8Array(_n+f.length),p=new Uint8Array(o.length),E=0;E<f.length;E++)o[E+_n]=f[E];return o.length<32||Xe(p,o,o.length,h,l)!==0?null:p.subarray(zn)},r.secretbox.keyLength=wo,r.secretbox.nonceLength=Fs,r.secretbox.overheadLength=_n,r.scalarMult=function(f,h){if(vt(f,h),f.length!==Ms)throw new Error("bad n size");if(h.length!==Gn)throw new Error("bad p size");var l=new Uint8Array(Gn);return yt(l,f,h),l},r.scalarMult.base=function(f){if(vt(f),f.length!==Ms)throw new Error("bad n size");var h=new Uint8Array(Gn);return Et(h,f),h},r.scalarMult.scalarLength=Ms,r.scalarMult.groupElementLength=Gn,r.box=function(f,h,l,o){var p=r.box.before(l,o);return r.secretbox(f,h,p)},r.box.before=function(f,h){vt(f,h),Id(f,h);var l=new Uint8Array(vo);return ir(l,f,h),l},r.box.after=r.secretbox,r.box.open=function(f,h,l,o){var p=r.box.before(l,o);return r.secretbox.open(f,h,p)},r.box.open.after=r.secretbox.open,r.box.keyPair=function(){var f=new Uint8Array(Yn),h=new Uint8Array(Xn);return wt(f,h),{publicKey:f,secretKey:h}},r.box.keyPair.fromSecretKey=function(f){if(vt(f),f.length!==Xn)throw new Error("bad secret key size");var h=new Uint8Array(Yn);return Et(h,f),{publicKey:h,secretKey:new Uint8Array(f)}},r.box.publicKeyLength=Yn,r.box.secretKeyLength=Xn,r.box.sharedKeyLength=vo,r.box.nonceLength=Zc,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(f,h){if(vt(f,h),h.length!==mn)throw new Error("bad secret key size");var l=new Uint8Array(or+f.length);return Jc(l,f,f.length,h),l},r.sign.open=function(f,h){if(vt(f,h),h.length!==Hr)throw new Error("bad public key size");var l=new Uint8Array(f.length),o=Eo(l,f,f.length,h);if(o<0)return null;for(var p=new Uint8Array(o),E=0;E<p.length;E++)p[E]=l[E];return p},r.sign.detached=function(f,h){for(var l=r.sign(f,h),o=new Uint8Array(or),p=0;p<o.length;p++)o[p]=l[p];return o},r.sign.detached.verify=function(f,h,l){if(vt(f,h,l),h.length!==or)throw new Error("bad signature size");if(l.length!==Hr)throw new Error("bad public key size");var o=new Uint8Array(or+f.length),p=new Uint8Array(or+f.length),E;for(E=0;E<or;E++)o[E]=h[E];for(E=0;E<f.length;E++)o[E+or]=f[E];return Eo(p,o,o.length,l)>=0},r.sign.keyPair=function(){var f=new Uint8Array(Hr),h=new Uint8Array(mn);return _o(f,h),{publicKey:f,secretKey:h}},r.sign.keyPair.fromSecretKey=function(f){if(vt(f),f.length!==mn)throw new Error("bad secret key size");for(var h=new Uint8Array(Hr),l=0;l<h.length;l++)h[l]=f[32+l];return{publicKey:h,secretKey:new Uint8Array(f)}},r.sign.keyPair.fromSeed=function(f){if(vt(f),f.length!==bo)throw new Error("bad seed size");for(var h=new Uint8Array(Hr),l=new Uint8Array(mn),o=0;o<32;o++)l[o]=f[o];return _o(h,l,!0),{publicKey:h,secretKey:l}},r.sign.publicKeyLength=Hr,r.sign.secretKeyLength=mn,r.sign.seedLength=bo,r.sign.signatureLength=or,r.hash=function(f){vt(f);var h=new Uint8Array(xo);return Wr(h,f,f.length),h},r.hash.hashLength=xo,r.verify=function(f,h){return vt(f,h),f.length===0||h.length===0||f.length!==h.length?!1:S(f,0,h,0,f.length)===0},r.setPRNG=function(f){t=f},(function(){var f=typeof self<"u"?self.crypto||self.msCrypto:null;if(f&&f.getRandomValues){var h=65536;r.setPRNG(function(l,o){var p,E=new Uint8Array(o);for(p=0;p<o;p+=h)f.getRandomValues(E.subarray(p,p+Math.min(o-p,h)));for(p=0;p<o;p++)l[p]=E[p];ef(E)})}else typeof require<"u"&&(f=require("crypto"),f&&f.randomBytes&&r.setPRNG(function(l,o){var p,E=f.randomBytes(o);for(p=0;p<o;p++)l[p]=E[p];ef(E)}))})()})(typeof Ys<"u"&&Ys.exports?Ys.exports:self.nacl=self.nacl||{})});var Po=D((vf,Xs)=>{(function(r,e){"use strict";typeof Xs<"u"&&Xs.exports?Xs.exports=e():(r.nacl||(r.nacl={}),r.nacl.util=e())})(vf,function(){"use strict";var r={};function e(t){if(!/^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(t))throw new TypeError("invalid encoding")}return r.decodeUTF8=function(t){if(typeof t!="string")throw new TypeError("expected string");var n,s=unescape(encodeURIComponent(t)),i=new Uint8Array(s.length);for(n=0;n<s.length;n++)i[n]=s.charCodeAt(n);return i},r.encodeUTF8=function(t){var n,s=[];for(n=0;n<t.length;n++)s.push(String.fromCharCode(t[n]));return decodeURIComponent(escape(s.join("")))},typeof atob>"u"?typeof Buffer.from<"u"?(r.encodeBase64=function(t){return Buffer.from(t).toString("base64")},r.decodeBase64=function(t){return e(t),new Uint8Array(Array.prototype.slice.call(Buffer.from(t,"base64"),0))}):(r.encodeBase64=function(t){return new Buffer(t).toString("base64")},r.decodeBase64=function(t){return e(t),new Uint8Array(Array.prototype.slice.call(new Buffer(t,"base64"),0))}):(r.encodeBase64=function(t){var n,s=[],i=t.length;for(n=0;n<i;n++)s.push(String.fromCharCode(t[n]));return btoa(s.join(""))},r.decodeBase64=function(t){e(t);var n,s=atob(t),i=new Uint8Array(s.length);for(n=0;n<s.length;n++)i[n]=s.charCodeAt(n);return i}),r})});var bf=D(Tr=>{"use strict";var ep=Tr&&Tr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Tr,"__esModule",{value:!0});Tr.encrypt=tp;Tr.decrypt=rp;Tr.encryptBinary=np;Tr.decryptBinary=sp;var fr=ep(ko()),Sr=Po();function tp(r,e,t){let n=fr.default.randomBytes(fr.default.secretbox.nonceLength),s=new TextEncoder().encode(r),i=fr.default.secretbox(s,n,e);return{v:1,sid:t,n:(0,Sr.encodeBase64)(n),c:(0,Sr.encodeBase64)(i)}}function rp(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Sr.decodeBase64)(r.n),n=(0,Sr.decodeBase64)(r.c);if(t.length!==fr.default.secretbox.nonceLength)throw new Error(`Invalid nonce length: ${t.length}`);let s=fr.default.secretbox.open(n,t,e);if(!s)throw new Error("Decryption failed: invalid ciphertext or wrong key");return new TextDecoder().decode(s)}function np(r,e,t){let n=fr.default.randomBytes(fr.default.secretbox.nonceLength),s=fr.default.secretbox(r,n,e);return{v:1,sid:t,n:(0,Sr.encodeBase64)(n),c:(0,Sr.encodeBase64)(s)}}function sp(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Sr.decodeBase64)(r.n),n=(0,Sr.decodeBase64)(r.c),s=fr.default.secretbox.open(n,t,e);if(!s)throw new Error("Decryption failed: invalid ciphertext or wrong key");return s}});var xf=D($t=>{"use strict";var ip=$t&&$t.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty($t,"__esModule",{value:!0});$t.generateKeyPair=op;$t.deriveSharedSecret=ap;$t.isValidPublicKey=cp;$t.clearKey=fp;$t.keyToBase64=up;$t.base64ToKey=lp;var es=ip(ko()),Vr=Po();function op(){let r=es.default.box.keyPair();return{publicKey:(0,Vr.encodeBase64)(r.publicKey),secretKey:(0,Vr.encodeBase64)(r.secretKey)}}function ap(r,e){let t=(0,Vr.decodeBase64)(r),n=(0,Vr.decodeBase64)(e);if(t.length!==es.default.box.publicKeyLength)throw new Error(`Invalid public key length: ${t.length}`);if(n.length!==es.default.box.secretKeyLength)throw new Error(`Invalid secret key length: ${n.length}`);return es.default.box.before(t,n)}function cp(r){try{return(0,Vr.decodeBase64)(r).length===es.default.box.publicKeyLength}catch{return!1}}function fp(r){r.fill(0)}function up(r){return(0,Vr.encodeBase64)(r)}function lp(r){return(0,Vr.decodeBase64)(r)}});var Tf=D(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.base64ToKey=De.keyToBase64=De.clearKey=De.isValidPublicKey=De.deriveSharedSecret=De.generateKeyPair=De.decryptBinary=De.encryptBinary=De.decrypt=De.encrypt=De.isMultiRecipientPayload=De.isEncryptedPayload=void 0;var Sf=wf();Object.defineProperty(De,"isEncryptedPayload",{enumerable:!0,get:function(){return Sf.isEncryptedPayload}});Object.defineProperty(De,"isMultiRecipientPayload",{enumerable:!0,get:function(){return Sf.isMultiRecipientPayload}});var Js=bf();Object.defineProperty(De,"encrypt",{enumerable:!0,get:function(){return Js.encrypt}});Object.defineProperty(De,"decrypt",{enumerable:!0,get:function(){return Js.decrypt}});Object.defineProperty(De,"encryptBinary",{enumerable:!0,get:function(){return Js.encryptBinary}});Object.defineProperty(De,"decryptBinary",{enumerable:!0,get:function(){return Js.decryptBinary}});var En=xf();Object.defineProperty(De,"generateKeyPair",{enumerable:!0,get:function(){return En.generateKeyPair}});Object.defineProperty(De,"deriveSharedSecret",{enumerable:!0,get:function(){return En.deriveSharedSecret}});Object.defineProperty(De,"isValidPublicKey",{enumerable:!0,get:function(){return En.isValidPublicKey}});Object.defineProperty(De,"clearKey",{enumerable:!0,get:function(){return En.clearKey}});Object.defineProperty(De,"keyToBase64",{enumerable:!0,get:function(){return En.keyToBase64}});Object.defineProperty(De,"base64ToKey",{enumerable:!0,get:function(){return En.base64ToKey}})});var Cf=D(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.MIN_CLIENT_VERSION=bt.PROTOCOL_VERSION_MINOR=bt.PROTOCOL_VERSION_MAJOR=bt.PROTOCOL_VERSION=void 0;bt.isCompatibleVersion=hp;bt.compareVersions=dp;bt.PROTOCOL_VERSION="2.0";bt.PROTOCOL_VERSION_MAJOR=2;bt.PROTOCOL_VERSION_MINOR=0;bt.MIN_CLIENT_VERSION="2.0";function hp(r){let[e]=r.split(".").map(Number);return e===bt.PROTOCOL_VERSION_MAJOR}function dp(r,e){let[t,n]=r.split(".").map(Number),[s,i]=e.split(".").map(Number);return t!==s?t<s?-1:1:n!==i?n<i?-1:1:0}});var Of=D(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.SERVER_CAPABILITIES=zt.DEFAULT_CLIENT_CAPABILITIES=zt.Capability=void 0;zt.hasCapability=pp;zt.negotiateCapabilities=gp;var ts;(function(r){r.FILE_TRANSFER="file-transfer",r.RELIABLE_MESSAGING="reliable-messaging",r.COMPRESSION="compression",r.E2E_ENCRYPTION="e2e-encryption",r.PRIORITY_QUEUES="priority-queues",r.OFFLINE_QUEUE="offline-queue",r.MULTI_DEVICE="multi-device",r.TERMINAL_EVENTS="terminal-events",r.E2E_PRIVACY="e2e-privacy"})(ts||(zt.Capability=ts={}));zt.DEFAULT_CLIENT_CAPABILITIES=[ts.E2E_ENCRYPTION,ts.TERMINAL_EVENTS];zt.SERVER_CAPABILITIES=Object.values(ts);function pp(r,e){return r.includes(e)}function gp(r,e){return r.filter(t=>e.includes(t))}});var kf=D(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.DEFAULT_PRIORITY=ur.PRIORITY_NAMES=ur.Priority=void 0;ur.comparePriority=_p;var Kr;(function(r){r[r.CRITICAL=0]="CRITICAL",r[r.HIGH=1]="HIGH",r[r.NORMAL=2]="NORMAL",r[r.LOW=3]="LOW"})(Kr||(ur.Priority=Kr={}));ur.PRIORITY_NAMES={[Kr.CRITICAL]:"CRITICAL",[Kr.HIGH]:"HIGH",[Kr.NORMAL]:"NORMAL",[Kr.LOW]:"LOW"};ur.DEFAULT_PRIORITY=Kr.NORMAL;function _p(r,e){return r-e}});var Pf=D(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.DEFAULT_RELIABILITY=Gt.RELIABILITY_NAMES=Gt.Reliability=void 0;Gt.requiresAck=mp;Gt.requiresBuffer=yp;var Cr;(function(r){r[r.FIRE_FORGET=0]="FIRE_FORGET",r[r.BUFFERED=1]="BUFFERED",r[r.GUARANTEED=2]="GUARANTEED"})(Cr||(Gt.Reliability=Cr={}));Gt.RELIABILITY_NAMES={[Cr.FIRE_FORGET]:"FIRE_FORGET",[Cr.BUFFERED]:"BUFFERED",[Cr.GUARANTEED]:"GUARANTEED"};Gt.DEFAULT_RELIABILITY=Cr.FIRE_FORGET;function mp(r){return r===Cr.GUARANTEED}function yp(r){return r>=Cr.BUFFERED}});var Rf=D(Ro=>{"use strict";Object.defineProperty(Ro,"__esModule",{value:!0});Ro.createMessage=Ep;function Ep(r,e,t={}){return{id:crypto.randomUUID(),type:r,payload:e,priority:t.priority??2,reliability:t.reliability??0,seq:t.seq,timestamp:new Date().toISOString()}}});var Af=D($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.TerminalEventType=void 0;$r.deriveStatusFromEvent=wp;$r.shouldTriggerPushNotification=vp;$r.getPushNotificationMessage=bp;var lt;(function(r){r.SESSION_START="session_start",r.SESSION_END="session_end",r.MESSAGE="message",r.TOOL_START="tool_start",r.TOOL_END="tool_end",r.WAITING_INPUT="waiting_input",r.ERROR="error"})(lt||($r.TerminalEventType=lt={}));function wp(r){switch(r.type){case lt.SESSION_START:case lt.TOOL_START:case lt.MESSAGE:return"working";case lt.WAITING_INPUT:return"waiting";case lt.SESSION_END:return r.status==="success"?"completed":"error";case lt.ERROR:return r.severity==="fatal"?"error":"working";case lt.TOOL_END:return r.status==="error"?"error":"working";default:return"idle"}}function vp(r){switch(r.type){case lt.WAITING_INPUT:return!0;case lt.SESSION_END:return!0;case lt.ERROR:return r.severity!=="warning";default:return!1}}function bp(r,e){switch(r.type){case lt.WAITING_INPUT:return{title:`${e}: Input Required`,body:r.question.slice(0,100)};case lt.SESSION_END:{let t=r;return t.status==="success"?{title:`${e}: Task Completed`,body:t.summary||"Session finished successfully"}:{title:`${e}: Task Failed`,body:t.summary||"Session ended with error"}}case lt.ERROR:{let t=r;return t.severity==="warning"?null:{title:`${e}: Error`,body:t.message.slice(0,100)}}default:return null}}});var Nf=D(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.TransferDirection=je.TransferStatus=je.CHUNK_TTL_SECONDS=je.TRANSFER_TTL_SECONDS=je.MAX_RETRIES=je.ACK_TIMEOUT_MS=je.WINDOW_SIZE=je.DEFAULT_MAX_FILE_SIZE=je.CHUNK_SIZE=void 0;je.calculateTotalChunks=xp;je.getMissingChunks=Sp;je.isTransferComplete=Tp;je.CHUNK_SIZE=64*1024;je.DEFAULT_MAX_FILE_SIZE=100*1024*1024;je.WINDOW_SIZE=10;je.ACK_TIMEOUT_MS=3e4;je.MAX_RETRIES=3;je.TRANSFER_TTL_SECONDS=1440*60;je.CHUNK_TTL_SECONDS=1440*60;var If;(function(r){r.PENDING="pending",r.ACTIVE="active",r.PAUSED="paused",r.COMPLETED="completed",r.FAILED="failed",r.CANCELLED="cancelled",r.EXPIRED="expired"})(If||(je.TransferStatus=If={}));var Lf;(function(r){r.DOWNLOAD="download",r.UPLOAD="upload"})(Lf||(je.TransferDirection=Lf={}));function xp(r,e=je.CHUNK_SIZE){return Math.ceil(r/e)}function Sp(r,e){let t=new Set(e),n=[];for(let s=0;s<r;s++)t.has(s)||n.push(s);return n}function Tp(r,e){return e.length===r}});var Df=D(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.ERROR_MESSAGES=lr.ErrorCode=void 0;lr.createError=Cp;lr.isRetryableError=Op;var Pe;(function(r){r.AUTH_FAILED="E001",r.TOKEN_EXPIRED="E002",r.TOKEN_INVALID="E003",r.NOT_FOUND="E011",r.ALREADY_EXISTS="E012",r.ACCESS_DENIED="E021",r.FORBIDDEN="E022",r.RATE_LIMITED="E031",r.TOO_MANY_CONNECTIONS="E032",r.QUOTA_EXCEEDED="E041",r.FILE_TOO_LARGE="E042",r.QUEUE_FULL="E043",r.TRANSFERS_LIMIT="E044",r.TRANSFER_FAILED="E051",r.TRANSFER_EXPIRED="E052",r.TRANSFER_CANCELLED="E053",r.CHECKSUM_MISMATCH="E054",r.CHUNK_MISSING="E055",r.INVALID_MESSAGE="E061",r.UNSUPPORTED_VERSION="E062",r.CAPABILITY_REQUIRED="E063",r.INVALID_STATE="E071",r.TIMEOUT="E072",r.CONNECTION_LOST="E073",r.INTERNAL_ERROR="E091",r.SERVICE_UNAVAILABLE="E092"})(Pe||(lr.ErrorCode=Pe={}));lr.ERROR_MESSAGES={[Pe.AUTH_FAILED]:"Authentication failed",[Pe.TOKEN_EXPIRED]:"Token expired",[Pe.TOKEN_INVALID]:"Invalid token",[Pe.NOT_FOUND]:"Resource not found",[Pe.ALREADY_EXISTS]:"Resource already exists",[Pe.ACCESS_DENIED]:"Access denied",[Pe.FORBIDDEN]:"Operation forbidden",[Pe.RATE_LIMITED]:"Rate limit exceeded",[Pe.TOO_MANY_CONNECTIONS]:"Too many connections",[Pe.QUOTA_EXCEEDED]:"Plan quota exceeded",[Pe.FILE_TOO_LARGE]:"File size exceeds limit",[Pe.QUEUE_FULL]:"Message queue is full",[Pe.TRANSFERS_LIMIT]:"Daily transfers limit reached",[Pe.TRANSFER_FAILED]:"File transfer failed",[Pe.TRANSFER_EXPIRED]:"Transfer expired",[Pe.TRANSFER_CANCELLED]:"Transfer cancelled",[Pe.CHECKSUM_MISMATCH]:"File checksum mismatch",[Pe.CHUNK_MISSING]:"Chunk missing or corrupted",[Pe.INVALID_MESSAGE]:"Invalid message format",[Pe.UNSUPPORTED_VERSION]:"Unsupported protocol version",[Pe.CAPABILITY_REQUIRED]:"Required capability not supported",[Pe.INVALID_STATE]:"Invalid state for this operation",[Pe.TIMEOUT]:"Operation timed out",[Pe.CONNECTION_LOST]:"Connection lost",[Pe.INTERNAL_ERROR]:"Internal server error",[Pe.SERVICE_UNAVAILABLE]:"Service temporarily unavailable"};function Cp(r,e={}){return{code:r,message:e.message||lr.ERROR_MESSAGES[r],details:e.details,retryable:e.retryable??!1,retryAfter:e.retryAfter}}function Op(r){return[Pe.RATE_LIMITED,Pe.TIMEOUT,Pe.CONNECTION_LOST,Pe.SERVICE_UNAVAILABLE].includes(r)}});var jf=D(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.FileEntryType=xt.DiffBase=xt.FileViewType=xt.FileChangeType=void 0;xt.getLanguageFromPath=kp;xt.parseUnifiedDiff=Pp;xt.createSimpleDiff=Rp;var Or;(function(r){r.CREATE="create",r.MODIFY="modify",r.DELETE="delete"})(Or||(xt.FileChangeType=Or={}));var Ff;(function(r){r.CONTENT="content",r.DIFF="diff"})(Ff||(xt.FileViewType=Ff={}));var Mf;(function(r){r.GIT="git",r.PREVIOUS="previous"})(Mf||(xt.DiffBase=Mf={}));function kp(r){let e=r.split(".").pop()?.toLowerCase(),t={js:"javascript",jsx:"javascript",ts:"typescript",tsx:"typescript",mjs:"javascript",cjs:"javascript",html:"html",htm:"html",css:"css",scss:"scss",sass:"scss",less:"less",json:"json",yaml:"yaml",yml:"yaml",xml:"xml",toml:"toml",md:"markdown",mdx:"markdown",env:"plaintext",gitignore:"plaintext",dockerignore:"plaintext",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",py:"python",pyw:"python",pyi:"python",go:"go",rs:"rust",java:"java",kt:"kotlin",kts:"kotlin",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp",hpp:"cpp",sql:"sql",graphql:"graphql",gql:"graphql",prisma:"prisma",dockerfile:"dockerfile"},n=r.split("/").pop()?.toLowerCase()||"";return{dockerfile:"dockerfile",makefile:"makefile",".gitignore":"plaintext",".env":"plaintext",".env.local":"plaintext",".env.development":"plaintext",".env.production":"plaintext"}[n]||t[e||""]||"plaintext"}function Pp(r,e){let t=r.split(`
|
|
3
|
-
`),n=[],s=0,i=0,a=null,c=0,u=0;for(let g of t){if(g.startsWith("diff ")||g.startsWith("index ")||g.startsWith("---")||g.startsWith("+++"))continue;let
|
|
2
|
+
"use strict";var Bd=Object.create;var To=Object.defineProperty;var jd=Object.getOwnPropertyDescriptor;var Ud=Object.getOwnPropertyNames;var qd=Object.getPrototypeOf,Wd=Object.prototype.hasOwnProperty;var Mt=(r,e)=>()=>(r&&(e=r(r=0)),e);var F=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Hd=(r,e)=>{for(var t in e)To(r,t,{get:e[t],enumerable:!0})},Vd=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ud(e))!Wd.call(r,s)&&s!==t&&To(r,s,{get:()=>e[s],enumerable:!(n=jd(e,s))||n.enumerable});return r};var fe=(r,e,t)=>(t=r!=null?Bd(qd(r)):{},Vd(e||!r||!r.__esModule?To(t,"default",{value:r,enumerable:!0}):t,r));var Hs=F(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});es.generateCorrelationId=zd;es.runWithCorrelation=Gd;es.getCurrentCorrelationId=Yd;var $d=require("async_hooks");function zd(){let r=new Uint8Array(4),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(r);else for(let t=0;t<4;t++)r[t]=Math.floor(Math.random()*256);return"c-"+Array.from(r,t=>t.toString(16).padStart(2,"0")).join("")}var of=new $d.AsyncLocalStorage;function Gd(r,e){return of.run(r,e)}function Yd(){return of.getStore()}});var cf=F(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.LOG_LEVELS=void 0;yn.shouldLog=Jd;yn.formatLogLine=Zd;var Xd=Hs();yn.LOG_LEVELS=["silent","error","warn","info","debug"];var af={silent:0,error:1,warn:2,info:3,debug:4};function Jd(r,e){return af[r]<=af[e]}function Zd(r,e,t,n){let s={ts:new Date().toISOString(),level:r,src:e,msg:t},i=(0,Xd.getCurrentCorrelationId)();i&&(s.cid=i);let a=n;a.length>0&&typeof a[0]=="object"&&a[0]!==null&&!(a[0]instanceof Error)&&!Array.isArray(a[0])&&(s.ctx=a[0],a=a.slice(1));let c=[...a].reverse().find(u=>u instanceof Error);c&&(s.err={message:c.message,stack:c.stack,name:c.name},a=a.filter(u=>u!==c)),a.length>0&&(s.args=a);try{return JSON.stringify(s)}catch{return JSON.stringify({ts:s.ts,level:r,src:e,msg:t,_unserializable:!0})}}});var ff=F(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.formatLogLine=xr.shouldLog=xr.LOG_LEVELS=void 0;var Co=cf();Object.defineProperty(xr,"LOG_LEVELS",{enumerable:!0,get:function(){return Co.LOG_LEVELS}});Object.defineProperty(xr,"shouldLog",{enumerable:!0,get:function(){return Co.shouldLog}});Object.defineProperty(xr,"formatLogLine",{enumerable:!0,get:function(){return Co.formatLogLine}})});var uf=F(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.CircularBuffer=void 0;var Oo=class{buffer=[];totalSize=0;maxSize;constructor(e=100){this.maxSize=e*1024}append(e){for(this.buffer.push(e),this.totalSize+=e.length;this.totalSize>this.maxSize&&this.buffer.length>1;){let t=this.buffer.shift();t&&(this.totalSize-=t.length)}}getContent(){return this.buffer.join("")}getLastBytes(e){let t=this.getContent();return t.length<=e?t:t.slice(-e)}getSize(){return this.totalSize}clear(){this.buffer=[],this.totalSize=0}};Vs.CircularBuffer=Oo});var $s=F(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.getApiUrl=Qd;Ks.getWsUrl=ep;function Qd(r){return`${r.getServerUrl()}/api`}function ep(r){let e=r.getServerUrl();return e.startsWith("https://")?e.replace(/^https:\/\//,"wss://"):e.replace(/^http:\/\//,"ws://")}});var hf=F(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.getCurrentCorrelationId=pt.runWithCorrelation=pt.generateCorrelationId=pt.getWsUrl=pt.getApiUrl=pt.CircularBuffer=void 0;var tp=uf();Object.defineProperty(pt,"CircularBuffer",{enumerable:!0,get:function(){return tp.CircularBuffer}});var lf=$s();Object.defineProperty(pt,"getApiUrl",{enumerable:!0,get:function(){return lf.getApiUrl}});Object.defineProperty(pt,"getWsUrl",{enumerable:!0,get:function(){return lf.getWsUrl}});var ko=Hs();Object.defineProperty(pt,"generateCorrelationId",{enumerable:!0,get:function(){return ko.generateCorrelationId}});Object.defineProperty(pt,"runWithCorrelation",{enumerable:!0,get:function(){return ko.runWithCorrelation}});Object.defineProperty(pt,"getCurrentCorrelationId",{enumerable:!0,get:function(){return ko.getCurrentCorrelationId}})});var pf=F(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0})});var mf=F(gf=>{"use strict";Object.defineProperty(gf,"__esModule",{value:!0})});var _f=F(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.PLAN_LIMITS=void 0;zs.PLAN_LIMITS={free:{maxAgents:1,maxTerminals:2,maxTeamMembers:1,historyDays:1},basic:{maxAgents:3,maxTerminals:10,maxTeamMembers:1,historyDays:7},pro:{maxAgents:10,maxTerminals:50,maxTeamMembers:5,historyDays:30}}});var Ef=F(yf=>{"use strict";Object.defineProperty(yf,"__esModule",{value:!0})});var vf=F(Kt=>{"use strict";var rp=Kt&&Kt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Gs=Kt&&Kt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&rp(e,r,t)};Object.defineProperty(Kt,"__esModule",{value:!0});Gs(pf(),Kt);Gs(mf(),Kt);Gs(_f(),Kt);Gs(Ef(),Kt)});var wf=F(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.API_VERSION=Ot.WS_NAMESPACES=Ot.TIMEOUTS=Ot.STATUS_PATTERNS=Ot.TERMINAL_STATUSES=void 0;Ot.TERMINAL_STATUSES={idle:{label:"Idle",color:"gray",icon:"\u25CF"},working:{label:"Working",color:"blue",icon:"\u27F3"},waiting:{label:"Awaiting input",color:"orange",icon:"\u26A0"},completed:{label:"Completed",color:"green",icon:"\u2713"},error:{label:"Error",color:"red",icon:"\u2715"},offline:{label:"Offline",color:"black",icon:"\u26AB"}};Ot.STATUS_PATTERNS={idle:[/[❯$]\s*$/,/>\s*$/],waiting:[/\[Y\/n\]/i,/\(y\/N\)/i,/Continue\?/i,/proceed\?/i],completed:[/✓/,/Done/,/Completed/,/Success/],error:[/Error/,/Failed/,/✕/,/Exception/]};Ot.TIMEOUTS={HEARTBEAT_INTERVAL:3e4,OFFLINE_THRESHOLD:6e4,DEVICE_CODE_EXPIRY:9e5,DEVICE_CODE_POLL_INTERVAL:5e3};Ot.WS_NAMESPACES={AGENT:"/agent",CLIENT:"/client"};Ot.API_VERSION="v1"});var bf=F(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});Ys.isMultiRecipientPayload=np;Ys.isEncryptedPayload=sp;function np(r){return typeof r=="object"&&r!==null&&"v"in r&&r.v===2&&"recipients"in r&&Array.isArray(r.recipients)}function sp(r){if(typeof r!="object"||r===null||!("encrypted"in r))return!1;let e=r.encrypted;if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.v=="number"&&typeof t.sid=="string"&&typeof t.n=="string"&&typeof t.c=="string"}});var Po=F((YE,Xs)=>{(function(r){"use strict";var e=function(f){var h,l=new Float64Array(16);if(f)for(h=0;h<f.length;h++)l[h]=f[h];return l},t=function(){throw new Error("no PRNG")},n=new Uint8Array(16),s=new Uint8Array(32);s[0]=9;var i=e(),a=e([1]),c=e([56129,1]),u=e([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),d=e([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),g=e([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),m=e([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),y=e([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function w(f,h,l,o){f[h]=l>>24&255,f[h+1]=l>>16&255,f[h+2]=l>>8&255,f[h+3]=l&255,f[h+4]=o>>24&255,f[h+5]=o>>16&255,f[h+6]=o>>8&255,f[h+7]=o&255}function S(f,h,l,o,p){var E,v=0;for(E=0;E<p;E++)v|=f[h+E]^l[o+E];return(1&v-1>>>8)-1}function C(f,h,l,o){return S(f,h,l,o,16)}function V(f,h,l,o){return S(f,h,l,o,32)}function de(f,h,l,o){for(var p=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,E=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,v=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,O=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,M=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,X=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,W=h[0]&255|(h[1]&255)<<8|(h[2]&255)<<16|(h[3]&255)<<24,Ce=h[4]&255|(h[5]&255)<<8|(h[6]&255)<<16|(h[7]&255)<<24,K=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,re=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,ne=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,ue=l[16]&255|(l[17]&255)<<8|(l[18]&255)<<16|(l[19]&255)<<24,ce=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,se=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,ae=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,ie=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,$=p,J=E,H=v,z=O,Y=M,q=X,b=W,x=Ce,R=K,T=re,k=ne,D=ue,ee=ce,le=se,ge=ae,he=ie,_,_e=0;_e<20;_e+=2)_=$+ee|0,Y^=_<<7|_>>>25,_=Y+$|0,R^=_<<9|_>>>23,_=R+Y|0,ee^=_<<13|_>>>19,_=ee+R|0,$^=_<<18|_>>>14,_=q+J|0,T^=_<<7|_>>>25,_=T+q|0,le^=_<<9|_>>>23,_=le+T|0,J^=_<<13|_>>>19,_=J+le|0,q^=_<<18|_>>>14,_=k+b|0,ge^=_<<7|_>>>25,_=ge+k|0,H^=_<<9|_>>>23,_=H+ge|0,b^=_<<13|_>>>19,_=b+H|0,k^=_<<18|_>>>14,_=he+D|0,z^=_<<7|_>>>25,_=z+he|0,x^=_<<9|_>>>23,_=x+z|0,D^=_<<13|_>>>19,_=D+x|0,he^=_<<18|_>>>14,_=$+z|0,J^=_<<7|_>>>25,_=J+$|0,H^=_<<9|_>>>23,_=H+J|0,z^=_<<13|_>>>19,_=z+H|0,$^=_<<18|_>>>14,_=q+Y|0,b^=_<<7|_>>>25,_=b+q|0,x^=_<<9|_>>>23,_=x+b|0,Y^=_<<13|_>>>19,_=Y+x|0,q^=_<<18|_>>>14,_=k+T|0,D^=_<<7|_>>>25,_=D+k|0,R^=_<<9|_>>>23,_=R+D|0,T^=_<<13|_>>>19,_=T+R|0,k^=_<<18|_>>>14,_=he+ge|0,ee^=_<<7|_>>>25,_=ee+he|0,le^=_<<9|_>>>23,_=le+ee|0,ge^=_<<13|_>>>19,_=ge+le|0,he^=_<<18|_>>>14;$=$+p|0,J=J+E|0,H=H+v|0,z=z+O|0,Y=Y+M|0,q=q+X|0,b=b+W|0,x=x+Ce|0,R=R+K|0,T=T+re|0,k=k+ne|0,D=D+ue|0,ee=ee+ce|0,le=le+se|0,ge=ge+ae|0,he=he+ie|0,f[0]=$>>>0&255,f[1]=$>>>8&255,f[2]=$>>>16&255,f[3]=$>>>24&255,f[4]=J>>>0&255,f[5]=J>>>8&255,f[6]=J>>>16&255,f[7]=J>>>24&255,f[8]=H>>>0&255,f[9]=H>>>8&255,f[10]=H>>>16&255,f[11]=H>>>24&255,f[12]=z>>>0&255,f[13]=z>>>8&255,f[14]=z>>>16&255,f[15]=z>>>24&255,f[16]=Y>>>0&255,f[17]=Y>>>8&255,f[18]=Y>>>16&255,f[19]=Y>>>24&255,f[20]=q>>>0&255,f[21]=q>>>8&255,f[22]=q>>>16&255,f[23]=q>>>24&255,f[24]=b>>>0&255,f[25]=b>>>8&255,f[26]=b>>>16&255,f[27]=b>>>24&255,f[28]=x>>>0&255,f[29]=x>>>8&255,f[30]=x>>>16&255,f[31]=x>>>24&255,f[32]=R>>>0&255,f[33]=R>>>8&255,f[34]=R>>>16&255,f[35]=R>>>24&255,f[36]=T>>>0&255,f[37]=T>>>8&255,f[38]=T>>>16&255,f[39]=T>>>24&255,f[40]=k>>>0&255,f[41]=k>>>8&255,f[42]=k>>>16&255,f[43]=k>>>24&255,f[44]=D>>>0&255,f[45]=D>>>8&255,f[46]=D>>>16&255,f[47]=D>>>24&255,f[48]=ee>>>0&255,f[49]=ee>>>8&255,f[50]=ee>>>16&255,f[51]=ee>>>24&255,f[52]=le>>>0&255,f[53]=le>>>8&255,f[54]=le>>>16&255,f[55]=le>>>24&255,f[56]=ge>>>0&255,f[57]=ge>>>8&255,f[58]=ge>>>16&255,f[59]=ge>>>24&255,f[60]=he>>>0&255,f[61]=he>>>8&255,f[62]=he>>>16&255,f[63]=he>>>24&255}function B(f,h,l,o){for(var p=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,E=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,v=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,O=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,M=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,X=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,W=h[0]&255|(h[1]&255)<<8|(h[2]&255)<<16|(h[3]&255)<<24,Ce=h[4]&255|(h[5]&255)<<8|(h[6]&255)<<16|(h[7]&255)<<24,K=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,re=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,ne=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,ue=l[16]&255|(l[17]&255)<<8|(l[18]&255)<<16|(l[19]&255)<<24,ce=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,se=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,ae=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,ie=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,$=p,J=E,H=v,z=O,Y=M,q=X,b=W,x=Ce,R=K,T=re,k=ne,D=ue,ee=ce,le=se,ge=ae,he=ie,_,_e=0;_e<20;_e+=2)_=$+ee|0,Y^=_<<7|_>>>25,_=Y+$|0,R^=_<<9|_>>>23,_=R+Y|0,ee^=_<<13|_>>>19,_=ee+R|0,$^=_<<18|_>>>14,_=q+J|0,T^=_<<7|_>>>25,_=T+q|0,le^=_<<9|_>>>23,_=le+T|0,J^=_<<13|_>>>19,_=J+le|0,q^=_<<18|_>>>14,_=k+b|0,ge^=_<<7|_>>>25,_=ge+k|0,H^=_<<9|_>>>23,_=H+ge|0,b^=_<<13|_>>>19,_=b+H|0,k^=_<<18|_>>>14,_=he+D|0,z^=_<<7|_>>>25,_=z+he|0,x^=_<<9|_>>>23,_=x+z|0,D^=_<<13|_>>>19,_=D+x|0,he^=_<<18|_>>>14,_=$+z|0,J^=_<<7|_>>>25,_=J+$|0,H^=_<<9|_>>>23,_=H+J|0,z^=_<<13|_>>>19,_=z+H|0,$^=_<<18|_>>>14,_=q+Y|0,b^=_<<7|_>>>25,_=b+q|0,x^=_<<9|_>>>23,_=x+b|0,Y^=_<<13|_>>>19,_=Y+x|0,q^=_<<18|_>>>14,_=k+T|0,D^=_<<7|_>>>25,_=D+k|0,R^=_<<9|_>>>23,_=R+D|0,T^=_<<13|_>>>19,_=T+R|0,k^=_<<18|_>>>14,_=he+ge|0,ee^=_<<7|_>>>25,_=ee+he|0,le^=_<<9|_>>>23,_=le+ee|0,ge^=_<<13|_>>>19,_=ge+le|0,he^=_<<18|_>>>14;f[0]=$>>>0&255,f[1]=$>>>8&255,f[2]=$>>>16&255,f[3]=$>>>24&255,f[4]=q>>>0&255,f[5]=q>>>8&255,f[6]=q>>>16&255,f[7]=q>>>24&255,f[8]=k>>>0&255,f[9]=k>>>8&255,f[10]=k>>>16&255,f[11]=k>>>24&255,f[12]=he>>>0&255,f[13]=he>>>8&255,f[14]=he>>>16&255,f[15]=he>>>24&255,f[16]=b>>>0&255,f[17]=b>>>8&255,f[18]=b>>>16&255,f[19]=b>>>24&255,f[20]=x>>>0&255,f[21]=x>>>8&255,f[22]=x>>>16&255,f[23]=x>>>24&255,f[24]=R>>>0&255,f[25]=R>>>8&255,f[26]=R>>>16&255,f[27]=R>>>24&255,f[28]=T>>>0&255,f[29]=T>>>8&255,f[30]=T>>>16&255,f[31]=T>>>24&255}function P(f,h,l,o){de(f,h,l,o)}function L(f,h,l,o){B(f,h,l,o)}var Q=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function j(f,h,l,o,p,E,v){var O=new Uint8Array(16),M=new Uint8Array(64),X,W;for(W=0;W<16;W++)O[W]=0;for(W=0;W<8;W++)O[W]=E[W];for(;p>=64;){for(P(M,O,v,Q),W=0;W<64;W++)f[h+W]=l[o+W]^M[W];for(X=1,W=8;W<16;W++)X=X+(O[W]&255)|0,O[W]=X&255,X>>>=8;p-=64,h+=64,o+=64}if(p>0)for(P(M,O,v,Q),W=0;W<p;W++)f[h+W]=l[o+W]^M[W];return 0}function Z(f,h,l,o,p){var E=new Uint8Array(16),v=new Uint8Array(64),O,M;for(M=0;M<16;M++)E[M]=0;for(M=0;M<8;M++)E[M]=o[M];for(;l>=64;){for(P(v,E,p,Q),M=0;M<64;M++)f[h+M]=v[M];for(O=1,M=8;M<16;M++)O=O+(E[M]&255)|0,E[M]=O&255,O>>>=8;l-=64,h+=64}if(l>0)for(P(v,E,p,Q),M=0;M<l;M++)f[h+M]=v[M];return 0}function pe(f,h,l,o,p){var E=new Uint8Array(32);L(E,o,p,Q);for(var v=new Uint8Array(8),O=0;O<8;O++)v[O]=o[O+16];return Z(f,h,l,v,E)}function Ee(f,h,l,o,p,E,v){var O=new Uint8Array(32);L(O,E,v,Q);for(var M=new Uint8Array(8),X=0;X<8;X++)M[X]=E[X+16];return j(f,h,l,o,p,M,O)}var ve=function(f){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var h,l,o,p,E,v,O,M;h=f[0]&255|(f[1]&255)<<8,this.r[0]=h&8191,l=f[2]&255|(f[3]&255)<<8,this.r[1]=(h>>>13|l<<3)&8191,o=f[4]&255|(f[5]&255)<<8,this.r[2]=(l>>>10|o<<6)&7939,p=f[6]&255|(f[7]&255)<<8,this.r[3]=(o>>>7|p<<9)&8191,E=f[8]&255|(f[9]&255)<<8,this.r[4]=(p>>>4|E<<12)&255,this.r[5]=E>>>1&8190,v=f[10]&255|(f[11]&255)<<8,this.r[6]=(E>>>14|v<<2)&8191,O=f[12]&255|(f[13]&255)<<8,this.r[7]=(v>>>11|O<<5)&8065,M=f[14]&255|(f[15]&255)<<8,this.r[8]=(O>>>8|M<<8)&8191,this.r[9]=M>>>5&127,this.pad[0]=f[16]&255|(f[17]&255)<<8,this.pad[1]=f[18]&255|(f[19]&255)<<8,this.pad[2]=f[20]&255|(f[21]&255)<<8,this.pad[3]=f[22]&255|(f[23]&255)<<8,this.pad[4]=f[24]&255|(f[25]&255)<<8,this.pad[5]=f[26]&255|(f[27]&255)<<8,this.pad[6]=f[28]&255|(f[29]&255)<<8,this.pad[7]=f[30]&255|(f[31]&255)<<8};ve.prototype.blocks=function(f,h,l){for(var o=this.fin?0:2048,p,E,v,O,M,X,W,Ce,K,re,ne,ue,ce,se,ae,ie,$,J,H,z=this.h[0],Y=this.h[1],q=this.h[2],b=this.h[3],x=this.h[4],R=this.h[5],T=this.h[6],k=this.h[7],D=this.h[8],ee=this.h[9],le=this.r[0],ge=this.r[1],he=this.r[2],_=this.r[3],_e=this.r[4],Oe=this.r[5],ke=this.r[6],me=this.r[7],we=this.r[8],be=this.r[9];l>=16;)p=f[h+0]&255|(f[h+1]&255)<<8,z+=p&8191,E=f[h+2]&255|(f[h+3]&255)<<8,Y+=(p>>>13|E<<3)&8191,v=f[h+4]&255|(f[h+5]&255)<<8,q+=(E>>>10|v<<6)&8191,O=f[h+6]&255|(f[h+7]&255)<<8,b+=(v>>>7|O<<9)&8191,M=f[h+8]&255|(f[h+9]&255)<<8,x+=(O>>>4|M<<12)&8191,R+=M>>>1&8191,X=f[h+10]&255|(f[h+11]&255)<<8,T+=(M>>>14|X<<2)&8191,W=f[h+12]&255|(f[h+13]&255)<<8,k+=(X>>>11|W<<5)&8191,Ce=f[h+14]&255|(f[h+15]&255)<<8,D+=(W>>>8|Ce<<8)&8191,ee+=Ce>>>5|o,K=0,re=K,re+=z*le,re+=Y*(5*be),re+=q*(5*we),re+=b*(5*me),re+=x*(5*ke),K=re>>>13,re&=8191,re+=R*(5*Oe),re+=T*(5*_e),re+=k*(5*_),re+=D*(5*he),re+=ee*(5*ge),K+=re>>>13,re&=8191,ne=K,ne+=z*ge,ne+=Y*le,ne+=q*(5*be),ne+=b*(5*we),ne+=x*(5*me),K=ne>>>13,ne&=8191,ne+=R*(5*ke),ne+=T*(5*Oe),ne+=k*(5*_e),ne+=D*(5*_),ne+=ee*(5*he),K+=ne>>>13,ne&=8191,ue=K,ue+=z*he,ue+=Y*ge,ue+=q*le,ue+=b*(5*be),ue+=x*(5*we),K=ue>>>13,ue&=8191,ue+=R*(5*me),ue+=T*(5*ke),ue+=k*(5*Oe),ue+=D*(5*_e),ue+=ee*(5*_),K+=ue>>>13,ue&=8191,ce=K,ce+=z*_,ce+=Y*he,ce+=q*ge,ce+=b*le,ce+=x*(5*be),K=ce>>>13,ce&=8191,ce+=R*(5*we),ce+=T*(5*me),ce+=k*(5*ke),ce+=D*(5*Oe),ce+=ee*(5*_e),K+=ce>>>13,ce&=8191,se=K,se+=z*_e,se+=Y*_,se+=q*he,se+=b*ge,se+=x*le,K=se>>>13,se&=8191,se+=R*(5*be),se+=T*(5*we),se+=k*(5*me),se+=D*(5*ke),se+=ee*(5*Oe),K+=se>>>13,se&=8191,ae=K,ae+=z*Oe,ae+=Y*_e,ae+=q*_,ae+=b*he,ae+=x*ge,K=ae>>>13,ae&=8191,ae+=R*le,ae+=T*(5*be),ae+=k*(5*we),ae+=D*(5*me),ae+=ee*(5*ke),K+=ae>>>13,ae&=8191,ie=K,ie+=z*ke,ie+=Y*Oe,ie+=q*_e,ie+=b*_,ie+=x*he,K=ie>>>13,ie&=8191,ie+=R*ge,ie+=T*le,ie+=k*(5*be),ie+=D*(5*we),ie+=ee*(5*me),K+=ie>>>13,ie&=8191,$=K,$+=z*me,$+=Y*ke,$+=q*Oe,$+=b*_e,$+=x*_,K=$>>>13,$&=8191,$+=R*he,$+=T*ge,$+=k*le,$+=D*(5*be),$+=ee*(5*we),K+=$>>>13,$&=8191,J=K,J+=z*we,J+=Y*me,J+=q*ke,J+=b*Oe,J+=x*_e,K=J>>>13,J&=8191,J+=R*_,J+=T*he,J+=k*ge,J+=D*le,J+=ee*(5*be),K+=J>>>13,J&=8191,H=K,H+=z*be,H+=Y*we,H+=q*me,H+=b*ke,H+=x*Oe,K=H>>>13,H&=8191,H+=R*_e,H+=T*_,H+=k*he,H+=D*ge,H+=ee*le,K+=H>>>13,H&=8191,K=(K<<2)+K|0,K=K+re|0,re=K&8191,K=K>>>13,ne+=K,z=re,Y=ne,q=ue,b=ce,x=se,R=ae,T=ie,k=$,D=J,ee=H,h+=16,l-=16;this.h[0]=z,this.h[1]=Y,this.h[2]=q,this.h[3]=b,this.h[4]=x,this.h[5]=R,this.h[6]=T,this.h[7]=k,this.h[8]=D,this.h[9]=ee},ve.prototype.finish=function(f,h){var l=new Uint16Array(10),o,p,E,v;if(this.leftover){for(v=this.leftover,this.buffer[v++]=1;v<16;v++)this.buffer[v]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(o=this.h[1]>>>13,this.h[1]&=8191,v=2;v<10;v++)this.h[v]+=o,o=this.h[v]>>>13,this.h[v]&=8191;for(this.h[0]+=o*5,o=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=o,o=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=o,l[0]=this.h[0]+5,o=l[0]>>>13,l[0]&=8191,v=1;v<10;v++)l[v]=this.h[v]+o,o=l[v]>>>13,l[v]&=8191;for(l[9]-=8192,p=(o^1)-1,v=0;v<10;v++)l[v]&=p;for(p=~p,v=0;v<10;v++)this.h[v]=this.h[v]&p|l[v];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,E=this.h[0]+this.pad[0],this.h[0]=E&65535,v=1;v<8;v++)E=(this.h[v]+this.pad[v]|0)+(E>>>16)|0,this.h[v]=E&65535;f[h+0]=this.h[0]>>>0&255,f[h+1]=this.h[0]>>>8&255,f[h+2]=this.h[1]>>>0&255,f[h+3]=this.h[1]>>>8&255,f[h+4]=this.h[2]>>>0&255,f[h+5]=this.h[2]>>>8&255,f[h+6]=this.h[3]>>>0&255,f[h+7]=this.h[3]>>>8&255,f[h+8]=this.h[4]>>>0&255,f[h+9]=this.h[4]>>>8&255,f[h+10]=this.h[5]>>>0&255,f[h+11]=this.h[5]>>>8&255,f[h+12]=this.h[6]>>>0&255,f[h+13]=this.h[6]>>>8&255,f[h+14]=this.h[7]>>>0&255,f[h+15]=this.h[7]>>>8&255},ve.prototype.update=function(f,h,l){var o,p;if(this.leftover){for(p=16-this.leftover,p>l&&(p=l),o=0;o<p;o++)this.buffer[this.leftover+o]=f[h+o];if(l-=p,h+=p,this.leftover+=p,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(l>=16&&(p=l-l%16,this.blocks(f,h,p),h+=p,l-=p),l){for(o=0;o<l;o++)this.buffer[this.leftover+o]=f[h+o];this.leftover+=l}};function We(f,h,l,o,p,E){var v=new ve(E);return v.update(l,o,p),v.finish(f,h),0}function Ke(f,h,l,o,p,E){var v=new Uint8Array(16);return We(v,0,l,o,p,E),C(f,h,v,0)}function Te(f,h,l,o,p){var E;if(l<32)return-1;for(Ee(f,0,h,0,l,o,p),We(f,16,f,32,l-32,f),E=0;E<16;E++)f[E]=0;return 0}function $e(f,h,l,o,p){var E,v=new Uint8Array(32);if(l<32||(pe(v,0,32,o,p),Ke(h,16,h,32,l-32,v)!==0))return-1;for(Ee(f,0,h,0,l,o,p),E=0;E<32;E++)f[E]=0;return 0}function He(f,h){var l;for(l=0;l<16;l++)f[l]=h[l]|0}function Ze(f){var h,l,o=1;for(h=0;h<16;h++)l=f[h]+o+65535,o=Math.floor(l/65536),f[h]=l-o*65536;f[0]+=o-1+37*(o-1)}function G(f,h,l){for(var o,p=~(l-1),E=0;E<16;E++)o=p&(f[E]^h[E]),f[E]^=o,h[E]^=o}function te(f,h){var l,o,p,E=e(),v=e();for(l=0;l<16;l++)v[l]=h[l];for(Ze(v),Ze(v),Ze(v),o=0;o<2;o++){for(E[0]=v[0]-65517,l=1;l<15;l++)E[l]=v[l]-65535-(E[l-1]>>16&1),E[l-1]&=65535;E[15]=v[15]-32767-(E[14]>>16&1),p=E[15]>>16&1,E[14]&=65535,G(v,E,1-p)}for(l=0;l<16;l++)f[2*l]=v[l]&255,f[2*l+1]=v[l]>>8}function Ae(f,h){var l=new Uint8Array(32),o=new Uint8Array(32);return te(l,f),te(o,h),V(l,0,o,0)}function Be(f){var h=new Uint8Array(32);return te(h,f),h[0]&1}function yt(f,h){var l;for(l=0;l<16;l++)f[l]=h[2*l]+(h[2*l+1]<<8);f[15]&=32767}function N(f,h,l){for(var o=0;o<16;o++)f[o]=h[o]+l[o]}function U(f,h,l){for(var o=0;o<16;o++)f[o]=h[o]-l[o]}function A(f,h,l){var o,p,E=0,v=0,O=0,M=0,X=0,W=0,Ce=0,K=0,re=0,ne=0,ue=0,ce=0,se=0,ae=0,ie=0,$=0,J=0,H=0,z=0,Y=0,q=0,b=0,x=0,R=0,T=0,k=0,D=0,ee=0,le=0,ge=0,he=0,_=l[0],_e=l[1],Oe=l[2],ke=l[3],me=l[4],we=l[5],be=l[6],Je=l[7],Re=l[8],ze=l[9],Ge=l[10],Ye=l[11],et=l[12],it=l[13],ot=l[14],at=l[15];o=h[0],E+=o*_,v+=o*_e,O+=o*Oe,M+=o*ke,X+=o*me,W+=o*we,Ce+=o*be,K+=o*Je,re+=o*Re,ne+=o*ze,ue+=o*Ge,ce+=o*Ye,se+=o*et,ae+=o*it,ie+=o*ot,$+=o*at,o=h[1],v+=o*_,O+=o*_e,M+=o*Oe,X+=o*ke,W+=o*me,Ce+=o*we,K+=o*be,re+=o*Je,ne+=o*Re,ue+=o*ze,ce+=o*Ge,se+=o*Ye,ae+=o*et,ie+=o*it,$+=o*ot,J+=o*at,o=h[2],O+=o*_,M+=o*_e,X+=o*Oe,W+=o*ke,Ce+=o*me,K+=o*we,re+=o*be,ne+=o*Je,ue+=o*Re,ce+=o*ze,se+=o*Ge,ae+=o*Ye,ie+=o*et,$+=o*it,J+=o*ot,H+=o*at,o=h[3],M+=o*_,X+=o*_e,W+=o*Oe,Ce+=o*ke,K+=o*me,re+=o*we,ne+=o*be,ue+=o*Je,ce+=o*Re,se+=o*ze,ae+=o*Ge,ie+=o*Ye,$+=o*et,J+=o*it,H+=o*ot,z+=o*at,o=h[4],X+=o*_,W+=o*_e,Ce+=o*Oe,K+=o*ke,re+=o*me,ne+=o*we,ue+=o*be,ce+=o*Je,se+=o*Re,ae+=o*ze,ie+=o*Ge,$+=o*Ye,J+=o*et,H+=o*it,z+=o*ot,Y+=o*at,o=h[5],W+=o*_,Ce+=o*_e,K+=o*Oe,re+=o*ke,ne+=o*me,ue+=o*we,ce+=o*be,se+=o*Je,ae+=o*Re,ie+=o*ze,$+=o*Ge,J+=o*Ye,H+=o*et,z+=o*it,Y+=o*ot,q+=o*at,o=h[6],Ce+=o*_,K+=o*_e,re+=o*Oe,ne+=o*ke,ue+=o*me,ce+=o*we,se+=o*be,ae+=o*Je,ie+=o*Re,$+=o*ze,J+=o*Ge,H+=o*Ye,z+=o*et,Y+=o*it,q+=o*ot,b+=o*at,o=h[7],K+=o*_,re+=o*_e,ne+=o*Oe,ue+=o*ke,ce+=o*me,se+=o*we,ae+=o*be,ie+=o*Je,$+=o*Re,J+=o*ze,H+=o*Ge,z+=o*Ye,Y+=o*et,q+=o*it,b+=o*ot,x+=o*at,o=h[8],re+=o*_,ne+=o*_e,ue+=o*Oe,ce+=o*ke,se+=o*me,ae+=o*we,ie+=o*be,$+=o*Je,J+=o*Re,H+=o*ze,z+=o*Ge,Y+=o*Ye,q+=o*et,b+=o*it,x+=o*ot,R+=o*at,o=h[9],ne+=o*_,ue+=o*_e,ce+=o*Oe,se+=o*ke,ae+=o*me,ie+=o*we,$+=o*be,J+=o*Je,H+=o*Re,z+=o*ze,Y+=o*Ge,q+=o*Ye,b+=o*et,x+=o*it,R+=o*ot,T+=o*at,o=h[10],ue+=o*_,ce+=o*_e,se+=o*Oe,ae+=o*ke,ie+=o*me,$+=o*we,J+=o*be,H+=o*Je,z+=o*Re,Y+=o*ze,q+=o*Ge,b+=o*Ye,x+=o*et,R+=o*it,T+=o*ot,k+=o*at,o=h[11],ce+=o*_,se+=o*_e,ae+=o*Oe,ie+=o*ke,$+=o*me,J+=o*we,H+=o*be,z+=o*Je,Y+=o*Re,q+=o*ze,b+=o*Ge,x+=o*Ye,R+=o*et,T+=o*it,k+=o*ot,D+=o*at,o=h[12],se+=o*_,ae+=o*_e,ie+=o*Oe,$+=o*ke,J+=o*me,H+=o*we,z+=o*be,Y+=o*Je,q+=o*Re,b+=o*ze,x+=o*Ge,R+=o*Ye,T+=o*et,k+=o*it,D+=o*ot,ee+=o*at,o=h[13],ae+=o*_,ie+=o*_e,$+=o*Oe,J+=o*ke,H+=o*me,z+=o*we,Y+=o*be,q+=o*Je,b+=o*Re,x+=o*ze,R+=o*Ge,T+=o*Ye,k+=o*et,D+=o*it,ee+=o*ot,le+=o*at,o=h[14],ie+=o*_,$+=o*_e,J+=o*Oe,H+=o*ke,z+=o*me,Y+=o*we,q+=o*be,b+=o*Je,x+=o*Re,R+=o*ze,T+=o*Ge,k+=o*Ye,D+=o*et,ee+=o*it,le+=o*ot,ge+=o*at,o=h[15],$+=o*_,J+=o*_e,H+=o*Oe,z+=o*ke,Y+=o*me,q+=o*we,b+=o*be,x+=o*Je,R+=o*Re,T+=o*ze,k+=o*Ge,D+=o*Ye,ee+=o*et,le+=o*it,ge+=o*ot,he+=o*at,E+=38*J,v+=38*H,O+=38*z,M+=38*Y,X+=38*q,W+=38*b,Ce+=38*x,K+=38*R,re+=38*T,ne+=38*k,ue+=38*D,ce+=38*ee,se+=38*le,ae+=38*ge,ie+=38*he,p=1,o=E+p+65535,p=Math.floor(o/65536),E=o-p*65536,o=v+p+65535,p=Math.floor(o/65536),v=o-p*65536,o=O+p+65535,p=Math.floor(o/65536),O=o-p*65536,o=M+p+65535,p=Math.floor(o/65536),M=o-p*65536,o=X+p+65535,p=Math.floor(o/65536),X=o-p*65536,o=W+p+65535,p=Math.floor(o/65536),W=o-p*65536,o=Ce+p+65535,p=Math.floor(o/65536),Ce=o-p*65536,o=K+p+65535,p=Math.floor(o/65536),K=o-p*65536,o=re+p+65535,p=Math.floor(o/65536),re=o-p*65536,o=ne+p+65535,p=Math.floor(o/65536),ne=o-p*65536,o=ue+p+65535,p=Math.floor(o/65536),ue=o-p*65536,o=ce+p+65535,p=Math.floor(o/65536),ce=o-p*65536,o=se+p+65535,p=Math.floor(o/65536),se=o-p*65536,o=ae+p+65535,p=Math.floor(o/65536),ae=o-p*65536,o=ie+p+65535,p=Math.floor(o/65536),ie=o-p*65536,o=$+p+65535,p=Math.floor(o/65536),$=o-p*65536,E+=p-1+37*(p-1),p=1,o=E+p+65535,p=Math.floor(o/65536),E=o-p*65536,o=v+p+65535,p=Math.floor(o/65536),v=o-p*65536,o=O+p+65535,p=Math.floor(o/65536),O=o-p*65536,o=M+p+65535,p=Math.floor(o/65536),M=o-p*65536,o=X+p+65535,p=Math.floor(o/65536),X=o-p*65536,o=W+p+65535,p=Math.floor(o/65536),W=o-p*65536,o=Ce+p+65535,p=Math.floor(o/65536),Ce=o-p*65536,o=K+p+65535,p=Math.floor(o/65536),K=o-p*65536,o=re+p+65535,p=Math.floor(o/65536),re=o-p*65536,o=ne+p+65535,p=Math.floor(o/65536),ne=o-p*65536,o=ue+p+65535,p=Math.floor(o/65536),ue=o-p*65536,o=ce+p+65535,p=Math.floor(o/65536),ce=o-p*65536,o=se+p+65535,p=Math.floor(o/65536),se=o-p*65536,o=ae+p+65535,p=Math.floor(o/65536),ae=o-p*65536,o=ie+p+65535,p=Math.floor(o/65536),ie=o-p*65536,o=$+p+65535,p=Math.floor(o/65536),$=o-p*65536,E+=p-1+37*(p-1),f[0]=E,f[1]=v,f[2]=O,f[3]=M,f[4]=X,f[5]=W,f[6]=Ce,f[7]=K,f[8]=re,f[9]=ne,f[10]=ue,f[11]=ce,f[12]=se,f[13]=ae,f[14]=ie,f[15]=$}function oe(f,h){A(f,h,h)}function Ie(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=253;o>=0;o--)oe(l,l),o!==2&&o!==4&&A(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function ut(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=250;o>=0;o--)oe(l,l),o!==1&&A(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function Et(f,h,l){var o=new Uint8Array(32),p=new Float64Array(80),E,v,O=e(),M=e(),X=e(),W=e(),Ce=e(),K=e();for(v=0;v<31;v++)o[v]=h[v];for(o[31]=h[31]&127|64,o[0]&=248,yt(p,l),v=0;v<16;v++)M[v]=p[v],W[v]=O[v]=X[v]=0;for(O[0]=W[0]=1,v=254;v>=0;--v)E=o[v>>>3]>>>(v&7)&1,G(O,M,E),G(X,W,E),N(Ce,O,X),U(O,O,X),N(X,M,W),U(M,M,W),oe(W,Ce),oe(K,O),A(O,X,O),A(X,M,Ce),N(Ce,O,X),U(O,O,X),oe(M,O),U(X,W,K),A(O,X,c),N(O,O,W),A(X,X,O),A(O,W,K),A(W,M,p),oe(M,Ce),G(O,M,E),G(X,W,E);for(v=0;v<16;v++)p[v+16]=O[v],p[v+32]=X[v],p[v+48]=M[v],p[v+64]=W[v];var re=p.subarray(32),ne=p.subarray(16);return Ie(re,re),A(ne,ne,re),te(f,ne),0}function vt(f,h){return Et(f,h,s)}function wt(f,h){return t(h,32),vt(f,h)}function ir(f,h,l){var o=new Uint8Array(32);return Et(o,l,h),L(f,n,o,Q)}var wr=Te,Wr=$e;function br(f,h,l,o,p,E){var v=new Uint8Array(32);return ir(v,p,E),wr(f,h,l,o,v)}function gn(f,h,l,o,p,E){var v=new Uint8Array(32);return ir(v,p,E),Wr(f,h,l,o,v)}var Ls=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function Jc(f,h,l,o){for(var p=new Int32Array(16),E=new Int32Array(16),v,O,M,X,W,Ce,K,re,ne,ue,ce,se,ae,ie,$,J,H,z,Y,q,b,x,R,T,k,D,ee=f[0],le=f[1],ge=f[2],he=f[3],_=f[4],_e=f[5],Oe=f[6],ke=f[7],me=h[0],we=h[1],be=h[2],Je=h[3],Re=h[4],ze=h[5],Ge=h[6],Ye=h[7],et=0;o>=128;){for(Y=0;Y<16;Y++)q=8*Y+et,p[Y]=l[q+0]<<24|l[q+1]<<16|l[q+2]<<8|l[q+3],E[Y]=l[q+4]<<24|l[q+5]<<16|l[q+6]<<8|l[q+7];for(Y=0;Y<80;Y++)if(v=ee,O=le,M=ge,X=he,W=_,Ce=_e,K=Oe,re=ke,ne=me,ue=we,ce=be,se=Je,ae=Re,ie=ze,$=Ge,J=Ye,b=ke,x=Ye,R=x&65535,T=x>>>16,k=b&65535,D=b>>>16,b=(_>>>14|Re<<18)^(_>>>18|Re<<14)^(Re>>>9|_<<23),x=(Re>>>14|_<<18)^(Re>>>18|_<<14)^(_>>>9|Re<<23),R+=x&65535,T+=x>>>16,k+=b&65535,D+=b>>>16,b=_&_e^~_&Oe,x=Re&ze^~Re&Ge,R+=x&65535,T+=x>>>16,k+=b&65535,D+=b>>>16,b=Ls[Y*2],x=Ls[Y*2+1],R+=x&65535,T+=x>>>16,k+=b&65535,D+=b>>>16,b=p[Y%16],x=E[Y%16],R+=x&65535,T+=x>>>16,k+=b&65535,D+=b>>>16,T+=R>>>16,k+=T>>>16,D+=k>>>16,H=k&65535|D<<16,z=R&65535|T<<16,b=H,x=z,R=x&65535,T=x>>>16,k=b&65535,D=b>>>16,b=(ee>>>28|me<<4)^(me>>>2|ee<<30)^(me>>>7|ee<<25),x=(me>>>28|ee<<4)^(ee>>>2|me<<30)^(ee>>>7|me<<25),R+=x&65535,T+=x>>>16,k+=b&65535,D+=b>>>16,b=ee&le^ee&ge^le&ge,x=me&we^me&be^we&be,R+=x&65535,T+=x>>>16,k+=b&65535,D+=b>>>16,T+=R>>>16,k+=T>>>16,D+=k>>>16,re=k&65535|D<<16,J=R&65535|T<<16,b=X,x=se,R=x&65535,T=x>>>16,k=b&65535,D=b>>>16,b=H,x=z,R+=x&65535,T+=x>>>16,k+=b&65535,D+=b>>>16,T+=R>>>16,k+=T>>>16,D+=k>>>16,X=k&65535|D<<16,se=R&65535|T<<16,le=v,ge=O,he=M,_=X,_e=W,Oe=Ce,ke=K,ee=re,we=ne,be=ue,Je=ce,Re=se,ze=ae,Ge=ie,Ye=$,me=J,Y%16===15)for(q=0;q<16;q++)b=p[q],x=E[q],R=x&65535,T=x>>>16,k=b&65535,D=b>>>16,b=p[(q+9)%16],x=E[(q+9)%16],R+=x&65535,T+=x>>>16,k+=b&65535,D+=b>>>16,H=p[(q+1)%16],z=E[(q+1)%16],b=(H>>>1|z<<31)^(H>>>8|z<<24)^H>>>7,x=(z>>>1|H<<31)^(z>>>8|H<<24)^(z>>>7|H<<25),R+=x&65535,T+=x>>>16,k+=b&65535,D+=b>>>16,H=p[(q+14)%16],z=E[(q+14)%16],b=(H>>>19|z<<13)^(z>>>29|H<<3)^H>>>6,x=(z>>>19|H<<13)^(H>>>29|z<<3)^(z>>>6|H<<26),R+=x&65535,T+=x>>>16,k+=b&65535,D+=b>>>16,T+=R>>>16,k+=T>>>16,D+=k>>>16,p[q]=k&65535|D<<16,E[q]=R&65535|T<<16;b=ee,x=me,R=x&65535,T=x>>>16,k=b&65535,D=b>>>16,b=f[0],x=h[0],R+=x&65535,T+=x>>>16,k+=b&65535,D+=b>>>16,T+=R>>>16,k+=T>>>16,D+=k>>>16,f[0]=ee=k&65535|D<<16,h[0]=me=R&65535|T<<16,b=le,x=we,R=x&65535,T=x>>>16,k=b&65535,D=b>>>16,b=f[1],x=h[1],R+=x&65535,T+=x>>>16,k+=b&65535,D+=b>>>16,T+=R>>>16,k+=T>>>16,D+=k>>>16,f[1]=le=k&65535|D<<16,h[1]=we=R&65535|T<<16,b=ge,x=be,R=x&65535,T=x>>>16,k=b&65535,D=b>>>16,b=f[2],x=h[2],R+=x&65535,T+=x>>>16,k+=b&65535,D+=b>>>16,T+=R>>>16,k+=T>>>16,D+=k>>>16,f[2]=ge=k&65535|D<<16,h[2]=be=R&65535|T<<16,b=he,x=Je,R=x&65535,T=x>>>16,k=b&65535,D=b>>>16,b=f[3],x=h[3],R+=x&65535,T+=x>>>16,k+=b&65535,D+=b>>>16,T+=R>>>16,k+=T>>>16,D+=k>>>16,f[3]=he=k&65535|D<<16,h[3]=Je=R&65535|T<<16,b=_,x=Re,R=x&65535,T=x>>>16,k=b&65535,D=b>>>16,b=f[4],x=h[4],R+=x&65535,T+=x>>>16,k+=b&65535,D+=b>>>16,T+=R>>>16,k+=T>>>16,D+=k>>>16,f[4]=_=k&65535|D<<16,h[4]=Re=R&65535|T<<16,b=_e,x=ze,R=x&65535,T=x>>>16,k=b&65535,D=b>>>16,b=f[5],x=h[5],R+=x&65535,T+=x>>>16,k+=b&65535,D+=b>>>16,T+=R>>>16,k+=T>>>16,D+=k>>>16,f[5]=_e=k&65535|D<<16,h[5]=ze=R&65535|T<<16,b=Oe,x=Ge,R=x&65535,T=x>>>16,k=b&65535,D=b>>>16,b=f[6],x=h[6],R+=x&65535,T+=x>>>16,k+=b&65535,D+=b>>>16,T+=R>>>16,k+=T>>>16,D+=k>>>16,f[6]=Oe=k&65535|D<<16,h[6]=Ge=R&65535|T<<16,b=ke,x=Ye,R=x&65535,T=x>>>16,k=b&65535,D=b>>>16,b=f[7],x=h[7],R+=x&65535,T+=x>>>16,k+=b&65535,D+=b>>>16,T+=R>>>16,k+=T>>>16,D+=k>>>16,f[7]=ke=k&65535|D<<16,h[7]=Ye=R&65535|T<<16,et+=128,o-=128}return o}function Hr(f,h,l){var o=new Int32Array(8),p=new Int32Array(8),E=new Uint8Array(256),v,O=l;for(o[0]=1779033703,o[1]=3144134277,o[2]=1013904242,o[3]=2773480762,o[4]=1359893119,o[5]=2600822924,o[6]=528734635,o[7]=1541459225,p[0]=4089235720,p[1]=2227873595,p[2]=4271175723,p[3]=1595750129,p[4]=2917565137,p[5]=725511199,p[6]=4215389547,p[7]=327033209,Jc(o,p,h,l),l%=128,v=0;v<l;v++)E[v]=h[O-l+v];for(E[l]=128,l=256-128*(l<112?1:0),E[l-9]=0,w(E,l-8,O/536870912|0,O<<3),Jc(o,p,E,l),v=0;v<8;v++)w(f,8*v,o[v],p[v]);return 0}function Ns(f,h){var l=e(),o=e(),p=e(),E=e(),v=e(),O=e(),M=e(),X=e(),W=e();U(l,f[1],f[0]),U(W,h[1],h[0]),A(l,l,W),N(o,f[0],f[1]),N(W,h[0],h[1]),A(o,o,W),A(p,f[3],h[3]),A(p,p,d),A(E,f[2],h[2]),N(E,E,E),U(v,o,l),U(O,E,p),N(M,E,p),N(X,o,l),A(f[0],v,O),A(f[1],X,M),A(f[2],M,O),A(f[3],v,X)}function Zc(f,h,l){var o;for(o=0;o<4;o++)G(f[o],h[o],l)}function go(f,h){var l=e(),o=e(),p=e();Ie(p,h[2]),A(l,h[0],p),A(o,h[1],p),te(f,o),f[31]^=Be(l)<<7}function mo(f,h,l){var o,p;for(He(f[0],i),He(f[1],a),He(f[2],a),He(f[3],i),p=255;p>=0;--p)o=l[p/8|0]>>(p&7)&1,Zc(f,h,o),Ns(h,f),Ns(f,f),Zc(f,h,o)}function Ds(f,h){var l=[e(),e(),e(),e()];He(l[0],g),He(l[1],m),He(l[2],a),A(l[3],g,m),mo(f,l,h)}function _o(f,h,l){var o=new Uint8Array(64),p=[e(),e(),e(),e()],E;for(l||t(h,32),Hr(o,h,32),o[0]&=248,o[31]&=127,o[31]|=64,Ds(p,o),go(f,p),E=0;E<32;E++)h[E+32]=f[E];return 0}var Fs=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function yo(f,h){var l,o,p,E;for(o=63;o>=32;--o){for(l=0,p=o-32,E=o-12;p<E;++p)h[p]+=l-16*h[o]*Fs[p-(o-32)],l=Math.floor((h[p]+128)/256),h[p]-=l*256;h[p]+=l,h[o]=0}for(l=0,p=0;p<32;p++)h[p]+=l-(h[31]>>4)*Fs[p],l=h[p]>>8,h[p]&=255;for(p=0;p<32;p++)h[p]-=l*Fs[p];for(o=0;o<32;o++)h[o+1]+=h[o]>>8,f[o]=h[o]&255}function Eo(f){var h=new Float64Array(64),l;for(l=0;l<64;l++)h[l]=f[l];for(l=0;l<64;l++)f[l]=0;yo(f,h)}function Qc(f,h,l,o){var p=new Uint8Array(64),E=new Uint8Array(64),v=new Uint8Array(64),O,M,X=new Float64Array(64),W=[e(),e(),e(),e()];Hr(p,o,32),p[0]&=248,p[31]&=127,p[31]|=64;var Ce=l+64;for(O=0;O<l;O++)f[64+O]=h[O];for(O=0;O<32;O++)f[32+O]=p[32+O];for(Hr(v,f.subarray(32),l+32),Eo(v),Ds(W,v),go(f,W),O=32;O<64;O++)f[O]=o[O];for(Hr(E,f,l+64),Eo(E),O=0;O<64;O++)X[O]=0;for(O=0;O<32;O++)X[O]=v[O];for(O=0;O<32;O++)for(M=0;M<32;M++)X[O+M]+=E[O]*p[M];return yo(f.subarray(32),X),Ce}function Nd(f,h){var l=e(),o=e(),p=e(),E=e(),v=e(),O=e(),M=e();return He(f[2],a),yt(f[1],h),oe(p,f[1]),A(E,p,u),U(p,p,f[2]),N(E,f[2],E),oe(v,E),oe(O,v),A(M,O,v),A(l,M,p),A(l,l,E),ut(l,l),A(l,l,p),A(l,l,E),A(l,l,E),A(f[0],l,E),oe(o,f[0]),A(o,o,E),Ae(o,p)&&A(f[0],f[0],y),oe(o,f[0]),A(o,o,E),Ae(o,p)?-1:(Be(f[0])===h[31]>>7&&U(f[0],i,f[0]),A(f[3],f[0],f[1]),0)}function vo(f,h,l,o){var p,E=new Uint8Array(32),v=new Uint8Array(64),O=[e(),e(),e(),e()],M=[e(),e(),e(),e()];if(l<64||Nd(M,o))return-1;for(p=0;p<l;p++)f[p]=h[p];for(p=0;p<32;p++)f[p+32]=o[p];if(Hr(v,f,l),Eo(v),mo(O,M,v),Ds(M,h.subarray(32)),Ns(O,M),go(E,O),l-=64,V(h,0,E,0)){for(p=0;p<l;p++)f[p]=0;return-1}for(p=0;p<l;p++)f[p]=h[p+64];return l}var wo=32,Ms=24,Gn=32,mn=16,Yn=32,Bs=32,Xn=32,Jn=32,bo=32,ef=Ms,Dd=Gn,Fd=mn,or=64,Vr=32,_n=64,xo=32,So=64;r.lowlevel={crypto_core_hsalsa20:L,crypto_stream_xor:Ee,crypto_stream:pe,crypto_stream_salsa20_xor:j,crypto_stream_salsa20:Z,crypto_onetimeauth:We,crypto_onetimeauth_verify:Ke,crypto_verify_16:C,crypto_verify_32:V,crypto_secretbox:Te,crypto_secretbox_open:$e,crypto_scalarmult:Et,crypto_scalarmult_base:vt,crypto_box_beforenm:ir,crypto_box_afternm:wr,crypto_box:br,crypto_box_open:gn,crypto_box_keypair:wt,crypto_hash:Hr,crypto_sign:Qc,crypto_sign_keypair:_o,crypto_sign_open:vo,crypto_secretbox_KEYBYTES:wo,crypto_secretbox_NONCEBYTES:Ms,crypto_secretbox_ZEROBYTES:Gn,crypto_secretbox_BOXZEROBYTES:mn,crypto_scalarmult_BYTES:Yn,crypto_scalarmult_SCALARBYTES:Bs,crypto_box_PUBLICKEYBYTES:Xn,crypto_box_SECRETKEYBYTES:Jn,crypto_box_BEFORENMBYTES:bo,crypto_box_NONCEBYTES:ef,crypto_box_ZEROBYTES:Dd,crypto_box_BOXZEROBYTES:Fd,crypto_sign_BYTES:or,crypto_sign_PUBLICKEYBYTES:Vr,crypto_sign_SECRETKEYBYTES:_n,crypto_sign_SEEDBYTES:xo,crypto_hash_BYTES:So,gf:e,D:u,L:Fs,pack25519:te,unpack25519:yt,M:A,A:N,S:oe,Z:U,pow2523:ut,add:Ns,set25519:He,modL:yo,scalarmult:mo,scalarbase:Ds};function tf(f,h){if(f.length!==wo)throw new Error("bad key size");if(h.length!==Ms)throw new Error("bad nonce size")}function Md(f,h){if(f.length!==Xn)throw new Error("bad public key size");if(h.length!==Jn)throw new Error("bad secret key size")}function bt(){for(var f=0;f<arguments.length;f++)if(!(arguments[f]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function rf(f){for(var h=0;h<f.length;h++)f[h]=0}r.randomBytes=function(f){var h=new Uint8Array(f);return t(h,f),h},r.secretbox=function(f,h,l){bt(f,h,l),tf(l,h);for(var o=new Uint8Array(Gn+f.length),p=new Uint8Array(o.length),E=0;E<f.length;E++)o[E+Gn]=f[E];return Te(p,o,o.length,h,l),p.subarray(mn)},r.secretbox.open=function(f,h,l){bt(f,h,l),tf(l,h);for(var o=new Uint8Array(mn+f.length),p=new Uint8Array(o.length),E=0;E<f.length;E++)o[E+mn]=f[E];return o.length<32||$e(p,o,o.length,h,l)!==0?null:p.subarray(Gn)},r.secretbox.keyLength=wo,r.secretbox.nonceLength=Ms,r.secretbox.overheadLength=mn,r.scalarMult=function(f,h){if(bt(f,h),f.length!==Bs)throw new Error("bad n size");if(h.length!==Yn)throw new Error("bad p size");var l=new Uint8Array(Yn);return Et(l,f,h),l},r.scalarMult.base=function(f){if(bt(f),f.length!==Bs)throw new Error("bad n size");var h=new Uint8Array(Yn);return vt(h,f),h},r.scalarMult.scalarLength=Bs,r.scalarMult.groupElementLength=Yn,r.box=function(f,h,l,o){var p=r.box.before(l,o);return r.secretbox(f,h,p)},r.box.before=function(f,h){bt(f,h),Md(f,h);var l=new Uint8Array(bo);return ir(l,f,h),l},r.box.after=r.secretbox,r.box.open=function(f,h,l,o){var p=r.box.before(l,o);return r.secretbox.open(f,h,p)},r.box.open.after=r.secretbox.open,r.box.keyPair=function(){var f=new Uint8Array(Xn),h=new Uint8Array(Jn);return wt(f,h),{publicKey:f,secretKey:h}},r.box.keyPair.fromSecretKey=function(f){if(bt(f),f.length!==Jn)throw new Error("bad secret key size");var h=new Uint8Array(Xn);return vt(h,f),{publicKey:h,secretKey:new Uint8Array(f)}},r.box.publicKeyLength=Xn,r.box.secretKeyLength=Jn,r.box.sharedKeyLength=bo,r.box.nonceLength=ef,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(f,h){if(bt(f,h),h.length!==_n)throw new Error("bad secret key size");var l=new Uint8Array(or+f.length);return Qc(l,f,f.length,h),l},r.sign.open=function(f,h){if(bt(f,h),h.length!==Vr)throw new Error("bad public key size");var l=new Uint8Array(f.length),o=vo(l,f,f.length,h);if(o<0)return null;for(var p=new Uint8Array(o),E=0;E<p.length;E++)p[E]=l[E];return p},r.sign.detached=function(f,h){for(var l=r.sign(f,h),o=new Uint8Array(or),p=0;p<o.length;p++)o[p]=l[p];return o},r.sign.detached.verify=function(f,h,l){if(bt(f,h,l),h.length!==or)throw new Error("bad signature size");if(l.length!==Vr)throw new Error("bad public key size");var o=new Uint8Array(or+f.length),p=new Uint8Array(or+f.length),E;for(E=0;E<or;E++)o[E]=h[E];for(E=0;E<f.length;E++)o[E+or]=f[E];return vo(p,o,o.length,l)>=0},r.sign.keyPair=function(){var f=new Uint8Array(Vr),h=new Uint8Array(_n);return _o(f,h),{publicKey:f,secretKey:h}},r.sign.keyPair.fromSecretKey=function(f){if(bt(f),f.length!==_n)throw new Error("bad secret key size");for(var h=new Uint8Array(Vr),l=0;l<h.length;l++)h[l]=f[32+l];return{publicKey:h,secretKey:new Uint8Array(f)}},r.sign.keyPair.fromSeed=function(f){if(bt(f),f.length!==xo)throw new Error("bad seed size");for(var h=new Uint8Array(Vr),l=new Uint8Array(_n),o=0;o<32;o++)l[o]=f[o];return _o(h,l,!0),{publicKey:h,secretKey:l}},r.sign.publicKeyLength=Vr,r.sign.secretKeyLength=_n,r.sign.seedLength=xo,r.sign.signatureLength=or,r.hash=function(f){bt(f);var h=new Uint8Array(So);return Hr(h,f,f.length),h},r.hash.hashLength=So,r.verify=function(f,h){return bt(f,h),f.length===0||h.length===0||f.length!==h.length?!1:S(f,0,h,0,f.length)===0},r.setPRNG=function(f){t=f},(function(){var f=typeof self<"u"?self.crypto||self.msCrypto:null;if(f&&f.getRandomValues){var h=65536;r.setPRNG(function(l,o){var p,E=new Uint8Array(o);for(p=0;p<o;p+=h)f.getRandomValues(E.subarray(p,p+Math.min(o-p,h)));for(p=0;p<o;p++)l[p]=E[p];rf(E)})}else typeof require<"u"&&(f=require("crypto"),f&&f.randomBytes&&r.setPRNG(function(l,o){var p,E=f.randomBytes(o);for(p=0;p<o;p++)l[p]=E[p];rf(E)}))})()})(typeof Xs<"u"&&Xs.exports?Xs.exports:self.nacl=self.nacl||{})});var Ro=F((xf,Js)=>{(function(r,e){"use strict";typeof Js<"u"&&Js.exports?Js.exports=e():(r.nacl||(r.nacl={}),r.nacl.util=e())})(xf,function(){"use strict";var r={};function e(t){if(!/^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(t))throw new TypeError("invalid encoding")}return r.decodeUTF8=function(t){if(typeof t!="string")throw new TypeError("expected string");var n,s=unescape(encodeURIComponent(t)),i=new Uint8Array(s.length);for(n=0;n<s.length;n++)i[n]=s.charCodeAt(n);return i},r.encodeUTF8=function(t){var n,s=[];for(n=0;n<t.length;n++)s.push(String.fromCharCode(t[n]));return decodeURIComponent(escape(s.join("")))},typeof atob>"u"?typeof Buffer.from<"u"?(r.encodeBase64=function(t){return Buffer.from(t).toString("base64")},r.decodeBase64=function(t){return e(t),new Uint8Array(Array.prototype.slice.call(Buffer.from(t,"base64"),0))}):(r.encodeBase64=function(t){return new Buffer(t).toString("base64")},r.decodeBase64=function(t){return e(t),new Uint8Array(Array.prototype.slice.call(new Buffer(t,"base64"),0))}):(r.encodeBase64=function(t){var n,s=[],i=t.length;for(n=0;n<i;n++)s.push(String.fromCharCode(t[n]));return btoa(s.join(""))},r.decodeBase64=function(t){e(t);var n,s=atob(t),i=new Uint8Array(s.length);for(n=0;n<s.length;n++)i[n]=s.charCodeAt(n);return i}),r})});var Sf=F(Tr=>{"use strict";var ip=Tr&&Tr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Tr,"__esModule",{value:!0});Tr.encrypt=op;Tr.decrypt=ap;Tr.encryptBinary=cp;Tr.decryptBinary=fp;var fr=ip(Po()),Sr=Ro();function op(r,e,t){let n=fr.default.randomBytes(fr.default.secretbox.nonceLength),s=new TextEncoder().encode(r),i=fr.default.secretbox(s,n,e);return{v:1,sid:t,n:(0,Sr.encodeBase64)(n),c:(0,Sr.encodeBase64)(i)}}function ap(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Sr.decodeBase64)(r.n),n=(0,Sr.decodeBase64)(r.c);if(t.length!==fr.default.secretbox.nonceLength)throw new Error(`Invalid nonce length: ${t.length}`);let s=fr.default.secretbox.open(n,t,e);if(!s)throw new Error("Decryption failed: invalid ciphertext or wrong key");return new TextDecoder().decode(s)}function cp(r,e,t){let n=fr.default.randomBytes(fr.default.secretbox.nonceLength),s=fr.default.secretbox(r,n,e);return{v:1,sid:t,n:(0,Sr.encodeBase64)(n),c:(0,Sr.encodeBase64)(s)}}function fp(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Sr.decodeBase64)(r.n),n=(0,Sr.decodeBase64)(r.c),s=fr.default.secretbox.open(n,t,e);if(!s)throw new Error("Decryption failed: invalid ciphertext or wrong key");return s}});var Tf=F($t=>{"use strict";var up=$t&&$t.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty($t,"__esModule",{value:!0});$t.generateKeyPair=lp;$t.deriveSharedSecret=hp;$t.isValidPublicKey=dp;$t.clearKey=pp;$t.keyToBase64=gp;$t.base64ToKey=mp;var ts=up(Po()),Kr=Ro();function lp(){let r=ts.default.box.keyPair();return{publicKey:(0,Kr.encodeBase64)(r.publicKey),secretKey:(0,Kr.encodeBase64)(r.secretKey)}}function hp(r,e){let t=(0,Kr.decodeBase64)(r),n=(0,Kr.decodeBase64)(e);if(t.length!==ts.default.box.publicKeyLength)throw new Error(`Invalid public key length: ${t.length}`);if(n.length!==ts.default.box.secretKeyLength)throw new Error(`Invalid secret key length: ${n.length}`);return ts.default.box.before(t,n)}function dp(r){try{return(0,Kr.decodeBase64)(r).length===ts.default.box.publicKeyLength}catch{return!1}}function pp(r){r.fill(0)}function gp(r){return(0,Kr.encodeBase64)(r)}function mp(r){return(0,Kr.decodeBase64)(r)}});var Of=F(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.base64ToKey=De.keyToBase64=De.clearKey=De.isValidPublicKey=De.deriveSharedSecret=De.generateKeyPair=De.decryptBinary=De.encryptBinary=De.decrypt=De.encrypt=De.isMultiRecipientPayload=De.isEncryptedPayload=void 0;var Cf=bf();Object.defineProperty(De,"isEncryptedPayload",{enumerable:!0,get:function(){return Cf.isEncryptedPayload}});Object.defineProperty(De,"isMultiRecipientPayload",{enumerable:!0,get:function(){return Cf.isMultiRecipientPayload}});var Zs=Sf();Object.defineProperty(De,"encrypt",{enumerable:!0,get:function(){return Zs.encrypt}});Object.defineProperty(De,"decrypt",{enumerable:!0,get:function(){return Zs.decrypt}});Object.defineProperty(De,"encryptBinary",{enumerable:!0,get:function(){return Zs.encryptBinary}});Object.defineProperty(De,"decryptBinary",{enumerable:!0,get:function(){return Zs.decryptBinary}});var En=Tf();Object.defineProperty(De,"generateKeyPair",{enumerable:!0,get:function(){return En.generateKeyPair}});Object.defineProperty(De,"deriveSharedSecret",{enumerable:!0,get:function(){return En.deriveSharedSecret}});Object.defineProperty(De,"isValidPublicKey",{enumerable:!0,get:function(){return En.isValidPublicKey}});Object.defineProperty(De,"clearKey",{enumerable:!0,get:function(){return En.clearKey}});Object.defineProperty(De,"keyToBase64",{enumerable:!0,get:function(){return En.keyToBase64}});Object.defineProperty(De,"base64ToKey",{enumerable:!0,get:function(){return En.base64ToKey}})});var kf=F(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.MIN_CLIENT_VERSION=xt.PROTOCOL_VERSION_MINOR=xt.PROTOCOL_VERSION_MAJOR=xt.PROTOCOL_VERSION=void 0;xt.isCompatibleVersion=_p;xt.compareVersions=yp;xt.PROTOCOL_VERSION="2.0";xt.PROTOCOL_VERSION_MAJOR=2;xt.PROTOCOL_VERSION_MINOR=0;xt.MIN_CLIENT_VERSION="2.0";function _p(r){let[e]=r.split(".").map(Number);return e===xt.PROTOCOL_VERSION_MAJOR}function yp(r,e){let[t,n]=r.split(".").map(Number),[s,i]=e.split(".").map(Number);return t!==s?t<s?-1:1:n!==i?n<i?-1:1:0}});var Pf=F(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.SERVER_CAPABILITIES=zt.DEFAULT_CLIENT_CAPABILITIES=zt.Capability=void 0;zt.hasCapability=Ep;zt.negotiateCapabilities=vp;var rs;(function(r){r.FILE_TRANSFER="file-transfer",r.RELIABLE_MESSAGING="reliable-messaging",r.COMPRESSION="compression",r.E2E_ENCRYPTION="e2e-encryption",r.PRIORITY_QUEUES="priority-queues",r.OFFLINE_QUEUE="offline-queue",r.MULTI_DEVICE="multi-device",r.TERMINAL_EVENTS="terminal-events",r.E2E_PRIVACY="e2e-privacy"})(rs||(zt.Capability=rs={}));zt.DEFAULT_CLIENT_CAPABILITIES=[rs.E2E_ENCRYPTION,rs.TERMINAL_EVENTS];zt.SERVER_CAPABILITIES=Object.values(rs);function Ep(r,e){return r.includes(e)}function vp(r,e){return r.filter(t=>e.includes(t))}});var Rf=F(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.DEFAULT_PRIORITY=ur.PRIORITY_NAMES=ur.Priority=void 0;ur.comparePriority=wp;var $r;(function(r){r[r.CRITICAL=0]="CRITICAL",r[r.HIGH=1]="HIGH",r[r.NORMAL=2]="NORMAL",r[r.LOW=3]="LOW"})($r||(ur.Priority=$r={}));ur.PRIORITY_NAMES={[$r.CRITICAL]:"CRITICAL",[$r.HIGH]:"HIGH",[$r.NORMAL]:"NORMAL",[$r.LOW]:"LOW"};ur.DEFAULT_PRIORITY=$r.NORMAL;function wp(r,e){return r-e}});var Af=F(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.DEFAULT_RELIABILITY=Gt.RELIABILITY_NAMES=Gt.Reliability=void 0;Gt.requiresAck=bp;Gt.requiresBuffer=xp;var Cr;(function(r){r[r.FIRE_FORGET=0]="FIRE_FORGET",r[r.BUFFERED=1]="BUFFERED",r[r.GUARANTEED=2]="GUARANTEED"})(Cr||(Gt.Reliability=Cr={}));Gt.RELIABILITY_NAMES={[Cr.FIRE_FORGET]:"FIRE_FORGET",[Cr.BUFFERED]:"BUFFERED",[Cr.GUARANTEED]:"GUARANTEED"};Gt.DEFAULT_RELIABILITY=Cr.FIRE_FORGET;function bp(r){return r===Cr.GUARANTEED}function xp(r){return r>=Cr.BUFFERED}});var If=F(Ao=>{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});Ao.createMessage=Sp;function Sp(r,e,t={}){return{id:crypto.randomUUID(),type:r,payload:e,priority:t.priority??2,reliability:t.reliability??0,seq:t.seq,timestamp:new Date().toISOString()}}});var Lf=F(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.TerminalEventType=void 0;zr.deriveStatusFromEvent=Tp;zr.shouldTriggerPushNotification=Cp;zr.getPushNotificationMessage=Op;var lt;(function(r){r.SESSION_START="session_start",r.SESSION_END="session_end",r.MESSAGE="message",r.TOOL_START="tool_start",r.TOOL_END="tool_end",r.WAITING_INPUT="waiting_input",r.ERROR="error"})(lt||(zr.TerminalEventType=lt={}));function Tp(r){switch(r.type){case lt.SESSION_START:case lt.TOOL_START:case lt.MESSAGE:return"working";case lt.WAITING_INPUT:return"waiting";case lt.SESSION_END:return r.status==="success"?"completed":"error";case lt.ERROR:return r.severity==="fatal"?"error":"working";case lt.TOOL_END:return r.status==="error"?"error":"working";default:return"idle"}}function Cp(r){switch(r.type){case lt.WAITING_INPUT:return!0;case lt.SESSION_END:return!0;case lt.ERROR:return r.severity!=="warning";default:return!1}}function Op(r,e){switch(r.type){case lt.WAITING_INPUT:return{title:`${e}: Input Required`,body:r.question.slice(0,100)};case lt.SESSION_END:{let t=r;return t.status==="success"?{title:`${e}: Task Completed`,body:t.summary||"Session finished successfully"}:{title:`${e}: Task Failed`,body:t.summary||"Session ended with error"}}case lt.ERROR:{let t=r;return t.severity==="warning"?null:{title:`${e}: Error`,body:t.message.slice(0,100)}}default:return null}}});var Ff=F(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.TransferDirection=je.TransferStatus=je.CHUNK_TTL_SECONDS=je.TRANSFER_TTL_SECONDS=je.MAX_RETRIES=je.ACK_TIMEOUT_MS=je.WINDOW_SIZE=je.DEFAULT_MAX_FILE_SIZE=je.CHUNK_SIZE=void 0;je.calculateTotalChunks=kp;je.getMissingChunks=Pp;je.isTransferComplete=Rp;je.CHUNK_SIZE=64*1024;je.DEFAULT_MAX_FILE_SIZE=100*1024*1024;je.WINDOW_SIZE=10;je.ACK_TIMEOUT_MS=3e4;je.MAX_RETRIES=3;je.TRANSFER_TTL_SECONDS=1440*60;je.CHUNK_TTL_SECONDS=1440*60;var Nf;(function(r){r.PENDING="pending",r.ACTIVE="active",r.PAUSED="paused",r.COMPLETED="completed",r.FAILED="failed",r.CANCELLED="cancelled",r.EXPIRED="expired"})(Nf||(je.TransferStatus=Nf={}));var Df;(function(r){r.DOWNLOAD="download",r.UPLOAD="upload"})(Df||(je.TransferDirection=Df={}));function kp(r,e=je.CHUNK_SIZE){return Math.ceil(r/e)}function Pp(r,e){let t=new Set(e),n=[];for(let s=0;s<r;s++)t.has(s)||n.push(s);return n}function Rp(r,e){return e.length===r}});var Mf=F(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.ERROR_MESSAGES=lr.ErrorCode=void 0;lr.createError=Ap;lr.isRetryableError=Ip;var Pe;(function(r){r.AUTH_FAILED="E001",r.TOKEN_EXPIRED="E002",r.TOKEN_INVALID="E003",r.NOT_FOUND="E011",r.ALREADY_EXISTS="E012",r.ACCESS_DENIED="E021",r.FORBIDDEN="E022",r.RATE_LIMITED="E031",r.TOO_MANY_CONNECTIONS="E032",r.QUOTA_EXCEEDED="E041",r.FILE_TOO_LARGE="E042",r.QUEUE_FULL="E043",r.TRANSFERS_LIMIT="E044",r.TRANSFER_FAILED="E051",r.TRANSFER_EXPIRED="E052",r.TRANSFER_CANCELLED="E053",r.CHECKSUM_MISMATCH="E054",r.CHUNK_MISSING="E055",r.INVALID_MESSAGE="E061",r.UNSUPPORTED_VERSION="E062",r.CAPABILITY_REQUIRED="E063",r.INVALID_STATE="E071",r.TIMEOUT="E072",r.CONNECTION_LOST="E073",r.INTERNAL_ERROR="E091",r.SERVICE_UNAVAILABLE="E092"})(Pe||(lr.ErrorCode=Pe={}));lr.ERROR_MESSAGES={[Pe.AUTH_FAILED]:"Authentication failed",[Pe.TOKEN_EXPIRED]:"Token expired",[Pe.TOKEN_INVALID]:"Invalid token",[Pe.NOT_FOUND]:"Resource not found",[Pe.ALREADY_EXISTS]:"Resource already exists",[Pe.ACCESS_DENIED]:"Access denied",[Pe.FORBIDDEN]:"Operation forbidden",[Pe.RATE_LIMITED]:"Rate limit exceeded",[Pe.TOO_MANY_CONNECTIONS]:"Too many connections",[Pe.QUOTA_EXCEEDED]:"Plan quota exceeded",[Pe.FILE_TOO_LARGE]:"File size exceeds limit",[Pe.QUEUE_FULL]:"Message queue is full",[Pe.TRANSFERS_LIMIT]:"Daily transfers limit reached",[Pe.TRANSFER_FAILED]:"File transfer failed",[Pe.TRANSFER_EXPIRED]:"Transfer expired",[Pe.TRANSFER_CANCELLED]:"Transfer cancelled",[Pe.CHECKSUM_MISMATCH]:"File checksum mismatch",[Pe.CHUNK_MISSING]:"Chunk missing or corrupted",[Pe.INVALID_MESSAGE]:"Invalid message format",[Pe.UNSUPPORTED_VERSION]:"Unsupported protocol version",[Pe.CAPABILITY_REQUIRED]:"Required capability not supported",[Pe.INVALID_STATE]:"Invalid state for this operation",[Pe.TIMEOUT]:"Operation timed out",[Pe.CONNECTION_LOST]:"Connection lost",[Pe.INTERNAL_ERROR]:"Internal server error",[Pe.SERVICE_UNAVAILABLE]:"Service temporarily unavailable"};function Ap(r,e={}){return{code:r,message:e.message||lr.ERROR_MESSAGES[r],details:e.details,retryable:e.retryable??!1,retryAfter:e.retryAfter}}function Ip(r){return[Pe.RATE_LIMITED,Pe.TIMEOUT,Pe.CONNECTION_LOST,Pe.SERVICE_UNAVAILABLE].includes(r)}});var qf=F(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.FileEntryType=St.DiffBase=St.FileViewType=St.FileChangeType=void 0;St.getLanguageFromPath=Lp;St.parseUnifiedDiff=Np;St.createSimpleDiff=Dp;var Or;(function(r){r.CREATE="create",r.MODIFY="modify",r.DELETE="delete"})(Or||(St.FileChangeType=Or={}));var Bf;(function(r){r.CONTENT="content",r.DIFF="diff"})(Bf||(St.FileViewType=Bf={}));var jf;(function(r){r.GIT="git",r.PREVIOUS="previous"})(jf||(St.DiffBase=jf={}));function Lp(r){let e=r.split(".").pop()?.toLowerCase(),t={js:"javascript",jsx:"javascript",ts:"typescript",tsx:"typescript",mjs:"javascript",cjs:"javascript",html:"html",htm:"html",css:"css",scss:"scss",sass:"scss",less:"less",json:"json",yaml:"yaml",yml:"yaml",xml:"xml",toml:"toml",md:"markdown",mdx:"markdown",env:"plaintext",gitignore:"plaintext",dockerignore:"plaintext",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",py:"python",pyw:"python",pyi:"python",go:"go",rs:"rust",java:"java",kt:"kotlin",kts:"kotlin",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp",hpp:"cpp",sql:"sql",graphql:"graphql",gql:"graphql",prisma:"prisma",dockerfile:"dockerfile"},n=r.split("/").pop()?.toLowerCase()||"";return{dockerfile:"dockerfile",makefile:"makefile",".gitignore":"plaintext",".env":"plaintext",".env.local":"plaintext",".env.development":"plaintext",".env.production":"plaintext"}[n]||t[e||""]||"plaintext"}function Np(r,e){let t=r.split(`
|
|
3
|
+
`),n=[],s=0,i=0,a=null,c=0,u=0;for(let g of t){if(g.startsWith("diff ")||g.startsWith("index ")||g.startsWith("---")||g.startsWith("+++"))continue;let m=g.match(/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@/);if(m){a&&n.push(a);let y=parseInt(m[1],10),w=parseInt(m[2]||"1",10),S=parseInt(m[3],10),C=parseInt(m[4]||"1",10);a={oldStart:y,oldLines:w,newStart:S,newLines:C,lines:[]},c=y,u=S;continue}a&&(g.startsWith("+")?(a.lines.push({type:"add",content:g.slice(1),oldLineNumber:null,newLineNumber:u++}),s++):g.startsWith("-")?(a.lines.push({type:"remove",content:g.slice(1),oldLineNumber:c++,newLineNumber:null}),i++):(g.startsWith(" ")||g==="")&&a.lines.push({type:"context",content:g.startsWith(" ")?g.slice(1):g,oldLineNumber:c++,newLineNumber:u++}))}a&&n.push(a);let d;return i===0&&s>0&&n.length===1&&n[0].oldLines===0?d=Or.CREATE:s===0&&i>0&&n.length===1&&n[0].newLines===0?d=Or.DELETE:d=Or.MODIFY,{path:e,changeType:d,hunks:n,additions:s,deletions:i,isBinary:!1}}function Dp(r,e,t){let n=r.split(`
|
|
4
4
|
`),s=e.split(`
|
|
5
|
-
`),i=[],a=0,c=0,u=Math.max(n.length,s.length);for(let g=0;g<u;g++){let _=n[g],y=s[g];_===y?_!==void 0&&i.push({type:"context",content:_,oldLineNumber:g+1,newLineNumber:g+1}):(_!==void 0&&(i.push({type:"remove",content:_,oldLineNumber:g+1,newLineNumber:null}),c++),y!==void 0&&(i.push({type:"add",content:y,oldLineNumber:null,newLineNumber:g+1}),a++))}let d;return r===""?d=Or.CREATE:e===""?d=Or.DELETE:d=Or.MODIFY,{path:t,changeType:d,hunks:[{oldStart:1,oldLines:n.length,newStart:1,newLines:s.length,lines:i}],additions:a,deletions:c,isBinary:!1}}var Bf;(function(r){r.FILE="file",r.DIRECTORY="directory"})(Bf||(xt.FileEntryType=Bf={}))});var Uf=D(I=>{"use strict";Object.defineProperty(I,"__esModule",{value:!0});I.createSimpleDiff=I.parseUnifiedDiff=I.getLanguageFromPath=I.FileEntryType=I.DiffBase=I.FileViewType=I.FileChangeType=I.isRetryableError=I.createError=I.ERROR_MESSAGES=I.ErrorCode=I.isTransferComplete=I.getMissingChunks=I.calculateTotalChunks=I.TransferDirection=I.TransferStatus=I.CHUNK_TTL_SECONDS=I.TRANSFER_TTL_SECONDS=I.MAX_RETRIES=I.ACK_TIMEOUT_MS=I.WINDOW_SIZE=I.DEFAULT_MAX_FILE_SIZE=I.CHUNK_SIZE=I.getPushNotificationMessage=I.shouldTriggerPushNotification=I.deriveStatusFromEvent=I.TerminalEventType=I.createMessage=I.requiresBuffer=I.requiresAck=I.DEFAULT_RELIABILITY=I.RELIABILITY_NAMES=I.Reliability=I.comparePriority=I.DEFAULT_PRIORITY=I.PRIORITY_NAMES=I.Priority=I.negotiateCapabilities=I.hasCapability=I.SERVER_CAPABILITIES=I.DEFAULT_CLIENT_CAPABILITIES=I.Capability=I.compareVersions=I.isCompatibleVersion=I.MIN_CLIENT_VERSION=I.PROTOCOL_VERSION_MINOR=I.PROTOCOL_VERSION_MAJOR=I.PROTOCOL_VERSION=void 0;var wn=Cf();Object.defineProperty(I,"PROTOCOL_VERSION",{enumerable:!0,get:function(){return wn.PROTOCOL_VERSION}});Object.defineProperty(I,"PROTOCOL_VERSION_MAJOR",{enumerable:!0,get:function(){return wn.PROTOCOL_VERSION_MAJOR}});Object.defineProperty(I,"PROTOCOL_VERSION_MINOR",{enumerable:!0,get:function(){return wn.PROTOCOL_VERSION_MINOR}});Object.defineProperty(I,"MIN_CLIENT_VERSION",{enumerable:!0,get:function(){return wn.MIN_CLIENT_VERSION}});Object.defineProperty(I,"isCompatibleVersion",{enumerable:!0,get:function(){return wn.isCompatibleVersion}});Object.defineProperty(I,"compareVersions",{enumerable:!0,get:function(){return wn.compareVersions}});var rs=Of();Object.defineProperty(I,"Capability",{enumerable:!0,get:function(){return rs.Capability}});Object.defineProperty(I,"DEFAULT_CLIENT_CAPABILITIES",{enumerable:!0,get:function(){return rs.DEFAULT_CLIENT_CAPABILITIES}});Object.defineProperty(I,"SERVER_CAPABILITIES",{enumerable:!0,get:function(){return rs.SERVER_CAPABILITIES}});Object.defineProperty(I,"hasCapability",{enumerable:!0,get:function(){return rs.hasCapability}});Object.defineProperty(I,"negotiateCapabilities",{enumerable:!0,get:function(){return rs.negotiateCapabilities}});var Zs=kf();Object.defineProperty(I,"Priority",{enumerable:!0,get:function(){return Zs.Priority}});Object.defineProperty(I,"PRIORITY_NAMES",{enumerable:!0,get:function(){return Zs.PRIORITY_NAMES}});Object.defineProperty(I,"DEFAULT_PRIORITY",{enumerable:!0,get:function(){return Zs.DEFAULT_PRIORITY}});Object.defineProperty(I,"comparePriority",{enumerable:!0,get:function(){return Zs.comparePriority}});var ns=Pf();Object.defineProperty(I,"Reliability",{enumerable:!0,get:function(){return ns.Reliability}});Object.defineProperty(I,"RELIABILITY_NAMES",{enumerable:!0,get:function(){return ns.RELIABILITY_NAMES}});Object.defineProperty(I,"DEFAULT_RELIABILITY",{enumerable:!0,get:function(){return ns.DEFAULT_RELIABILITY}});Object.defineProperty(I,"requiresAck",{enumerable:!0,get:function(){return ns.requiresAck}});Object.defineProperty(I,"requiresBuffer",{enumerable:!0,get:function(){return ns.requiresBuffer}});var Ap=Rf();Object.defineProperty(I,"createMessage",{enumerable:!0,get:function(){return Ap.createMessage}});var Qs=Af();Object.defineProperty(I,"TerminalEventType",{enumerable:!0,get:function(){return Qs.TerminalEventType}});Object.defineProperty(I,"deriveStatusFromEvent",{enumerable:!0,get:function(){return Qs.deriveStatusFromEvent}});Object.defineProperty(I,"shouldTriggerPushNotification",{enumerable:!0,get:function(){return Qs.shouldTriggerPushNotification}});Object.defineProperty(I,"getPushNotificationMessage",{enumerable:!0,get:function(){return Qs.getPushNotificationMessage}});var Ot=Nf();Object.defineProperty(I,"CHUNK_SIZE",{enumerable:!0,get:function(){return Ot.CHUNK_SIZE}});Object.defineProperty(I,"DEFAULT_MAX_FILE_SIZE",{enumerable:!0,get:function(){return Ot.DEFAULT_MAX_FILE_SIZE}});Object.defineProperty(I,"WINDOW_SIZE",{enumerable:!0,get:function(){return Ot.WINDOW_SIZE}});Object.defineProperty(I,"ACK_TIMEOUT_MS",{enumerable:!0,get:function(){return Ot.ACK_TIMEOUT_MS}});Object.defineProperty(I,"MAX_RETRIES",{enumerable:!0,get:function(){return Ot.MAX_RETRIES}});Object.defineProperty(I,"TRANSFER_TTL_SECONDS",{enumerable:!0,get:function(){return Ot.TRANSFER_TTL_SECONDS}});Object.defineProperty(I,"CHUNK_TTL_SECONDS",{enumerable:!0,get:function(){return Ot.CHUNK_TTL_SECONDS}});Object.defineProperty(I,"TransferStatus",{enumerable:!0,get:function(){return Ot.TransferStatus}});Object.defineProperty(I,"TransferDirection",{enumerable:!0,get:function(){return Ot.TransferDirection}});Object.defineProperty(I,"calculateTotalChunks",{enumerable:!0,get:function(){return Ot.calculateTotalChunks}});Object.defineProperty(I,"getMissingChunks",{enumerable:!0,get:function(){return Ot.getMissingChunks}});Object.defineProperty(I,"isTransferComplete",{enumerable:!0,get:function(){return Ot.isTransferComplete}});var ei=Df();Object.defineProperty(I,"ErrorCode",{enumerable:!0,get:function(){return ei.ErrorCode}});Object.defineProperty(I,"ERROR_MESSAGES",{enumerable:!0,get:function(){return ei.ERROR_MESSAGES}});Object.defineProperty(I,"createError",{enumerable:!0,get:function(){return ei.createError}});Object.defineProperty(I,"isRetryableError",{enumerable:!0,get:function(){return ei.isRetryableError}});var zr=jf();Object.defineProperty(I,"FileChangeType",{enumerable:!0,get:function(){return zr.FileChangeType}});Object.defineProperty(I,"FileViewType",{enumerable:!0,get:function(){return zr.FileViewType}});Object.defineProperty(I,"DiffBase",{enumerable:!0,get:function(){return zr.DiffBase}});Object.defineProperty(I,"FileEntryType",{enumerable:!0,get:function(){return zr.FileEntryType}});Object.defineProperty(I,"getLanguageFromPath",{enumerable:!0,get:function(){return zr.getLanguageFromPath}});Object.defineProperty(I,"parseUnifiedDiff",{enumerable:!0,get:function(){return zr.parseUnifiedDiff}});Object.defineProperty(I,"createSimpleDiff",{enumerable:!0,get:function(){return zr.createSimpleDiff}})});var Gr=D(Yt=>{"use strict";var Ip=Yt&&Yt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),ti=Yt&&Yt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Ip(e,r,t)};Object.defineProperty(Yt,"__esModule",{value:!0});ti(yf(),Yt);ti(Ef(),Yt);ti(Tf(),Yt);ti(Uf(),Yt)});var Wf=D(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});ri.CryptoService=void 0;var ct=Gr(),Lp=3600*1e3,qf=10,Ao=class{storage;logger;sessions=new Map;agentSessions=new Map;keyPair=null;publicKeyKey;secretKeyKey;keyVersionKey;constructor(e,t,n,s){this.storage=e,this.logger=t;let i=`termiq.${n}.${s}`;this.publicKeyKey=`${i}.crypto.publicKey`,this.secretKeyKey=`${i}.crypto.secretKey`,this.keyVersionKey=`${i}.crypto.keyVersion`,this.logger.info("CryptoService namespace",n,s)}async initialize(){let e=await this.storage.get(this.publicKeyKey),t=await this.storage.get(this.secretKeyKey);e&&t?(this.keyPair={publicKey:e,secretKey:t},this.logger.info("Loaded existing identity key pair")):await this.generateIdentityKeyPair()}async generateIdentityKeyPair(){this.logger.info("Generating new identity key pair"),this.keyPair=(0,ct.generateKeyPair)(),await this.storage.set(this.publicKeyKey,this.keyPair.publicKey),await this.storage.set(this.secretKeyKey,this.keyPair.secretKey);let e=await this.getKeyVersion();return await this.storage.set(this.keyVersionKey,String(e+1)),this.logger.info("Identity key pair generated and stored"),this.keyPair}async getPublicKey(){return this.keyPair?this.keyPair.publicKey:await this.storage.get(this.publicKeyKey)||null}async getKeyVersion(){let e=await this.storage.get(this.keyVersionKey);return e?parseInt(e,10):1}async handleKeyExchange(e,t,n){if(!this.keyPair&&(this.logger.warn("Key pair missing, attempting re-initialization"),await this.initialize(),!this.keyPair))return this.logger.error("No identity key pair available after re-initialization"),!1;this.logger.info("Starting key exchange",e,n);try{let s=this.sessions.get(e);s||(s=new Map,this.sessions.set(e,s));let i=(0,ct.deriveSharedSecret)(t,this.keyPair.secretKey),a={terminalId:e,clientPublicKey:t,sharedSecret:i,createdAt:Date.now(),sessionId:n};return s.set(n,a),this.logger.info("Key exchange completed",e,n,"total:",s.size),!0}catch(s){return this.logger.error("Key exchange failed",s),!1}}encryptOutput(e,t){let n=this.sessions.get(e);if(!n||n.size===0)return null;try{if(n.size===1){let i=n.values().next().value;return i?(0,ct.encrypt)(t,i.sharedSecret,i.sessionId):null}let s=[];for(let i of n.values()){let a=(0,ct.encrypt)(t,i.sharedSecret,i.sessionId);s.push({sid:a.sid,n:a.n,c:a.c})}return{v:2,recipients:s}}catch(s){return this.logger.error("Encryption failed",s),null}}decryptInput(e,t){let n=this.sessions.get(e);if(!n)return this.logger.error("No sessions for terminal",e),null;let s=n.get(t.sid);if(!s)return this.logger.error("No session for sessionId",t.sid),null;try{return(0,ct.decrypt)(t,s.sharedSecret)}catch(i){return this.logger.error("Decryption failed",i),null}}hasSession(e){let t=this.sessions.get(e);return t!==void 0&&t.size>0}removeSession(e,t){let n=this.sessions.get(e);if(n)if(t){let s=n.get(t);s&&((0,ct.clearKey)(s.sharedSecret),n.delete(t),this.logger.info("Session removed",e,t)),n.size===0&&this.sessions.delete(e)}else{for(let s of n.values())(0,ct.clearKey)(s.sharedSecret);this.sessions.delete(e),this.logger.debug("All sessions removed for terminal",e)}}clearAllSessions(){for(let e of this.sessions.values())for(let t of e.values())(0,ct.clearKey)(t.sharedSecret);this.sessions.clear(),this.logger.debug("All sessions cleared")}cleanupStaleSessions(e){let t=this.sessions.get(e);if(!t||t.size===0)return;let n=Date.now(),s=[];for(let[i,a]of t)n-a.createdAt>Lp&&s.push(i);for(let i of s){let a=t.get(i);a&&((0,ct.clearKey)(a.sharedSecret),t.delete(i))}if(t.size>qf){let a=Array.from(t.entries()).sort((c,u)=>c[1].createdAt-u[1].createdAt).slice(0,t.size-qf);for(let[,c]of a)(0,ct.clearKey)(c.sharedSecret),t.delete(c.sessionId)}t.size===0&&this.sessions.delete(e)}cleanupAllStaleSessions(){for(let e of this.sessions.keys())this.cleanupStaleSessions(e)}getSessionInfo(){let e=[];for(let[t,n]of this.sessions.entries())for(let s of n.values())e.push({terminalId:t,createdAt:s.createdAt,sessionId:s.sessionId});return e}async handleAgentKeyExchange(e,t){if(!this.keyPair&&(this.logger.warn("Key pair missing for agent key exchange"),await this.initialize(),!this.keyPair))return this.logger.error("No identity key pair available for agent key exchange"),!1;try{let n=this.agentSessions.get(t);n&&(this.logger.info("Rekeying existing agent session",t),(0,ct.clearKey)(n.sharedSecret));let s=(0,ct.deriveSharedSecret)(e,this.keyPair.secretKey),i={sessionId:t,clientPublicKey:e,sharedSecret:s,createdAt:Date.now()};return this.agentSessions.set(t,i),this.logger.info("Agent key exchange completed",t,"total:",this.agentSessions.size),!0}catch(n){return this.logger.error("Agent key exchange failed",n),!1}}removeAgentSession(e){let t=this.agentSessions.get(e);t&&((0,ct.clearKey)(t.sharedSecret),this.agentSessions.delete(e),this.logger.info("Agent session removed",e))}hasAgentSessions(){return this.agentSessions.size>0}encryptWorkspaceInfo(e){if(this.agentSessions.size===0)return null;let t=JSON.stringify(e),n=this.encryptForAllAgentSessions(t);return n?{encrypted:n}:null}encryptTerminalInfo(e){if(this.agentSessions.size===0)return null;let t=JSON.stringify(e),n=this.encryptForAllAgentSessions(t);return n?{encrypted:n}:null}encryptPromptInfo(e){if(this.agentSessions.size===0)return null;let t=JSON.stringify(e),n=this.encryptForAllAgentSessions(t);return n?{encrypted:n}:null}encryptForAllAgentSessions(e){if(this.agentSessions.size===0)return null;try{if(this.agentSessions.size===1){let n=this.agentSessions.values().next().value;return n?(0,ct.encrypt)(e,n.sharedSecret,n.sessionId):null}let t=[];for(let n of this.agentSessions.values()){let s=(0,ct.encrypt)(e,n.sharedSecret,n.sessionId);t.push({sid:s.sid,n:s.n,c:s.c})}return{v:2,recipients:t}}catch(t){return this.logger.error("Encryption for agent sessions failed",t),null}}clearAllAgentSessions(){for(let e of this.agentSessions.values())(0,ct.clearKey)(e.sharedSecret);this.agentSessions.clear(),this.logger.debug("All agent sessions cleared")}async deleteKeys(){await this.storage.delete(this.publicKeyKey),await this.storage.delete(this.secretKeyKey),await this.storage.delete(this.keyVersionKey),this.keyPair=null,this.clearAllSessions(),this.clearAllAgentSessions(),this.logger.info("All crypto keys deleted")}};ri.CryptoService=Ao});var Hf=D(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.AuthService=void 0;var ss=Ks(),Io=class{storage;cryptoService;machineId;config;logger;notification;browser;pollingAbortController=null;tokenKey;refreshTokenKey;agentIdKey;constructor(e,t,n,s,i,a,c,u,d){this.storage=e,this.cryptoService=t,this.machineId=n,this.config=s,this.logger=i,this.notification=a,this.browser=c;let g=`termiq.${u}.${d}`;this.tokenKey=`${g}.accessToken`,this.refreshTokenKey=`${g}.refreshToken`,this.agentIdKey=`${g}.agentId`,this.logger.info("AuthService namespace",u,d)}cancelPolling(){this.pollingAbortController&&(this.logger.info("Cancelling active polling"),this.pollingAbortController.abort(),this.pollingAbortController=null)}async startDeviceCodeFlow(){this.cancelPolling();let e=(0,ss.getApiUrl)(this.config),t=await this.machineId.getMachineId(),n=this.machineId.getMachineName(),s=await this.cryptoService.getPublicKey();s||(await this.cryptoService.generateIdentityKeyPair(),s=await this.cryptoService.getPublicKey()),this.logger.info("Starting device code flow",t,n);let i=await fetch(`${e}/auth/device/code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machineId:t,machineName:n,publicKey:s})});if(!i.ok){let a=await i.text();throw new Error(`Failed to get device code: ${a}`)}return i.json()}async pollForToken(e){this.cancelPolling();let t=(0,ss.getApiUrl)(this.config),n=5e3,s=60;this.pollingAbortController=new AbortController;let i=this.pollingAbortController.signal;this.logger.info("Starting token polling");for(let a=0;a<s;a++){if(i.aborted)return this.logger.info("Polling was cancelled"),null;if(await this.sleep(n),i.aborted)return this.logger.info("Polling was cancelled"),null;try{let c=await fetch(`${t}/auth/device/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:e}),signal:i});if(!c.ok){if(c.status===403)try{let d=await c.json();if(d.error==="AGENT_LIMIT_EXCEEDED")return this.logger.warn("Agent limit exceeded",String(d.current),"/",String(d.max)),this.notification.warn(`Agent limit reached (${d.current}/${d.max}). Upgrade your plan to add more devices.`),null}catch{}this.logger.warn("Poll request failed",String(c.status));continue}let u=await c.json();if(u.status==="success"&&u.accessToken)return this.logger.info("Token received successfully"),this.pollingAbortController=null,await this.saveTokens(u),u;if(u.status==="expired")return this.logger.warn("Device code expired"),null;if(u.status==="limit_exceeded")return this.logger.warn("Agent limit exceeded",String(u.current),"/",String(u.max)),this.notification.warn(`Agent limit reached (${u.current}/${u.max}). Remove an old agent or upgrade your plan.`),null;this.logger.debug("Token pending, continuing poll",String(a))}catch(c){if(i.aborted)return this.logger.info("Polling was cancelled"),null;let u=c instanceof Error?c.message:String(c);this.logger.warn(`Poll error: ${u}`)}}return this.logger.warn("Polling timed out"),this.pollingAbortController=null,null}async loginWithApiKey(e){let t=(0,ss.getApiUrl)(this.config),n=await this.machineId.getMachineId(),s=this.machineId.getMachineName(),i=await this.cryptoService.getPublicKey();i||(await this.cryptoService.generateIdentityKeyPair(),i=await this.cryptoService.getPublicKey()),this.logger.info("Logging in with API key");try{let a=await fetch(`${t}/auth/api-key/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e,machineId:n,machineName:s,publicKey:i})});if(!a.ok){let u=await a.text();return this.logger.error("API key login failed",u),!1}let c=await a.json();return c.accessToken?(await this.saveTokens(c),this.logger.info("API key login successful"),!0):!1}catch(a){return this.logger.error("API key login error",a),!1}}async hasValidToken(){let e=await this.storage.get(this.tokenKey);if(!e)return!1;try{let n=JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()).exp*1e3;return Date.now()<n}catch{return!1}}async getAccessToken(){return await this.storage.get(this.tokenKey)||null}async getAgentId(){return await this.storage.get(this.agentIdKey)||null}async refreshAccessToken(){let e=await this.storage.get(this.refreshTokenKey);if(!e)return this.logger.debug("No refresh token available"),null;let t=(0,ss.getApiUrl)(this.config);try{this.logger.info("Refreshing access token");let n=await fetch(`${t}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!n.ok)return this.logger.warn("Token refresh failed",String(n.status)),n.status===401&&await this.storage.delete(this.refreshTokenKey),null;let s=await n.json();return await this.storage.set(this.tokenKey,s.accessToken),await this.storage.set(this.refreshTokenKey,s.refreshToken),this.logger.info("Access token refreshed successfully"),s.accessToken}catch(n){return this.logger.warn("Token refresh error",n),null}}async logout(){this.logger.info("Logging out"),this.cancelPolling(),await this.storage.delete(this.tokenKey),await this.storage.delete(this.refreshTokenKey),await this.storage.delete(this.agentIdKey),await this.cryptoService.deleteKeys()}async saveTokens(e){e.accessToken&&await this.storage.set(this.tokenKey,e.accessToken),e.refreshToken&&await this.storage.set(this.refreshTokenKey,e.refreshToken),e.agentId&&await this.storage.set(this.agentIdKey,e.agentId)}async getLimits(){let e=await this.getAccessToken();if(!e)return this.logger.warn("Cannot fetch limits: no access token"),null;let t=(0,ss.getApiUrl)(this.config);try{let n=await fetch(`${t}/users/me/limits`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});return n.ok?await n.json():(this.logger.error("Failed to fetch limits",String(n.status)),null)}catch(n){let s=n instanceof Error?n.message:String(n);return this.logger.error(`Error fetching limits: ${s}`),null}}async openUrl(e){await this.browser.openUrl(e)}async canCreateTerminal(){let e=await this.getLimits();return e?e.terminals.unlimited?{allowed:!0,limits:e}:e.terminals.current>=e.terminals.max?{allowed:!1,reason:`Terminal limit reached (${e.terminals.current}/${e.terminals.max}). Upgrade your plan to create more terminals.`,limits:e}:{allowed:!0,limits:e}:{allowed:!0}}sleep(e){return new Promise(t=>setTimeout(t,e))}};ni.AuthService=Io});var Vf=D(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.StatusDetector=void 0;var si={working:[/✶/,/⠋|⠙|⠹|⠸|⠼|⠴|⠦|⠧|⠇|⠏/],idle:[/[❯$#>]\s*$/,/^\s*\d+\s*[❯$#>]\s*$/,/\(base\)\s*[❯$#>]\s*$/,/\)\s*[❯$#>]\s*$/],waiting:[/\[Y\/n\]/i,/\[y\/N\]/i,/\(y\/n\)/i,/\(yes\/no\)/i,/Continue\?/i,/Proceed\?/i,/Are you sure\?/i,/Confirm\?/i,/Press Enter to continue/i,/Press any key/i,/\[Enter\]/i,/Do you want to/i,/Would you like to/i,/Shall I/i,/^\s*\d+[.)]\s+.+$/m,/Select.*:/i,/Choose.*:/i,/Which.*\?/i,/Какой вариант/i,/Выберите/i],completed:[/✓\s*(Done|Complete|Success|Finished)/i,/\[done\]/i,/\[success\]/i,/completed successfully/i,/Build succeeded/i,/All tests passed/i],error:[/✕\s*(Error|Failed|Failure)/i,/\[error\]/i,/\[failed\]/i,/Error:/i,/Exception:/i,/FATAL:/i,/Build failed/i,/Tests failed/i,/command not found/i,/Permission denied/i,/No such file or directory/i]},is={IDLE_TIMEOUT_MS:5e3,DEBOUNCE_MS:500,BUFFER_SIZE:2e3,WORKING_TIMEOUT_MS:3e4},Lo=class{states=new Map;onStatusChange;constructor(e){this.onStatusChange=e}startTracking(e){if(this.states.has(e))return;let t={status:"idle",lastUpdate:Date.now(),lastOutput:Date.now(),outputBuffer:"",pendingUpdate:null,workingTimeout:null};this.states.set(e,t),this.emitStatus(e,"idle")}stopTracking(e){let t=this.states.get(e);t&&(t.pendingUpdate&&clearTimeout(t.pendingUpdate),t.workingTimeout&&clearTimeout(t.workingTimeout)),this.states.delete(e)}processOutput(e,t){let n=this.states.get(e);if(!n)return;n.lastOutput=Date.now(),n.outputBuffer+=t,n.outputBuffer.length>is.BUFFER_SIZE&&(n.outputBuffer=n.outputBuffer.slice(-is.BUFFER_SIZE));let s=this.analyzeOutput(n.outputBuffer);s&&this.scheduleStatusUpdate(e,s),this.resetWorkingTimeout(e,n)}onCommandStart(e){let t=this.states.get(e);t&&(t.outputBuffer="",this.scheduleStatusUpdate(e,"working"),this.resetWorkingTimeout(e,t))}onCommandEnd(e,t){let n=this.states.get(e);if(!n)return;n.workingTimeout&&(clearTimeout(n.workingTimeout),n.workingTimeout=null);let s;if(t!==void 0&&t!==0)s="error";else{let i=this.analyzeOutput(n.outputBuffer);i==="waiting"?s="waiting":i==="error"?s="error":i==="completed"?s="completed":s="idle"}this.scheduleStatusUpdate(e,s),(s==="completed"||s==="error")&&setTimeout(()=>{let i=this.states.get(e);i&&(i.status==="completed"||i.status==="error")&&this.scheduleStatusUpdate(e,"idle")},is.IDLE_TIMEOUT_MS)}analyzeOutput(e){let t=e.split(`
|
|
5
|
+
`),i=[],a=0,c=0,u=Math.max(n.length,s.length);for(let g=0;g<u;g++){let m=n[g],y=s[g];m===y?m!==void 0&&i.push({type:"context",content:m,oldLineNumber:g+1,newLineNumber:g+1}):(m!==void 0&&(i.push({type:"remove",content:m,oldLineNumber:g+1,newLineNumber:null}),c++),y!==void 0&&(i.push({type:"add",content:y,oldLineNumber:null,newLineNumber:g+1}),a++))}let d;return r===""?d=Or.CREATE:e===""?d=Or.DELETE:d=Or.MODIFY,{path:t,changeType:d,hunks:[{oldStart:1,oldLines:n.length,newStart:1,newLines:s.length,lines:i}],additions:a,deletions:c,isBinary:!1}}var Uf;(function(r){r.FILE="file",r.DIRECTORY="directory"})(Uf||(St.FileEntryType=Uf={}))});var Wf=F(I=>{"use strict";Object.defineProperty(I,"__esModule",{value:!0});I.createSimpleDiff=I.parseUnifiedDiff=I.getLanguageFromPath=I.FileEntryType=I.DiffBase=I.FileViewType=I.FileChangeType=I.isRetryableError=I.createError=I.ERROR_MESSAGES=I.ErrorCode=I.isTransferComplete=I.getMissingChunks=I.calculateTotalChunks=I.TransferDirection=I.TransferStatus=I.CHUNK_TTL_SECONDS=I.TRANSFER_TTL_SECONDS=I.MAX_RETRIES=I.ACK_TIMEOUT_MS=I.WINDOW_SIZE=I.DEFAULT_MAX_FILE_SIZE=I.CHUNK_SIZE=I.getPushNotificationMessage=I.shouldTriggerPushNotification=I.deriveStatusFromEvent=I.TerminalEventType=I.createMessage=I.requiresBuffer=I.requiresAck=I.DEFAULT_RELIABILITY=I.RELIABILITY_NAMES=I.Reliability=I.comparePriority=I.DEFAULT_PRIORITY=I.PRIORITY_NAMES=I.Priority=I.negotiateCapabilities=I.hasCapability=I.SERVER_CAPABILITIES=I.DEFAULT_CLIENT_CAPABILITIES=I.Capability=I.compareVersions=I.isCompatibleVersion=I.MIN_CLIENT_VERSION=I.PROTOCOL_VERSION_MINOR=I.PROTOCOL_VERSION_MAJOR=I.PROTOCOL_VERSION=void 0;var vn=kf();Object.defineProperty(I,"PROTOCOL_VERSION",{enumerable:!0,get:function(){return vn.PROTOCOL_VERSION}});Object.defineProperty(I,"PROTOCOL_VERSION_MAJOR",{enumerable:!0,get:function(){return vn.PROTOCOL_VERSION_MAJOR}});Object.defineProperty(I,"PROTOCOL_VERSION_MINOR",{enumerable:!0,get:function(){return vn.PROTOCOL_VERSION_MINOR}});Object.defineProperty(I,"MIN_CLIENT_VERSION",{enumerable:!0,get:function(){return vn.MIN_CLIENT_VERSION}});Object.defineProperty(I,"isCompatibleVersion",{enumerable:!0,get:function(){return vn.isCompatibleVersion}});Object.defineProperty(I,"compareVersions",{enumerable:!0,get:function(){return vn.compareVersions}});var ns=Pf();Object.defineProperty(I,"Capability",{enumerable:!0,get:function(){return ns.Capability}});Object.defineProperty(I,"DEFAULT_CLIENT_CAPABILITIES",{enumerable:!0,get:function(){return ns.DEFAULT_CLIENT_CAPABILITIES}});Object.defineProperty(I,"SERVER_CAPABILITIES",{enumerable:!0,get:function(){return ns.SERVER_CAPABILITIES}});Object.defineProperty(I,"hasCapability",{enumerable:!0,get:function(){return ns.hasCapability}});Object.defineProperty(I,"negotiateCapabilities",{enumerable:!0,get:function(){return ns.negotiateCapabilities}});var Qs=Rf();Object.defineProperty(I,"Priority",{enumerable:!0,get:function(){return Qs.Priority}});Object.defineProperty(I,"PRIORITY_NAMES",{enumerable:!0,get:function(){return Qs.PRIORITY_NAMES}});Object.defineProperty(I,"DEFAULT_PRIORITY",{enumerable:!0,get:function(){return Qs.DEFAULT_PRIORITY}});Object.defineProperty(I,"comparePriority",{enumerable:!0,get:function(){return Qs.comparePriority}});var ss=Af();Object.defineProperty(I,"Reliability",{enumerable:!0,get:function(){return ss.Reliability}});Object.defineProperty(I,"RELIABILITY_NAMES",{enumerable:!0,get:function(){return ss.RELIABILITY_NAMES}});Object.defineProperty(I,"DEFAULT_RELIABILITY",{enumerable:!0,get:function(){return ss.DEFAULT_RELIABILITY}});Object.defineProperty(I,"requiresAck",{enumerable:!0,get:function(){return ss.requiresAck}});Object.defineProperty(I,"requiresBuffer",{enumerable:!0,get:function(){return ss.requiresBuffer}});var Fp=If();Object.defineProperty(I,"createMessage",{enumerable:!0,get:function(){return Fp.createMessage}});var ei=Lf();Object.defineProperty(I,"TerminalEventType",{enumerable:!0,get:function(){return ei.TerminalEventType}});Object.defineProperty(I,"deriveStatusFromEvent",{enumerable:!0,get:function(){return ei.deriveStatusFromEvent}});Object.defineProperty(I,"shouldTriggerPushNotification",{enumerable:!0,get:function(){return ei.shouldTriggerPushNotification}});Object.defineProperty(I,"getPushNotificationMessage",{enumerable:!0,get:function(){return ei.getPushNotificationMessage}});var kt=Ff();Object.defineProperty(I,"CHUNK_SIZE",{enumerable:!0,get:function(){return kt.CHUNK_SIZE}});Object.defineProperty(I,"DEFAULT_MAX_FILE_SIZE",{enumerable:!0,get:function(){return kt.DEFAULT_MAX_FILE_SIZE}});Object.defineProperty(I,"WINDOW_SIZE",{enumerable:!0,get:function(){return kt.WINDOW_SIZE}});Object.defineProperty(I,"ACK_TIMEOUT_MS",{enumerable:!0,get:function(){return kt.ACK_TIMEOUT_MS}});Object.defineProperty(I,"MAX_RETRIES",{enumerable:!0,get:function(){return kt.MAX_RETRIES}});Object.defineProperty(I,"TRANSFER_TTL_SECONDS",{enumerable:!0,get:function(){return kt.TRANSFER_TTL_SECONDS}});Object.defineProperty(I,"CHUNK_TTL_SECONDS",{enumerable:!0,get:function(){return kt.CHUNK_TTL_SECONDS}});Object.defineProperty(I,"TransferStatus",{enumerable:!0,get:function(){return kt.TransferStatus}});Object.defineProperty(I,"TransferDirection",{enumerable:!0,get:function(){return kt.TransferDirection}});Object.defineProperty(I,"calculateTotalChunks",{enumerable:!0,get:function(){return kt.calculateTotalChunks}});Object.defineProperty(I,"getMissingChunks",{enumerable:!0,get:function(){return kt.getMissingChunks}});Object.defineProperty(I,"isTransferComplete",{enumerable:!0,get:function(){return kt.isTransferComplete}});var ti=Mf();Object.defineProperty(I,"ErrorCode",{enumerable:!0,get:function(){return ti.ErrorCode}});Object.defineProperty(I,"ERROR_MESSAGES",{enumerable:!0,get:function(){return ti.ERROR_MESSAGES}});Object.defineProperty(I,"createError",{enumerable:!0,get:function(){return ti.createError}});Object.defineProperty(I,"isRetryableError",{enumerable:!0,get:function(){return ti.isRetryableError}});var Gr=qf();Object.defineProperty(I,"FileChangeType",{enumerable:!0,get:function(){return Gr.FileChangeType}});Object.defineProperty(I,"FileViewType",{enumerable:!0,get:function(){return Gr.FileViewType}});Object.defineProperty(I,"DiffBase",{enumerable:!0,get:function(){return Gr.DiffBase}});Object.defineProperty(I,"FileEntryType",{enumerable:!0,get:function(){return Gr.FileEntryType}});Object.defineProperty(I,"getLanguageFromPath",{enumerable:!0,get:function(){return Gr.getLanguageFromPath}});Object.defineProperty(I,"parseUnifiedDiff",{enumerable:!0,get:function(){return Gr.parseUnifiedDiff}});Object.defineProperty(I,"createSimpleDiff",{enumerable:!0,get:function(){return Gr.createSimpleDiff}})});var kr=F(Yt=>{"use strict";var Mp=Yt&&Yt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),ri=Yt&&Yt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Mp(e,r,t)};Object.defineProperty(Yt,"__esModule",{value:!0});ri(vf(),Yt);ri(wf(),Yt);ri(Of(),Yt);ri(Wf(),Yt)});var Vf=F(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.CryptoService=void 0;var ct=kr(),Bp=3600*1e3,Hf=10,Io=class{storage;logger;sessions=new Map;agentSessions=new Map;keyPair=null;publicKeyKey;secretKeyKey;keyVersionKey;constructor(e,t,n,s){this.storage=e,this.logger=t;let i=`termiq.${n}.${s}`;this.publicKeyKey=`${i}.crypto.publicKey`,this.secretKeyKey=`${i}.crypto.secretKey`,this.keyVersionKey=`${i}.crypto.keyVersion`,this.logger.info("CryptoService namespace",n,s)}async initialize(){let e=await this.storage.get(this.publicKeyKey),t=await this.storage.get(this.secretKeyKey);e&&t?(this.keyPair={publicKey:e,secretKey:t},this.logger.info("Loaded existing identity key pair")):await this.generateIdentityKeyPair()}async generateIdentityKeyPair(){this.logger.info("Generating new identity key pair"),this.keyPair=(0,ct.generateKeyPair)(),await this.storage.set(this.publicKeyKey,this.keyPair.publicKey),await this.storage.set(this.secretKeyKey,this.keyPair.secretKey);let e=await this.getKeyVersion();return await this.storage.set(this.keyVersionKey,String(e+1)),this.logger.info("Identity key pair generated and stored"),this.keyPair}async getPublicKey(){return this.keyPair?this.keyPair.publicKey:await this.storage.get(this.publicKeyKey)||null}async getKeyVersion(){let e=await this.storage.get(this.keyVersionKey);return e?parseInt(e,10):1}async handleKeyExchange(e,t,n){if(!this.keyPair&&(this.logger.warn("Key pair missing, attempting re-initialization"),await this.initialize(),!this.keyPair))return this.logger.error("No identity key pair available after re-initialization"),!1;this.logger.info("Starting key exchange",e,n);try{let s=this.sessions.get(e);s||(s=new Map,this.sessions.set(e,s));let i=(0,ct.deriveSharedSecret)(t,this.keyPair.secretKey),a={terminalId:e,clientPublicKey:t,sharedSecret:i,createdAt:Date.now(),sessionId:n};return s.set(n,a),this.logger.info("Key exchange completed",e,n,"total:",s.size),!0}catch(s){return this.logger.error("Key exchange failed",s),!1}}encryptOutput(e,t){let n=this.sessions.get(e);if(!n||n.size===0)return null;try{if(n.size===1){let i=n.values().next().value;return i?(0,ct.encrypt)(t,i.sharedSecret,i.sessionId):null}let s=[];for(let i of n.values()){let a=(0,ct.encrypt)(t,i.sharedSecret,i.sessionId);s.push({sid:a.sid,n:a.n,c:a.c})}return{v:2,recipients:s}}catch(s){return this.logger.error("Encryption failed",s),null}}decryptInput(e,t){let n=this.sessions.get(e);if(!n)return this.logger.error("No sessions for terminal",e),null;let s=n.get(t.sid);if(!s)return this.logger.error("No session for sessionId",t.sid),null;try{return(0,ct.decrypt)(t,s.sharedSecret)}catch(i){return this.logger.error("Decryption failed",i),null}}hasSession(e){let t=this.sessions.get(e);return t!==void 0&&t.size>0}removeSession(e,t){let n=this.sessions.get(e);if(n)if(t){let s=n.get(t);s&&((0,ct.clearKey)(s.sharedSecret),n.delete(t),this.logger.info("Session removed",e,t)),n.size===0&&this.sessions.delete(e)}else{for(let s of n.values())(0,ct.clearKey)(s.sharedSecret);this.sessions.delete(e),this.logger.debug("All sessions removed for terminal",e)}}clearAllSessions(){for(let e of this.sessions.values())for(let t of e.values())(0,ct.clearKey)(t.sharedSecret);this.sessions.clear(),this.logger.debug("All sessions cleared")}cleanupStaleSessions(e){let t=this.sessions.get(e);if(!t||t.size===0)return;let n=Date.now(),s=[];for(let[i,a]of t)n-a.createdAt>Bp&&s.push(i);for(let i of s){let a=t.get(i);a&&((0,ct.clearKey)(a.sharedSecret),t.delete(i))}if(t.size>Hf){let a=Array.from(t.entries()).sort((c,u)=>c[1].createdAt-u[1].createdAt).slice(0,t.size-Hf);for(let[,c]of a)(0,ct.clearKey)(c.sharedSecret),t.delete(c.sessionId)}t.size===0&&this.sessions.delete(e)}cleanupAllStaleSessions(){for(let e of this.sessions.keys())this.cleanupStaleSessions(e)}getSessionInfo(){let e=[];for(let[t,n]of this.sessions.entries())for(let s of n.values())e.push({terminalId:t,createdAt:s.createdAt,sessionId:s.sessionId});return e}async handleAgentKeyExchange(e,t){if(!this.keyPair&&(this.logger.warn("Key pair missing for agent key exchange"),await this.initialize(),!this.keyPair))return this.logger.error("No identity key pair available for agent key exchange"),!1;try{let n=this.agentSessions.get(t);n&&(this.logger.info("Rekeying existing agent session",t),(0,ct.clearKey)(n.sharedSecret));let s=(0,ct.deriveSharedSecret)(e,this.keyPair.secretKey),i={sessionId:t,clientPublicKey:e,sharedSecret:s,createdAt:Date.now()};return this.agentSessions.set(t,i),this.logger.info("Agent key exchange completed",t,"total:",this.agentSessions.size),!0}catch(n){return this.logger.error("Agent key exchange failed",n),!1}}removeAgentSession(e){let t=this.agentSessions.get(e);t&&((0,ct.clearKey)(t.sharedSecret),this.agentSessions.delete(e),this.logger.info("Agent session removed",e))}hasAgentSessions(){return this.agentSessions.size>0}encryptWorkspaceInfo(e){if(this.agentSessions.size===0)return null;let t=JSON.stringify(e),n=this.encryptForAllAgentSessions(t);return n?{encrypted:n}:null}encryptTerminalInfo(e){if(this.agentSessions.size===0)return null;let t=JSON.stringify(e),n=this.encryptForAllAgentSessions(t);return n?{encrypted:n}:null}encryptPromptInfo(e){if(this.agentSessions.size===0)return null;let t=JSON.stringify(e),n=this.encryptForAllAgentSessions(t);return n?{encrypted:n}:null}encryptForAllAgentSessions(e){if(this.agentSessions.size===0)return null;try{if(this.agentSessions.size===1){let n=this.agentSessions.values().next().value;return n?(0,ct.encrypt)(e,n.sharedSecret,n.sessionId):null}let t=[];for(let n of this.agentSessions.values()){let s=(0,ct.encrypt)(e,n.sharedSecret,n.sessionId);t.push({sid:s.sid,n:s.n,c:s.c})}return{v:2,recipients:t}}catch(t){return this.logger.error("Encryption for agent sessions failed",t),null}}clearAllAgentSessions(){for(let e of this.agentSessions.values())(0,ct.clearKey)(e.sharedSecret);this.agentSessions.clear(),this.logger.debug("All agent sessions cleared")}async deleteKeys(){await this.storage.delete(this.publicKeyKey),await this.storage.delete(this.secretKeyKey),await this.storage.delete(this.keyVersionKey),this.keyPair=null,this.clearAllSessions(),this.clearAllAgentSessions(),this.logger.info("All crypto keys deleted")}};ni.CryptoService=Io});var Kf=F(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.AuthService=void 0;var is=$s(),Lo=class{storage;cryptoService;machineId;config;logger;notification;browser;pollingAbortController=null;tokenKey;refreshTokenKey;agentIdKey;constructor(e,t,n,s,i,a,c,u,d){this.storage=e,this.cryptoService=t,this.machineId=n,this.config=s,this.logger=i,this.notification=a,this.browser=c;let g=`termiq.${u}.${d}`;this.tokenKey=`${g}.accessToken`,this.refreshTokenKey=`${g}.refreshToken`,this.agentIdKey=`${g}.agentId`,this.logger.info("AuthService namespace",u,d)}cancelPolling(){this.pollingAbortController&&(this.logger.info("Cancelling active polling"),this.pollingAbortController.abort(),this.pollingAbortController=null)}async startDeviceCodeFlow(){this.cancelPolling();let e=(0,is.getApiUrl)(this.config),t=await this.machineId.getMachineId(),n=this.machineId.getMachineName(),s=await this.cryptoService.getPublicKey();s||(await this.cryptoService.generateIdentityKeyPair(),s=await this.cryptoService.getPublicKey()),this.logger.info("Starting device code flow",t,n);let i=await fetch(`${e}/auth/device/code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machineId:t,machineName:n,publicKey:s})});if(!i.ok){let a=await i.text();throw new Error(`Failed to get device code: ${a}`)}return i.json()}async pollForToken(e){this.cancelPolling();let t=(0,is.getApiUrl)(this.config),n=5e3,s=60;this.pollingAbortController=new AbortController;let i=this.pollingAbortController.signal;this.logger.info("Starting token polling");for(let a=0;a<s;a++){if(i.aborted)return this.logger.info("Polling was cancelled"),null;if(await this.sleep(n),i.aborted)return this.logger.info("Polling was cancelled"),null;try{let c=await fetch(`${t}/auth/device/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:e}),signal:i});if(!c.ok){if(c.status===403)try{let d=await c.json();if(d.error==="AGENT_LIMIT_EXCEEDED")return this.logger.warn("Agent limit exceeded",String(d.current),"/",String(d.max)),this.notification.warn(`Agent limit reached (${d.current}/${d.max}). Upgrade your plan to add more devices.`),null}catch{}this.logger.warn("Poll request failed",String(c.status));continue}let u=await c.json();if(u.status==="success"&&u.accessToken)return this.logger.info("Token received successfully"),this.pollingAbortController=null,await this.saveTokens(u),u;if(u.status==="expired")return this.logger.warn("Device code expired"),null;if(u.status==="limit_exceeded")return this.logger.warn("Agent limit exceeded",String(u.current),"/",String(u.max)),this.notification.warn(`Agent limit reached (${u.current}/${u.max}). Remove an old agent or upgrade your plan.`),null;this.logger.debug("Token pending, continuing poll",String(a))}catch(c){if(i.aborted)return this.logger.info("Polling was cancelled"),null;let u=c instanceof Error?c.message:String(c);this.logger.warn(`Poll error: ${u}`)}}return this.logger.warn("Polling timed out"),this.pollingAbortController=null,null}async loginWithApiKey(e){let t=(0,is.getApiUrl)(this.config),n=await this.machineId.getMachineId(),s=this.machineId.getMachineName(),i=await this.cryptoService.getPublicKey();i||(await this.cryptoService.generateIdentityKeyPair(),i=await this.cryptoService.getPublicKey()),this.logger.info("Logging in with API key");try{let a=await fetch(`${t}/auth/api-key/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e,machineId:n,machineName:s,publicKey:i})});if(!a.ok){let u=await a.text();return this.logger.error("API key login failed",u),!1}let c=await a.json();return c.accessToken?(await this.saveTokens(c),this.logger.info("API key login successful"),!0):!1}catch(a){return this.logger.error("API key login error",a),!1}}async hasValidToken(){let e=await this.storage.get(this.tokenKey);if(!e)return!1;try{let n=JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()).exp*1e3;return Date.now()<n}catch{return!1}}async getAccessToken(){return await this.storage.get(this.tokenKey)||null}async getAgentId(){return await this.storage.get(this.agentIdKey)||null}async refreshAccessToken(){let e=await this.storage.get(this.refreshTokenKey);if(!e)return this.logger.debug("No refresh token available"),null;let t=(0,is.getApiUrl)(this.config);try{this.logger.info("Refreshing access token");let n=await fetch(`${t}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!n.ok)return this.logger.warn("Token refresh failed",String(n.status)),n.status===401&&await this.storage.delete(this.refreshTokenKey),null;let s=await n.json();return await this.storage.set(this.tokenKey,s.accessToken),await this.storage.set(this.refreshTokenKey,s.refreshToken),this.logger.info("Access token refreshed successfully"),s.accessToken}catch(n){return this.logger.warn("Token refresh error",n),null}}async logout(){this.logger.info("Logging out"),this.cancelPolling(),await this.storage.delete(this.tokenKey),await this.storage.delete(this.refreshTokenKey),await this.storage.delete(this.agentIdKey),await this.cryptoService.deleteKeys()}async saveTokens(e){e.accessToken&&await this.storage.set(this.tokenKey,e.accessToken),e.refreshToken&&await this.storage.set(this.refreshTokenKey,e.refreshToken),e.agentId&&await this.storage.set(this.agentIdKey,e.agentId)}async getLimits(){let e=await this.getAccessToken();if(!e)return this.logger.warn("Cannot fetch limits: no access token"),null;let t=(0,is.getApiUrl)(this.config);try{let n=await fetch(`${t}/users/me/limits`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});return n.ok?await n.json():(this.logger.error("Failed to fetch limits",String(n.status)),null)}catch(n){let s=n instanceof Error?n.message:String(n);return this.logger.error(`Error fetching limits: ${s}`),null}}async openUrl(e){await this.browser.openUrl(e)}async canCreateTerminal(){let e=await this.getLimits();return e?e.terminals.unlimited?{allowed:!0,limits:e}:e.terminals.current>=e.terminals.max?{allowed:!1,reason:`Terminal limit reached (${e.terminals.current}/${e.terminals.max}). Upgrade your plan to create more terminals.`,limits:e}:{allowed:!0,limits:e}:{allowed:!0}}sleep(e){return new Promise(t=>setTimeout(t,e))}};si.AuthService=Lo});var $f=F(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});oi.StatusDetector=void 0;var ii={working:[/✶/,/⠋|⠙|⠹|⠸|⠼|⠴|⠦|⠧|⠇|⠏/],idle:[/[❯$#>]\s*$/,/^\s*\d+\s*[❯$#>]\s*$/,/\(base\)\s*[❯$#>]\s*$/,/\)\s*[❯$#>]\s*$/],waiting:[/\[Y\/n\]/i,/\[y\/N\]/i,/\(y\/n\)/i,/\(yes\/no\)/i,/Continue\?/i,/Proceed\?/i,/Are you sure\?/i,/Confirm\?/i,/Press Enter to continue/i,/Press any key/i,/\[Enter\]/i,/Do you want to/i,/Would you like to/i,/Shall I/i,/^\s*\d+[.)]\s+.+$/m,/Select.*:/i,/Choose.*:/i,/Which.*\?/i,/Какой вариант/i,/Выберите/i],completed:[/✓\s*(Done|Complete|Success|Finished)/i,/\[done\]/i,/\[success\]/i,/completed successfully/i,/Build succeeded/i,/All tests passed/i],error:[/✕\s*(Error|Failed|Failure)/i,/\[error\]/i,/\[failed\]/i,/Error:/i,/Exception:/i,/FATAL:/i,/Build failed/i,/Tests failed/i,/command not found/i,/Permission denied/i,/No such file or directory/i]},os={IDLE_TIMEOUT_MS:5e3,DEBOUNCE_MS:500,BUFFER_SIZE:2e3,WORKING_TIMEOUT_MS:3e4},No=class{states=new Map;onStatusChange;constructor(e){this.onStatusChange=e}startTracking(e){if(this.states.has(e))return;let t={status:"idle",lastUpdate:Date.now(),lastOutput:Date.now(),outputBuffer:"",pendingUpdate:null,workingTimeout:null};this.states.set(e,t),this.emitStatus(e,"idle")}stopTracking(e){let t=this.states.get(e);t&&(t.pendingUpdate&&clearTimeout(t.pendingUpdate),t.workingTimeout&&clearTimeout(t.workingTimeout)),this.states.delete(e)}processOutput(e,t){let n=this.states.get(e);if(!n)return;n.lastOutput=Date.now(),n.outputBuffer+=t,n.outputBuffer.length>os.BUFFER_SIZE&&(n.outputBuffer=n.outputBuffer.slice(-os.BUFFER_SIZE));let s=this.analyzeOutput(n.outputBuffer);s&&this.scheduleStatusUpdate(e,s),this.resetWorkingTimeout(e,n)}onCommandStart(e){let t=this.states.get(e);t&&(t.outputBuffer="",this.scheduleStatusUpdate(e,"working"),this.resetWorkingTimeout(e,t))}onCommandEnd(e,t){let n=this.states.get(e);if(!n)return;n.workingTimeout&&(clearTimeout(n.workingTimeout),n.workingTimeout=null);let s;if(t!==void 0&&t!==0)s="error";else{let i=this.analyzeOutput(n.outputBuffer);i==="waiting"?s="waiting":i==="error"?s="error":i==="completed"?s="completed":s="idle"}this.scheduleStatusUpdate(e,s),(s==="completed"||s==="error")&&setTimeout(()=>{let i=this.states.get(e);i&&(i.status==="completed"||i.status==="error")&&this.scheduleStatusUpdate(e,"idle")},os.IDLE_TIMEOUT_MS)}analyzeOutput(e){let t=e.split(`
|
|
6
6
|
`).slice(-10),n=t.join(`
|
|
7
|
-
`),s=t[t.length-1]||"";for(let i of
|
|
7
|
+
`),s=t[t.length-1]||"";for(let i of ii.waiting)if(i.test(n))return"waiting";for(let i of ii.working)if(i.test(s))return"working";for(let i of ii.completed)if(i.test(n))return"completed";for(let i of ii.idle)if(i.test(s))return"idle";return null}detectPrompt(e){let s=this.normalizeBuffer(this.stripAnsi(e)).split(`
|
|
8
8
|
`).slice(-20),i=s.join(`
|
|
9
|
-
`),a=s[s.length-1]||"",c=this.extractNumberedChoices(e);if(c.length>=2)return{type:"numbered-choice",question:this.extractQuestion(i)||"Select an option:",choices:c};let u=[/\[Y\/n\]/i,/\[y\/N\]/i,/\(y\/n\)/i,/\(yes\/no\)/i];for(let
|
|
9
|
+
`),a=s[s.length-1]||"",c=this.extractNumberedChoices(e);if(c.length>=2)return{type:"numbered-choice",question:this.extractQuestion(i)||"Select an option:",choices:c};let u=[/\[Y\/n\]/i,/\[y\/N\]/i,/\(y\/n\)/i,/\(yes\/no\)/i];for(let m of u)if(m.test(i))return{type:"yes-no",question:this.extractQuestion(i)||"Confirm?"};let d=[/Press Enter to continue/i,/Press Enter/i,/Hit Enter/i,/\[Enter\]/i,/press return/i];for(let m of d)if(m.test(i))return{type:"enter",question:this.extractQuestion(i)||"Press Enter to continue"};let g=[/Press any key/i,/press a key/i];for(let m of g)if(m.test(i))return{type:"any-key",question:this.extractQuestion(i)||"Press any key"};return(a.endsWith("?")||a.endsWith(":"))&&!a.startsWith("/")&&!a.includes("error")&&a.length<100?{type:"free-input",question:a}:null}extractNumberedChoices(e){let t=[],s=this.normalizeBuffer(this.stripAnsi(e)).split(`
|
|
10
10
|
`),i=/^\s*[❯>*]?\s*(?:(\d+)[.)]\s*|\[(\d+)\]\s*)(.+)$/;for(let a of s){let c=a.match(i);if(c){let u=c[1]||c[2],d=c[3].trim();if(u&&d&&d.length<100&&!d.includes("error")){let g=t.length+1;parseInt(u)===g&&t.push({key:u,label:d})}}}return t}extractQuestion(e){let t=e.split(`
|
|
11
11
|
`).filter(n=>n.trim());for(let n=t.length-1;n>=Math.max(0,t.length-5);n--){let s=t[n].trim();if(!s||/^\s*\d+[.)]\s/.test(s)||/^\s*\[/.test(s))continue;let i=this.stripAnsi(s);if(i.endsWith("?")||i.endsWith(":"))return i.replace(/\s*\[Y\/n\]\s*$/i,"").replace(/\s*\(y\/n\)\s*$/i,"").replace(/\s*\(yes\/no\)\s*$/i,"").trim()}return null}stripAnsi(e){return e.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g,"").replace(/\x1b\][^\x07]*\x07/g,"").replace(/\x1b[()][AB012]/g,"").replace(/\x1b[=>]/g,"").replace(/\x1b[78DMEHc]/g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g,"")}normalizeBuffer(e){return e.replace(/\r\n/g,`
|
|
12
12
|
`).replace(/\r/g,`
|
|
13
13
|
`).replace(/\n{3,}/g,`
|
|
14
14
|
|
|
15
|
-
`)}scheduleStatusUpdate(e,t){let n=this.states.get(e);n&&n.status!==t&&(n.pendingUpdate&&clearTimeout(n.pendingUpdate),n.pendingUpdate=setTimeout(()=>{this.emitStatus(e,t),n.pendingUpdate=null},
|
|
16
|
-
`);return T.substr(0,T.length-2)},this.getRequestHeader=function(T){return typeof T=="string"&&d[T]?d[T]:""},this.send=function(T){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");if(y)throw new Error("INVALID_STATE_ERR: send has already been called");var M=!1,Q=!1,B=Kf.parse(a.url),ie;switch(B.protocol){case"https:":M=!0;case"http:":ie=B.hostname;break;case"file:":Q=!0;break;case void 0:case"":ie="localhost";break;default:throw new Error("Protocol not supported.")}if(Q){if(a.method!=="GET")throw new Error("XMLHttpRequest: Only GET method is supported");if(a.async)vn.readFile(unescape(B.pathname),function(A,oe){A?e.handleError(A,A.errno||-1):(e.status=200,e.responseText=oe.toString("utf8"),e.response=oe,X(e.DONE))});else try{this.response=vn.readFileSync(unescape(B.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,X(e.DONE)}catch(A){this.handleError(A,A.errno||-1)}return}var he=B.port||(M?443:80),de=B.pathname+(B.search?B.search:"");if(d.Host=ie,M&&he===443||he===80||(d.Host+=":"+B.port),a.user){typeof a.password>"u"&&(a.password="");var Re=new Buffer(a.user+":"+a.password);d.Authorization="Basic "+Re.toString("base64")}if(a.method==="GET"||a.method==="HEAD")T=null;else if(T){d["Content-Length"]=Buffer.isBuffer(T)?T.length:Buffer.byteLength(T);var We=Object.keys(d);We.some(function(A){return A.toLowerCase()==="content-type"})||(d["Content-Type"]="text/plain;charset=UTF-8")}else a.method==="POST"&&(d["Content-Length"]=0);var Ye=r.agent||!1,ve={host:ie,port:he,path:de,method:a.method,headers:d,agent:Ye};if(M&&(ve.pfx=r.pfx,ve.key=r.key,ve.passphrase=r.passphrase,ve.cert=r.cert,ve.ca=r.ca,ve.ciphers=r.ciphers,ve.rejectUnauthorized=r.rejectUnauthorized!==!1),v=!1,a.async){var Xe=M?n.request:t.request;y=!0,e.dispatchEvent("readystatechange");var Fe=function(A){if(i=A,i.statusCode===302||i.statusCode===303||i.statusCode===307){a.url=i.headers.location;var oe=Kf.parse(a.url);ie=oe.hostname;var Ie={hostname:oe.hostname,port:oe.port,path:oe.path,method:i.statusCode===303?"GET":a.method,headers:d};M&&(Ie.pfx=r.pfx,Ie.key=r.key,Ie.passphrase=r.passphrase,Ie.cert=r.cert,Ie.ca=r.ca,Ie.ciphers=r.ciphers,Ie.rejectUnauthorized=r.rejectUnauthorized!==!1),s=Xe(Ie,Fe).on("error",J),s.end();return}X(e.HEADERS_RECEIVED),e.status=i.statusCode,i.on("data",function(ut){if(ut){var yt=Buffer.from(ut);e.response=Buffer.concat([e.response,yt])}y&&X(e.LOADING)}),i.on("end",function(){y&&(y=!1,X(e.DONE),e.responseText=e.response.toString("utf8"))}),i.on("error",function(ut){e.handleError(ut)})},J=function(A){if(s.reusedSocket&&A.code==="ECONNRESET")return Xe(ve,Fe).on("error",J);e.handleError(A)};s=Xe(ve,Fe).on("error",J),r.autoUnref&&s.on("socket",A=>{A.unref()}),T&&s.write(T),s.end(),e.dispatchEvent("loadstart")}else{var Ee=".node-xmlhttprequest-content-"+process.pid,pe=".node-xmlhttprequest-sync-"+process.pid;vn.writeFileSync(pe,"","utf8");for(var nt="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(M?"s":"")+".request;var options = "+JSON.stringify(ve)+";var responseText = '';var responseData = Buffer.alloc(0);var req = doRequest(options, function(response) {response.on('data', function(chunk) { var data = Buffer.from(chunk); responseText += data.toString('utf8'); responseData = Buffer.concat([responseData, data]);});response.on('end', function() {fs.writeFileSync('"+Ee+"', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');fs.unlinkSync('"+pe+"');});response.on('error', function(error) {fs.writeFileSync('"+Ee+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+pe+"');});}).on('error', function(error) {fs.writeFileSync('"+Ee+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+pe+"');});"+(T?"req.write('"+JSON.stringify(T).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",Qe=Np(process.argv[0],["-e",nt]),Vt;vn.existsSync(pe););if(e.responseText=vn.readFileSync(Ee,"utf8"),Qe.stdin.end(),vn.unlinkSync(Ee),e.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var L=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,""));e.handleError(L,503)}else{e.status=e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/,"$1");var j=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"));i={statusCode:e.status,headers:j.data.headers},e.responseText=j.data.text,e.response=Buffer.from(j.data.data,"base64"),X(e.DONE,!0)}}},this.handleError=function(T,M){this.status=M||0,this.statusText=T,this.responseText=T.stack,v=!0,X(this.DONE)},this.abort=function(){s&&(s.abort(),s=null),d=Object.assign({},u),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),v=S=!0,this.readyState!==this.UNSENT&&(this.readyState!==this.OPENED||y)&&this.readyState!==this.DONE&&(y=!1,X(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(T,M){T in O||(O[T]=[]),O[T].push(M)},this.removeEventListener=function(T,M){T in O&&(O[T]=O[T].filter(function(Q){return Q!==M}))},this.dispatchEvent=function(T){if(typeof e["on"+T]=="function"&&(this.readyState===this.DONE&&a.async?setTimeout(function(){e["on"+T]()},0):e["on"+T]()),T in O)for(let M=0,Q=O[T].length;M<Q;M++)this.readyState===this.DONE?setTimeout(function(){O[T][M].call(e)},0):O[T][M].call(e)};var X=function(T){if(!(e.readyState===T||e.readyState===e.UNSENT&&S)&&(e.readyState=T,(a.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let M;S?M="abort":v?M="error":M="load",e.dispatchEvent(M),e.dispatchEvent("loadend")}}}});var oi=D(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.ERROR_PACKET=kr.PACKET_TYPES_REVERSE=kr.PACKET_TYPES=void 0;var Xt=Object.create(null);kr.PACKET_TYPES=Xt;Xt.open="0";Xt.close="1";Xt.ping="2";Xt.pong="3";Xt.message="4";Xt.upgrade="5";Xt.noop="6";var Gf=Object.create(null);kr.PACKET_TYPES_REVERSE=Gf;Object.keys(Xt).forEach(r=>{Gf[Xt[r]]=r});var Dp={type:"error",data:"parser error"};kr.ERROR_PACKET=Dp});var Xf=D(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.encodePacket=void 0;bn.encodePacketToBinary=Bp;var Fp=oi(),Mp=({type:r,data:e},t,n)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?n(t?e:"b"+Yf(e,!0).toString("base64")):n(Fp.PACKET_TYPES[r]+(e||""));bn.encodePacket=Mp;var Yf=(r,e)=>Buffer.isBuffer(r)||r instanceof Uint8Array&&!e?r:r instanceof ArrayBuffer?Buffer.from(r):Buffer.from(r.buffer,r.byteOffset,r.byteLength),Do;function Bp(r,e){if(r.data instanceof ArrayBuffer||ArrayBuffer.isView(r.data))return e(Yf(r.data,!1));(0,bn.encodePacket)(r,!0,t=>{Do||(Do=new TextEncoder),e(Do.encode(t))})}});var Zf=D(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.decodePacket=void 0;var ai=oi(),jp=(r,e)=>{if(typeof r!="string")return{type:"message",data:Jf(r,e)};let t=r.charAt(0);if(t==="b"){let n=Buffer.from(r.substring(1),"base64");return{type:"message",data:Jf(n,e)}}return ai.PACKET_TYPES_REVERSE[t]?r.length>1?{type:ai.PACKET_TYPES_REVERSE[t],data:r.substring(1)}:{type:ai.PACKET_TYPES_REVERSE[t]}:ai.ERROR_PACKET};ci.decodePacket=jp;var Jf=(r,e)=>e==="arraybuffer"?r instanceof ArrayBuffer?r:Buffer.isBuffer(r)?r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength):r.buffer:Buffer.isBuffer(r)?r:Buffer.from(r)});var xn=D(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.decodePayload=gt.decodePacket=gt.encodePayload=gt.encodePacket=gt.protocol=void 0;gt.createPacketEncoderStream=Wp;gt.createPacketDecoderStream=Hp;var Mo=Xf();Object.defineProperty(gt,"encodePacket",{enumerable:!0,get:function(){return Mo.encodePacket}});var Bo=Zf();Object.defineProperty(gt,"decodePacket",{enumerable:!0,get:function(){return Bo.decodePacket}});var Qf=oi(),eu="",Up=(r,e)=>{let t=r.length,n=new Array(t),s=0;r.forEach((i,a)=>{(0,Mo.encodePacket)(i,!1,c=>{n[a]=c,++s===t&&e(n.join(eu))})})};gt.encodePayload=Up;var qp=(r,e)=>{let t=r.split(eu),n=[];for(let s=0;s<t.length;s++){let i=(0,Bo.decodePacket)(t[s],e);if(n.push(i),i.type==="error")break}return n};gt.decodePayload=qp;function Wp(){return new TransformStream({transform(r,e){(0,Mo.encodePacketToBinary)(r,t=>{let n=t.length,s;if(n<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,n);else if(n<65536){s=new Uint8Array(3);let i=new DataView(s.buffer);i.setUint8(0,126),i.setUint16(1,n)}else{s=new Uint8Array(9);let i=new DataView(s.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(n))}r.data&&typeof r.data!="string"&&(s[0]|=128),e.enqueue(s),e.enqueue(t)})}})}var Fo;function fi(r){return r.reduce((e,t)=>e+t.length,0)}function ui(r,e){if(r[0].length===e)return r.shift();let t=new Uint8Array(e),n=0;for(let s=0;s<e;s++)t[s]=r[0][n++],n===r[0].length&&(r.shift(),n=0);return r.length&&n<r[0].length&&(r[0]=r[0].slice(n)),t}function Hp(r,e){Fo||(Fo=new TextDecoder);let t=[],n=0,s=-1,i=!1;return new TransformStream({transform(a,c){for(t.push(a);;){if(n===0){if(fi(t)<1)break;let u=ui(t,1);i=(u[0]&128)===128,s=u[0]&127,s<126?n=3:s===126?n=1:n=2}else if(n===1){if(fi(t)<2)break;let u=ui(t,2);s=new DataView(u.buffer,u.byteOffset,u.length).getUint16(0),n=3}else if(n===2){if(fi(t)<8)break;let u=ui(t,8),d=new DataView(u.buffer,u.byteOffset,u.length),g=d.getUint32(0);if(g>Math.pow(2,21)-1){c.enqueue(Qf.ERROR_PACKET);break}s=g*Math.pow(2,32)+d.getUint32(4),n=3}else{if(fi(t)<s)break;let u=ui(t,s);c.enqueue((0,Bo.decodePacket)(i?u:Fo.decode(u),e)),n=0}if(s===0||s>r){c.enqueue(Qf.ERROR_PACKET);break}}}})}gt.protocol=4});var Yr=D(tu=>{tu.Emitter=ht;function ht(r){if(r)return Vp(r)}function Vp(r){for(var e in ht.prototype)r[e]=ht.prototype[e];return r}ht.prototype.on=ht.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this};ht.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this};ht.prototype.off=ht.prototype.removeListener=ht.prototype.removeAllListeners=ht.prototype.removeEventListener=function(r,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+r];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+r],this;for(var n,s=0;s<t.length;s++)if(n=t[s],n===e||n.fn===e){t.splice(s,1);break}return t.length===0&&delete this._callbacks["$"+r],this};ht.prototype.emit=function(r){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+r],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t){t=t.slice(0);for(var n=0,s=t.length;n<s;++n)t[n].apply(this,e)}return this};ht.prototype.emitReserved=ht.prototype.emit;ht.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};ht.prototype.hasListeners=function(r){return!!this.listeners(r).length}});var Xr=D(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.CookieJar=kt.defaultBinaryType=kt.globalThisShim=kt.nextTick=void 0;kt.createCookieJar=Kp;kt.parse=ru;kt.nextTick=process.nextTick;kt.globalThisShim=global;kt.defaultBinaryType="nodebuffer";function Kp(){return new li}function ru(r){let e=r.split("; "),t=e[0].indexOf("=");if(t===-1)return;let n=e[0].substring(0,t).trim();if(!n.length)return;let s=e[0].substring(t+1).trim();s.charCodeAt(0)===34&&(s=s.slice(1,-1));let i={name:n,value:s};for(let a=1;a<e.length;a++){let c=e[a].split("=");if(c.length!==2)continue;let u=c[0].trim(),d=c[1].trim();switch(u){case"Expires":i.expires=new Date(d);break;case"Max-Age":let g=new Date;g.setUTCSeconds(g.getUTCSeconds()+parseInt(d,10)),i.expires=g;break;default:}}return i}var li=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let n=ru(t);n&&this._cookies.set(n.name,n)})}get cookies(){let e=Date.now();return this._cookies.forEach((t,n)=>{var s;((s=t.expires)===null||s===void 0?void 0:s.getTime())<e&&this._cookies.delete(n)}),this._cookies.entries()}addCookies(e){let t=[];for(let[n,s]of this.cookies)t.push(`${n}=${s.value}`);t.length&&(e.setDisableHeaderCheck(!0),e.setRequestHeader("cookie",t.join("; ")))}appendCookies(e){for(let[t,n]of this.cookies)e.append("cookie",`${t}=${n.value}`)}};kt.CookieJar=li});var Jr=D(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.pick=$p;Sn.installTimerFunctions=Yp;Sn.byteLength=Jp;Sn.randomString=Qp;var Pr=Xr();function $p(r,...e){return e.reduce((t,n)=>(r.hasOwnProperty(n)&&(t[n]=r[n]),t),{})}var zp=Pr.globalThisShim.setTimeout,Gp=Pr.globalThisShim.clearTimeout;function Yp(r,e){e.useNativeTimers?(r.setTimeoutFn=zp.bind(Pr.globalThisShim),r.clearTimeoutFn=Gp.bind(Pr.globalThisShim)):(r.setTimeoutFn=Pr.globalThisShim.setTimeout.bind(Pr.globalThisShim),r.clearTimeoutFn=Pr.globalThisShim.clearTimeout.bind(Pr.globalThisShim))}var Xp=1.33;function Jp(r){return typeof r=="string"?Zp(r):Math.ceil((r.byteLength||r.size)*Xp)}function Zp(r){let e=0,t=0;for(let n=0,s=r.length;n<s;n++)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(n++,t+=4);return t}function Qp(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}});var jo=D(hi=>{"use strict";Object.defineProperty(hi,"__esModule",{value:!0});hi.encode=eg;hi.decode=tg;function eg(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function tg(r){let e={},t=r.split("&");for(let n=0,s=t.length;n<s;n++){let i=t[n].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}});var su=D((_w,nu)=>{var Tn=1e3,Cn=Tn*60,On=Cn*60,Zr=On*24,rg=Zr*7,ng=Zr*365.25;nu.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return sg(r);if(t==="number"&&isFinite(r))return e.long?og(r):ig(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function sg(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*ng;case"weeks":case"week":case"w":return t*rg;case"days":case"day":case"d":return t*Zr;case"hours":case"hour":case"hrs":case"hr":case"h":return t*On;case"minutes":case"minute":case"mins":case"min":case"m":return t*Cn;case"seconds":case"second":case"secs":case"sec":case"s":return t*Tn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function ig(r){var e=Math.abs(r);return e>=Zr?Math.round(r/Zr)+"d":e>=On?Math.round(r/On)+"h":e>=Cn?Math.round(r/Cn)+"m":e>=Tn?Math.round(r/Tn)+"s":r+"ms"}function og(r){var e=Math.abs(r);return e>=Zr?di(r,e,Zr,"day"):e>=On?di(r,e,On,"hour"):e>=Cn?di(r,e,Cn,"minute"):e>=Tn?di(r,e,Tn,"second"):r+" ms"}function di(r,e,t,n){var s=e>=t*1.5;return Math.round(r/t)+" "+n+(s?"s":"")}});var Uo=D((mw,iu)=>{function ag(r){t.debug=t,t.default=t,t.coerce=u,t.disable=a,t.enable=s,t.enabled=c,t.humanize=su(),t.destroy=d,Object.keys(r).forEach(g=>{t[g]=r[g]}),t.names=[],t.skips=[],t.formatters={};function e(g){let _=0;for(let y=0;y<g.length;y++)_=(_<<5)-_+g.charCodeAt(y),_|=0;return t.colors[Math.abs(_)%t.colors.length]}t.selectColor=e;function t(g){let _,y=null,v,S;function O(...H){if(!O.enabled)return;let z=O,X=Number(new Date),T=X-(_||X);z.diff=T,z.prev=_,z.curr=X,_=X,H[0]=t.coerce(H[0]),typeof H[0]!="string"&&H.unshift("%O");let M=0;H[0]=H[0].replace(/%([a-zA-Z%])/g,(B,ie)=>{if(B==="%%")return"%";M++;let he=t.formatters[ie];if(typeof he=="function"){let de=H[M];B=he.call(z,de),H.splice(M,1),M--}return B}),t.formatArgs.call(z,H),(z.log||t.log).apply(z,H)}return O.namespace=g,O.useColors=t.useColors(),O.color=t.selectColor(g),O.extend=n,O.destroy=t.destroy,Object.defineProperty(O,"enabled",{enumerable:!0,configurable:!1,get:()=>y!==null?y:(v!==t.namespaces&&(v=t.namespaces,S=t.enabled(g)),S),set:H=>{y=H}}),typeof t.init=="function"&&t.init(O),O}function n(g,_){let y=t(this.namespace+(typeof _>"u"?":":_)+g);return y.log=this.log,y}function s(g){t.save(g),t.namespaces=g,t.names=[],t.skips=[];let _=(typeof g=="string"?g:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let y of _)y[0]==="-"?t.skips.push(y.slice(1)):t.names.push(y)}function i(g,_){let y=0,v=0,S=-1,O=0;for(;y<g.length;)if(v<_.length&&(_[v]===g[y]||_[v]==="*"))_[v]==="*"?(S=v,O=y,v++):(y++,v++);else if(S!==-1)v=S+1,O++,y=O;else return!1;for(;v<_.length&&_[v]==="*";)v++;return v===_.length}function a(){let g=[...t.names,...t.skips.map(_=>"-"+_)].join(",");return t.enable(""),g}function c(g){for(let _ of t.skips)if(i(g,_))return!1;for(let _ of t.names)if(i(g,_))return!0;return!1}function u(g){return g instanceof Error?g.stack||g.message:g}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}iu.exports=ag});var ou=D((_t,pi)=>{_t.formatArgs=fg;_t.save=ug;_t.load=lg;_t.useColors=cg;_t.storage=hg();_t.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();_t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function cg(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function fg(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+pi.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(n=t))}),r.splice(n,0,e)}_t.log=console.debug||console.log||(()=>{});function ug(r){try{r?_t.storage.setItem("debug",r):_t.storage.removeItem("debug")}catch{}}function lg(){let r;try{r=_t.storage.getItem("debug")||_t.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function hg(){try{return localStorage}catch{}}pi.exports=Uo()(_t);var{formatters:dg}=pi.exports;dg.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var cu=D((yw,au)=>{"use strict";au.exports=(r,e=process.argv)=>{let t=r.startsWith("-")?"":r.length===1?"-":"--",n=e.indexOf(t+r),s=e.indexOf("--");return n!==-1&&(s===-1||n<s)}});var lu=D((Ew,uu)=>{"use strict";var pg=require("os"),fu=require("tty"),Pt=cu(),{env:et}=process,Rr;Pt("no-color")||Pt("no-colors")||Pt("color=false")||Pt("color=never")?Rr=0:(Pt("color")||Pt("colors")||Pt("color=true")||Pt("color=always"))&&(Rr=1);"FORCE_COLOR"in et&&(et.FORCE_COLOR==="true"?Rr=1:et.FORCE_COLOR==="false"?Rr=0:Rr=et.FORCE_COLOR.length===0?1:Math.min(parseInt(et.FORCE_COLOR,10),3));function qo(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function Wo(r,e){if(Rr===0)return 0;if(Pt("color=16m")||Pt("color=full")||Pt("color=truecolor"))return 3;if(Pt("color=256"))return 2;if(r&&!e&&Rr===void 0)return 0;let t=Rr||0;if(et.TERM==="dumb")return t;if(process.platform==="win32"){let n=pg.release().split(".");return Number(n[0])>=10&&Number(n[2])>=10586?Number(n[2])>=14931?3:2:1}if("CI"in et)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(n=>n in et)||et.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in et)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(et.TEAMCITY_VERSION)?1:0;if(et.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in et){let n=parseInt((et.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(et.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(et.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(et.TERM)||"COLORTERM"in et?1:t}function gg(r){let e=Wo(r,r&&r.isTTY);return qo(e)}uu.exports={supportsColor:gg,stdout:qo(Wo(!0,fu.isatty(1))),stderr:qo(Wo(!0,fu.isatty(2)))}});var du=D((tt,_i)=>{var _g=require("tty"),gi=require("util");tt.init=xg;tt.log=wg;tt.formatArgs=yg;tt.save=vg;tt.load=bg;tt.useColors=mg;tt.destroy=gi.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");tt.colors=[6,2,3,4,5,1];try{let r=lu();r&&(r.stderr||r).level>=2&&(tt.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}tt.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,i)=>i.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),r[t]=n,r},{});function mg(){return"colors"in tt.inspectOpts?!!tt.inspectOpts.colors:_g.isatty(process.stderr.fd)}function yg(r){let{namespace:e,useColors:t}=this;if(t){let n=this.color,s="\x1B[3"+(n<8?n:"8;5;"+n),i=` ${s};1m${e} \x1B[0m`;r[0]=i+r[0].split(`
|
|
15
|
+
`)}scheduleStatusUpdate(e,t){let n=this.states.get(e);n&&n.status!==t&&(n.pendingUpdate&&clearTimeout(n.pendingUpdate),n.pendingUpdate=setTimeout(()=>{this.emitStatus(e,t),n.pendingUpdate=null},os.DEBOUNCE_MS))}emitStatus(e,t){let n=this.states.get(e);if(!n||n.status===t)return;n.status=t,n.lastUpdate=Date.now();let s;t==="waiting"&&(s=this.detectPrompt(n.outputBuffer)||void 0),this.onStatusChange(e,t,s)}resetWorkingTimeout(e,t){t.workingTimeout&&clearTimeout(t.workingTimeout),t.status==="working"&&(t.workingTimeout=setTimeout(()=>{let n=this.states.get(e);n&&n.status==="working"&&(this.analyzeOutput(n.outputBuffer)==="waiting"?this.emitStatus(e,"waiting"):this.onStatusChange(e,"working",void 0))},os.WORKING_TIMEOUT_MS))}forceStatus(e,t){this.emitStatus(e,t)}getStatus(e){return this.states.get(e)?.status??null}dispose(){for(let e of this.states.keys())this.stopTracking(e)}};oi.StatusDetector=No});var Yf=F((dv,Gf)=>{var wn=require("fs"),zf=require("url"),jp=require("child_process").spawn;Gf.exports=Do;Do.XMLHttpRequest=Do;function Do(r){"use strict";r=r||{};var e=this,t=require("http"),n=require("https"),s,i,a={},c=!1,u={"User-Agent":"node-XMLHttpRequest",Accept:"*/*"},d=Object.assign({},u),g=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","content-transfer-encoding","cookie","cookie2","date","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"],m=["TRACE","TRACK","CONNECT"],y=!1,w=!1,S=!1,C={};this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.readyState=this.UNSENT,this.onreadystatechange=null,this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),this.status=null,this.statusText=null;var V=function(P){return c||P&&g.indexOf(P.toLowerCase())===-1},de=function(P){return P&&m.indexOf(P)===-1};this.open=function(P,L,Q,j,Z){if(this.abort(),w=!1,S=!1,!de(P))throw new Error("SecurityError: Request method not allowed");a={method:P,url:L.toString(),async:typeof Q!="boolean"?!0:Q,user:j||null,password:Z||null},B(this.OPENED)},this.setDisableHeaderCheck=function(P){c=P},this.setRequestHeader=function(P,L){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");if(!V(P))return console.warn('Refused to set unsafe header "'+P+'"'),!1;if(y)throw new Error("INVALID_STATE_ERR: send flag is true");return d[P]=L,!0},this.getResponseHeader=function(P){return typeof P=="string"&&this.readyState>this.OPENED&&i.headers[P.toLowerCase()]&&!w?i.headers[P.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||w)return"";var P="";for(var L in i.headers)L!=="set-cookie"&&L!=="set-cookie2"&&(P+=L+": "+i.headers[L]+`\r
|
|
16
|
+
`);return P.substr(0,P.length-2)},this.getRequestHeader=function(P){return typeof P=="string"&&d[P]?d[P]:""},this.send=function(P){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");if(y)throw new Error("INVALID_STATE_ERR: send has already been called");var L=!1,Q=!1,j=zf.parse(a.url),Z;switch(j.protocol){case"https:":L=!0;case"http:":Z=j.hostname;break;case"file:":Q=!0;break;case void 0:case"":Z="localhost";break;default:throw new Error("Protocol not supported.")}if(Q){if(a.method!=="GET")throw new Error("XMLHttpRequest: Only GET method is supported");if(a.async)wn.readFile(unescape(j.pathname),function(A,oe){A?e.handleError(A,A.errno||-1):(e.status=200,e.responseText=oe.toString("utf8"),e.response=oe,B(e.DONE))});else try{this.response=wn.readFileSync(unescape(j.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,B(e.DONE)}catch(A){this.handleError(A,A.errno||-1)}return}var pe=j.port||(L?443:80),Ee=j.pathname+(j.search?j.search:"");if(d.Host=Z,L&&pe===443||pe===80||(d.Host+=":"+j.port),a.user){typeof a.password>"u"&&(a.password="");var ve=new Buffer(a.user+":"+a.password);d.Authorization="Basic "+ve.toString("base64")}if(a.method==="GET"||a.method==="HEAD")P=null;else if(P){d["Content-Length"]=Buffer.isBuffer(P)?P.length:Buffer.byteLength(P);var We=Object.keys(d);We.some(function(A){return A.toLowerCase()==="content-type"})||(d["Content-Type"]="text/plain;charset=UTF-8")}else a.method==="POST"&&(d["Content-Length"]=0);var Ke=r.agent||!1,Te={host:Z,port:pe,path:Ee,method:a.method,headers:d,agent:Ke};if(L&&(Te.pfx=r.pfx,Te.key=r.key,Te.passphrase=r.passphrase,Te.cert=r.cert,Te.ca=r.ca,Te.ciphers=r.ciphers,Te.rejectUnauthorized=r.rejectUnauthorized!==!1),w=!1,a.async){var $e=L?n.request:t.request;y=!0,e.dispatchEvent("readystatechange");var He=function(A){if(i=A,i.statusCode===302||i.statusCode===303||i.statusCode===307){a.url=i.headers.location;var oe=zf.parse(a.url);Z=oe.hostname;var Ie={hostname:oe.hostname,port:oe.port,path:oe.path,method:i.statusCode===303?"GET":a.method,headers:d};L&&(Ie.pfx=r.pfx,Ie.key=r.key,Ie.passphrase=r.passphrase,Ie.cert=r.cert,Ie.ca=r.ca,Ie.ciphers=r.ciphers,Ie.rejectUnauthorized=r.rejectUnauthorized!==!1),s=$e(Ie,He).on("error",Ze),s.end();return}B(e.HEADERS_RECEIVED),e.status=i.statusCode,i.on("data",function(ut){if(ut){var Et=Buffer.from(ut);e.response=Buffer.concat([e.response,Et])}y&&B(e.LOADING)}),i.on("end",function(){y&&(y=!1,B(e.DONE),e.responseText=e.response.toString("utf8"))}),i.on("error",function(ut){e.handleError(ut)})},Ze=function(A){if(s.reusedSocket&&A.code==="ECONNRESET")return $e(Te,He).on("error",Ze);e.handleError(A)};s=$e(Te,He).on("error",Ze),r.autoUnref&&s.on("socket",A=>{A.unref()}),P&&s.write(P),s.end(),e.dispatchEvent("loadstart")}else{var G=".node-xmlhttprequest-content-"+process.pid,te=".node-xmlhttprequest-sync-"+process.pid;wn.writeFileSync(te,"","utf8");for(var Ae="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(L?"s":"")+".request;var options = "+JSON.stringify(Te)+";var responseText = '';var responseData = Buffer.alloc(0);var req = doRequest(options, function(response) {response.on('data', function(chunk) { var data = Buffer.from(chunk); responseText += data.toString('utf8'); responseData = Buffer.concat([responseData, data]);});response.on('end', function() {fs.writeFileSync('"+G+"', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');fs.unlinkSync('"+te+"');});response.on('error', function(error) {fs.writeFileSync('"+G+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+te+"');});}).on('error', function(error) {fs.writeFileSync('"+G+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+te+"');});"+(P?"req.write('"+JSON.stringify(P).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",Be=jp(process.argv[0],["-e",Ae]),yt;wn.existsSync(te););if(e.responseText=wn.readFileSync(G,"utf8"),Be.stdin.end(),wn.unlinkSync(G),e.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var N=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,""));e.handleError(N,503)}else{e.status=e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/,"$1");var U=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"));i={statusCode:e.status,headers:U.data.headers},e.responseText=U.data.text,e.response=Buffer.from(U.data.data,"base64"),B(e.DONE,!0)}}},this.handleError=function(P,L){this.status=L||0,this.statusText=P,this.responseText=P.stack,w=!0,B(this.DONE)},this.abort=function(){s&&(s.abort(),s=null),d=Object.assign({},u),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),w=S=!0,this.readyState!==this.UNSENT&&(this.readyState!==this.OPENED||y)&&this.readyState!==this.DONE&&(y=!1,B(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(P,L){P in C||(C[P]=[]),C[P].push(L)},this.removeEventListener=function(P,L){P in C&&(C[P]=C[P].filter(function(Q){return Q!==L}))},this.dispatchEvent=function(P){if(typeof e["on"+P]=="function"&&(this.readyState===this.DONE&&a.async?setTimeout(function(){e["on"+P]()},0):e["on"+P]()),P in C)for(let L=0,Q=C[P].length;L<Q;L++)this.readyState===this.DONE?setTimeout(function(){C[P][L].call(e)},0):C[P][L].call(e)};var B=function(P){if(!(e.readyState===P||e.readyState===e.UNSENT&&S)&&(e.readyState=P,(a.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let L;S?L="abort":w?L="error":L="load",e.dispatchEvent(L),e.dispatchEvent("loadend")}}}});var ai=F(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.ERROR_PACKET=Pr.PACKET_TYPES_REVERSE=Pr.PACKET_TYPES=void 0;var Xt=Object.create(null);Pr.PACKET_TYPES=Xt;Xt.open="0";Xt.close="1";Xt.ping="2";Xt.pong="3";Xt.message="4";Xt.upgrade="5";Xt.noop="6";var Xf=Object.create(null);Pr.PACKET_TYPES_REVERSE=Xf;Object.keys(Xt).forEach(r=>{Xf[Xt[r]]=r});var Up={type:"error",data:"parser error"};Pr.ERROR_PACKET=Up});var Zf=F(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.encodePacket=void 0;bn.encodePacketToBinary=Hp;var qp=ai(),Wp=({type:r,data:e},t,n)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?n(t?e:"b"+Jf(e,!0).toString("base64")):n(qp.PACKET_TYPES[r]+(e||""));bn.encodePacket=Wp;var Jf=(r,e)=>Buffer.isBuffer(r)||r instanceof Uint8Array&&!e?r:r instanceof ArrayBuffer?Buffer.from(r):Buffer.from(r.buffer,r.byteOffset,r.byteLength),Fo;function Hp(r,e){if(r.data instanceof ArrayBuffer||ArrayBuffer.isView(r.data))return e(Jf(r.data,!1));(0,bn.encodePacket)(r,!0,t=>{Fo||(Fo=new TextEncoder),e(Fo.encode(t))})}});var eu=F(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.decodePacket=void 0;var ci=ai(),Vp=(r,e)=>{if(typeof r!="string")return{type:"message",data:Qf(r,e)};let t=r.charAt(0);if(t==="b"){let n=Buffer.from(r.substring(1),"base64");return{type:"message",data:Qf(n,e)}}return ci.PACKET_TYPES_REVERSE[t]?r.length>1?{type:ci.PACKET_TYPES_REVERSE[t],data:r.substring(1)}:{type:ci.PACKET_TYPES_REVERSE[t]}:ci.ERROR_PACKET};fi.decodePacket=Vp;var Qf=(r,e)=>e==="arraybuffer"?r instanceof ArrayBuffer?r:Buffer.isBuffer(r)?r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength):r.buffer:Buffer.isBuffer(r)?r:Buffer.from(r)});var xn=F(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.decodePayload=gt.decodePacket=gt.encodePayload=gt.encodePacket=gt.protocol=void 0;gt.createPacketEncoderStream=zp;gt.createPacketDecoderStream=Gp;var Bo=Zf();Object.defineProperty(gt,"encodePacket",{enumerable:!0,get:function(){return Bo.encodePacket}});var jo=eu();Object.defineProperty(gt,"decodePacket",{enumerable:!0,get:function(){return jo.decodePacket}});var tu=ai(),ru="",Kp=(r,e)=>{let t=r.length,n=new Array(t),s=0;r.forEach((i,a)=>{(0,Bo.encodePacket)(i,!1,c=>{n[a]=c,++s===t&&e(n.join(ru))})})};gt.encodePayload=Kp;var $p=(r,e)=>{let t=r.split(ru),n=[];for(let s=0;s<t.length;s++){let i=(0,jo.decodePacket)(t[s],e);if(n.push(i),i.type==="error")break}return n};gt.decodePayload=$p;function zp(){return new TransformStream({transform(r,e){(0,Bo.encodePacketToBinary)(r,t=>{let n=t.length,s;if(n<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,n);else if(n<65536){s=new Uint8Array(3);let i=new DataView(s.buffer);i.setUint8(0,126),i.setUint16(1,n)}else{s=new Uint8Array(9);let i=new DataView(s.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(n))}r.data&&typeof r.data!="string"&&(s[0]|=128),e.enqueue(s),e.enqueue(t)})}})}var Mo;function ui(r){return r.reduce((e,t)=>e+t.length,0)}function li(r,e){if(r[0].length===e)return r.shift();let t=new Uint8Array(e),n=0;for(let s=0;s<e;s++)t[s]=r[0][n++],n===r[0].length&&(r.shift(),n=0);return r.length&&n<r[0].length&&(r[0]=r[0].slice(n)),t}function Gp(r,e){Mo||(Mo=new TextDecoder);let t=[],n=0,s=-1,i=!1;return new TransformStream({transform(a,c){for(t.push(a);;){if(n===0){if(ui(t)<1)break;let u=li(t,1);i=(u[0]&128)===128,s=u[0]&127,s<126?n=3:s===126?n=1:n=2}else if(n===1){if(ui(t)<2)break;let u=li(t,2);s=new DataView(u.buffer,u.byteOffset,u.length).getUint16(0),n=3}else if(n===2){if(ui(t)<8)break;let u=li(t,8),d=new DataView(u.buffer,u.byteOffset,u.length),g=d.getUint32(0);if(g>Math.pow(2,21)-1){c.enqueue(tu.ERROR_PACKET);break}s=g*Math.pow(2,32)+d.getUint32(4),n=3}else{if(ui(t)<s)break;let u=li(t,s);c.enqueue((0,jo.decodePacket)(i?u:Mo.decode(u),e)),n=0}if(s===0||s>r){c.enqueue(tu.ERROR_PACKET);break}}}})}gt.protocol=4});var Yr=F(nu=>{nu.Emitter=ht;function ht(r){if(r)return Yp(r)}function Yp(r){for(var e in ht.prototype)r[e]=ht.prototype[e];return r}ht.prototype.on=ht.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this};ht.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this};ht.prototype.off=ht.prototype.removeListener=ht.prototype.removeAllListeners=ht.prototype.removeEventListener=function(r,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+r];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+r],this;for(var n,s=0;s<t.length;s++)if(n=t[s],n===e||n.fn===e){t.splice(s,1);break}return t.length===0&&delete this._callbacks["$"+r],this};ht.prototype.emit=function(r){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+r],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t){t=t.slice(0);for(var n=0,s=t.length;n<s;++n)t[n].apply(this,e)}return this};ht.prototype.emitReserved=ht.prototype.emit;ht.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};ht.prototype.hasListeners=function(r){return!!this.listeners(r).length}});var Xr=F(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.CookieJar=Pt.defaultBinaryType=Pt.globalThisShim=Pt.nextTick=void 0;Pt.createCookieJar=Xp;Pt.parse=su;Pt.nextTick=process.nextTick;Pt.globalThisShim=global;Pt.defaultBinaryType="nodebuffer";function Xp(){return new hi}function su(r){let e=r.split("; "),t=e[0].indexOf("=");if(t===-1)return;let n=e[0].substring(0,t).trim();if(!n.length)return;let s=e[0].substring(t+1).trim();s.charCodeAt(0)===34&&(s=s.slice(1,-1));let i={name:n,value:s};for(let a=1;a<e.length;a++){let c=e[a].split("=");if(c.length!==2)continue;let u=c[0].trim(),d=c[1].trim();switch(u){case"Expires":i.expires=new Date(d);break;case"Max-Age":let g=new Date;g.setUTCSeconds(g.getUTCSeconds()+parseInt(d,10)),i.expires=g;break;default:}}return i}var hi=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let n=su(t);n&&this._cookies.set(n.name,n)})}get cookies(){let e=Date.now();return this._cookies.forEach((t,n)=>{var s;((s=t.expires)===null||s===void 0?void 0:s.getTime())<e&&this._cookies.delete(n)}),this._cookies.entries()}addCookies(e){let t=[];for(let[n,s]of this.cookies)t.push(`${n}=${s.value}`);t.length&&(e.setDisableHeaderCheck(!0),e.setRequestHeader("cookie",t.join("; ")))}appendCookies(e){for(let[t,n]of this.cookies)e.append("cookie",`${t}=${n.value}`)}};Pt.CookieJar=hi});var Jr=F(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.pick=Jp;Sn.installTimerFunctions=eg;Sn.byteLength=rg;Sn.randomString=sg;var Rr=Xr();function Jp(r,...e){return e.reduce((t,n)=>(r.hasOwnProperty(n)&&(t[n]=r[n]),t),{})}var Zp=Rr.globalThisShim.setTimeout,Qp=Rr.globalThisShim.clearTimeout;function eg(r,e){e.useNativeTimers?(r.setTimeoutFn=Zp.bind(Rr.globalThisShim),r.clearTimeoutFn=Qp.bind(Rr.globalThisShim)):(r.setTimeoutFn=Rr.globalThisShim.setTimeout.bind(Rr.globalThisShim),r.clearTimeoutFn=Rr.globalThisShim.clearTimeout.bind(Rr.globalThisShim))}var tg=1.33;function rg(r){return typeof r=="string"?ng(r):Math.ceil((r.byteLength||r.size)*tg)}function ng(r){let e=0,t=0;for(let n=0,s=r.length;n<s;n++)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(n++,t+=4);return t}function sg(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}});var Uo=F(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});di.encode=ig;di.decode=og;function ig(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function og(r){let e={},t=r.split("&");for(let n=0,s=t.length;n<s;n++){let i=t[n].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}});var ou=F((bv,iu)=>{var Tn=1e3,Cn=Tn*60,On=Cn*60,Zr=On*24,ag=Zr*7,cg=Zr*365.25;iu.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return fg(r);if(t==="number"&&isFinite(r))return e.long?lg(r):ug(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function fg(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*cg;case"weeks":case"week":case"w":return t*ag;case"days":case"day":case"d":return t*Zr;case"hours":case"hour":case"hrs":case"hr":case"h":return t*On;case"minutes":case"minute":case"mins":case"min":case"m":return t*Cn;case"seconds":case"second":case"secs":case"sec":case"s":return t*Tn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function ug(r){var e=Math.abs(r);return e>=Zr?Math.round(r/Zr)+"d":e>=On?Math.round(r/On)+"h":e>=Cn?Math.round(r/Cn)+"m":e>=Tn?Math.round(r/Tn)+"s":r+"ms"}function lg(r){var e=Math.abs(r);return e>=Zr?pi(r,e,Zr,"day"):e>=On?pi(r,e,On,"hour"):e>=Cn?pi(r,e,Cn,"minute"):e>=Tn?pi(r,e,Tn,"second"):r+" ms"}function pi(r,e,t,n){var s=e>=t*1.5;return Math.round(r/t)+" "+n+(s?"s":"")}});var qo=F((xv,au)=>{function hg(r){t.debug=t,t.default=t,t.coerce=u,t.disable=a,t.enable=s,t.enabled=c,t.humanize=ou(),t.destroy=d,Object.keys(r).forEach(g=>{t[g]=r[g]}),t.names=[],t.skips=[],t.formatters={};function e(g){let m=0;for(let y=0;y<g.length;y++)m=(m<<5)-m+g.charCodeAt(y),m|=0;return t.colors[Math.abs(m)%t.colors.length]}t.selectColor=e;function t(g){let m,y=null,w,S;function C(...V){if(!C.enabled)return;let de=C,B=Number(new Date),P=B-(m||B);de.diff=P,de.prev=m,de.curr=B,m=B,V[0]=t.coerce(V[0]),typeof V[0]!="string"&&V.unshift("%O");let L=0;V[0]=V[0].replace(/%([a-zA-Z%])/g,(j,Z)=>{if(j==="%%")return"%";L++;let pe=t.formatters[Z];if(typeof pe=="function"){let Ee=V[L];j=pe.call(de,Ee),V.splice(L,1),L--}return j}),t.formatArgs.call(de,V),(de.log||t.log).apply(de,V)}return C.namespace=g,C.useColors=t.useColors(),C.color=t.selectColor(g),C.extend=n,C.destroy=t.destroy,Object.defineProperty(C,"enabled",{enumerable:!0,configurable:!1,get:()=>y!==null?y:(w!==t.namespaces&&(w=t.namespaces,S=t.enabled(g)),S),set:V=>{y=V}}),typeof t.init=="function"&&t.init(C),C}function n(g,m){let y=t(this.namespace+(typeof m>"u"?":":m)+g);return y.log=this.log,y}function s(g){t.save(g),t.namespaces=g,t.names=[],t.skips=[];let m=(typeof g=="string"?g:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let y of m)y[0]==="-"?t.skips.push(y.slice(1)):t.names.push(y)}function i(g,m){let y=0,w=0,S=-1,C=0;for(;y<g.length;)if(w<m.length&&(m[w]===g[y]||m[w]==="*"))m[w]==="*"?(S=w,C=y,w++):(y++,w++);else if(S!==-1)w=S+1,C++,y=C;else return!1;for(;w<m.length&&m[w]==="*";)w++;return w===m.length}function a(){let g=[...t.names,...t.skips.map(m=>"-"+m)].join(",");return t.enable(""),g}function c(g){for(let m of t.skips)if(i(g,m))return!1;for(let m of t.names)if(i(g,m))return!0;return!1}function u(g){return g instanceof Error?g.stack||g.message:g}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}au.exports=hg});var cu=F((mt,gi)=>{mt.formatArgs=pg;mt.save=gg;mt.load=mg;mt.useColors=dg;mt.storage=_g();mt.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();mt.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function dg(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function pg(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+gi.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(n=t))}),r.splice(n,0,e)}mt.log=console.debug||console.log||(()=>{});function gg(r){try{r?mt.storage.setItem("debug",r):mt.storage.removeItem("debug")}catch{}}function mg(){let r;try{r=mt.storage.getItem("debug")||mt.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function _g(){try{return localStorage}catch{}}gi.exports=qo()(mt);var{formatters:yg}=gi.exports;yg.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var uu=F((Sv,fu)=>{"use strict";fu.exports=(r,e=process.argv)=>{let t=r.startsWith("-")?"":r.length===1?"-":"--",n=e.indexOf(t+r),s=e.indexOf("--");return n!==-1&&(s===-1||n<s)}});var du=F((Tv,hu)=>{"use strict";var Eg=require("os"),lu=require("tty"),Rt=uu(),{env:tt}=process,Ar;Rt("no-color")||Rt("no-colors")||Rt("color=false")||Rt("color=never")?Ar=0:(Rt("color")||Rt("colors")||Rt("color=true")||Rt("color=always"))&&(Ar=1);"FORCE_COLOR"in tt&&(tt.FORCE_COLOR==="true"?Ar=1:tt.FORCE_COLOR==="false"?Ar=0:Ar=tt.FORCE_COLOR.length===0?1:Math.min(parseInt(tt.FORCE_COLOR,10),3));function Wo(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function Ho(r,e){if(Ar===0)return 0;if(Rt("color=16m")||Rt("color=full")||Rt("color=truecolor"))return 3;if(Rt("color=256"))return 2;if(r&&!e&&Ar===void 0)return 0;let t=Ar||0;if(tt.TERM==="dumb")return t;if(process.platform==="win32"){let n=Eg.release().split(".");return Number(n[0])>=10&&Number(n[2])>=10586?Number(n[2])>=14931?3:2:1}if("CI"in tt)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(n=>n in tt)||tt.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in tt)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(tt.TEAMCITY_VERSION)?1:0;if(tt.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in tt){let n=parseInt((tt.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(tt.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(tt.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(tt.TERM)||"COLORTERM"in tt?1:t}function vg(r){let e=Ho(r,r&&r.isTTY);return Wo(e)}hu.exports={supportsColor:vg,stdout:Wo(Ho(!0,lu.isatty(1))),stderr:Wo(Ho(!0,lu.isatty(2)))}});var gu=F((rt,_i)=>{var wg=require("tty"),mi=require("util");rt.init=kg;rt.log=Tg;rt.formatArgs=xg;rt.save=Cg;rt.load=Og;rt.useColors=bg;rt.destroy=mi.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");rt.colors=[6,2,3,4,5,1];try{let r=du();r&&(r.stderr||r).level>=2&&(rt.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}rt.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,i)=>i.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),r[t]=n,r},{});function bg(){return"colors"in rt.inspectOpts?!!rt.inspectOpts.colors:wg.isatty(process.stderr.fd)}function xg(r){let{namespace:e,useColors:t}=this;if(t){let n=this.color,s="\x1B[3"+(n<8?n:"8;5;"+n),i=` ${s};1m${e} \x1B[0m`;r[0]=i+r[0].split(`
|
|
17
17
|
`).join(`
|
|
18
|
-
`+i),r.push(s+"m+"+_i.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=
|
|
19
|
-
`)}function
|
|
20
|
-
`).map(e=>e.trim()).join(" ")};hu.O=function(r){return this.inspectOpts.colors=this.useColors,gi.inspect(r,this.inspectOpts)}});var Rt=D((ww,Ho)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Ho.exports=ou():Ho.exports=du()});var os=D(Ar=>{"use strict";var Sg=Ar&&Ar.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ar,"__esModule",{value:!0});Ar.Transport=Ar.TransportError=void 0;var Tg=xn(),Cg=Yr(),Og=Jr(),kg=jo(),Pg=Sg(Rt()),Rg=(0,Pg.default)("engine.io-client:transport"),mi=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}};Ar.TransportError=mi;var Vo=class extends Cg.Emitter{constructor(e){super(),this.writable=!1,(0,Og.installTimerFunctions)(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new mi(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"?this.write(e):Rg("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=(0,Tg.decodePacket)(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){let t=(0,kg.encode)(e);return t.length?"?"+t:""}};Ar.Transport=Vo});var $o=D(kn=>{"use strict";var Ag=kn&&kn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(kn,"__esModule",{value:!0});kn.Polling=void 0;var Ig=os(),Lg=Jr(),pu=xn(),Ng=Ag(Rt()),Mt=(0,Ng.default)("engine.io-client:polling"),Ko=class extends Ig.Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{Mt("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let n=0;this._polling&&(Mt("we are currently polling - waiting to pause"),n++,this.once("pollComplete",function(){Mt("pre-pause polling complete"),--n||t()})),this.writable||(Mt("we are currently writing - waiting to pause"),n++,this.once("drain",function(){Mt("pre-pause writing complete"),--n||t()}))}else t()}_poll(){Mt("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){Mt("polling got data %s",e);let t=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};(0,pu.decodePayload)(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Mt('ignoring poll - transport state "%s"',this.readyState))}doClose(){let e=()=>{Mt("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Mt("transport open - closing"),e()):(Mt("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,(0,pu.encodePayload)(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=(0,Lg.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}};kn.Polling=Ko});var _u=D(yi=>{"use strict";Object.defineProperty(yi,"__esModule",{value:!0});yi.hasCORS=void 0;var gu=!1;try{gu=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}yi.hasCORS=gu});var Yo=D(Jt=>{"use strict";var Dg=Jt&&Jt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Jt,"__esModule",{value:!0});Jt.XHR=Jt.Request=Jt.BaseXHR=void 0;var Fg=$o(),Mg=Yr(),mu=Jr(),Eu=Xr(),Bg=_u(),jg=Dg(Rt()),zo=(0,jg.default)("engine.io-client:polling");function Ug(){}var Ei=class extends Fg.Polling{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",n=location.port;n||(n=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){let n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(s,i)=>{this.onError("xhr post error",s,i)})}doPoll(){zo("xhr poll");let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=e}};Jt.BaseXHR=Ei;var hr=class r extends Mg.Emitter{constructor(e,t,n){super(),this.createRequest=e,(0,mu.installTimerFunctions)(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var e;let t=(0,mu.pick)(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let n=this._xhr=this.createRequest(t);try{zo("xhr open %s: %s",this._method,this._uri),n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let s in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(s)&&n.setRequestHeader(s,this._opts.extraHeaders[s])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var s;n.readyState===3&&((s=this._opts.cookieJar)===null||s===void 0||s.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},zo("xhr data %s",this._data),n.send(this._data)}catch(s){this.setTimeoutFn(()=>{this._onError(s)},0);return}typeof document<"u"&&(this._index=r.requestsCount++,r.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Ug,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete r.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};Jt.Request=hr;hr.requestsCount=0;hr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",yu);else if(typeof addEventListener=="function"){let r="onpagehide"in Eu.globalThisShim?"pagehide":"unload";addEventListener(r,yu,!1)}}function yu(){for(let r in hr.requests)hr.requests.hasOwnProperty(r)&&hr.requests[r].abort()}var qg=(function(){let r=wu({xdomain:!1});return r&&r.responseType!==null})(),Go=class extends Ei{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=qg&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new hr(wu,this.uri(),e)}};Jt.XHR=Go;function wu(r){let e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Bg.hasCORS))return new XMLHttpRequest}catch{}if(!e)try{return new Eu.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}});var Jo=D(Zt=>{"use strict";var Wg=Zt&&Zt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Hg=Zt&&Zt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Vg=Zt&&Zt.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&Wg(e,r,t);return Hg(e,r),e};Object.defineProperty(Zt,"__esModule",{value:!0});Zt.XHR=void 0;var vu=Vg(zf()),bu=Yo(),Kg=vu.default||vu,Xo=class extends bu.BaseXHR{request(e={}){var t;return Object.assign(e,{xd:this.xd,cookieJar:(t=this.socket)===null||t===void 0?void 0:t._cookieJar},this.opts),new bu.Request(n=>new Kg(n),this.uri(),e)}};Zt.XHR=Xo});var dr=D((Cw,Tu)=>{"use strict";var xu=["nodebuffer","arraybuffer","fragments"],Su=typeof Blob<"u";Su&&xu.push("blob");Tu.exports={BINARY_TYPES:xu,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Su,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var as=D((Ow,wi)=>{"use strict";var{EMPTY_BUFFER:$g}=dr(),Zo=Buffer[Symbol.species];function zg(r,e){if(r.length===0)return $g;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let s=0;s<r.length;s++){let i=r[s];t.set(i,n),n+=i.length}return n<e?new Zo(t.buffer,t.byteOffset,n):t}function Cu(r,e,t,n,s){for(let i=0;i<s;i++)t[n+i]=r[i]^e[i&3]}function Ou(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function Gg(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function Qo(r){if(Qo.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new Zo(r):ArrayBuffer.isView(r)?e=new Zo(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),Qo.readOnly=!1),e}wi.exports={concat:zg,mask:Cu,toArrayBuffer:Gg,toBuffer:Qo,unmask:Ou};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");wi.exports.mask=function(e,t,n,s,i){i<48?Cu(e,t,n,s,i):r.mask(e,t,n,s,i)},wi.exports.unmask=function(e,t){e.length<32?Ou(e,t):r.unmask(e,t)}}catch{}});var Ru=D((kw,Pu)=>{"use strict";var ku=Symbol("kDone"),ea=Symbol("kRun"),ta=class{constructor(e){this[ku]=()=>{this.pending--,this[ea]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ea]()}[ea](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[ku])}}};Pu.exports=ta});var fs=D((Pw,Nu)=>{"use strict";var cs=require("zlib"),Au=as(),Yg=Ru(),{kStatusCode:Iu}=dr(),Xg=Buffer[Symbol.species],Jg=Buffer.from([0,0,255,255]),bi=Symbol("permessage-deflate"),pr=Symbol("total-length"),Pn=Symbol("callback"),Ir=Symbol("buffers"),Rn=Symbol("error"),vi,ra=class{constructor(e,t,n){if(this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!vi){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;vi=new Yg(s)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Pn];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,n=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(n=>{let s=t[n];if(s.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(s=s[0],n==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else if(n==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=s})}),e}decompress(e,t,n){vi.add(s=>{this._decompress(e,t,(i,a)=>{s(),n(i,a)})})}compress(e,t,n){vi.add(s=>{this._compress(e,t,(i,a)=>{s(),n(i,a)})})}_decompress(e,t,n){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,a=typeof this.params[i]!="number"?cs.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=cs.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[bi]=this,this._inflate[pr]=0,this._inflate[Ir]=[],this._inflate.on("error",Qg),this._inflate.on("data",Lu)}this._inflate[Pn]=n,this._inflate.write(e),t&&this._inflate.write(Jg),this._inflate.flush(()=>{let i=this._inflate[Rn];if(i){this._inflate.close(),this._inflate=null,n(i);return}let a=Au.concat(this._inflate[Ir],this._inflate[pr]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[pr]=0,this._inflate[Ir]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),n(null,a)})}_compress(e,t,n){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,a=typeof this.params[i]!="number"?cs.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=cs.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[pr]=0,this._deflate[Ir]=[],this._deflate.on("data",Zg)}this._deflate[Pn]=n,this._deflate.write(e),this._deflate.flush(cs.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Au.concat(this._deflate[Ir],this._deflate[pr]);t&&(i=new Xg(i.buffer,i.byteOffset,i.length-4)),this._deflate[Pn]=null,this._deflate[pr]=0,this._deflate[Ir]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};Nu.exports=ra;function Zg(r){this[Ir].push(r),this[pr]+=r.length}function Lu(r){if(this[pr]+=r.length,this[bi]._maxPayload<1||this[pr]<=this[bi]._maxPayload){this[Ir].push(r);return}this[Rn]=new RangeError("Max payload size exceeded"),this[Rn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Rn][Iu]=1009,this.removeListener("data",Lu),this.reset()}function Qg(r){if(this[bi]._inflate=null,this[Rn]){this[Pn](this[Rn]);return}r[Iu]=1007,this[Pn](r)}});var An=D((Rw,xi)=>{"use strict";var{isUtf8:Du}=require("buffer"),{hasBlob:e0}=dr(),t0=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function r0(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function na(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function n0(r){return e0&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}xi.exports={isBlob:n0,isValidStatusCode:r0,isValidUTF8:na,tokenChars:t0};if(Du)xi.exports.isValidUTF8=function(r){return r.length<24?na(r):Du(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");xi.exports.isValidUTF8=function(e){return e.length<32?na(e):r(e)}}catch{}});var ca=D((Aw,Wu)=>{"use strict";var{Writable:s0}=require("stream"),Fu=fs(),{BINARY_TYPES:i0,EMPTY_BUFFER:Mu,kStatusCode:o0,kWebSocket:a0}=dr(),{concat:sa,toArrayBuffer:c0,unmask:f0}=as(),{isValidStatusCode:u0,isValidUTF8:Bu}=An(),Si=Buffer[Symbol.species],At=0,ju=1,Uu=2,qu=3,ia=4,oa=5,Ti=6,aa=class extends s0{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||i0[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[a0]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=At}_write(e,t,n){if(this._opcode===8&&this._state==At)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new Si(n.buffer,n.byteOffset+e,n.length-e),new Si(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],s=t.length-e;e>=n.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),s),this._buffers[0]=new Si(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case At:this.getInfo(e);break;case ju:this.getPayloadLength16(e);break;case Uu:this.getPayloadLength64(e);break;case qu:this.getMask();break;case ia:this.getData(e);break;case oa:case Ti:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let n=(t[0]&64)===64;if(n&&!this._extensions[Fu.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=ju:this._payloadLength===127?this._state=Uu:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=qu:this._state=ia}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ia}getData(e){let t=Mu;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&f0(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=oa,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Fu.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let a=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(a);return}this._fragments.push(i)}this.dataMessage(t),this._state===At&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=At;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=sa(n,t):this._binaryType==="arraybuffer"?s=c0(sa(n,t)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=At):(this._state=Ti,setImmediate(()=>{this.emit("message",s,!0),this._state=At,this.startLoop(e)}))}else{let s=sa(n,t);if(!this._skipUTF8Validation&&!Bu(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===oa||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=At):(this._state=Ti,setImmediate(()=>{this.emit("message",s,!1),this._state=At,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Mu),this.end();else{let n=e.readUInt16BE(0);if(!u0(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Si(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Bu(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",n,s),this.end()}this._state=At;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=At):(this._state=Ti,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=At,this.startLoop(t)}))}createError(e,t,n,s,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o0]=s,a}};Wu.exports=aa});var la=D((Lw,Ku)=>{"use strict";var{Duplex:Iw}=require("stream"),{randomFillSync:l0}=require("crypto"),Hu=fs(),{EMPTY_BUFFER:h0,kWebSocket:d0,NOOP:p0}=dr(),{isBlob:In,isValidStatusCode:g0}=An(),{mask:Vu,toBuffer:Qr}=as(),It=Symbol("kByteLength"),_0=Buffer.alloc(4),Ci=8*1024,en,Ln=Ci,Bt=0,m0=1,y0=2,fa=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Bt,this.onerror=p0,this[d0]=void 0}static frame(e,t){let n,s=!1,i=2,a=!1;t.mask&&(n=t.maskBuffer||_0,t.generateMask?t.generateMask(n):(Ln===Ci&&(en===void 0&&(en=Buffer.alloc(Ci)),l0(en,0,Ci),Ln=0),n[0]=en[Ln++],n[1]=en[Ln++],n[2]=en[Ln++],n[3]=en[Ln++]),a=(n[0]|n[1]|n[2]|n[3])===0,i=6);let c;typeof e=="string"?(!t.mask||a)&&t[It]!==void 0?c=t[It]:(e=Buffer.from(e),c=e.length):(c=e.length,s=t.mask&&t.readOnly&&!a);let u=c;c>=65536?(i+=8,u=127):c>125&&(i+=2,u=126);let d=Buffer.allocUnsafe(s?c+i:i);return d[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(d[0]|=64),d[1]=u,u===126?d.writeUInt16BE(c,2):u===127&&(d[2]=d[3]=0,d.writeUIntBE(c,4,6)),t.mask?(d[1]|=128,d[i-4]=n[0],d[i-3]=n[1],d[i-2]=n[2],d[i-1]=n[3],a?[d,e]:s?(Vu(e,n,d,i,c),[d]):(Vu(e,n,e,0,c),[d,e])):[d,e]}close(e,t,n,s){let i;if(e===void 0)i=h0;else{if(typeof e!="number"||!g0(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let c=Buffer.byteLength(t);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+c),i.writeUInt16BE(e,0),typeof t=="string"?i.write(t,2):i.set(t,2)}}let a={[It]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Bt?this.enqueue([this.dispatch,i,!1,a,s]):this.sendFrame(r.frame(i,a),s)}ping(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):In(e)?(s=e.size,i=!1):(e=Qr(e),s=e.length,i=Qr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[It]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};In(e)?this._state!==Bt?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==Bt?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(r.frame(e,a),n)}pong(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):In(e)?(s=e.size,i=!1):(e=Qr(e),s=e.length,i=Qr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[It]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};In(e)?this._state!==Bt?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==Bt?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(r.frame(e,a),n)}send(e,t,n){let s=this._extensions[Hu.extensionName],i=t.binary?2:1,a=t.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):In(e)?(c=e.size,u=!1):(e=Qr(e),c=e.length,u=Qr.readOnly),this._firstFragment?(this._firstFragment=!1,a&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=c>=s._threshold),this._compress=a):(a=!1,i=0),t.fin&&(this._firstFragment=!0);let d={[It]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:u,rsv1:a};In(e)?this._state!==Bt?this.enqueue([this.getBlobData,e,this._compress,d,n]):this.getBlobData(e,this._compress,d,n):this._state!==Bt?this.enqueue([this.dispatch,e,this._compress,d,n]):this.dispatch(e,this._compress,d,n)}getBlobData(e,t,n,s){this._bufferedBytes+=n[It],this._state=y0,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(ua,this,c,s);return}this._bufferedBytes-=n[It];let a=Qr(i);t?this.dispatch(a,t,n,s):(this._state=Bt,this.sendFrame(r.frame(a,n),s),this.dequeue())}).catch(i=>{process.nextTick(E0,this,i,s)})}dispatch(e,t,n,s){if(!t){this.sendFrame(r.frame(e,n),s);return}let i=this._extensions[Hu.extensionName];this._bufferedBytes+=n[It],this._state=m0,i.compress(e,n.fin,(a,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");ua(this,u,s);return}this._bufferedBytes-=n[It],this._state=Bt,n.readOnly=!1,this.sendFrame(r.frame(c,n),s),this.dequeue()})}dequeue(){for(;this._state===Bt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][It],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][It],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};Ku.exports=fa;function ua(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let s=r._queue[n],i=s[s.length-1];typeof i=="function"&&i(e)}}function E0(r,e,t){ua(r,e,t),r.onerror(e)}});var el=D((Nw,Qu)=>{"use strict";var{kForOnEventAttribute:us,kListener:ha}=dr(),$u=Symbol("kCode"),zu=Symbol("kData"),Gu=Symbol("kError"),Yu=Symbol("kMessage"),Xu=Symbol("kReason"),Nn=Symbol("kTarget"),Ju=Symbol("kType"),Zu=Symbol("kWasClean"),gr=class{constructor(e){this[Nn]=null,this[Ju]=e}get target(){return this[Nn]}get type(){return this[Ju]}};Object.defineProperty(gr.prototype,"target",{enumerable:!0});Object.defineProperty(gr.prototype,"type",{enumerable:!0});var tn=class extends gr{constructor(e,t={}){super(e),this[$u]=t.code===void 0?0:t.code,this[Xu]=t.reason===void 0?"":t.reason,this[Zu]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[$u]}get reason(){return this[Xu]}get wasClean(){return this[Zu]}};Object.defineProperty(tn.prototype,"code",{enumerable:!0});Object.defineProperty(tn.prototype,"reason",{enumerable:!0});Object.defineProperty(tn.prototype,"wasClean",{enumerable:!0});var Dn=class extends gr{constructor(e,t={}){super(e),this[Gu]=t.error===void 0?null:t.error,this[Yu]=t.message===void 0?"":t.message}get error(){return this[Gu]}get message(){return this[Yu]}};Object.defineProperty(Dn.prototype,"error",{enumerable:!0});Object.defineProperty(Dn.prototype,"message",{enumerable:!0});var ls=class extends gr{constructor(e,t={}){super(e),this[zu]=t.data===void 0?null:t.data}get data(){return this[zu]}};Object.defineProperty(ls.prototype,"data",{enumerable:!0});var w0={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[us]&&s[ha]===e&&!s[us])return;let n;if(r==="message")n=function(i,a){let c=new ls("message",{data:a?i:i.toString()});c[Nn]=this,Oi(e,this,c)};else if(r==="close")n=function(i,a){let c=new tn("close",{code:i,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[Nn]=this,Oi(e,this,c)};else if(r==="error")n=function(i){let a=new Dn("error",{error:i,message:i.message});a[Nn]=this,Oi(e,this,a)};else if(r==="open")n=function(){let i=new gr("open");i[Nn]=this,Oi(e,this,i)};else return;n[us]=!!t[us],n[ha]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[ha]===e&&!t[us]){this.removeListener(r,t);break}}};Qu.exports={CloseEvent:tn,ErrorEvent:Dn,Event:gr,EventTarget:w0,MessageEvent:ls};function Oi(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var da=D((Dw,tl)=>{"use strict";var{tokenChars:hs}=An();function Qt(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function v0(r){let e=Object.create(null),t=Object.create(null),n=!1,s=!1,i=!1,a,c,u=-1,d=-1,g=-1,_=0;for(;_<r.length;_++)if(d=r.charCodeAt(_),a===void 0)if(g===-1&&hs[d]===1)u===-1&&(u=_);else if(_!==0&&(d===32||d===9))g===-1&&u!==-1&&(g=_);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${_}`);g===-1&&(g=_);let v=r.slice(u,g);d===44?(Qt(e,v,t),t=Object.create(null)):a=v,u=g=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);else if(c===void 0)if(g===-1&&hs[d]===1)u===-1&&(u=_);else if(d===32||d===9)g===-1&&u!==-1&&(g=_);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${_}`);g===-1&&(g=_),Qt(t,r.slice(u,g),!0),d===44&&(Qt(e,a,t),t=Object.create(null),a=void 0),u=g=-1}else if(d===61&&u!==-1&&g===-1)c=r.slice(u,_),u=g=-1;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(s){if(hs[d]!==1)throw new SyntaxError(`Unexpected character at index ${_}`);u===-1?u=_:n||(n=!0),s=!1}else if(i)if(hs[d]===1)u===-1&&(u=_);else if(d===34&&u!==-1)i=!1,g=_;else if(d===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(d===34&&r.charCodeAt(_-1)===61)i=!0;else if(g===-1&&hs[d]===1)u===-1&&(u=_);else if(u!==-1&&(d===32||d===9))g===-1&&(g=_);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${_}`);g===-1&&(g=_);let v=r.slice(u,g);n&&(v=v.replace(/\\/g,""),n=!1),Qt(t,c,v),d===44&&(Qt(e,a,t),t=Object.create(null),a=void 0),c=void 0,u=g=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);if(u===-1||i||d===32||d===9)throw new SyntaxError("Unexpected end of input");g===-1&&(g=_);let y=r.slice(u,g);return a===void 0?Qt(e,y,t):(c===void 0?Qt(t,y,!0):n?Qt(t,c,y.replace(/\\/g,"")):Qt(t,c,y),Qt(e,a,t)),e}function b0(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(s=>{let i=n[s];return Array.isArray(i)||(i=[i]),i.map(a=>a===!0?s:`${s}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}tl.exports={format:b0,parse:v0}});var Ai=D((Bw,dl)=>{"use strict";var x0=require("events"),S0=require("https"),T0=require("http"),sl=require("net"),C0=require("tls"),{randomBytes:O0,createHash:k0}=require("crypto"),{Duplex:Fw,Readable:Mw}=require("stream"),{URL:pa}=require("url"),Lr=fs(),P0=ca(),R0=la(),{isBlob:A0}=An(),{BINARY_TYPES:rl,EMPTY_BUFFER:ki,GUID:I0,kForOnEventAttribute:ga,kListener:L0,kStatusCode:N0,kWebSocket:rt,NOOP:il}=dr(),{EventTarget:{addEventListener:D0,removeEventListener:F0}}=el(),{format:M0,parse:B0}=da(),{toBuffer:j0}=as(),U0=30*1e3,ol=Symbol("kAborted"),_a=[8,13],_r=["CONNECTING","OPEN","CLOSING","CLOSED"],q0=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Ue=class r extends x0{constructor(e,t,n){super(),this._binaryType=rl[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ki,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(n=t,t=[]):t=[t]),al(this,e,t,n)):(this._autoPong=n.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){rl.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,n){let s=new P0({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new R0(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[rt]=this,i[rt]=this,e[rt]=this,s.on("conclude",V0),s.on("drain",K0),s.on("error",$0),s.on("message",z0),s.on("ping",G0),s.on("pong",Y0),i.onerror=X0,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",ul),e.on("data",Ri),e.on("end",ll),e.on("error",hl),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Lr.extensionName]&&this._extensions[Lr.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){St(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),fl(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){ma(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||ki,t,n)}pong(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){ma(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||ki,t,n)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(n=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){ma(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Lr.extensionName]||(s.compress=!1),this._sender.send(e||ki,s,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){St(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(Ue,"CONNECTING",{enumerable:!0,value:_r.indexOf("CONNECTING")});Object.defineProperty(Ue.prototype,"CONNECTING",{enumerable:!0,value:_r.indexOf("CONNECTING")});Object.defineProperty(Ue,"OPEN",{enumerable:!0,value:_r.indexOf("OPEN")});Object.defineProperty(Ue.prototype,"OPEN",{enumerable:!0,value:_r.indexOf("OPEN")});Object.defineProperty(Ue,"CLOSING",{enumerable:!0,value:_r.indexOf("CLOSING")});Object.defineProperty(Ue.prototype,"CLOSING",{enumerable:!0,value:_r.indexOf("CLOSING")});Object.defineProperty(Ue,"CLOSED",{enumerable:!0,value:_r.indexOf("CLOSED")});Object.defineProperty(Ue.prototype,"CLOSED",{enumerable:!0,value:_r.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(Ue.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(Ue.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[ga])return e[L0];return null},set(e){for(let t of this.listeners(r))if(t[ga]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[ga]:!0})}})});Ue.prototype.addEventListener=D0;Ue.prototype.removeEventListener=F0;dl.exports=Ue;function al(r,e,t,n){let s={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:_a[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=s.autoPong,!_a.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${_a.join(", ")})`);let i;if(e instanceof pa)i=e;else try{i=new pa(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),r._url=i.href;let a=i.protocol==="wss:",c=i.protocol==="ws+unix:",u;if(i.protocol!=="ws:"&&!a&&!c?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!i.pathname?u="The URL's pathname is empty":i.hash&&(u="The URL contains a fragment identifier"),u){let O=new SyntaxError(u);if(r._redirects===0)throw O;Pi(r,O);return}let d=a?443:80,g=O0(16).toString("base64"),_=a?S0.request:T0.request,y=new Set,v;if(s.createConnection=s.createConnection||(a?H0:W0),s.defaultPort=s.defaultPort||d,s.port=i.port||d,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":g,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(v=new Lr(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=M0({[Lr.extensionName]:v.offer()})),t.length){for(let O of t){if(typeof O!="string"||!q0.test(O)||y.has(O))throw new SyntaxError("An invalid or duplicated subprotocol was specified");y.add(O)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),c){let O=s.path.split(":");s.socketPath=O[0],s.path=O[1]}let S;if(s.followRedirects){if(r._redirects===0){r._originalIpc=c,r._originalSecure=a,r._originalHostOrSocketPath=c?s.socketPath:i.host;let O=n&&n.headers;if(n={...n,headers:{}},O)for(let[H,z]of Object.entries(O))n.headers[H.toLowerCase()]=z}else if(r.listenerCount("redirect")===0){let O=c?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!O||r._originalSecure&&!a)&&(delete s.headers.authorization,delete s.headers.cookie,O||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),S=r._req=_(s),r._redirects&&r.emit("redirect",r.url,S)}else S=r._req=_(s);s.timeout&&S.on("timeout",()=>{St(r,S,"Opening handshake has timed out")}),S.on("error",O=>{S===null||S[ol]||(S=r._req=null,Pi(r,O))}),S.on("response",O=>{let H=O.headers.location,z=O.statusCode;if(H&&s.followRedirects&&z>=300&&z<400){if(++r._redirects>s.maxRedirects){St(r,S,"Maximum redirects exceeded");return}S.abort();let X;try{X=new pa(H,e)}catch{let M=new SyntaxError(`Invalid URL: ${H}`);Pi(r,M);return}al(r,X,t,n)}else r.emit("unexpected-response",S,O)||St(r,S,`Unexpected server response: ${O.statusCode}`)}),S.on("upgrade",(O,H,z)=>{if(r.emit("upgrade",O),r.readyState!==Ue.CONNECTING)return;S=r._req=null;let X=O.headers.upgrade;if(X===void 0||X.toLowerCase()!=="websocket"){St(r,H,"Invalid Upgrade header");return}let T=k0("sha1").update(g+I0).digest("base64");if(O.headers["sec-websocket-accept"]!==T){St(r,H,"Invalid Sec-WebSocket-Accept header");return}let M=O.headers["sec-websocket-protocol"],Q;if(M!==void 0?y.size?y.has(M)||(Q="Server sent an invalid subprotocol"):Q="Server sent a subprotocol but none was requested":y.size&&(Q="Server sent no subprotocol"),Q){St(r,H,Q);return}M&&(r._protocol=M);let B=O.headers["sec-websocket-extensions"];if(B!==void 0){if(!v){St(r,H,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ie;try{ie=B0(B)}catch{St(r,H,"Invalid Sec-WebSocket-Extensions header");return}let he=Object.keys(ie);if(he.length!==1||he[0]!==Lr.extensionName){St(r,H,"Server indicated an extension that was not requested");return}try{v.accept(ie[Lr.extensionName])}catch{St(r,H,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Lr.extensionName]=v}r.setSocket(H,z,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(S,r):S.end()}function Pi(r,e){r._readyState=Ue.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function W0(r){return r.path=r.socketPath,sl.connect(r)}function H0(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=sl.isIP(r.host)?"":r.host),C0.connect(r)}function St(r,e,t){r._readyState=Ue.CLOSING;let n=new Error(t);Error.captureStackTrace(n,St),e.setHeader?(e[ol]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Pi,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function ma(r,e,t){if(e){let n=A0(e)?e.size:j0(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${_r[r.readyState]})`);process.nextTick(t,n)}}function V0(r,e){let t=this[rt];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[rt]!==void 0&&(t._socket.removeListener("data",Ri),process.nextTick(cl,t._socket),r===1005?t.close():t.close(r,e))}function K0(){let r=this[rt];r.isPaused||r._socket.resume()}function $0(r){let e=this[rt];e._socket[rt]!==void 0&&(e._socket.removeListener("data",Ri),process.nextTick(cl,e._socket),e.close(r[N0])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function nl(){this[rt].emitClose()}function z0(r,e){this[rt].emit("message",r,e)}function G0(r){let e=this[rt];e._autoPong&&e.pong(r,!this._isServer,il),e.emit("ping",r)}function Y0(r){this[rt].emit("pong",r)}function cl(r){r.resume()}function X0(r){let e=this[rt];e.readyState!==Ue.CLOSED&&(e.readyState===Ue.OPEN&&(e._readyState=Ue.CLOSING,fl(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function fl(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),U0)}function ul(){let r=this[rt];this.removeListener("close",ul),this.removeListener("data",Ri),this.removeListener("end",ll),r._readyState=Ue.CLOSING;let e;!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&(e=r._socket.read())!==null&&r._receiver.write(e),r._receiver.end(),this[rt]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",nl),r._receiver.on("finish",nl))}function Ri(r){this[rt]._receiver.write(r)||this.pause()}function ll(){let r=this[rt];r._readyState=Ue.CLOSING,r._receiver.end(),this.end()}function hl(){let r=this[rt];this.removeListener("error",hl),this.on("error",il),r&&(r._readyState=Ue.CLOSING,this.destroy())}});var ml=D((Uw,_l)=>{"use strict";var jw=Ai(),{Duplex:J0}=require("stream");function pl(r){r.emit("close")}function Z0(){!this.destroyed&&this._writableState.finished&&this.destroy()}function gl(r){this.removeListener("error",gl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function Q0(r,e){let t=!0,n=new J0({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(i,a){let c=!a&&n._readableState.objectMode?i.toString():i;n.push(c)||r.pause()}),r.once("error",function(i){n.destroyed||(t=!1,n.destroy(i))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(s,i){if(r.readyState===r.CLOSED){i(s),process.nextTick(pl,n);return}let a=!1;r.once("error",function(u){a=!0,i(u)}),r.once("close",function(){a||i(s),process.nextTick(pl,n)}),t&&r.terminate()},n._final=function(s){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(s)});return}r._socket!==null&&(r._socket._writableState.finished?(s(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){s()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(s,i,a){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(s,i,a)});return}r.send(s,a)},n.on("end",Z0),n.on("error",gl),n}_l.exports=Q0});var El=D((qw,yl)=>{"use strict";var{tokenChars:e_}=An();function t_(r){let e=new Set,t=-1,n=-1,s=0;for(s;s<r.length;s++){let a=r.charCodeAt(s);if(n===-1&&e_[a]===1)t===-1&&(t=s);else if(s!==0&&(a===32||a===9))n===-1&&t!==-1&&(n=s);else if(a===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);n===-1&&(n=s);let c=r.slice(t,n);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);e.add(c),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=r.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}yl.exports={parse:t_}});var Cl=D((Hw,Tl)=>{"use strict";var r_=require("events"),Ii=require("http"),{Duplex:Ww}=require("stream"),{createHash:n_}=require("crypto"),wl=da(),rn=fs(),s_=El(),i_=Ai(),{GUID:o_,kWebSocket:a_}=dr(),c_=/^[+/0-9A-Za-z]{22}==$/,vl=0,bl=1,Sl=2,ya=class extends r_{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:i_,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Ii.createServer((n,s)=>{let i=Ii.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=f_(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,a)=>{this.handleUpgrade(s,i,a,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=vl}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Sl){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ds,this);return}if(e&&this.once("close",e),this._state!==bl)if(this._state=bl,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(ds,this):process.nextTick(ds,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{ds(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,s){t.on("error",xl);let i=e.headers["sec-websocket-key"],a=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){nn(this,e,t,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){nn(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!c_.test(i)){nn(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){nn(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ps(t,400);return}let u=e.headers["sec-websocket-protocol"],d=new Set;if(u!==void 0)try{d=s_.parse(u)}catch{nn(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let g=e.headers["sec-websocket-extensions"],_={};if(this.options.perMessageDeflate&&g!==void 0){let y=new rn(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let v=wl.parse(g);v[rn.extensionName]&&(y.accept(v[rn.extensionName]),_[rn.extensionName]=y)}catch{nn(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let y={origin:e.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(y,(v,S,O,H)=>{if(!v)return ps(t,S||401,O,H);this.completeUpgrade(_,i,d,e,t,n,s)});return}if(!this.options.verifyClient(y))return ps(t,401)}this.completeUpgrade(_,i,d,e,t,n,s)}completeUpgrade(e,t,n,s,i,a,c){if(!i.readable||!i.writable)return i.destroy();if(i[a_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>vl)return ps(i,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${n_("sha1").update(t+o_).digest("base64")}`],g=new this.options.WebSocket(null,void 0,this.options);if(n.size){let _=this.options.handleProtocols?this.options.handleProtocols(n,s):n.values().next().value;_&&(d.push(`Sec-WebSocket-Protocol: ${_}`),g._protocol=_)}if(e[rn.extensionName]){let _=e[rn.extensionName].params,y=wl.format({[rn.extensionName]:[_]});d.push(`Sec-WebSocket-Extensions: ${y}`),g._extensions=e}this.emit("headers",d,s),i.write(d.concat(`\r
|
|
18
|
+
`+i),r.push(s+"m+"+_i.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=Sg()+e+" "+r[0]}function Sg(){return rt.inspectOpts.hideDate?"":new Date().toISOString()+" "}function Tg(...r){return process.stderr.write(mi.formatWithOptions(rt.inspectOpts,...r)+`
|
|
19
|
+
`)}function Cg(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function Og(){return process.env.DEBUG}function kg(r){r.inspectOpts={};let e=Object.keys(rt.inspectOpts);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=rt.inspectOpts[e[t]]}_i.exports=qo()(rt);var{formatters:pu}=_i.exports;pu.o=function(r){return this.inspectOpts.colors=this.useColors,mi.inspect(r,this.inspectOpts).split(`
|
|
20
|
+
`).map(e=>e.trim()).join(" ")};pu.O=function(r){return this.inspectOpts.colors=this.useColors,mi.inspect(r,this.inspectOpts)}});var At=F((Cv,Vo)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Vo.exports=cu():Vo.exports=gu()});var as=F(Ir=>{"use strict";var Pg=Ir&&Ir.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ir,"__esModule",{value:!0});Ir.Transport=Ir.TransportError=void 0;var Rg=xn(),Ag=Yr(),Ig=Jr(),Lg=Uo(),Ng=Pg(At()),Dg=(0,Ng.default)("engine.io-client:transport"),yi=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}};Ir.TransportError=yi;var Ko=class extends Ag.Emitter{constructor(e){super(),this.writable=!1,(0,Ig.installTimerFunctions)(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new yi(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"?this.write(e):Dg("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=(0,Rg.decodePacket)(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){let t=(0,Lg.encode)(e);return t.length?"?"+t:""}};Ir.Transport=Ko});var zo=F(kn=>{"use strict";var Fg=kn&&kn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(kn,"__esModule",{value:!0});kn.Polling=void 0;var Mg=as(),Bg=Jr(),mu=xn(),jg=Fg(At()),Bt=(0,jg.default)("engine.io-client:polling"),$o=class extends Mg.Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{Bt("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let n=0;this._polling&&(Bt("we are currently polling - waiting to pause"),n++,this.once("pollComplete",function(){Bt("pre-pause polling complete"),--n||t()})),this.writable||(Bt("we are currently writing - waiting to pause"),n++,this.once("drain",function(){Bt("pre-pause writing complete"),--n||t()}))}else t()}_poll(){Bt("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){Bt("polling got data %s",e);let t=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};(0,mu.decodePayload)(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Bt('ignoring poll - transport state "%s"',this.readyState))}doClose(){let e=()=>{Bt("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Bt("transport open - closing"),e()):(Bt("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,(0,mu.encodePayload)(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=(0,Bg.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}};kn.Polling=$o});var yu=F(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});Ei.hasCORS=void 0;var _u=!1;try{_u=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}Ei.hasCORS=_u});var Xo=F(Jt=>{"use strict";var Ug=Jt&&Jt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Jt,"__esModule",{value:!0});Jt.XHR=Jt.Request=Jt.BaseXHR=void 0;var qg=zo(),Wg=Yr(),Eu=Jr(),wu=Xr(),Hg=yu(),Vg=Ug(At()),Go=(0,Vg.default)("engine.io-client:polling");function Kg(){}var vi=class extends qg.Polling{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",n=location.port;n||(n=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){let n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(s,i)=>{this.onError("xhr post error",s,i)})}doPoll(){Go("xhr poll");let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=e}};Jt.BaseXHR=vi;var hr=class r extends Wg.Emitter{constructor(e,t,n){super(),this.createRequest=e,(0,Eu.installTimerFunctions)(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var e;let t=(0,Eu.pick)(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let n=this._xhr=this.createRequest(t);try{Go("xhr open %s: %s",this._method,this._uri),n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let s in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(s)&&n.setRequestHeader(s,this._opts.extraHeaders[s])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var s;n.readyState===3&&((s=this._opts.cookieJar)===null||s===void 0||s.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},Go("xhr data %s",this._data),n.send(this._data)}catch(s){this.setTimeoutFn(()=>{this._onError(s)},0);return}typeof document<"u"&&(this._index=r.requestsCount++,r.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Kg,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete r.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};Jt.Request=hr;hr.requestsCount=0;hr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",vu);else if(typeof addEventListener=="function"){let r="onpagehide"in wu.globalThisShim?"pagehide":"unload";addEventListener(r,vu,!1)}}function vu(){for(let r in hr.requests)hr.requests.hasOwnProperty(r)&&hr.requests[r].abort()}var $g=(function(){let r=bu({xdomain:!1});return r&&r.responseType!==null})(),Yo=class extends vi{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=$g&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new hr(bu,this.uri(),e)}};Jt.XHR=Yo;function bu(r){let e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Hg.hasCORS))return new XMLHttpRequest}catch{}if(!e)try{return new wu.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}});var Zo=F(Zt=>{"use strict";var zg=Zt&&Zt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Gg=Zt&&Zt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Yg=Zt&&Zt.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&zg(e,r,t);return Gg(e,r),e};Object.defineProperty(Zt,"__esModule",{value:!0});Zt.XHR=void 0;var xu=Yg(Yf()),Su=Xo(),Xg=xu.default||xu,Jo=class extends Su.BaseXHR{request(e={}){var t;return Object.assign(e,{xd:this.xd,cookieJar:(t=this.socket)===null||t===void 0?void 0:t._cookieJar},this.opts),new Su.Request(n=>new Xg(n),this.uri(),e)}};Zt.XHR=Jo});var dr=F((Iv,Ou)=>{"use strict";var Tu=["nodebuffer","arraybuffer","fragments"],Cu=typeof Blob<"u";Cu&&Tu.push("blob");Ou.exports={BINARY_TYPES:Tu,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Cu,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var cs=F((Lv,wi)=>{"use strict";var{EMPTY_BUFFER:Jg}=dr(),Qo=Buffer[Symbol.species];function Zg(r,e){if(r.length===0)return Jg;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let s=0;s<r.length;s++){let i=r[s];t.set(i,n),n+=i.length}return n<e?new Qo(t.buffer,t.byteOffset,n):t}function ku(r,e,t,n,s){for(let i=0;i<s;i++)t[n+i]=r[i]^e[i&3]}function Pu(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function Qg(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function ea(r){if(ea.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new Qo(r):ArrayBuffer.isView(r)?e=new Qo(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),ea.readOnly=!1),e}wi.exports={concat:Zg,mask:ku,toArrayBuffer:Qg,toBuffer:ea,unmask:Pu};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");wi.exports.mask=function(e,t,n,s,i){i<48?ku(e,t,n,s,i):r.mask(e,t,n,s,i)},wi.exports.unmask=function(e,t){e.length<32?Pu(e,t):r.unmask(e,t)}}catch{}});var Iu=F((Nv,Au)=>{"use strict";var Ru=Symbol("kDone"),ta=Symbol("kRun"),ra=class{constructor(e){this[Ru]=()=>{this.pending--,this[ta]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ta]()}[ta](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ru])}}};Au.exports=ra});var us=F((Dv,Fu)=>{"use strict";var fs=require("zlib"),Lu=cs(),e0=Iu(),{kStatusCode:Nu}=dr(),t0=Buffer[Symbol.species],r0=Buffer.from([0,0,255,255]),xi=Symbol("permessage-deflate"),pr=Symbol("total-length"),Pn=Symbol("callback"),Lr=Symbol("buffers"),Rn=Symbol("error"),bi,na=class{constructor(e,t,n){if(this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!bi){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;bi=new e0(s)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Pn];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,n=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(n=>{let s=t[n];if(s.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(s=s[0],n==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else if(n==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=s})}),e}decompress(e,t,n){bi.add(s=>{this._decompress(e,t,(i,a)=>{s(),n(i,a)})})}compress(e,t,n){bi.add(s=>{this._compress(e,t,(i,a)=>{s(),n(i,a)})})}_decompress(e,t,n){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,a=typeof this.params[i]!="number"?fs.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=fs.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[xi]=this,this._inflate[pr]=0,this._inflate[Lr]=[],this._inflate.on("error",s0),this._inflate.on("data",Du)}this._inflate[Pn]=n,this._inflate.write(e),t&&this._inflate.write(r0),this._inflate.flush(()=>{let i=this._inflate[Rn];if(i){this._inflate.close(),this._inflate=null,n(i);return}let a=Lu.concat(this._inflate[Lr],this._inflate[pr]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[pr]=0,this._inflate[Lr]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),n(null,a)})}_compress(e,t,n){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,a=typeof this.params[i]!="number"?fs.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=fs.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[pr]=0,this._deflate[Lr]=[],this._deflate.on("data",n0)}this._deflate[Pn]=n,this._deflate.write(e),this._deflate.flush(fs.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Lu.concat(this._deflate[Lr],this._deflate[pr]);t&&(i=new t0(i.buffer,i.byteOffset,i.length-4)),this._deflate[Pn]=null,this._deflate[pr]=0,this._deflate[Lr]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};Fu.exports=na;function n0(r){this[Lr].push(r),this[pr]+=r.length}function Du(r){if(this[pr]+=r.length,this[xi]._maxPayload<1||this[pr]<=this[xi]._maxPayload){this[Lr].push(r);return}this[Rn]=new RangeError("Max payload size exceeded"),this[Rn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Rn][Nu]=1009,this.removeListener("data",Du),this.reset()}function s0(r){if(this[xi]._inflate=null,this[Rn]){this[Pn](this[Rn]);return}r[Nu]=1007,this[Pn](r)}});var An=F((Fv,Si)=>{"use strict";var{isUtf8:Mu}=require("buffer"),{hasBlob:i0}=dr(),o0=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a0(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function sa(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function c0(r){return i0&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}Si.exports={isBlob:c0,isValidStatusCode:a0,isValidUTF8:sa,tokenChars:o0};if(Mu)Si.exports.isValidUTF8=function(r){return r.length<24?sa(r):Mu(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");Si.exports.isValidUTF8=function(e){return e.length<32?sa(e):r(e)}}catch{}});var fa=F((Mv,Vu)=>{"use strict";var{Writable:f0}=require("stream"),Bu=us(),{BINARY_TYPES:u0,EMPTY_BUFFER:ju,kStatusCode:l0,kWebSocket:h0}=dr(),{concat:ia,toArrayBuffer:d0,unmask:p0}=cs(),{isValidStatusCode:g0,isValidUTF8:Uu}=An(),Ti=Buffer[Symbol.species],It=0,qu=1,Wu=2,Hu=3,oa=4,aa=5,Ci=6,ca=class extends f0{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||u0[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[h0]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=It}_write(e,t,n){if(this._opcode===8&&this._state==It)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new Ti(n.buffer,n.byteOffset+e,n.length-e),new Ti(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],s=t.length-e;e>=n.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),s),this._buffers[0]=new Ti(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case It:this.getInfo(e);break;case qu:this.getPayloadLength16(e);break;case Wu:this.getPayloadLength64(e);break;case Hu:this.getMask();break;case oa:this.getData(e);break;case aa:case Ci:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let n=(t[0]&64)===64;if(n&&!this._extensions[Bu.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=qu:this._payloadLength===127?this._state=Wu:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=Hu:this._state=oa}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=oa}getData(e){let t=ju;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&p0(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=aa,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Bu.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let a=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(a);return}this._fragments.push(i)}this.dataMessage(t),this._state===It&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=It;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=ia(n,t):this._binaryType==="arraybuffer"?s=d0(ia(n,t)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=It):(this._state=Ci,setImmediate(()=>{this.emit("message",s,!0),this._state=It,this.startLoop(e)}))}else{let s=ia(n,t);if(!this._skipUTF8Validation&&!Uu(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===aa||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=It):(this._state=Ci,setImmediate(()=>{this.emit("message",s,!1),this._state=It,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,ju),this.end();else{let n=e.readUInt16BE(0);if(!g0(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Ti(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Uu(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",n,s),this.end()}this._state=It;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=It):(this._state=Ci,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=It,this.startLoop(t)}))}createError(e,t,n,s,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[l0]=s,a}};Vu.exports=ca});var ha=F((jv,zu)=>{"use strict";var{Duplex:Bv}=require("stream"),{randomFillSync:m0}=require("crypto"),Ku=us(),{EMPTY_BUFFER:_0,kWebSocket:y0,NOOP:E0}=dr(),{isBlob:In,isValidStatusCode:v0}=An(),{mask:$u,toBuffer:Qr}=cs(),Lt=Symbol("kByteLength"),w0=Buffer.alloc(4),Oi=8*1024,en,Ln=Oi,jt=0,b0=1,x0=2,ua=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=jt,this.onerror=E0,this[y0]=void 0}static frame(e,t){let n,s=!1,i=2,a=!1;t.mask&&(n=t.maskBuffer||w0,t.generateMask?t.generateMask(n):(Ln===Oi&&(en===void 0&&(en=Buffer.alloc(Oi)),m0(en,0,Oi),Ln=0),n[0]=en[Ln++],n[1]=en[Ln++],n[2]=en[Ln++],n[3]=en[Ln++]),a=(n[0]|n[1]|n[2]|n[3])===0,i=6);let c;typeof e=="string"?(!t.mask||a)&&t[Lt]!==void 0?c=t[Lt]:(e=Buffer.from(e),c=e.length):(c=e.length,s=t.mask&&t.readOnly&&!a);let u=c;c>=65536?(i+=8,u=127):c>125&&(i+=2,u=126);let d=Buffer.allocUnsafe(s?c+i:i);return d[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(d[0]|=64),d[1]=u,u===126?d.writeUInt16BE(c,2):u===127&&(d[2]=d[3]=0,d.writeUIntBE(c,4,6)),t.mask?(d[1]|=128,d[i-4]=n[0],d[i-3]=n[1],d[i-2]=n[2],d[i-1]=n[3],a?[d,e]:s?($u(e,n,d,i,c),[d]):($u(e,n,e,0,c),[d,e])):[d,e]}close(e,t,n,s){let i;if(e===void 0)i=_0;else{if(typeof e!="number"||!v0(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let c=Buffer.byteLength(t);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+c),i.writeUInt16BE(e,0),typeof t=="string"?i.write(t,2):i.set(t,2)}}let a={[Lt]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==jt?this.enqueue([this.dispatch,i,!1,a,s]):this.sendFrame(r.frame(i,a),s)}ping(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):In(e)?(s=e.size,i=!1):(e=Qr(e),s=e.length,i=Qr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Lt]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};In(e)?this._state!==jt?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==jt?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(r.frame(e,a),n)}pong(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):In(e)?(s=e.size,i=!1):(e=Qr(e),s=e.length,i=Qr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Lt]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};In(e)?this._state!==jt?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==jt?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(r.frame(e,a),n)}send(e,t,n){let s=this._extensions[Ku.extensionName],i=t.binary?2:1,a=t.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):In(e)?(c=e.size,u=!1):(e=Qr(e),c=e.length,u=Qr.readOnly),this._firstFragment?(this._firstFragment=!1,a&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=c>=s._threshold),this._compress=a):(a=!1,i=0),t.fin&&(this._firstFragment=!0);let d={[Lt]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:u,rsv1:a};In(e)?this._state!==jt?this.enqueue([this.getBlobData,e,this._compress,d,n]):this.getBlobData(e,this._compress,d,n):this._state!==jt?this.enqueue([this.dispatch,e,this._compress,d,n]):this.dispatch(e,this._compress,d,n)}getBlobData(e,t,n,s){this._bufferedBytes+=n[Lt],this._state=x0,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(la,this,c,s);return}this._bufferedBytes-=n[Lt];let a=Qr(i);t?this.dispatch(a,t,n,s):(this._state=jt,this.sendFrame(r.frame(a,n),s),this.dequeue())}).catch(i=>{process.nextTick(S0,this,i,s)})}dispatch(e,t,n,s){if(!t){this.sendFrame(r.frame(e,n),s);return}let i=this._extensions[Ku.extensionName];this._bufferedBytes+=n[Lt],this._state=b0,i.compress(e,n.fin,(a,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");la(this,u,s);return}this._bufferedBytes-=n[Lt],this._state=jt,n.readOnly=!1,this.sendFrame(r.frame(c,n),s),this.dequeue()})}dequeue(){for(;this._state===jt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Lt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Lt],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};zu.exports=ua;function la(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let s=r._queue[n],i=s[s.length-1];typeof i=="function"&&i(e)}}function S0(r,e,t){la(r,e,t),r.onerror(e)}});var rl=F((Uv,tl)=>{"use strict";var{kForOnEventAttribute:ls,kListener:da}=dr(),Gu=Symbol("kCode"),Yu=Symbol("kData"),Xu=Symbol("kError"),Ju=Symbol("kMessage"),Zu=Symbol("kReason"),Nn=Symbol("kTarget"),Qu=Symbol("kType"),el=Symbol("kWasClean"),gr=class{constructor(e){this[Nn]=null,this[Qu]=e}get target(){return this[Nn]}get type(){return this[Qu]}};Object.defineProperty(gr.prototype,"target",{enumerable:!0});Object.defineProperty(gr.prototype,"type",{enumerable:!0});var tn=class extends gr{constructor(e,t={}){super(e),this[Gu]=t.code===void 0?0:t.code,this[Zu]=t.reason===void 0?"":t.reason,this[el]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Gu]}get reason(){return this[Zu]}get wasClean(){return this[el]}};Object.defineProperty(tn.prototype,"code",{enumerable:!0});Object.defineProperty(tn.prototype,"reason",{enumerable:!0});Object.defineProperty(tn.prototype,"wasClean",{enumerable:!0});var Dn=class extends gr{constructor(e,t={}){super(e),this[Xu]=t.error===void 0?null:t.error,this[Ju]=t.message===void 0?"":t.message}get error(){return this[Xu]}get message(){return this[Ju]}};Object.defineProperty(Dn.prototype,"error",{enumerable:!0});Object.defineProperty(Dn.prototype,"message",{enumerable:!0});var hs=class extends gr{constructor(e,t={}){super(e),this[Yu]=t.data===void 0?null:t.data}get data(){return this[Yu]}};Object.defineProperty(hs.prototype,"data",{enumerable:!0});var T0={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[ls]&&s[da]===e&&!s[ls])return;let n;if(r==="message")n=function(i,a){let c=new hs("message",{data:a?i:i.toString()});c[Nn]=this,ki(e,this,c)};else if(r==="close")n=function(i,a){let c=new tn("close",{code:i,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[Nn]=this,ki(e,this,c)};else if(r==="error")n=function(i){let a=new Dn("error",{error:i,message:i.message});a[Nn]=this,ki(e,this,a)};else if(r==="open")n=function(){let i=new gr("open");i[Nn]=this,ki(e,this,i)};else return;n[ls]=!!t[ls],n[da]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[da]===e&&!t[ls]){this.removeListener(r,t);break}}};tl.exports={CloseEvent:tn,ErrorEvent:Dn,Event:gr,EventTarget:T0,MessageEvent:hs};function ki(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var pa=F((qv,nl)=>{"use strict";var{tokenChars:ds}=An();function Qt(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function C0(r){let e=Object.create(null),t=Object.create(null),n=!1,s=!1,i=!1,a,c,u=-1,d=-1,g=-1,m=0;for(;m<r.length;m++)if(d=r.charCodeAt(m),a===void 0)if(g===-1&&ds[d]===1)u===-1&&(u=m);else if(m!==0&&(d===32||d===9))g===-1&&u!==-1&&(g=m);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${m}`);g===-1&&(g=m);let w=r.slice(u,g);d===44?(Qt(e,w,t),t=Object.create(null)):a=w,u=g=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);else if(c===void 0)if(g===-1&&ds[d]===1)u===-1&&(u=m);else if(d===32||d===9)g===-1&&u!==-1&&(g=m);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${m}`);g===-1&&(g=m),Qt(t,r.slice(u,g),!0),d===44&&(Qt(e,a,t),t=Object.create(null),a=void 0),u=g=-1}else if(d===61&&u!==-1&&g===-1)c=r.slice(u,m),u=g=-1;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(s){if(ds[d]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);u===-1?u=m:n||(n=!0),s=!1}else if(i)if(ds[d]===1)u===-1&&(u=m);else if(d===34&&u!==-1)i=!1,g=m;else if(d===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(d===34&&r.charCodeAt(m-1)===61)i=!0;else if(g===-1&&ds[d]===1)u===-1&&(u=m);else if(u!==-1&&(d===32||d===9))g===-1&&(g=m);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${m}`);g===-1&&(g=m);let w=r.slice(u,g);n&&(w=w.replace(/\\/g,""),n=!1),Qt(t,c,w),d===44&&(Qt(e,a,t),t=Object.create(null),a=void 0),c=void 0,u=g=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);if(u===-1||i||d===32||d===9)throw new SyntaxError("Unexpected end of input");g===-1&&(g=m);let y=r.slice(u,g);return a===void 0?Qt(e,y,t):(c===void 0?Qt(t,y,!0):n?Qt(t,c,y.replace(/\\/g,"")):Qt(t,c,y),Qt(e,a,t)),e}function O0(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(s=>{let i=n[s];return Array.isArray(i)||(i=[i]),i.map(a=>a===!0?s:`${s}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}nl.exports={format:O0,parse:C0}});var Ii=F((Vv,gl)=>{"use strict";var k0=require("events"),P0=require("https"),R0=require("http"),ol=require("net"),A0=require("tls"),{randomBytes:I0,createHash:L0}=require("crypto"),{Duplex:Wv,Readable:Hv}=require("stream"),{URL:ga}=require("url"),Nr=us(),N0=fa(),D0=ha(),{isBlob:F0}=An(),{BINARY_TYPES:sl,EMPTY_BUFFER:Pi,GUID:M0,kForOnEventAttribute:ma,kListener:B0,kStatusCode:j0,kWebSocket:nt,NOOP:al}=dr(),{EventTarget:{addEventListener:U0,removeEventListener:q0}}=rl(),{format:W0,parse:H0}=pa(),{toBuffer:V0}=cs(),K0=30*1e3,cl=Symbol("kAborted"),_a=[8,13],mr=["CONNECTING","OPEN","CLOSING","CLOSED"],$0=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Ue=class r extends k0{constructor(e,t,n){super(),this._binaryType=sl[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Pi,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(n=t,t=[]):t=[t]),fl(this,e,t,n)):(this._autoPong=n.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){sl.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,n){let s=new N0({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new D0(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[nt]=this,i[nt]=this,e[nt]=this,s.on("conclude",Y0),s.on("drain",X0),s.on("error",J0),s.on("message",Z0),s.on("ping",Q0),s.on("pong",em),i.onerror=tm,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",hl),e.on("data",Ai),e.on("end",dl),e.on("error",pl),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Nr.extensionName]&&this._extensions[Nr.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Tt(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ll(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){ya(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Pi,t,n)}pong(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){ya(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Pi,t,n)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(n=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){ya(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Nr.extensionName]||(s.compress=!1),this._sender.send(e||Pi,s,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Tt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(Ue,"CONNECTING",{enumerable:!0,value:mr.indexOf("CONNECTING")});Object.defineProperty(Ue.prototype,"CONNECTING",{enumerable:!0,value:mr.indexOf("CONNECTING")});Object.defineProperty(Ue,"OPEN",{enumerable:!0,value:mr.indexOf("OPEN")});Object.defineProperty(Ue.prototype,"OPEN",{enumerable:!0,value:mr.indexOf("OPEN")});Object.defineProperty(Ue,"CLOSING",{enumerable:!0,value:mr.indexOf("CLOSING")});Object.defineProperty(Ue.prototype,"CLOSING",{enumerable:!0,value:mr.indexOf("CLOSING")});Object.defineProperty(Ue,"CLOSED",{enumerable:!0,value:mr.indexOf("CLOSED")});Object.defineProperty(Ue.prototype,"CLOSED",{enumerable:!0,value:mr.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(Ue.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(Ue.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[ma])return e[B0];return null},set(e){for(let t of this.listeners(r))if(t[ma]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[ma]:!0})}})});Ue.prototype.addEventListener=U0;Ue.prototype.removeEventListener=q0;gl.exports=Ue;function fl(r,e,t,n){let s={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:_a[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=s.autoPong,!_a.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${_a.join(", ")})`);let i;if(e instanceof ga)i=e;else try{i=new ga(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),r._url=i.href;let a=i.protocol==="wss:",c=i.protocol==="ws+unix:",u;if(i.protocol!=="ws:"&&!a&&!c?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!i.pathname?u="The URL's pathname is empty":i.hash&&(u="The URL contains a fragment identifier"),u){let C=new SyntaxError(u);if(r._redirects===0)throw C;Ri(r,C);return}let d=a?443:80,g=I0(16).toString("base64"),m=a?P0.request:R0.request,y=new Set,w;if(s.createConnection=s.createConnection||(a?G0:z0),s.defaultPort=s.defaultPort||d,s.port=i.port||d,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":g,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(w=new Nr(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=W0({[Nr.extensionName]:w.offer()})),t.length){for(let C of t){if(typeof C!="string"||!$0.test(C)||y.has(C))throw new SyntaxError("An invalid or duplicated subprotocol was specified");y.add(C)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),c){let C=s.path.split(":");s.socketPath=C[0],s.path=C[1]}let S;if(s.followRedirects){if(r._redirects===0){r._originalIpc=c,r._originalSecure=a,r._originalHostOrSocketPath=c?s.socketPath:i.host;let C=n&&n.headers;if(n={...n,headers:{}},C)for(let[V,de]of Object.entries(C))n.headers[V.toLowerCase()]=de}else if(r.listenerCount("redirect")===0){let C=c?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!C||r._originalSecure&&!a)&&(delete s.headers.authorization,delete s.headers.cookie,C||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),S=r._req=m(s),r._redirects&&r.emit("redirect",r.url,S)}else S=r._req=m(s);s.timeout&&S.on("timeout",()=>{Tt(r,S,"Opening handshake has timed out")}),S.on("error",C=>{S===null||S[cl]||(S=r._req=null,Ri(r,C))}),S.on("response",C=>{let V=C.headers.location,de=C.statusCode;if(V&&s.followRedirects&&de>=300&&de<400){if(++r._redirects>s.maxRedirects){Tt(r,S,"Maximum redirects exceeded");return}S.abort();let B;try{B=new ga(V,e)}catch{let L=new SyntaxError(`Invalid URL: ${V}`);Ri(r,L);return}fl(r,B,t,n)}else r.emit("unexpected-response",S,C)||Tt(r,S,`Unexpected server response: ${C.statusCode}`)}),S.on("upgrade",(C,V,de)=>{if(r.emit("upgrade",C),r.readyState!==Ue.CONNECTING)return;S=r._req=null;let B=C.headers.upgrade;if(B===void 0||B.toLowerCase()!=="websocket"){Tt(r,V,"Invalid Upgrade header");return}let P=L0("sha1").update(g+M0).digest("base64");if(C.headers["sec-websocket-accept"]!==P){Tt(r,V,"Invalid Sec-WebSocket-Accept header");return}let L=C.headers["sec-websocket-protocol"],Q;if(L!==void 0?y.size?y.has(L)||(Q="Server sent an invalid subprotocol"):Q="Server sent a subprotocol but none was requested":y.size&&(Q="Server sent no subprotocol"),Q){Tt(r,V,Q);return}L&&(r._protocol=L);let j=C.headers["sec-websocket-extensions"];if(j!==void 0){if(!w){Tt(r,V,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let Z;try{Z=H0(j)}catch{Tt(r,V,"Invalid Sec-WebSocket-Extensions header");return}let pe=Object.keys(Z);if(pe.length!==1||pe[0]!==Nr.extensionName){Tt(r,V,"Server indicated an extension that was not requested");return}try{w.accept(Z[Nr.extensionName])}catch{Tt(r,V,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Nr.extensionName]=w}r.setSocket(V,de,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(S,r):S.end()}function Ri(r,e){r._readyState=Ue.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function z0(r){return r.path=r.socketPath,ol.connect(r)}function G0(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=ol.isIP(r.host)?"":r.host),A0.connect(r)}function Tt(r,e,t){r._readyState=Ue.CLOSING;let n=new Error(t);Error.captureStackTrace(n,Tt),e.setHeader?(e[cl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Ri,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function ya(r,e,t){if(e){let n=F0(e)?e.size:V0(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${mr[r.readyState]})`);process.nextTick(t,n)}}function Y0(r,e){let t=this[nt];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[nt]!==void 0&&(t._socket.removeListener("data",Ai),process.nextTick(ul,t._socket),r===1005?t.close():t.close(r,e))}function X0(){let r=this[nt];r.isPaused||r._socket.resume()}function J0(r){let e=this[nt];e._socket[nt]!==void 0&&(e._socket.removeListener("data",Ai),process.nextTick(ul,e._socket),e.close(r[j0])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function il(){this[nt].emitClose()}function Z0(r,e){this[nt].emit("message",r,e)}function Q0(r){let e=this[nt];e._autoPong&&e.pong(r,!this._isServer,al),e.emit("ping",r)}function em(r){this[nt].emit("pong",r)}function ul(r){r.resume()}function tm(r){let e=this[nt];e.readyState!==Ue.CLOSED&&(e.readyState===Ue.OPEN&&(e._readyState=Ue.CLOSING,ll(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function ll(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),K0)}function hl(){let r=this[nt];this.removeListener("close",hl),this.removeListener("data",Ai),this.removeListener("end",dl),r._readyState=Ue.CLOSING;let e;!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&(e=r._socket.read())!==null&&r._receiver.write(e),r._receiver.end(),this[nt]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",il),r._receiver.on("finish",il))}function Ai(r){this[nt]._receiver.write(r)||this.pause()}function dl(){let r=this[nt];r._readyState=Ue.CLOSING,r._receiver.end(),this.end()}function pl(){let r=this[nt];this.removeListener("error",pl),this.on("error",al),r&&(r._readyState=Ue.CLOSING,this.destroy())}});var El=F(($v,yl)=>{"use strict";var Kv=Ii(),{Duplex:rm}=require("stream");function ml(r){r.emit("close")}function nm(){!this.destroyed&&this._writableState.finished&&this.destroy()}function _l(r){this.removeListener("error",_l),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function sm(r,e){let t=!0,n=new rm({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(i,a){let c=!a&&n._readableState.objectMode?i.toString():i;n.push(c)||r.pause()}),r.once("error",function(i){n.destroyed||(t=!1,n.destroy(i))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(s,i){if(r.readyState===r.CLOSED){i(s),process.nextTick(ml,n);return}let a=!1;r.once("error",function(u){a=!0,i(u)}),r.once("close",function(){a||i(s),process.nextTick(ml,n)}),t&&r.terminate()},n._final=function(s){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(s)});return}r._socket!==null&&(r._socket._writableState.finished?(s(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){s()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(s,i,a){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(s,i,a)});return}r.send(s,a)},n.on("end",nm),n.on("error",_l),n}yl.exports=sm});var wl=F((zv,vl)=>{"use strict";var{tokenChars:im}=An();function om(r){let e=new Set,t=-1,n=-1,s=0;for(s;s<r.length;s++){let a=r.charCodeAt(s);if(n===-1&&im[a]===1)t===-1&&(t=s);else if(s!==0&&(a===32||a===9))n===-1&&t!==-1&&(n=s);else if(a===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);n===-1&&(n=s);let c=r.slice(t,n);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);e.add(c),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=r.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}vl.exports={parse:om}});var kl=F((Yv,Ol)=>{"use strict";var am=require("events"),Li=require("http"),{Duplex:Gv}=require("stream"),{createHash:cm}=require("crypto"),bl=pa(),rn=us(),fm=wl(),um=Ii(),{GUID:lm,kWebSocket:hm}=dr(),dm=/^[+/0-9A-Za-z]{22}==$/,xl=0,Sl=1,Cl=2,Ea=class extends am{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:um,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Li.createServer((n,s)=>{let i=Li.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=pm(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,a)=>{this.handleUpgrade(s,i,a,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=xl}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Cl){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ps,this);return}if(e&&this.once("close",e),this._state!==Sl)if(this._state=Sl,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(ps,this):process.nextTick(ps,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{ps(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,s){t.on("error",Tl);let i=e.headers["sec-websocket-key"],a=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){nn(this,e,t,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){nn(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!dm.test(i)){nn(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){nn(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){gs(t,400);return}let u=e.headers["sec-websocket-protocol"],d=new Set;if(u!==void 0)try{d=fm.parse(u)}catch{nn(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let g=e.headers["sec-websocket-extensions"],m={};if(this.options.perMessageDeflate&&g!==void 0){let y=new rn(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let w=bl.parse(g);w[rn.extensionName]&&(y.accept(w[rn.extensionName]),m[rn.extensionName]=y)}catch{nn(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let y={origin:e.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(y,(w,S,C,V)=>{if(!w)return gs(t,S||401,C,V);this.completeUpgrade(m,i,d,e,t,n,s)});return}if(!this.options.verifyClient(y))return gs(t,401)}this.completeUpgrade(m,i,d,e,t,n,s)}completeUpgrade(e,t,n,s,i,a,c){if(!i.readable||!i.writable)return i.destroy();if(i[hm])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>xl)return gs(i,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${cm("sha1").update(t+lm).digest("base64")}`],g=new this.options.WebSocket(null,void 0,this.options);if(n.size){let m=this.options.handleProtocols?this.options.handleProtocols(n,s):n.values().next().value;m&&(d.push(`Sec-WebSocket-Protocol: ${m}`),g._protocol=m)}if(e[rn.extensionName]){let m=e[rn.extensionName].params,y=bl.format({[rn.extensionName]:[m]});d.push(`Sec-WebSocket-Extensions: ${y}`),g._extensions=e}this.emit("headers",d,s),i.write(d.concat(`\r
|
|
21
21
|
`).join(`\r
|
|
22
|
-
`)),i.removeListener("error",
|
|
22
|
+
`)),i.removeListener("error",Tl),g.setSocket(i,a,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(g),g.on("close",()=>{this.clients.delete(g),this._shouldEmitClose&&!this.clients.size&&process.nextTick(ps,this)})),c(g,s)}};Ol.exports=Ea;function pm(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let n of Object.keys(e))r.removeListener(n,e[n])}}function ps(r){r._state=Cl,r.emit("close")}function Tl(){this.destroy()}function gs(r,e,t,n){t=t||Li.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...n},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${Li.STATUS_CODES[e]}\r
|
|
23
23
|
`+Object.keys(n).map(s=>`${s}: ${n[s]}`).join(`\r
|
|
24
24
|
`)+`\r
|
|
25
25
|
\r
|
|
26
|
-
`+t)}function nn(r,e,t,n,s,i){if(r.listenerCount("wsClientError")){let a=new Error(s);Error.captureStackTrace(a,nn),r.emit("wsClientError",a,t,e)}else ps(t,n,s,i)}});var kl=D((Vw,Ol)=>{"use strict";var mr=Ai();mr.createWebSocketStream=ml();mr.Server=Cl();mr.Receiver=ca();mr.Sender=la();mr.WebSocket=mr;mr.WebSocketServer=mr.Server;Ol.exports=mr});var ba=D(Nr=>{"use strict";var u_=Nr&&Nr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Nr,"__esModule",{value:!0});Nr.WS=Nr.BaseWS=void 0;var l_=os(),Pl=Jr(),h_=xn(),wa=Xr(),d_=u_(Rt()),p_=(0,d_.default)("engine.io-client:websocket"),Rl=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Li=class extends l_.Transport{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,n=Rl?{}:(0,Pl.pick)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(s){return this.emitReserved("error",s)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],s=t===e.length-1;(0,h_.encodePacket)(n,this.supportsBinary,i=>{try{this.doWrite(n,i)}catch{p_("websocket closed before onclose event")}s&&(0,wa.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=(0,Pl.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}};Nr.BaseWS=Li;var Ea=wa.globalThisShim.WebSocket||wa.globalThisShim.MozWebSocket,va=class extends Li{createSocket(e,t,n){return Rl?new Ea(e,t,n):t?new Ea(e,t):new Ea(e)}doWrite(e,t){this.ws.send(t)}};Nr.WS=va});var Sa=D(er=>{"use strict";var g_=er&&er.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),__=er&&er.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),m_=er&&er.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&g_(e,r,t);return __(e,r),e};Object.defineProperty(er,"__esModule",{value:!0});er.WS=void 0;var y_=m_(kl()),E_=ba(),xa=class extends E_.BaseWS{createSocket(e,t,n){var s;if(!((s=this.socket)===null||s===void 0)&&s._cookieJar){n.headers=n.headers||{},n.headers.cookie=typeof n.headers.cookie=="string"?[n.headers.cookie]:n.headers.cookie||[];for(let[i,a]of this.socket._cookieJar.cookies)n.headers.cookie.push(`${i}=${a.value}`)}return new y_.WebSocket(e,t,n)}doWrite(e,t){let n={};e.options&&(n.compress=e.options.compress),this.opts.perMessageDeflate&&(typeof t=="string"?Buffer.byteLength(t):t.length)<this.opts.perMessageDeflate.threshold&&(n.compress=!1),this.ws.send(t,n)}};er.WS=xa});var Ca=D(Fn=>{"use strict";var w_=Fn&&Fn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Fn,"__esModule",{value:!0});Fn.WT=void 0;var v_=os(),b_=Xr(),Al=xn(),x_=w_(Rt()),gs=(0,x_.default)("engine.io-client:webtransport"),Ta=class extends v_.Transport{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{gs("transport closed gracefully"),this.onClose()}).catch(e=>{gs("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=(0,Al.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),s=(0,Al.createPacketEncoderStream)();s.readable.pipeTo(e.writable),this._writer=s.writable.getWriter();let i=()=>{n.read().then(({done:c,value:u})=>{if(c){gs("session is closed");return}gs("received chunk: %o",u),this.onPacket(u),i()}).catch(c=>{gs("an error occurred while reading: %s",c)})};i();let a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],s=t===e.length-1;this._writer.write(n).then(()=>{s&&(0,b_.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};Fn.WT=Ta});var Oa=D(Ni=>{"use strict";Object.defineProperty(Ni,"__esModule",{value:!0});Ni.transports=void 0;var S_=Jo(),T_=Sa(),C_=Ca();Ni.transports={websocket:T_.WS,webtransport:C_.WT,polling:S_.XHR}});var Pa=D(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.parse=P_;var O_=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,k_=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function P_(r){if(r.length>8e3)throw"URI too long";let e=r,t=r.indexOf("["),n=r.indexOf("]");t!=-1&&n!=-1&&(r=r.substring(0,t)+r.substring(t,n).replace(/:/g,";")+r.substring(n,r.length));let s=O_.exec(r||""),i={},a=14;for(;a--;)i[k_[a]]=s[a]||"";return t!=-1&&n!=-1&&(i.source=e,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=R_(i,i.path),i.queryKey=A_(i,i.query),i}function R_(r,e){let t=/\/{2,9}/g,n=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&n.splice(0,1),e.slice(-1)=="/"&&n.splice(n.length-1,1),n}function A_(r,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,s,i){s&&(t[s]=i)}),t}});var La=D(tr=>{"use strict";var I_=tr&&tr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(tr,"__esModule",{value:!0});tr.Socket=tr.SocketWithUpgrade=tr.SocketWithoutUpgrade=void 0;var L_=Oa(),Il=Jr(),N_=jo(),Ll=Pa(),D_=Yr(),Nl=xn(),Ra=Xr(),F_=I_(Rt()),Ne=(0,F_.default)("engine.io-client:socket"),Aa=typeof addEventListener=="function"&&typeof removeEventListener=="function",_s=[];Aa&&addEventListener("offline",()=>{Ne("closing %d connection(s) because the network was lost",_s.length),_s.forEach(r=>r())},!1);var sn=class r extends D_.Emitter{constructor(e,t){if(super(),this.binaryType=Ra.defaultBinaryType,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){let n=(0,Ll.parse)(e);t.hostname=n.host,t.secure=n.protocol==="https"||n.protocol==="wss",t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=(0,Ll.parse)(t.host).host);(0,Il.installTimerFunctions)(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(n=>{let s=n.prototype.name;this.transports.push(s),this._transportsByName[s]=n}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=(0,N_.decode)(this.opts.query)),Aa&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(Ne("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},_s.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,Ra.createCookieJar)()),this._open()}createTransport(e){Ne('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=Nl.protocol,t.transport=e,this.id&&(t.sid=this.id);let n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return Ne("options: %j",n),new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let e=this.opts.rememberUpgrade&&r.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){Ne("setting transport %s",e.name),this.transport&&(Ne("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){Ne("socket open"),this.readyState="open",r.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(Ne('socket receive: type "%s", data "%s"',e.type,e.data),this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}else Ne('packet received with socket readyState "%s"',this.readyState)}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();Ne("flushing %d packets in socket",e.length),this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let n=0;n<this.writeBuffer.length;n++){let s=this.writeBuffer[n].data;if(s&&(t+=(0,Il.byteLength)(s)),n>0&&t>this._maxPayload)return Ne("only send %d out of %d packets",n,this.writeBuffer.length),this.writeBuffer.slice(0,n);t+=2}return Ne("payload size is %d (max: %d)",t,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(Ne("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,Ra.nextTick)(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,s){if(typeof t=="function"&&(s=t,t=void 0),typeof n=="function"&&(s=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;let i={type:e,data:t,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),s&&this.once("flush",s),this.flush()}close(){let e=()=>{this._onClose("forced close"),Ne("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(Ne("socket error %j",e),r.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return Ne("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(Ne('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Aa&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let n=_s.indexOf(this._offlineEventListener);n!==-1&&(Ne("removing listener for the 'offline' event"),_s.splice(n,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};tr.SocketWithoutUpgrade=sn;sn.protocol=Nl.protocol;var Di=class extends sn{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){Ne("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){Ne('probing transport "%s"',e);let t=this.createTransport(e),n=!1;sn.priorWebsocketSuccess=!1;let s=()=>{n||(Ne('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",_=>{if(!n)if(_.type==="pong"&&_.data==="probe"){if(Ne('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;sn.priorWebsocketSuccess=t.name==="websocket",Ne('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{n||this.readyState!=="closed"&&(Ne("changing transport and sending upgrade packet"),g(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{Ne('probe transport "%s" failed',e);let y=new Error("probe error");y.transport=t.name,this.emitReserved("upgradeError",y)}}))};function i(){n||(n=!0,g(),t.close(),t=null)}let a=_=>{let y=new Error("probe error: "+_);y.transport=t.name,i(),Ne('probe transport "%s" failed because of error: %s',e,_),this.emitReserved("upgradeError",y)};function c(){a("transport closed")}function u(){a("socket closed")}function d(_){t&&_.name!==t.name&&(Ne('"%s" works - aborting "%s"',_.name,t.name),i())}let g=()=>{t.removeListener("open",s),t.removeListener("error",a),t.removeListener("close",c),this.off("close",u),this.off("upgrading",d)};t.once("open",s),t.once("error",a),t.once("close",c),this.once("close",u),this.once("upgrading",d),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}};tr.SocketWithUpgrade=Di;var Ia=class extends Di{constructor(e,t={}){let n=typeof e=="object"?e:t;(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(s=>L_.transports[s]).filter(s=>!!s)),super(e,n)}};tr.Socket=Ia});var Dl=D(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});Fi.Fetch=void 0;var M_=$o(),Na=class extends M_.Polling{doPoll(){this._fetch().then(e=>{if(!e.ok)return this.onError("fetch read error",e.status,e);e.text().then(t=>this.onData(t))}).catch(e=>{this.onError("fetch read error",e)})}doWrite(e,t){this._fetch(e).then(n=>{if(!n.ok)return this.onError("fetch write error",n.status,n);t()}).catch(n=>{this.onError("fetch write error",n)})}_fetch(e){var t;let n=e!==void 0,s=new Headers(this.opts.extraHeaders);return n&&s.set("content-type","text/plain;charset=UTF-8"),(t=this.socket._cookieJar)===null||t===void 0||t.appendCookies(s),fetch(this.uri(),{method:n?"POST":"GET",body:n?e:null,headers:s,credentials:this.opts.withCredentials?"include":"omit"}).then(i=>{var a;return(a=this.socket._cookieJar)===null||a===void 0||a.parseCookies(i.headers.getSetCookie()),i})}};Fi.Fetch=Na});var Mi=D(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.WebTransport=Se.WebSocket=Se.NodeWebSocket=Se.XHR=Se.NodeXHR=Se.Fetch=Se.nextTick=Se.parse=Se.installTimerFunctions=Se.transports=Se.TransportError=Se.Transport=Se.protocol=Se.SocketWithUpgrade=Se.SocketWithoutUpgrade=Se.Socket=void 0;var Fl=La();Object.defineProperty(Se,"Socket",{enumerable:!0,get:function(){return Fl.Socket}});var Ml=La();Object.defineProperty(Se,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return Ml.SocketWithoutUpgrade}});Object.defineProperty(Se,"SocketWithUpgrade",{enumerable:!0,get:function(){return Ml.SocketWithUpgrade}});Se.protocol=Fl.Socket.protocol;var Bl=os();Object.defineProperty(Se,"Transport",{enumerable:!0,get:function(){return Bl.Transport}});Object.defineProperty(Se,"TransportError",{enumerable:!0,get:function(){return Bl.TransportError}});var B_=Oa();Object.defineProperty(Se,"transports",{enumerable:!0,get:function(){return B_.transports}});var j_=Jr();Object.defineProperty(Se,"installTimerFunctions",{enumerable:!0,get:function(){return j_.installTimerFunctions}});var U_=Pa();Object.defineProperty(Se,"parse",{enumerable:!0,get:function(){return U_.parse}});var q_=Xr();Object.defineProperty(Se,"nextTick",{enumerable:!0,get:function(){return q_.nextTick}});var W_=Dl();Object.defineProperty(Se,"Fetch",{enumerable:!0,get:function(){return W_.Fetch}});var H_=Jo();Object.defineProperty(Se,"NodeXHR",{enumerable:!0,get:function(){return H_.XHR}});var V_=Yo();Object.defineProperty(Se,"XHR",{enumerable:!0,get:function(){return V_.XHR}});var K_=Sa();Object.defineProperty(Se,"NodeWebSocket",{enumerable:!0,get:function(){return K_.WS}});var $_=ba();Object.defineProperty(Se,"WebSocket",{enumerable:!0,get:function(){return $_.WS}});var z_=Ca();Object.defineProperty(Se,"WebTransport",{enumerable:!0,get:function(){return z_.WT}})});var Ul=D(ms=>{"use strict";var G_=ms&&ms.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ms,"__esModule",{value:!0});ms.url=J_;var Y_=Mi(),X_=G_(Rt()),jl=(0,X_.default)("socket.io-client:url");function J_(r,e="",t){let n=r;t=t||typeof location<"u"&&location,r==null&&(r=t.protocol+"//"+t.host),typeof r=="string"&&(r.charAt(0)==="/"&&(r.charAt(1)==="/"?r=t.protocol+r:r=t.host+r),/^(https?|wss?):\/\//.test(r)||(jl("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),jl("parse %s",r),n=(0,Y_.parse)(r)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";let i=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+e,n.href=n.protocol+"://"+i+(t&&t.port===n.port?"":":"+n.port),n}});var Da=D(ji=>{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});ji.isBinary=Wl;ji.hasBinary=Bi;var Z_=typeof ArrayBuffer=="function",Q_=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,ql=Object.prototype.toString,em=typeof Blob=="function"||typeof Blob<"u"&&ql.call(Blob)==="[object BlobConstructor]",tm=typeof File=="function"||typeof File<"u"&&ql.call(File)==="[object FileConstructor]";function Wl(r){return Z_&&(r instanceof ArrayBuffer||Q_(r))||em&&r instanceof Blob||tm&&r instanceof File}function Bi(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,n=r.length;t<n;t++)if(Bi(r[t]))return!0;return!1}if(Wl(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return Bi(r.toJSON(),!0);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&Bi(r[t]))return!0;return!1}});var Hl=D(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.deconstructPacket=nm;Ui.reconstructPacket=sm;var rm=Da();function nm(r){let e=[],t=r.data,n=r;return n.data=Fa(t,e),n.attachments=e.length,{packet:n,buffers:e}}function Fa(r,e){if(!r)return r;if((0,rm.isBinary)(r)){let t={_placeholder:!0,num:e.length};return e.push(r),t}else if(Array.isArray(r)){let t=new Array(r.length);for(let n=0;n<r.length;n++)t[n]=Fa(r[n],e);return t}else if(typeof r=="object"&&!(r instanceof Date)){let t={};for(let n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=Fa(r[n],e));return t}return r}function sm(r,e){return r.data=Ma(r.data,e),delete r.attachments,r}function Ma(r,e){if(!r)return r;if(r&&r._placeholder===!0){if(typeof r.num=="number"&&r.num>=0&&r.num<e.length)return e[r.num];throw new Error("illegal attachments")}else if(Array.isArray(r))for(let t=0;t<r.length;t++)r[t]=Ma(r[t],e);else if(typeof r=="object")for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=Ma(r[t],e));return r}});var Wi=D(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.Decoder=jt.Encoder=jt.PacketType=jt.protocol=void 0;jt.isPacketValid=lm;var im=Yr(),Vl=Hl(),Kl=Da(),om=Rt(),Ba=(0,om.default)("socket.io-parser"),$l=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];jt.protocol=5;var Le;(function(r){r[r.CONNECT=0]="CONNECT",r[r.DISCONNECT=1]="DISCONNECT",r[r.EVENT=2]="EVENT",r[r.ACK=3]="ACK",r[r.CONNECT_ERROR=4]="CONNECT_ERROR",r[r.BINARY_EVENT=5]="BINARY_EVENT",r[r.BINARY_ACK=6]="BINARY_ACK"})(Le||(jt.PacketType=Le={}));var ja=class{constructor(e){this.replacer=e}encode(e){return Ba("encoding packet %j",e),(e.type===Le.EVENT||e.type===Le.ACK)&&(0,Kl.hasBinary)(e)?this.encodeAsBinary({type:e.type===Le.EVENT?Le.BINARY_EVENT:Le.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===Le.BINARY_EVENT||e.type===Le.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),Ba("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=(0,Vl.deconstructPacket)(e),n=this.encodeAsString(t.packet),s=t.buffers;return s.unshift(n),s}};jt.Encoder=ja;var Ua=class r extends im.Emitter{constructor(e){super(),this.reviver=e}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);let n=t.type===Le.BINARY_EVENT;n||t.type===Le.BINARY_ACK?(t.type=n?Le.EVENT:Le.ACK,this.reconstructor=new qa(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,Kl.isBinary)(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0,n={type:Number(e.charAt(0))};if(Le[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===Le.BINARY_EVENT||n.type===Le.BINARY_ACK){let i=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);let a=e.substring(i,t);if(a!=Number(a)||e.charAt(t)!=="-")throw new Error("Illegal attachments");n.attachments=Number(a)}if(e.charAt(t+1)==="/"){let i=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););n.nsp=e.substring(i,t)}else n.nsp="/";let s=e.charAt(t+1);if(s!==""&&Number(s)==s){let i=t+1;for(;++t;){let a=e.charAt(t);if(a==null||Number(a)!=a){--t;break}if(t===e.length)break}n.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){let i=this.tryParse(e.substr(t));if(r.isPayloadValid(n.type,i))n.data=i;else throw new Error("invalid payload")}return Ba("decoded %s as %j",e,n),n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case Le.CONNECT:return qi(t);case Le.DISCONNECT:return t===void 0;case Le.CONNECT_ERROR:return typeof t=="string"||qi(t);case Le.EVENT:case Le.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&$l.indexOf(t[0])===-1);case Le.ACK:case Le.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};jt.Decoder=Ua;var qa=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let t=(0,Vl.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function am(r){return typeof r=="string"}var cm=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function fm(r){return r===void 0||cm(r)}function qi(r){return Object.prototype.toString.call(r)==="[object Object]"}function um(r,e){switch(r){case Le.CONNECT:return e===void 0||qi(e);case Le.DISCONNECT:return e===void 0;case Le.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&$l.indexOf(e[0])===-1);case Le.ACK:return Array.isArray(e);case Le.CONNECT_ERROR:return typeof e=="string"||qi(e);default:return!1}}function lm(r){return am(r.nsp)&&fm(r.id)&&um(r.type,r.data)}});var Ha=D(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.on=hm;function hm(r,e,t){return r.on(e,t),function(){r.off(e,t)}}});var Ka=D(Mn=>{"use strict";var dm=Mn&&Mn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Mn,"__esModule",{value:!0});Mn.Socket=void 0;var Ut=Wi(),Hi=Ha(),pm=Yr(),gm=dm(Rt()),Je=(0,gm.default)("socket.io-client:socket"),_m=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Va=class extends pm.Emitter{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[(0,Hi.on)(e,"open",this.onopen.bind(this)),(0,Hi.on)(e,"packet",this.onpacket.bind(this)),(0,Hi.on)(e,"error",this.onerror.bind(this)),(0,Hi.on)(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,s,i;if(_m.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let a={type:Ut.PacketType.EVENT,data:t};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let g=this.ids++;Je("emitting packet with ack id %d",g);let _=t.pop();this._registerAckCallback(g,_),a.id=g}let c=(s=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||s===void 0?void 0:s.writable,u=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!c?Je("discard packet as the transport is not currently writable"):u?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a),this.flags={},this}_registerAckCallback(e,t){var n;let s=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(s===void 0){this.acks[e]=t;return}let i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===e&&(Je("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(c,1));Je("event with ack id %d has timed out after %d ms",e,s),t.call(this,new Error("operation has timed out"))},s),a=(...c)=>{this.io.clearTimeoutFn(i),t.apply(this,c)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((n,s)=>{let i=(a,c)=>a?s(a):n(c);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((s,...i)=>n!==this._queue[0]?Je("packet [%d] already acknowledged",n.id):(s!==null?n.tryCount>this._opts.retries&&(Je("packet [%d] is discarded after %d tries",n.id,n.tryCount),this._queue.shift(),t&&t(s)):(Je("packet [%d] was successfully sent",n.id),this._queue.shift(),t&&t(null,...i)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(Je("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){Je("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,Je("sending packet [%d] (try n\xB0%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){Je("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Ut.PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){Je("close (%s)",e),this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(n=>String(n.id)===e)){let n=this.acks[e];delete this.acks[e],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Ut.PacketType.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Ut.PacketType.EVENT:case Ut.PacketType.BINARY_EVENT:this.onevent(e);break;case Ut.PacketType.ACK:case Ut.PacketType.BINARY_ACK:this.onack(e);break;case Ut.PacketType.DISCONNECT:this.ondisconnect();break;case Ut.PacketType.CONNECT_ERROR:this.destroy();let n=new Error(e.data.message);n.data=e.data.data,this.emitReserved("connect_error",n);break}}onevent(e){let t=e.data||[];Je("emitting event %j",t),e.id!=null&&(Je("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,n=!1;return function(...s){n||(n=!0,Je("sending ack %j",s),t.packet({type:Ut.PacketType.ACK,id:e,data:s}))}}onack(e){let t=this.acks[e.id];if(typeof t!="function"){Je("bad ack %s",e.id);return}delete this.acks[e.id],Je("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){Je("socket connected with id %s",e),this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){Je("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(Je("performing disconnect (%s)",this.nsp),this.packet({type:Ut.PacketType.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let n of t)n.apply(this,e.data)}}};Mn.Socket=Va});var zl=D($a=>{"use strict";Object.defineProperty($a,"__esModule",{value:!0});$a.Backoff=Bn;function Bn(r){r=r||{},this.ms=r.min||100,this.max=r.max||1e4,this.factor=r.factor||2,this.jitter=r.jitter>0&&r.jitter<=1?r.jitter:0,this.attempts=0}Bn.prototype.duration=function(){var r=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*r);r=(Math.floor(e*10)&1)==0?r-t:r+t}return Math.min(r,this.max)|0};Bn.prototype.reset=function(){this.attempts=0};Bn.prototype.setMin=function(r){this.ms=r};Bn.prototype.setMax=function(r){this.max=r};Bn.prototype.setJitter=function(r){this.jitter=r}});var Gl=D(Lt=>{"use strict";var mm=Lt&&Lt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),ym=Lt&&Lt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Em=Lt&&Lt.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&mm(e,r,t);return ym(e,r),e},wm=Lt&&Lt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Lt,"__esModule",{value:!0});Lt.Manager=void 0;var za=Mi(),vm=Ka(),bm=Em(Wi()),on=Ha(),xm=zl(),Sm=Yr(),Tm=wm(Rt()),st=(0,Tm.default)("socket.io-client:manager"),Ga=class extends Sm.Emitter{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,(0,za.installTimerFunctions)(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((n=t.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new xm.Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;let s=t.parser||bm;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(st("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;st("opening %s",this.uri),this.engine=new za.Socket(this.uri,this.opts);let t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;let s=(0,on.on)(t,"open",function(){n.onopen(),e&&e()}),i=c=>{st("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},a=(0,on.on)(t,"error",i);if(this._timeout!==!1){let c=this._timeout;st("connect attempt will timeout after %d",c);let u=this.setTimeoutFn(()=>{st("connect attempt timed out after %d",c),s(),i(new Error("timeout")),t.close()},c);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(s),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){st("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push((0,on.on)(e,"ping",this.onping.bind(this)),(0,on.on)(e,"data",this.ondata.bind(this)),(0,on.on)(e,"error",this.onerror.bind(this)),(0,on.on)(e,"close",this.onclose.bind(this)),(0,on.on)(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){(0,za.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){st("error",e),this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new vm.Socket(this,e,t),this.nsps[e]=n),n}_destroy(e){let t=Object.keys(this.nsps);for(let n of t)if(this.nsps[n].active){st("socket %s is still active, skipping close",n);return}this._close()}_packet(e){st("writing packet %j",e);let t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){st("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){st("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;st("closed due to %s",e),this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)st("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();st("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(st("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(s=>{s?(st("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",s)):(st("reconnect success"),e.onreconnect())}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}};Lt.Manager=Ga});var Zl=D((Me,Jl)=>{"use strict";var Cm=Me&&Me.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Me,"__esModule",{value:!0});Me.WebTransport=Me.WebSocket=Me.NodeWebSocket=Me.XHR=Me.NodeXHR=Me.Fetch=Me.Socket=Me.Manager=Me.protocol=void 0;Me.io=an;Me.connect=an;Me.default=an;var Om=Ul(),Vi=Gl();Object.defineProperty(Me,"Manager",{enumerable:!0,get:function(){return Vi.Manager}});var Xl=Ka();Object.defineProperty(Me,"Socket",{enumerable:!0,get:function(){return Xl.Socket}});var km=Cm(Rt()),Yl=(0,km.default)("socket.io-client"),ys={};function an(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};let t=(0,Om.url)(r,e.path||"/socket.io"),n=t.source,s=t.id,i=t.path,a=ys[s]&&i in ys[s].nsps,c=e.forceNew||e["force new connection"]||e.multiplex===!1||a,u;return c?(Yl("ignoring socket cache for %s",n),u=new Vi.Manager(n,e)):(ys[s]||(Yl("new io instance for %s",n),ys[s]=new Vi.Manager(n,e)),u=ys[s]),t.query&&!e.query&&(e.query=t.queryKey),u.socket(t.path,e)}Object.assign(an,{Manager:Vi.Manager,Socket:Xl.Socket,io:an,connect:an});var Pm=Wi();Object.defineProperty(Me,"protocol",{enumerable:!0,get:function(){return Pm.protocol}});var jn=Mi();Object.defineProperty(Me,"Fetch",{enumerable:!0,get:function(){return jn.Fetch}});Object.defineProperty(Me,"NodeXHR",{enumerable:!0,get:function(){return jn.NodeXHR}});Object.defineProperty(Me,"XHR",{enumerable:!0,get:function(){return jn.XHR}});Object.defineProperty(Me,"NodeWebSocket",{enumerable:!0,get:function(){return jn.NodeWebSocket}});Object.defineProperty(Me,"WebSocket",{enumerable:!0,get:function(){return jn.WebSocket}});Object.defineProperty(Me,"WebTransport",{enumerable:!0,get:function(){return jn.WebTransport}});Jl.exports=an});var rh=D(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});Ki.WebSocketService=void 0;var Rm=Zl(),Ql=Gr(),eh=Ks(),th=Ws(),Ya=class{authService;cryptoService;config;logger;notification;deviceId;platform;socket=null;inputHandler=null;createTerminalHandler=null;getBufferHandler=null;redrawHandler=null;resizeHandler=null;reconnectHandlers=[];authFailureHandler=null;fileViewRequestHandler=null;fileListRequestHandler=null;fileDownloadRequestHandler=null;statusChangeHandler=null;agentNameSyncHandler=null;agentId=null;hasConnectedOnce=!1;isRemoteRename=!1;negotiatedCapabilities=[];HEARTBEAT_INTERVAL=3e4;HEARTBEAT_TIMEOUT=1e4;heartbeatTimer=null;pongTimer=null;lastPongTime=0;isManualDisconnect=!1;reconnectAttempts=0;reconnectTimer=null;networkCheckTimer=null;isOnline=!0;lastNetworkCheck=0;rekeyingTerminals=new Set;outputBuffer=new Map;OUTPUT_BUFFER_MAX_SIZE=1e3;RECONNECT_BASE_DELAY=1e3;RECONNECT_MAX_DELAY=3e4;RECONNECT_JITTER=.2;NETWORK_CHECK_INTERVAL=5e3;constructor(e,t,n,s,i,a,c="vscode"){this.authService=e,this.cryptoService=t,this.config=n,this.logger=s,this.notification=i,this.deviceId=a,this.platform=c}async connect(){let e=await this.authService.getAccessToken();if(!e)throw new Error("No access token available");this.isManualDisconnect=!1,this.stopReconnect(),this.reconnectAttempts=0,this.agentId=await this.authService.getAgentId();let t=(0,eh.getWsUrl)(this.config);this.logger.info("Connecting to WebSocket",t),this.statusChangeHandler?.("connecting");let n=await this.cryptoService.getPublicKey();return new Promise((s,i)=>{this.socket=(0,Rm.io)(`${t}/agent`,{auth:{token:e,protocolVersion:Ql.PROTOCOL_VERSION,deviceId:this.deviceId,platform:this.platform,capabilities:Ql.DEFAULT_CLIENT_CAPABILITIES,publicKey:n},transports:["websocket"],reconnection:!1}),this.socket.on("connect",()=>{if(this.logger.info("WebSocket connected"),this.reconnectAttempts=0,this.statusChangeHandler?.("connected",this.agentId??void 0),this.startHeartbeat(),this.cryptoService.cleanupAllStaleSessions(),this.hasConnectedOnce){this.logger.info("Reconnected - triggering workspace re-registration");for(let a of this.reconnectHandlers)a()}else this.hasConnectedOnce=!0,s()}),this.socket.on("error",a=>{this.logger.error(`Server error [${a.code}]: ${a.message}`),a.code==="E401"&&(this.logger.warn("Auth failure (E401)"),this.authFailureHandler?.())}),this.socket.on("disconnect",a=>{this.logger.warn("WebSocket disconnected",a),this.stopHeartbeat(),this.statusChangeHandler?.("disconnected"),this.isManualDisconnect||(a==="transport close"?(this.logger.info("Transport close - attempting immediate reconnect"),this.attemptReconnect(!0)):this.scheduleReconnect())}),this.socket.on("protocol:info",a=>{this.logger.info("Protocol info received",a.protocolVersion),this.negotiatedCapabilities=a.negotiatedCapabilities,a.agentName&&this.config.getAgentName()!==a.agentName&&(this.isRemoteRename=!0,this.config.setAgentName(a.agentName).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(a.agentName),this.logger.info("Agent name synced from server",a.agentName))}),this.socket.on("pong",()=>{this.lastPongTime=Date.now(),this.clearPongTimeout(),this.logger.debug("Heartbeat pong received")}),this.socket.on("connect_error",a=>{this.logger.error("WebSocket connection error",a),this.statusChangeHandler?.("error"),this.hasConnectedOnce||i(a),this.scheduleReconnect()}),this.socket.on("terminal:input",a=>{this.handleTerminalInput(a)}),this.socket.on("crypto:keyExchange",async(a,c)=>{this.logger.info("Received key exchange request",a.terminalId,a.sessionId),this.rekeyingTerminals.add(a.terminalId),this.outputBuffer.set(a.terminalId,[]);try{if(await this.cryptoService.handleKeyExchange(a.terminalId,a.clientPublicKey,a.sessionId)){let d=await this.cryptoService.getPublicKey();c?.({success:!0,agentPublicKey:d||void 0}),this.flushOutputBuffer(a.terminalId)}else c?.({success:!1,error:"Key exchange failed"})}catch(u){this.logger.error("Key exchange error",u),c?.({success:!1,error:String(u)})}finally{this.rekeyingTerminals.delete(a.terminalId),this.outputBuffer.delete(a.terminalId)}}),this.socket.on("crypto:sessionCleanup",a=>{this.cryptoService.removeSession(a.terminalId,a.sessionId)}),this.socket.on("agent:keyExchangeRequest",async a=>{try{let c=await this.cryptoService.handleAgentKeyExchange(a.clientPublicKey,a.sessionId),u={agentId:a.agentId,sessionId:a.sessionId,ok:c,error:c?void 0:"Key exchange failed"};this.socket?.emit("agent:keyExchangeAck",u)}catch(c){this.logger.error("Agent key exchange error",c);let u={agentId:a.agentId,sessionId:a.sessionId,ok:!1,error:String(c)};this.socket?.emit("agent:keyExchangeAck",u)}}),this.socket.on("agent:sessionEnd",a=>{this.cryptoService.removeAgentSession(a.sessionId)}),this.socket.on("agent:renamed",a=>{this.logger.info("Agent renamed from web client",a.name),this.isRemoteRename=!0,this.config.setAgentName(a.name).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(a.name)}),this.socket.on("terminal:createRequest",a=>{this.createTerminalHandler?.(a.name)}),this.socket.on("terminal:getBuffer",(a,c)=>{if(!this.getBufferHandler){c?.({success:!1,error:"Buffer handler not set"});return}let u=this.getBufferHandler(a.terminalId);if(u===null){c?.({success:!1,error:"Terminal not found"});return}let d=this.cryptoService.encryptOutput(a.terminalId,u);c?.(d?{success:!0,encrypted:d}:{success:!0,data:u}),this.redrawHandler?.(a.terminalId)}),this.socket.on("terminal:resize",a=>{this.resizeHandler?.(a.terminalId,a.cols,a.rows)}),this.socket.on("file:view",a=>{this.fileViewRequestHandler?.(a.terminalId,a.request)}),this.socket.on("file:list",a=>{this.fileListRequestHandler?.(a.terminalId,a.request)}),this.socket.on("file:download:request",a=>{this.fileDownloadRequestHandler?.(a.terminalId,a.path,a.requestId)})})}disconnect(){this.isManualDisconnect=!0,this.hasConnectedOnce=!1,this.stopReconnect(),this.stopHeartbeat(),this.cryptoService.clearAllSessions(),this.socket&&(this.logger.info("Disconnecting WebSocket"),this.socket.disconnect(),this.socket=null)}softDisconnect(){this.stopReconnect(),this.stopHeartbeat(),this.socket&&(this.logger.info("Soft disconnecting WebSocket (for reconnect)"),this.socket.disconnect(),this.socket=null)}getStatus(){return{connected:this.socket?.connected??!1,agentId:this.agentId}}onInput(e){this.inputHandler=e}onCreateTerminalRequest(e){this.createTerminalHandler=e}onGetBufferRequest(e){this.getBufferHandler=e}onRedrawRequest(e){this.redrawHandler=e}onResizeRequest(e){this.resizeHandler=e}onReconnect(e){this.reconnectHandlers.push(e)}onAuthFailure(e){this.authFailureHandler=e}onFileViewRequest(e){this.fileViewRequestHandler=e}onFileListRequest(e){this.fileListRequestHandler=e}onFileDownloadRequest(e){this.fileDownloadRequestHandler=e}onStatusChange(e){this.statusChangeHandler=e}onAgentNameSync(e){this.agentNameSyncHandler=e}async registerWorkspace(e){return this.emit("workspace:register",e)}async unregisterWorkspace(e){await this.emit("workspace:unregister",{instanceId:e})}async terminalCreated(e){return this.emit("terminal:created",e)}async terminalClosed(e){this.cryptoService.removeSession(e.terminalId),await this.emit("terminal:closed",e)}terminalNotFound(e){this.socket?.emit("terminal:notFound",{terminalId:e})}sendOutput(e,t,n){if(!this.socket?.connected)return;if(this.rekeyingTerminals.has(t)){let a=this.outputBuffer.get(t);a&&a.length<this.OUTPUT_BUFFER_MAX_SIZE&&a.push({instanceId:e,data:n});return}let s=this.cryptoService.encryptOutput(t,n),i={instanceId:e,terminalId:t,...s?{encrypted:s}:{data:n}};this.socket?.emit("terminal:output",i)}flushOutputBuffer(e){let t=this.outputBuffer.get(e);if(!(!t||t.length===0)){this.logger.info("Flushing output buffer after rekey",e,String(t.length));for(let{instanceId:n,data:s}of t){let i=this.cryptoService.encryptOutput(e,s),a={instanceId:n,terminalId:e,...i?{encrypted:i}:{data:s}};this.socket?.emit("terminal:output",a)}}}async updateStatus(e){await this.emit("terminal:status",e)}sendTerminalEvent(e,t,n){let s={instanceId:e,terminalId:t,event:n};this.socket?.emit("terminal:event",s)}hasCapability(e){return this.negotiatedCapabilities.includes(e)}sendFileChangedEvent(e,t,n){let s={instanceId:e,terminalId:t,event:n};this.socket?.emit("file:changed",s)}sendFileListResponse(e,t){let n={instanceId:e,response:t};this.socket?.emit("file:list:response",n)}sendAgentRename(e){this.socket?.emit("agent:rename",{name:e})}isRemoteRenameInProgress(){return this.isRemoteRename}getSocket(){return this.socket}emit(e,t){let n=(0,th.generateCorrelationId)(),s=t&&typeof t=="object"&&!Array.isArray(t)?{...t,_cid:n}:t;return(0,th.runWithCorrelation)(n,()=>new Promise((i,a)=>{if(!this.socket?.connected){a(new Error("WebSocket not connected"));return}this.socket.emit(e,s,c=>{c.success?i(c):a(new Error(c.error||"Unknown error"))})}))}startHeartbeat(){this.stopHeartbeat(),this.lastPongTime=Date.now(),this.heartbeatTimer=setInterval(()=>{if(!this.socket?.connected){this.stopHeartbeat();return}if(Date.now()-this.lastPongTime>this.HEARTBEAT_INTERVAL+this.HEARTBEAT_TIMEOUT){this.logger.warn("Heartbeat timeout"),this.socket.disconnect();return}this.socket.emit("ping"),this.pongTimer=setTimeout(()=>{this.logger.warn("Pong timeout - server not responding"),this.statusChangeHandler?.("error")},this.HEARTBEAT_TIMEOUT)},this.HEARTBEAT_INTERVAL)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.clearPongTimeout()}clearPongTimeout(){this.pongTimer&&(clearTimeout(this.pongTimer),this.pongTimer=null)}handleTerminalInput(e){let t;if(e.encrypted){let n=this.cryptoService.decryptInput(e.terminalId,e.encrypted);if(!n){this.logger.error("Failed to decrypt terminal input",e.terminalId);return}t=n}else if(e.data)t=Buffer.from(e.data,"base64").toString("utf8");else{this.logger.error("Invalid terminal input payload");return}this.inputHandler?.(e.terminalId,t,e.dbTerminalId)}hasE2ESession(e){return this.cryptoService.hasSession(e)}getReconnectDelay(){let e=Math.min(this.RECONNECT_BASE_DELAY*Math.pow(2,this.reconnectAttempts),this.RECONNECT_MAX_DELAY),t=1+(Math.random()*2-1)*this.RECONNECT_JITTER;return Math.floor(e*t)}scheduleReconnect(){if(this.isManualDisconnect)return;this.stopReconnect();let e=this.getReconnectDelay();if(this.logger.info("Scheduling reconnect",String(this.reconnectAttempts+1),"delay:",String(e)),!this.isOnline){this.statusChangeHandler?.("disconnected"),this.startNetworkCheck();return}this.statusChangeHandler?.("connecting"),this.reconnectTimer=setTimeout(()=>{this.attemptReconnect()},e)}async attemptReconnect(e=!1){if(this.isManualDisconnect||this.socket?.connected)return;let t=await this.authService.hasValidToken();if(!t){if(this.logger.info("Access token expired, attempting refresh"),!await this.authService.refreshAccessToken()){this.logger.info("Token refresh failed, stopping reconnect"),this.stopReconnect(),this.statusChangeHandler?.("disconnected"),this.notification.warn("Session expired. Please log in again."),this.authFailureHandler?.();return}t=!0}this.reconnectAttempts++;try{if(this.socket&&(this.socket.disconnect(),this.socket=null),!e&&!await this.checkNetwork()){this.isOnline=!1,this.scheduleReconnect();return}this.isOnline=!0,await this.connect(),this.reconnectAttempts=0}catch(n){this.logger.warn("Reconnect failed",n),this.statusChangeHandler?.("error"),this.scheduleReconnect()}}stopReconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stopNetworkCheck()}async checkNetwork(){let e=Date.now();if(e-this.lastNetworkCheck<1e3)return this.isOnline;this.lastNetworkCheck=e;try{let t=`${(0,eh.getApiUrl)(this.config)}/health`,n=new AbortController,s=setTimeout(()=>n.abort(),5e3),i=await fetch(t,{method:"GET",signal:n.signal});return clearTimeout(s),this.logger.debug("Network check OK",String(i.status)),!0}catch{return this.logger.debug("Network check failed (offline)"),!1}}startNetworkCheck(){this.stopNetworkCheck(),this.networkCheckTimer=setInterval(async()=>{if(this.isManualDisconnect){this.stopNetworkCheck();return}if(this.socket?.connected){this.stopNetworkCheck();return}let e=await this.checkNetwork();e&&!this.isOnline?(this.logger.info("Network restored! Triggering immediate reconnect"),this.isOnline=!0,this.stopNetworkCheck(),this.reconnectAttempts=0,this.attemptReconnect()):e&&this.isOnline?(this.stopNetworkCheck(),this.attemptReconnect()):e||(this.isOnline=!1)},this.NETWORK_CHECK_INTERVAL)}stopNetworkCheck(){this.networkCheckTimer&&(clearInterval(this.networkCheckTimer),this.networkCheckTimer=null)}};Ki.WebSocketService=Ya});var sh=D(rr=>{"use strict";var Am=rr&&rr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Im=rr&&rr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Ja=rr&&rr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[n.length]=s);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),s=0;s<n.length;s++)n[s]!=="default"&&Am(t,e,n[s]);return Im(t,e),t}})();Object.defineProperty(rr,"__esModule",{value:!0});rr.FileTransferService=void 0;var $i=Ja(require("fs")),Lm=Ja(require("path")),nh=Ja(require("crypto")),Be=Gr(),Xa=class{socket=null;activeTransfers=new Map;instanceId="";logger;fallbackDir;constructor(e,t="/tmp"){this.logger=e,this.fallbackDir=t}attach(e,t){this.socket=e,this.instanceId=t,this.setupEventHandlers(),this.logger.info("FileTransferService attached")}detach(){this.socket=null;for(let[e]of this.activeTransfers)this.cancelTransfer(e,"Disconnected");this.logger.info("FileTransferService detached")}async sendFile(e,t,n,s,i){let a=$i.readFileSync(t),c=t.split("/").pop()||"file";return this.initAndSendChunks(e,a,c,{mimeType:this.getMimeType(c),requestId:i,onProgress:n,onComplete:s})}async sendBuffer(e,t,n,s,i){return this.initAndSendChunks(e,t,n,{mimeType:s,purpose:i?.purpose,viewMetadata:i?.viewMetadata,requestId:i?.requestId,onProgress:i?.onProgress,onComplete:i?.onComplete})}async initAndSendChunks(e,t,n,s){if(!this.socket)throw new Error("Socket not connected");let i=t.length,a=(0,Be.calculateTotalChunks)(i),c=this.calculateChecksum(t),u=nh.randomUUID(),d={id:u,terminalId:e,filename:n,size:i,totalChunks:a,direction:Be.TransferDirection.DOWNLOAD,status:Be.TransferStatus.PENDING,deliveredChunks:new Set,pendingChunks:new Map,checksum:c,checksumAlgorithm:"sha256",onProgress:s.onProgress?(_,y)=>s.onProgress(u,_,y):void 0,onComplete:s.onComplete?(_,y)=>s.onComplete(u,_,y):void 0,ackTimeouts:new Map};d.chunks=[];for(let _=0;_<a;_++){let y=_*Be.CHUNK_SIZE,v=Math.min(y+Be.CHUNK_SIZE,i);d.chunks.push(t.subarray(y,v))}this.activeTransfers.set(u,d);let g={transferId:u,terminalId:e,filename:n,size:i,totalChunks:a,mimeType:s.mimeType||"application/octet-stream",checksum:c,direction:Be.TransferDirection.DOWNLOAD,instanceId:this.instanceId};return s.requestId&&(g.requestId=s.requestId),s.purpose&&(g.purpose=s.purpose),s.viewMetadata&&(g.viewMetadata=s.viewMetadata),new Promise((_,y)=>{this.socket.emit("file:init",g,v=>{v.accepted?(d.status=Be.TransferStatus.ACTIVE,this.startSendingChunks(u),_(u)):(this.activeTransfers.delete(u),y(new Error(v.error||"Transfer rejected")))})})}async receiveFile(e,t,n,s,i,a,c,u="sha256",d,g){let _={id:e,terminalId:t,filename:n,filePath:c,size:s,totalChunks:i,direction:Be.TransferDirection.UPLOAD,status:Be.TransferStatus.ACTIVE,deliveredChunks:new Set,pendingChunks:new Map,chunks:new Array(i).fill(null),checksum:a,checksumAlgorithm:u,onProgress:d?(y,v)=>d(e,y,v):void 0,onComplete:g?(y,v)=>g(e,y,v):void 0,ackTimeouts:new Map};this.activeTransfers.set(e,_)}cancelTransfer(e,t){let n=this.activeTransfers.get(e);if(n){for(let s of n.ackTimeouts.values())clearTimeout(s);if(n.status=Be.TransferStatus.CANCELLED,n.onComplete?.(!1,t),this.socket){let s={transferId:e,reason:t};this.socket.emit("file:cancel",s)}this.activeTransfers.delete(e)}}async resumeTransfer(e){let t=this.activeTransfers.get(e);!t||!this.socket||this.socket.emit("file:sync",{transferId:e},n=>{if(n.status===Be.TransferStatus.EXPIRED){t.onComplete?.(!1,"Transfer expired"),this.activeTransfers.delete(e);return}if(n.deliveredChunks)for(let s of n.deliveredChunks)t.deliveredChunks.add(s);if(t.direction===Be.TransferDirection.DOWNLOAD&&n.missingChunks){t.status=Be.TransferStatus.ACTIVE;for(let s of n.missingChunks)this.sendChunk(t,s)}})}getTransferStatus(e){return this.activeTransfers.get(e)?.status??null}getTransferProgress(e){let t=this.activeTransfers.get(e);return t?{delivered:t.deliveredChunks.size,total:t.totalChunks}:null}setupEventHandlers(){this.socket&&(this.socket.on("file:chunk",e=>{this.handleIncomingChunk(e)}),this.socket.on("file:chunk:ack",e=>{this.handleChunkAck(e)}),this.socket.on("file:complete",e=>{this.handleComplete(e)}),this.socket.on("file:progress",e=>{this.handleProgress(e)}),this.socket.on("file:init",(e,t)=>{this.handleIncomingFileInit(e,t)}),this.socket.on("file:cancel",e=>{let t=this.activeTransfers.get(e.transferId);if(t){for(let n of t.ackTimeouts.values())clearTimeout(n);t.status=Be.TransferStatus.CANCELLED,t.onComplete?.(!1,e.reason||"Cancelled by remote"),this.activeTransfers.delete(e.transferId)}}))}startSendingChunks(e){let t=this.activeTransfers.get(e);if(!(!t||!t.chunks))for(let n=0;n<Math.min(Be.WINDOW_SIZE,t.totalChunks);n++)t.deliveredChunks.has(n)||this.sendChunk(t,n)}sendChunk(e,t){if(!this.socket||!e.chunks)return;let n=e.chunks[t];if(!n)return;let s=e.pendingChunks.get(t),i={seq:t,data:n,retries:s?s.retries:0,sentAt:Date.now()};e.pendingChunks.set(t,i);let a={transferId:e.id,seq:t,data:n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)};this.socket.emit("file:chunk",a,u=>{u&&!u.success&&this.cancelTransfer(e.id,u.error||"Server rejected chunk")});let c=setTimeout(()=>{this.handleAckTimeout(e.id,t)},Be.ACK_TIMEOUT_MS);e.ackTimeouts.set(t,c)}handleChunkAck(e){let t=this.activeTransfers.get(e.transferId);if(!t||t.status===Be.TransferStatus.COMPLETED)return;let n=t.ackTimeouts.get(e.seq);n&&(clearTimeout(n),t.ackTimeouts.delete(e.seq)),t.deliveredChunks.add(e.seq),t.pendingChunks.delete(e.seq),t.onProgress?.(t.deliveredChunks.size,t.totalChunks);let s=e.seq+Be.WINDOW_SIZE;s<t.totalChunks&&!t.deliveredChunks.has(s)&&this.sendChunk(t,s),t.deliveredChunks.size===t.totalChunks&&this.finishSending(t)}handleAckTimeout(e,t){let n=this.activeTransfers.get(e);if(!n)return;let s=n.pendingChunks.get(t);s&&(s.retries<Be.MAX_RETRIES?(s.retries++,this.sendChunk(n,t)):this.cancelTransfer(e,"Max retries exceeded"))}finishSending(e){if(!this.socket)return;e.status=Be.TransferStatus.COMPLETED;let t={transferId:e.id,checksum:e.checksum};this.socket.emit("file:end",t)}handleIncomingChunk(e){let t=this.activeTransfers.get(e.transferId);if(!(!t||!t.chunks)){if(t.chunks[e.seq]=Buffer.from(e.data),t.deliveredChunks.add(e.seq),this.socket){let n={transferId:e.transferId,seq:e.seq};this.socket.emit("file:chunk:ack",n)}t.onProgress?.(t.deliveredChunks.size,t.totalChunks),t.deliveredChunks.size===t.totalChunks&&this.finishReceiving(t)}}finishReceiving(e){if(!e.chunks||!e.filePath)return;let t=Buffer.concat(e.chunks);if(this.calculateChecksum(t,e.checksumAlgorithm)!==e.checksum){e.status=Be.TransferStatus.FAILED,e.onComplete?.(!1,"Checksum mismatch"),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!1,error:"Checksum mismatch"});return}try{let s=Lm.dirname(e.filePath);$i.existsSync(s)||$i.mkdirSync(s,{recursive:!0}),$i.writeFileSync(e.filePath,t),e.status=Be.TransferStatus.COMPLETED,e.onComplete?.(!0),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!0})}catch(s){let i=s instanceof Error?s.message:String(s);e.status=Be.TransferStatus.FAILED,e.onComplete?.(!1,`Failed to save file: ${i}`),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!1,error:`Failed to save file: ${i}`})}this.activeTransfers.delete(e.id)}handleComplete(e){let t=this.activeTransfers.get(e.transferId);if(t){e.success?(t.status=Be.TransferStatus.COMPLETED,t.onComplete?.(!0)):(t.status=Be.TransferStatus.FAILED,t.onComplete?.(!1,e.error));for(let n of t.ackTimeouts.values())clearTimeout(n);this.activeTransfers.delete(e.transferId)}}handleProgress(e){let t=this.activeTransfers.get(e.transferId);t&&t.onProgress?.(e.deliveredChunks,e.totalChunks)}handleIncomingFileInit(e,t){let s=`${e.targetPath||this.fallbackDir}/${e.filename}`;this.receiveFile(e.transferId,e.terminalId,e.filename,e.size,e.totalChunks,e.checksum,s,e.checksumAlgorithm||"sha256").then(()=>t({accepted:!0})).catch(i=>t({accepted:!1,error:i.message}))}calculateChecksum(e,t="sha256"){return t==="fnv1a"?this.fnv1aHash(e):nh.createHash("sha256").update(e).digest("hex")}fnv1aHash(e){let t=2166136261;for(let s=0;s<e.length;s++)t^=e[s],t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0").repeat(8)}getMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{txt:"text/plain",json:"application/json",js:"application/javascript",ts:"application/typescript",html:"text/html",css:"text/css",md:"text/markdown",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf",zip:"application/zip",tar:"application/x-tar",gz:"application/gzip"}[t||""]||"application/octet-stream"}};rr.FileTransferService=Xa});var sc=D((fv,Yi)=>{function ah(r){return Array.isArray(r)?r:[r]}var Nm=void 0,Qa="",ih=" ",Za="\\",Dm=/^\s+$/,Fm=/(?:[^\\]|^)\\$/,Mm=/^\\!/,Bm=/^\\#/,jm=/\r?\n/g,Um=/^\.{0,2}\/|^\.{1,2}$/,qm=/\/$/,Un="/",ch="node-ignore";typeof Symbol<"u"&&(ch=Symbol.for("node-ignore"));var fh=ch,qn=(r,e,t)=>(Object.defineProperty(r,e,{value:t}),t),Wm=/([0-z])-([0-z])/g,uh=()=>!1,Hm=r=>r.replace(Wm,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:Qa),Vm=r=>{let{length:e}=r;return r.slice(0,e-e%2)},Km=[[/^\uFEFF/,()=>Qa],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?ih:Qa)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+ih}],[/[\\$.|*+(){^]/g,r=>`\\${r}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(r,e,t)=>e+6<t.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(r,e,t)=>{let n=t.replace(/\\\*/g,"[^\\/]*");return e+n}],[/\\\\\\(?=[$.|*+(){^])/g,()=>Za],[/\\\\/g,()=>Za],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,n,s)=>e===Za?`\\[${t}${Vm(n)}${s}`:s==="]"&&n.length%2===0?`[${Hm(t)}${n}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`]],$m=/(^|\\\/)?\\\*$/,Es="regex",zi="checkRegex",oh="_",zm={[Es](r,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[zi](r,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},Gm=r=>Km.reduce((e,[t,n])=>e.replace(t,n.bind(r)),r),Gi=r=>typeof r=="string",Ym=r=>r&&Gi(r)&&!Dm.test(r)&&!Fm.test(r)&&r.indexOf("#")!==0,Xm=r=>r.split(jm).filter(Boolean),ec=class{constructor(e,t,n,s,i,a){this.pattern=e,this.mark=t,this.negative=i,qn(this,"body",n),qn(this,"ignoreCase",s),qn(this,"regexPrefix",a)}get regex(){let e=oh+Es;return this[e]?this[e]:this._make(Es,e)}get checkRegex(){let e=oh+zi;return this[e]?this[e]:this._make(zi,e)}_make(e,t){let n=this.regexPrefix.replace($m,zm[e]),s=this.ignoreCase?new RegExp(n,"i"):new RegExp(n);return qn(this,t,s)}},Jm=({pattern:r,mark:e},t)=>{let n=!1,s=r;s.indexOf("!")===0&&(n=!0,s=s.substr(1)),s=s.replace(Mm,"!").replace(Bm,"#");let i=Gm(s);return new ec(r,e,s,t,n,i)},tc=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[fh]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(Gi(e)&&(e={pattern:e}),Ym(e.pattern)){let t=Jm(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,ah(Gi(e)?Xm(e):e).forEach(this._add,this),this._added}test(e,t,n){let s=!1,i=!1,a;this._rules.forEach(u=>{let{negative:d}=u;i===d&&s!==i||d&&!s&&!i&&!t||!u[n].test(e)||(s=!d,i=d,a=d?Nm:u)});let c={ignored:s,unignored:i};return a&&(c.rule=a),c}},Zm=(r,e)=>{throw new e(r)},yr=(r,e,t)=>Gi(r)?r?yr.isNotRelative(r)?t(`path should be a \`path.relative()\`d string, but got "${e}"`,RangeError):!0:t("path must not be empty",TypeError):t(`path must be a string, but got \`${e}\``,TypeError),lh=r=>Um.test(r);yr.isNotRelative=lh;yr.convert=r=>r;var rc=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){qn(this,fh,!0),this._rules=new tc(t),this._strictPathCheck=!n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(e){return this._rules.add(e)&&this._initCache(),this}addPattern(e){return this.add(e)}_test(e,t,n,s){let i=e&&yr.convert(e);return yr(i,e,this._strictPathCheck?Zm:uh),this._t(i,t,n,s)}checkIgnore(e){if(!qm.test(e))return this.test(e);let t=e.split(Un).filter(Boolean);if(t.pop(),t.length){let n=this._t(t.join(Un)+Un,this._testCache,!0,t);if(n.ignored)return n}return this._rules.test(e,!1,zi)}_t(e,t,n,s){if(e in t)return t[e];if(s||(s=e.split(Un).filter(Boolean)),s.pop(),!s.length)return t[e]=this._rules.test(e,n,Es);let i=this._t(s.join(Un)+Un,t,n,s);return t[e]=i.ignored?i:this._rules.test(e,n,Es)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return ah(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},nc=r=>new rc(r),Qm=r=>yr(r&&yr.convert(r),r,uh),hh=()=>{let r=t=>/^\\\\\?\\/.test(t)||/["<>|\u0000-\u001F]+/u.test(t)?t:t.replace(/\\/g,"/");yr.convert=r;let e=/^[a-z]:\//i;yr.isNotRelative=t=>e.test(t)||lh(t)};typeof process<"u"&&process.platform==="win32"&&hh();Yi.exports=nc;nc.default=nc;Yi.exports.isPathValid=Qm;qn(Yi.exports,Symbol.for("setupWindows"),hh)});var ph=D(Nt=>{"use strict";var ey=Nt&&Nt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),ty=Nt&&Nt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),dh=Nt&&Nt.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[n.length]=s);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),s=0;s<n.length;s++)n[s]!=="default"&&ey(t,e,n[s]);return ty(t,e),t}})(),ry=Nt&&Nt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Nt,"__esModule",{value:!0});Nt.FileListService=void 0;var ws=dh(require("path")),ic=dh(require("fs/promises")),ny=ry(sc()),oc=Gr(),sy=["node_modules",".pnpm","vendor",".git","dist","build","out",".next",".nuxt",".output",".cache",".turbo",".idea",".vscode",".DS_Store","Thumbs.db"],ac=class{ignoreFilter;workspaceRoot;onResponseCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,ny.default)(),this.ignoreFilter.add(sy),this.workspaceRoot&&this.loadGitignore(),this.logger.info("FileListService initialized",t||"null")}async loadGitignore(){if(!this.workspaceRoot)return;let e=ws.join(this.workspaceRoot,".gitignore");try{let t=await ic.readFile(e,"utf-8");this.ignoreFilter.add(t)}catch{}}onResponse(e){this.onResponseCallback=e}async handleListRequest(e){if(!this.workspaceRoot){this.sendResponse({requestId:e.requestId,path:e.path,entries:[],error:"No workspace root"});return}try{let t=this.resolvePath(e.path),n=await this.listDirectory(t,e.path);this.sendResponse({requestId:e.requestId,path:e.path,entries:n})}catch(t){this.logger.error("Failed to list directory",String(t)),this.sendResponse({requestId:e.requestId,path:e.path,entries:[],error:t instanceof Error?t.message:"Unknown error"})}}async listDirectory(e,t){let n=await ic.readdir(e,{withFileTypes:!0}),s=[];for(let i of n){let a=t==="."||t===""?i.name:ws.join(t,i.name);if(this.shouldHide(a,i.isDirectory()))continue;let c=ws.join(e,i.name),u={name:i.name,path:a,type:i.isDirectory()?oc.FileEntryType.DIRECTORY:oc.FileEntryType.FILE};if(!i.isDirectory())try{let d=await ic.stat(c);u.size=d.size,u.modified=d.mtime.toISOString()}catch{}s.push(u)}return s.sort((i,a)=>i.type!==a.type?i.type===oc.FileEntryType.DIRECTORY?-1:1:i.name.localeCompare(a.name))}shouldHide(e,t){let n=e.split(ws.sep).join("/"),s=t?`${n}/`:n;return this.ignoreFilter.ignores(s)}resolvePath(e){if(!this.workspaceRoot)throw new Error("No workspace root");if(e==="."||e==="")return this.workspaceRoot;let t=ws.join(this.workspaceRoot,e);if(!t.startsWith(this.workspaceRoot))throw new Error("Path outside workspace");return t}sendResponse(e){this.onResponseCallback?.(e)}dispose(){this.onResponseCallback=null}};Nt.FileListService=ac});var _h=D(nr=>{"use strict";var iy=nr&&nr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),oy=nr&&nr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),gh=nr&&nr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[n.length]=s);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),s=0;s<n.length;s++)n[s]!=="default"&&iy(t,e,n[s]);return oy(t,e),t}})();Object.defineProperty(nr,"__esModule",{value:!0});nr.FileTrackerService=void 0;var cc=gh(require("path")),cn=gh(require("fs/promises")),ay=require("child_process"),cy=require("util"),qt=Gr(),fc=(0,cy.promisify)(ay.exec),uc={toolStart:/⏺\s*(Write|Edit|NotebookEdit)\s*\(\s*(?:file_path|notebook_path)\s*=\s*"([^"]+)"/,toolSuccess:/[✓✔]\s*(?:Wrote|Edited|Updated|Created)\s+([^\s\n]+)/,toolError:/[✗✘]\s*(?:Failed|Error)/i},lc=class{trackedFiles=new Map;pendingToolCalls=new Map;outputBuffers=new Map;workspaceRoot;onFileChangedCallback=null;onFileViewTransferCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t}onFileChanged(e){this.onFileChangedCallback=e}onFileViewTransfer(e){this.onFileViewTransferCallback=e}async processOutput(e,t){let n=this.outputBuffers.get(e)||"";n+=t,n.length>10240&&(n=n.slice(-10240)),this.outputBuffers.set(e,n);try{await this.parseToolCalls(e,n)}catch(s){this.logger.error("Error parsing tool calls",s)}}async parseToolCalls(e,t){let n=this.stripAnsi(t),s=n.match(uc.toolStart);if(s){let a=s[1],c=s[2],u=`${a}_${Date.now()}_${c}`;this.pendingToolCalls.has(u)||await this.handleToolStart(e,u,a,{file_path:c})}let i=n.match(uc.toolSuccess);if(i){let a=i[1];for(let[c,u]of this.pendingToolCalls)if(u.filePath===a||a.endsWith(u.filePath)||u.filePath.endsWith(a)){await this.handleToolEnd(e,c,u.toolName,"success");break}}if(uc.toolError.test(n))for(let[a,c]of this.pendingToolCalls)await this.handleToolEnd(e,a,c.toolName,"error")}stripAnsi(e){return e.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g,"").replace(/\x1b\][^\x07]*\x07/g,"").replace(/\x1b[()][AB012]/g,"").replace(/\x1b[=>]/g,"").replace(/\x1b[78DMEHc]/g,"")}async handleToolStart(e,t,n,s){if(!this.isFileModifyingTool(n))return;let i=this.extractFilePath(n,s);if(!i)return;let a=this.resolveFilePath(i),c={toolId:t,toolName:n,filePath:i,timestamp:new Date().toISOString()};this.pendingToolCalls.set(t,c);let u;try{u=await cn.readFile(a,"utf-8")}catch{u=void 0}let d={path:i,changeType:u===void 0?qt.FileChangeType.CREATE:qt.FileChangeType.MODIFY,toolName:n,toolId:t,timestamp:c.timestamp,previousContent:u},g=this.trackedFiles.get(e)||[];g.push(d),this.trackedFiles.set(e,g)}async handleToolEnd(e,t,n,s){if(!this.isFileModifyingTool(n)||!this.pendingToolCalls.get(t))return;if(this.pendingToolCalls.delete(t),s==="error"){let g=this.trackedFiles.get(e)||[],_=g.findIndex(y=>y.toolId===t);_!==-1&&g.splice(_,1);return}let c=(this.trackedFiles.get(e)||[]).find(g=>g.toolId===t);if(!c)return;let u=this.resolveFilePath(c.path);try{let g=await cn.stat(u);c.size=g.size}catch{c.changeType=qt.FileChangeType.DELETE,c.size=void 0}let d={path:c.path,changeType:c.changeType,timestamp:new Date().toISOString(),source:"tool-call",toolName:c.toolName,toolId:c.toolId,size:c.size};this.onFileChangedCallback?.(e,d)}async handleViewRequest(e,t){let n=this.resolveFilePath(t.path),s=this.getViewableMimeType(t.path);if(s&&this.onFileViewTransferCallback){try{let a=await cn.readFile(n),c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:s};this.onFileViewTransferCallback(e,Buffer.from(a),c)}catch(a){let c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:s,error:a instanceof Error?a.message:"Unknown error"};this.onFileViewTransferCallback(e,Buffer.alloc(0),c)}return}let i;try{t.type===qt.FileViewType.CONTENT?i=await this.getFileContent(t,n):i=await this.getFileDiff(e,t,n)}catch(a){i={requestId:t.requestId,path:t.path,type:t.type,error:a instanceof Error?a.message:"Unknown error"}}if(this.onFileViewTransferCallback){let a={requestId:t.requestId,path:t.path,viewType:i.type===qt.FileViewType.CONTENT?"content":"diff",language:i.language,truncated:i.truncated,error:i.error},c=Buffer.from(i.content||"","utf-8");this.onFileViewTransferCallback(e,c,a)}}getViewableMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf"}[t||""]||null}async getFileContent(e,t){let n=e.maxSize||1048576,s=await cn.stat(t),i=await cn.readFile(t,"utf-8"),a=!1,c=i;return i.length>n&&(c=i.slice(0,n),a=!0),{requestId:e.requestId,path:e.path,type:qt.FileViewType.CONTENT,content:c,language:(0,qt.getLanguageFromPath)(e.path),size:s.size,truncated:a}}async getFileDiff(e,t,n){let s=t.diffBase||qt.DiffBase.GIT,i;return s===qt.DiffBase.GIT?i=await this.getGitDiff(n):i=await this.getPreviousDiff(e,t.path,n),{requestId:t.requestId,path:t.path,type:qt.FileViewType.DIFF,content:i,language:"diff"}}async getGitDiff(e){if(!this.workspaceRoot)throw new Error("No workspace root");try{let{stdout:t}=await fc(`git diff --cached -- "${e}"`,{cwd:this.workspaceRoot});if(t.trim())return t;let{stdout:n}=await fc(`git diff -- "${e}"`,{cwd:this.workspaceRoot});if(n.trim())return n;let{stdout:s}=await fc(`git status --porcelain -- "${e}"`,{cwd:this.workspaceRoot});if(s.startsWith("??")||s.startsWith("A ")){let a=(await cn.readFile(e,"utf-8")).split(`
|
|
27
|
-
`),c=
|
|
28
|
-
`)}return"(no changes)"}catch{throw new Error("Git not available")}}async getPreviousDiff(e,t,n){let a=(this.trackedFiles.get(e)||[]).find(d=>d.path===t&&d.previousContent!==void 0)?.previousContent||"",c;try{c=await cn.readFile(n,"utf-8")}catch{c=""}let u=(0,
|
|
29
|
-
`)}clearTerminal(e){this.trackedFiles.delete(e),this.outputBuffers.delete(e)}getChangedFiles(e){return(this.trackedFiles.get(e)||[]).map(n=>({path:n.path,changeType:n.changeType,timestamp:n.timestamp,source:"tool-call",toolName:n.toolName,toolId:n.toolId,size:n.size}))}isFileModifyingTool(e){return["Write","Edit","NotebookEdit"].includes(e)}extractFilePath(e,t){return t?e==="Write"||e==="Edit"?t.file_path||null:e==="NotebookEdit"&&t.notebook_path||null:null}resolveFilePath(e){return cc.isAbsolute(e)?e:this.workspaceRoot?cc.join(this.workspaceRoot,e):e}dispose(){this.trackedFiles.clear(),this.pendingToolCalls.clear(),this.onFileChangedCallback=null,this.onFileViewTransferCallback=null}};nr.FileTrackerService=lc});var mh=D(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.FileTrackerService=ft.FileListService=ft.FileTransferService=ft.WebSocketService=ft.StatusDetector=ft.AuthService=ft.CryptoService=void 0;var fy=Wf();Object.defineProperty(ft,"CryptoService",{enumerable:!0,get:function(){return fy.CryptoService}});var uy=Hf();Object.defineProperty(ft,"AuthService",{enumerable:!0,get:function(){return uy.AuthService}});var ly=Vf();Object.defineProperty(ft,"StatusDetector",{enumerable:!0,get:function(){return ly.StatusDetector}});var hy=rh();Object.defineProperty(ft,"WebSocketService",{enumerable:!0,get:function(){return hy.WebSocketService}});var dy=sh();Object.defineProperty(ft,"FileTransferService",{enumerable:!0,get:function(){return dy.FileTransferService}});var py=ph();Object.defineProperty(ft,"FileListService",{enumerable:!0,get:function(){return py.FileListService}});var gy=_h();Object.defineProperty(ft,"FileTrackerService",{enumerable:!0,get:function(){return gy.FileTrackerService}})});var vs=D(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.FileTrackerService=Te.FileListService=Te.FileTransferService=Te.WebSocketService=Te.StatusDetector=Te.AuthService=Te.CryptoService=Te.getCurrentCorrelationId=Te.runWithCorrelation=Te.generateCorrelationId=Te.getWsUrl=Te.getApiUrl=Te.CircularBuffer=Te.formatLogLine=Te.shouldLog=Te.LOG_LEVELS=void 0;var hc=af();Object.defineProperty(Te,"LOG_LEVELS",{enumerable:!0,get:function(){return hc.LOG_LEVELS}});Object.defineProperty(Te,"shouldLog",{enumerable:!0,get:function(){return hc.shouldLog}});Object.defineProperty(Te,"formatLogLine",{enumerable:!0,get:function(){return hc.formatLogLine}});var Wn=uf();Object.defineProperty(Te,"CircularBuffer",{enumerable:!0,get:function(){return Wn.CircularBuffer}});Object.defineProperty(Te,"getApiUrl",{enumerable:!0,get:function(){return Wn.getApiUrl}});Object.defineProperty(Te,"getWsUrl",{enumerable:!0,get:function(){return Wn.getWsUrl}});Object.defineProperty(Te,"generateCorrelationId",{enumerable:!0,get:function(){return Wn.generateCorrelationId}});Object.defineProperty(Te,"runWithCorrelation",{enumerable:!0,get:function(){return Wn.runWithCorrelation}});Object.defineProperty(Te,"getCurrentCorrelationId",{enumerable:!0,get:function(){return Wn.getCurrentCorrelationId}});var fn=mh();Object.defineProperty(Te,"CryptoService",{enumerable:!0,get:function(){return fn.CryptoService}});Object.defineProperty(Te,"AuthService",{enumerable:!0,get:function(){return fn.AuthService}});Object.defineProperty(Te,"StatusDetector",{enumerable:!0,get:function(){return fn.StatusDetector}});Object.defineProperty(Te,"WebSocketService",{enumerable:!0,get:function(){return fn.WebSocketService}});Object.defineProperty(Te,"FileTransferService",{enumerable:!0,get:function(){return fn.FileTransferService}});Object.defineProperty(Te,"FileListService",{enumerable:!0,get:function(){return fn.FileListService}});Object.defineProperty(Te,"FileTrackerService",{enumerable:!0,get:function(){return fn.FileTrackerService}})});var _c=D((xs,gc)=>{(function(r,e){typeof xs=="object"&&typeof gc=="object"?gc.exports=e(require("child_process"),require("crypto")):typeof define=="function"&&define.amd?define(["child_process","crypto"],e):typeof xs=="object"?xs["electron-machine-id"]=e(require("child_process"),require("crypto")):r["electron-machine-id"]=e(r.child_process,r.crypto)})(xs,function(r,e){return(function(t){function n(i){if(s[i])return s[i].exports;var a=s[i]={exports:{},id:i,loaded:!1};return t[i].call(a.exports,a,a.exports,n),a.loaded=!0,a.exports}var s={};return n.m=t,n.c=s,n.p="",n(0)})([function(t,n,s){t.exports=s(34)},function(t,n,s){var i=s(29)("wks"),a=s(33),c=s(2).Symbol,u=typeof c=="function",d=t.exports=function(g){return i[g]||(i[g]=u&&c[g]||(u?c:a)("Symbol."+g))};d.store=i},function(t,n){var s=t.exports=typeof window<"u"&&window.Math==Math?window:typeof self<"u"&&self.Math==Math?self:Function("return this")();typeof __g=="number"&&(__g=s)},function(t,n,s){var i=s(9);t.exports=function(a){if(!i(a))throw TypeError(a+" is not an object!");return a}},function(t,n,s){t.exports=!s(24)(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7})},function(t,n,s){var i=s(12),a=s(17);t.exports=s(4)?function(c,u,d){return i.f(c,u,a(1,d))}:function(c,u,d){return c[u]=d,c}},function(t,n){var s=t.exports={version:"2.4.0"};typeof __e=="number"&&(__e=s)},function(t,n,s){var i=s(14);t.exports=function(a,c,u){if(i(a),c===void 0)return a;switch(u){case 1:return function(d){return a.call(c,d)};case 2:return function(d,g){return a.call(c,d,g)};case 3:return function(d,g,_){return a.call(c,d,g,_)}}return function(){return a.apply(c,arguments)}}},function(t,n){var s={}.hasOwnProperty;t.exports=function(i,a){return s.call(i,a)}},function(t,n){t.exports=function(s){return typeof s=="object"?s!==null:typeof s=="function"}},function(t,n){t.exports={}},function(t,n){var s={}.toString;t.exports=function(i){return s.call(i).slice(8,-1)}},function(t,n,s){var i=s(3),a=s(26),c=s(32),u=Object.defineProperty;n.f=s(4)?Object.defineProperty:function(d,g,_){if(i(d),g=c(g,!0),i(_),a)try{return u(d,g,_)}catch{}if("get"in _||"set"in _)throw TypeError("Accessors not supported!");return"value"in _&&(d[g]=_.value),d}},function(t,n,s){var i=s(42),a=s(15);t.exports=function(c){return i(a(c))}},function(t,n){t.exports=function(s){if(typeof s!="function")throw TypeError(s+" is not a function!");return s}},function(t,n){t.exports=function(s){if(s==null)throw TypeError("Can't call method on "+s);return s}},function(t,n,s){var i=s(9),a=s(2).document,c=i(a)&&i(a.createElement);t.exports=function(u){return c?a.createElement(u):{}}},function(t,n){t.exports=function(s,i){return{enumerable:!(1&s),configurable:!(2&s),writable:!(4&s),value:i}}},function(t,n,s){var i=s(12).f,a=s(8),c=s(1)("toStringTag");t.exports=function(u,d,g){u&&!a(u=g?u:u.prototype,c)&&i(u,c,{configurable:!0,value:d})}},function(t,n,s){var i=s(29)("keys"),a=s(33);t.exports=function(c){return i[c]||(i[c]=a(c))}},function(t,n){var s=Math.ceil,i=Math.floor;t.exports=function(a){return isNaN(a=+a)?0:(a>0?i:s)(a)}},function(t,n,s){var i=s(11),a=s(1)("toStringTag"),c=i((function(){return arguments})())=="Arguments",u=function(d,g){try{return d[g]}catch{}};t.exports=function(d){var g,_,y;return d===void 0?"Undefined":d===null?"Null":typeof(_=u(g=Object(d),a))=="string"?_:c?i(g):(y=i(g))=="Object"&&typeof g.callee=="function"?"Arguments":y}},function(t,n){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,n,s){var i=s(2),a=s(6),c=s(7),u=s(5),d="prototype",g=function(_,y,v){var S,O,H,z=_&g.F,X=_&g.G,T=_&g.S,M=_&g.P,Q=_&g.B,B=_&g.W,ie=X?a:a[y]||(a[y]={}),he=ie[d],de=X?i:T?i[y]:(i[y]||{})[d];X&&(v=y);for(S in v)O=!z&&de&&de[S]!==void 0,O&&S in ie||(H=O?de[S]:v[S],ie[S]=X&&typeof de[S]!="function"?v[S]:Q&&O?c(H,i):B&&de[S]==H?(function(Re){var We=function(Ye,ve,Xe){if(this instanceof Re){switch(arguments.length){case 0:return new Re;case 1:return new Re(Ye);case 2:return new Re(Ye,ve)}return new Re(Ye,ve,Xe)}return Re.apply(this,arguments)};return We[d]=Re[d],We})(H):M&&typeof H=="function"?c(Function.call,H):H,M&&((ie.virtual||(ie.virtual={}))[S]=H,_&g.R&&he&&!he[S]&&u(he,S,H)))};g.F=1,g.G=2,g.S=4,g.P=8,g.B=16,g.W=32,g.U=64,g.R=128,t.exports=g},function(t,n){t.exports=function(s){try{return!!s()}catch{return!0}}},function(t,n,s){t.exports=s(2).document&&document.documentElement},function(t,n,s){t.exports=!s(4)&&!s(24)(function(){return Object.defineProperty(s(16)("div"),"a",{get:function(){return 7}}).a!=7})},function(t,n,s){"use strict";var i=s(28),a=s(23),c=s(57),u=s(5),d=s(8),g=s(10),_=s(45),y=s(18),v=s(52),S=s(1)("iterator"),O=!([].keys&&"next"in[].keys()),H="@@iterator",z="keys",X="values",T=function(){return this};t.exports=function(M,Q,B,ie,he,de,Re){_(B,Q,ie);var We,Ye,ve,Xe=function(j){if(!O&&j in pe)return pe[j];switch(j){case z:return function(){return new B(this,j)};case X:return function(){return new B(this,j)}}return function(){return new B(this,j)}},Fe=Q+" Iterator",J=he==X,Ee=!1,pe=M.prototype,nt=pe[S]||pe[H]||he&&pe[he],Qe=nt||Xe(he),Vt=he?J?Xe("entries"):Qe:void 0,L=Q=="Array"&&pe.entries||nt;if(L&&(ve=v(L.call(new M)),ve!==Object.prototype&&(y(ve,Fe,!0),i||d(ve,S)||u(ve,S,T))),J&&nt&&nt.name!==X&&(Ee=!0,Qe=function(){return nt.call(this)}),i&&!Re||!O&&!Ee&&pe[S]||u(pe,S,Qe),g[Q]=Qe,g[Fe]=T,he)if(We={values:J?Qe:Xe(X),keys:de?Qe:Xe(z),entries:Vt},Re)for(Ye in We)Ye in pe||c(pe,Ye,We[Ye]);else a(a.P+a.F*(O||Ee),Q,We);return We}},function(t,n){t.exports=!0},function(t,n,s){var i=s(2),a="__core-js_shared__",c=i[a]||(i[a]={});t.exports=function(u){return c[u]||(c[u]={})}},function(t,n,s){var i,a,c,u=s(7),d=s(41),g=s(25),_=s(16),y=s(2),v=y.process,S=y.setImmediate,O=y.clearImmediate,H=y.MessageChannel,z=0,X={},T="onreadystatechange",M=function(){var B=+this;if(X.hasOwnProperty(B)){var ie=X[B];delete X[B],ie()}},Q=function(B){M.call(B.data)};S&&O||(S=function(B){for(var ie=[],he=1;arguments.length>he;)ie.push(arguments[he++]);return X[++z]=function(){d(typeof B=="function"?B:Function(B),ie)},i(z),z},O=function(B){delete X[B]},s(11)(v)=="process"?i=function(B){v.nextTick(u(M,B,1))}:H?(a=new H,c=a.port2,a.port1.onmessage=Q,i=u(c.postMessage,c,1)):y.addEventListener&&typeof postMessage=="function"&&!y.importScripts?(i=function(B){y.postMessage(B+"","*")},y.addEventListener("message",Q,!1)):i=T in _("script")?function(B){g.appendChild(_("script"))[T]=function(){g.removeChild(this),M.call(B)}}:function(B){setTimeout(u(M,B,1),0)}),t.exports={set:S,clear:O}},function(t,n,s){var i=s(20),a=Math.min;t.exports=function(c){return c>0?a(i(c),9007199254740991):0}},function(t,n,s){var i=s(9);t.exports=function(a,c){if(!i(a))return a;var u,d;if(c&&typeof(u=a.toString)=="function"&&!i(d=u.call(a))||typeof(u=a.valueOf)=="function"&&!i(d=u.call(a))||!c&&typeof(u=a.toString)=="function"&&!i(d=u.call(a)))return d;throw TypeError("Can't convert object to primitive value")}},function(t,n){var s=0,i=Math.random();t.exports=function(a){return"Symbol(".concat(a===void 0?"":a,")_",(++s+i).toString(36))}},function(t,n,s){"use strict";function i(T){return T&&T.__esModule?T:{default:T}}function a(){return process.platform!=="win32"?"":process.arch==="ia32"&&process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432")?"mixed":"native"}function c(T){return(0,S.createHash)("sha256").update(T).digest("hex")}function u(T){switch(H){case"darwin":return T.split("IOPlatformUUID")[1].split(`
|
|
30
|
-
`)[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return T.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return T.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"freebsd":return T.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error("Unsupported platform: "+process.platform)}}function d(T){var M=u((0,v.execSync)(X[H]).toString());return T?M:c(M)}function g(T){return new y.default(function(M,Q){return(0,v.exec)(X[H],{},function(B,ie,he){if(B)return Q(new Error("Error while obtaining machine id: "+B.stack));var de=u(ie.toString());return M(T?de:c(de))})})}Object.defineProperty(n,"__esModule",{value:!0});var _=s(35),y=i(_);n.machineIdSync=d,n.machineId=g;var v=s(70),S=s(71),O=process,H=O.platform,z={native:"%windir%\\System32",mixed:"%windir%\\sysnative\\cmd.exe /c %windir%\\System32"},X={darwin:"ioreg -rd1 -c IOPlatformExpertDevice",win32:z[a()]+"\\REG.exe QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",linux:"( cat /var/lib/dbus/machine-id /etc/machine-id 2> /dev/null || hostname ) | head -n 1 || :",freebsd:"kenv -q smbios.system.uuid || sysctl -n kern.hostuuid"}},function(t,n,s){t.exports={default:s(36),__esModule:!0}},function(t,n,s){s(66),s(68),s(69),s(67),t.exports=s(6).Promise},function(t,n){t.exports=function(){}},function(t,n){t.exports=function(s,i,a,c){if(!(s instanceof i)||c!==void 0&&c in s)throw TypeError(a+": incorrect invocation!");return s}},function(t,n,s){var i=s(13),a=s(31),c=s(62);t.exports=function(u){return function(d,g,_){var y,v=i(d),S=a(v.length),O=c(_,S);if(u&&g!=g){for(;S>O;)if(y=v[O++],y!=y)return!0}else for(;S>O;O++)if((u||O in v)&&v[O]===g)return u||O||0;return!u&&-1}}},function(t,v,s){var i=s(7),a=s(44),c=s(43),u=s(3),d=s(31),g=s(64),_={},y={},v=t.exports=function(S,O,H,z,X){var T,M,Q,B,ie=X?function(){return S}:g(S),he=i(H,z,O?2:1),de=0;if(typeof ie!="function")throw TypeError(S+" is not iterable!");if(c(ie)){for(T=d(S.length);T>de;de++)if(B=O?he(u(M=S[de])[0],M[1]):he(S[de]),B===_||B===y)return B}else for(Q=ie.call(S);!(M=Q.next()).done;)if(B=a(Q,he,M.value,O),B===_||B===y)return B};v.BREAK=_,v.RETURN=y},function(t,n){t.exports=function(s,i,a){var c=a===void 0;switch(i.length){case 0:return c?s():s.call(a);case 1:return c?s(i[0]):s.call(a,i[0]);case 2:return c?s(i[0],i[1]):s.call(a,i[0],i[1]);case 3:return c?s(i[0],i[1],i[2]):s.call(a,i[0],i[1],i[2]);case 4:return c?s(i[0],i[1],i[2],i[3]):s.call(a,i[0],i[1],i[2],i[3])}return s.apply(a,i)}},function(t,n,s){var i=s(11);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(a){return i(a)=="String"?a.split(""):Object(a)}},function(t,n,s){var i=s(10),a=s(1)("iterator"),c=Array.prototype;t.exports=function(u){return u!==void 0&&(i.Array===u||c[a]===u)}},function(t,n,s){var i=s(3);t.exports=function(a,c,u,d){try{return d?c(i(u)[0],u[1]):c(u)}catch(_){var g=a.return;throw g!==void 0&&i(g.call(a)),_}}},function(t,n,s){"use strict";var i=s(49),a=s(17),c=s(18),u={};s(5)(u,s(1)("iterator"),function(){return this}),t.exports=function(d,g,_){d.prototype=i(u,{next:a(1,_)}),c(d,g+" Iterator")}},function(t,n,s){var i=s(1)("iterator"),a=!1;try{var c=[7][i]();c.return=function(){a=!0},Array.from(c,function(){throw 2})}catch{}t.exports=function(u,d){if(!d&&!a)return!1;var g=!1;try{var _=[7],y=_[i]();y.next=function(){return{done:g=!0}},_[i]=function(){return y},u(_)}catch{}return g}},function(t,n){t.exports=function(s,i){return{value:i,done:!!s}}},function(t,n,s){var i=s(2),a=s(30).set,c=i.MutationObserver||i.WebKitMutationObserver,u=i.process,d=i.Promise,g=s(11)(u)=="process";t.exports=function(){var _,y,v,S=function(){var X,T;for(g&&(X=u.domain)&&X.exit();_;){T=_.fn,_=_.next;try{T()}catch(M){throw _?v():y=void 0,M}}y=void 0,X&&X.enter()};if(g)v=function(){u.nextTick(S)};else if(c){var O=!0,H=document.createTextNode("");new c(S).observe(H,{characterData:!0}),v=function(){H.data=O=!O}}else if(d&&d.resolve){var z=d.resolve();v=function(){z.then(S)}}else v=function(){a.call(i,S)};return function(X){var T={fn:X,next:void 0};y&&(y.next=T),_||(_=T,v()),y=T}}},function(t,n,s){var i=s(3),a=s(50),c=s(22),u=s(19)("IE_PROTO"),d=function(){},g="prototype",_=function(){var y,v=s(16)("iframe"),S=c.length,O=">";for(v.style.display="none",s(25).appendChild(v),v.src="javascript:",y=v.contentWindow.document,y.open(),y.write("<script>document.F=Object</script"+O),y.close(),_=y.F;S--;)delete _[g][c[S]];return _()};t.exports=Object.create||function(y,v){var S;return y!==null?(d[g]=i(y),S=new d,d[g]=null,S[u]=y):S=_(),v===void 0?S:a(S,v)}},function(t,n,s){var i=s(12),a=s(3),c=s(54);t.exports=s(4)?Object.defineProperties:function(u,d){a(u);for(var g,_=c(d),y=_.length,v=0;y>v;)i.f(u,g=_[v++],d[g]);return u}},function(t,n,s){var i=s(55),a=s(17),c=s(13),u=s(32),d=s(8),g=s(26),_=Object.getOwnPropertyDescriptor;n.f=s(4)?_:function(y,v){if(y=c(y),v=u(v,!0),g)try{return _(y,v)}catch{}if(d(y,v))return a(!i.f.call(y,v),y[v])}},function(t,n,s){var i=s(8),a=s(63),c=s(19)("IE_PROTO"),u=Object.prototype;t.exports=Object.getPrototypeOf||function(d){return d=a(d),i(d,c)?d[c]:typeof d.constructor=="function"&&d instanceof d.constructor?d.constructor.prototype:d instanceof Object?u:null}},function(t,n,s){var i=s(8),a=s(13),c=s(39)(!1),u=s(19)("IE_PROTO");t.exports=function(d,g){var _,y=a(d),v=0,S=[];for(_ in y)_!=u&&i(y,_)&&S.push(_);for(;g.length>v;)i(y,_=g[v++])&&(~c(S,_)||S.push(_));return S}},function(t,n,s){var i=s(53),a=s(22);t.exports=Object.keys||function(c){return i(c,a)}},function(t,n){n.f={}.propertyIsEnumerable},function(t,n,s){var i=s(5);t.exports=function(a,c,u){for(var d in c)u&&a[d]?a[d]=c[d]:i(a,d,c[d]);return a}},function(t,n,s){t.exports=s(5)},function(t,n,s){var i=s(9),a=s(3),c=function(u,d){if(a(u),!i(d)&&d!==null)throw TypeError(d+": can't set as prototype!")};t.exports={set:Object.setPrototypeOf||("__proto__"in{}?(function(u,d,g){try{g=s(7)(Function.call,s(51).f(Object.prototype,"__proto__").set,2),g(u,[]),d=!(u instanceof Array)}catch{d=!0}return function(_,y){return c(_,y),d?_.__proto__=y:g(_,y),_}})({},!1):void 0),check:c}},function(t,n,s){"use strict";var i=s(2),a=s(6),c=s(12),u=s(4),d=s(1)("species");t.exports=function(g){var _=typeof a[g]=="function"?a[g]:i[g];u&&_&&!_[d]&&c.f(_,d,{configurable:!0,get:function(){return this}})}},function(t,n,s){var i=s(3),a=s(14),c=s(1)("species");t.exports=function(u,d){var g,_=i(u).constructor;return _===void 0||(g=i(_)[c])==null?d:a(g)}},function(t,n,s){var i=s(20),a=s(15);t.exports=function(c){return function(u,d){var g,_,y=String(a(u)),v=i(d),S=y.length;return v<0||v>=S?c?"":void 0:(g=y.charCodeAt(v),g<55296||g>56319||v+1===S||(_=y.charCodeAt(v+1))<56320||_>57343?c?y.charAt(v):g:c?y.slice(v,v+2):(g-55296<<10)+(_-56320)+65536)}}},function(t,n,s){var i=s(20),a=Math.max,c=Math.min;t.exports=function(u,d){return u=i(u),u<0?a(u+d,0):c(u,d)}},function(t,n,s){var i=s(15);t.exports=function(a){return Object(i(a))}},function(t,n,s){var i=s(21),a=s(1)("iterator"),c=s(10);t.exports=s(6).getIteratorMethod=function(u){if(u!=null)return u[a]||u["@@iterator"]||c[i(u)]}},function(t,n,s){"use strict";var i=s(37),a=s(47),c=s(10),u=s(13);t.exports=s(27)(Array,"Array",function(d,g){this._t=u(d),this._i=0,this._k=g},function(){var d=this._t,g=this._k,_=this._i++;return!d||_>=d.length?(this._t=void 0,a(1)):g=="keys"?a(0,_):g=="values"?a(0,d[_]):a(0,[_,d[_]])},"values"),c.Arguments=c.Array,i("keys"),i("values"),i("entries")},function(t,n){},function(t,n,s){"use strict";var i,a,c,u=s(28),d=s(2),g=s(7),_=s(21),y=s(23),v=s(9),S=(s(3),s(14)),O=s(38),H=s(40),z=(s(58).set,s(60)),X=s(30).set,T=s(48)(),M="Promise",Q=d.TypeError,ie=d.process,B=d[M],ie=d.process,he=_(ie)=="process",de=function(){},Re=!!(function(){try{var L=B.resolve(1),j=(L.constructor={})[s(1)("species")]=function(A){A(de,de)};return(he||typeof PromiseRejectionEvent=="function")&&L.then(de)instanceof j}catch{}})(),We=function(L,j){return L===j||L===B&&j===c},Ye=function(L){var j;return!(!v(L)||typeof(j=L.then)!="function")&&j},ve=function(L){return We(B,L)?new Xe(L):new a(L)},Xe=a=function(L){var j,A;this.promise=new L(function(oe,Ie){if(j!==void 0||A!==void 0)throw Q("Bad Promise constructor");j=oe,A=Ie}),this.resolve=S(j),this.reject=S(A)},Fe=function(L){try{L()}catch(j){return{error:j}}},J=function(L,j){if(!L._n){L._n=!0;var A=L._c;T(function(){for(var oe=L._v,Ie=L._s==1,ut=0,yt=function(Et){var wt,ir,vr=Ie?Et.ok:Et.fail,qr=Et.resolve,br=Et.reject,gn=Et.domain;try{vr?(Ie||(L._h==2&&nt(L),L._h=1),vr===!0?wt=oe:(gn&&gn.enter(),wt=vr(oe),gn&&gn.exit()),wt===Et.promise?br(Q("Promise-chain cycle")):(ir=Ye(wt))?ir.call(wt,qr,br):qr(wt)):br(oe)}catch(Is){br(Is)}};A.length>ut;)yt(A[ut++]);L._c=[],L._n=!1,j&&!L._h&&Ee(L)})}},Ee=function(L){X.call(d,function(){var j,A,oe,Ie=L._v;if(pe(L)&&(j=Fe(function(){he?ie.emit("unhandledRejection",Ie,L):(A=d.onunhandledrejection)?A({promise:L,reason:Ie}):(oe=d.console)&&oe.error&&oe.error("Unhandled promise rejection",Ie)}),L._h=he||pe(L)?2:1),L._a=void 0,j)throw j.error})},pe=function(L){if(L._h==1)return!1;for(var j,A=L._a||L._c,oe=0;A.length>oe;)if(j=A[oe++],j.fail||!pe(j.promise))return!1;return!0},nt=function(L){X.call(d,function(){var j;he?ie.emit("rejectionHandled",L):(j=d.onrejectionhandled)&&j({promise:L,reason:L._v})})},Qe=function(L){var j=this;j._d||(j._d=!0,j=j._w||j,j._v=L,j._s=2,j._a||(j._a=j._c.slice()),J(j,!0))},Vt=function(L){var j,A=this;if(!A._d){A._d=!0,A=A._w||A;try{if(A===L)throw Q("Promise can't be resolved itself");(j=Ye(L))?T(function(){var oe={_w:A,_d:!1};try{j.call(L,g(Vt,oe,1),g(Qe,oe,1))}catch(Ie){Qe.call(oe,Ie)}}):(A._v=L,A._s=1,J(A,!1))}catch(oe){Qe.call({_w:A,_d:!1},oe)}}};Re||(B=function(L){O(this,B,M,"_h"),S(L),i.call(this);try{L(g(Vt,this,1),g(Qe,this,1))}catch(j){Qe.call(this,j)}},i=function(L){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},i.prototype=s(56)(B.prototype,{then:function(L,j){var A=ve(z(this,B));return A.ok=typeof L!="function"||L,A.fail=typeof j=="function"&&j,A.domain=he?ie.domain:void 0,this._c.push(A),this._a&&this._a.push(A),this._s&&J(this,!1),A.promise},catch:function(L){return this.then(void 0,L)}}),Xe=function(){var L=new i;this.promise=L,this.resolve=g(Vt,L,1),this.reject=g(Qe,L,1)}),y(y.G+y.W+y.F*!Re,{Promise:B}),s(18)(B,M),s(59)(M),c=s(6)[M],y(y.S+y.F*!Re,M,{reject:function(L){var j=ve(this),A=j.reject;return A(L),j.promise}}),y(y.S+y.F*(u||!Re),M,{resolve:function(L){if(L instanceof B&&We(L.constructor,this))return L;var j=ve(this),A=j.resolve;return A(L),j.promise}}),y(y.S+y.F*!(Re&&s(46)(function(L){B.all(L).catch(de)})),M,{all:function(L){var j=this,A=ve(j),oe=A.resolve,Ie=A.reject,ut=Fe(function(){var yt=[],Et=0,wt=1;H(L,!1,function(ir){var vr=Et++,qr=!1;yt.push(void 0),wt++,j.resolve(ir).then(function(br){qr||(qr=!0,yt[vr]=br,--wt||oe(yt))},Ie)}),--wt||oe(yt)});return ut&&Ie(ut.error),A.promise},race:function(L){var j=this,A=ve(j),oe=A.reject,Ie=Fe(function(){H(L,!1,function(ut){j.resolve(ut).then(A.resolve,oe)})});return Ie&&oe(Ie.error),A.promise}})},function(t,n,s){"use strict";var i=s(61)(!0);s(27)(String,"String",function(a){this._t=String(a),this._i=0},function(){var a,c=this._t,u=this._i;return u>=c.length?{value:void 0,done:!0}:(a=i(c,u),this._i+=a.length,{value:a,done:!1})})},function(t,n,s){s(65);for(var i=s(2),a=s(5),c=s(10),u=s(1)("toStringTag"),d=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],g=0;g<5;g++){var _=d[g],y=i[_],v=y&&y.prototype;v&&!v[u]&&a(v,u,_),c[_]=c.Array}},function(t,n){t.exports=require("child_process")},function(t,n){t.exports=require("crypto")}])})});function wy(){try{return yc.default.statSync("/.dockerenv"),!0}catch{return!1}}function vy(){try{return yc.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Ec(){return mc===void 0&&(mc=wy()||vy()),mc}var yc,mc,bh=Ft(()=>{yc=me(require("node:fs"),1)});function Hn(){return wc===void 0&&(wc=by()||Ec()),wc}var xh,wc,by,vc=Ft(()=>{xh=me(require("node:fs"),1);bh();by=()=>{try{return xh.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var bc,Th,Ch,Sh,Fr,xc=Ft(()=>{bc=me(require("node:process"),1),Th=me(require("node:os"),1),Ch=me(require("node:fs"),1);vc();Sh=()=>{if(bc.default.platform!=="linux")return!1;if(Th.default.release().toLowerCase().includes("microsoft"))return!Hn();try{return Ch.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!Hn():!1}catch{return!1}},Fr=bc.default.env.__IS_WSL_TEST__?Sh:Sh()});var Sc,Cs,xy,Sy,Tc,Oh=Ft(()=>{Sc=me(require("node:process"),1),Cs=me(require("node:fs/promises"),1);xc();xc();xy=(()=>{let r="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",n=!1;try{await Cs.default.access(t,Cs.constants.F_OK),n=!0}catch{}if(!n)return r;let s=await Cs.default.readFile(t,{encoding:"utf8"}),i=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(s);return i?(e=i.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):r}})(),Sy=async()=>`${await xy()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Tc=async()=>Fr?Sy():`${Sc.default.env.SYSTEMROOT||Sc.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function Mr(r,e,t){let n=s=>Object.defineProperty(r,e,{value:s,enumerable:!0,writable:!0});return Object.defineProperty(r,e,{configurable:!0,enumerable:!0,get(){let s=t();return n(s),s},set(s){n(s)}}),r}var kh=Ft(()=>{});async function Cc(){if(Rh.default.platform!=="darwin")throw new Error("macOS only");let{stdout:r}=await Ty("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(r)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}var Ph,Rh,Ah,Ty,Ih=Ft(()=>{Ph=require("node:util"),Rh=me(require("node:process"),1),Ah=require("node:child_process"),Ty=(0,Ph.promisify)(Ah.execFile)});async function Dh(r,{humanReadableOutput:e=!0,signal:t}={}){if(Lh.default.platform!=="darwin")throw new Error("macOS only");let n=e?[]:["-ss"],s={};t&&(s.signal=t);let{stdout:i}=await Cy("osascript",["-e",r,n],s);return i.trim()}var Lh,Nh,Oc,Cy,Fh=Ft(()=>{Lh=me(require("node:process"),1),Nh=require("node:util"),Oc=require("node:child_process"),Cy=(0,Nh.promisify)(Oc.execFile)});async function kc(r){return Dh(`tell application "Finder" to set app_path to application file id "${r}" as string
|
|
31
|
-
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var
|
|
32
|
-
`,{encoding:"utf8"})}catch{}}var
|
|
33
|
-
`),this.toFile&&
|
|
26
|
+
`+t)}function nn(r,e,t,n,s,i){if(r.listenerCount("wsClientError")){let a=new Error(s);Error.captureStackTrace(a,nn),r.emit("wsClientError",a,t,e)}else gs(t,n,s,i)}});var Rl=F((Xv,Pl)=>{"use strict";var _r=Ii();_r.createWebSocketStream=El();_r.Server=kl();_r.Receiver=fa();_r.Sender=ha();_r.WebSocket=_r;_r.WebSocketServer=_r.Server;Pl.exports=_r});var xa=F(Dr=>{"use strict";var gm=Dr&&Dr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Dr,"__esModule",{value:!0});Dr.WS=Dr.BaseWS=void 0;var mm=as(),Al=Jr(),_m=xn(),wa=Xr(),ym=gm(At()),Em=(0,ym.default)("engine.io-client:websocket"),Il=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Ni=class extends mm.Transport{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,n=Il?{}:(0,Al.pick)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(s){return this.emitReserved("error",s)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],s=t===e.length-1;(0,_m.encodePacket)(n,this.supportsBinary,i=>{try{this.doWrite(n,i)}catch{Em("websocket closed before onclose event")}s&&(0,wa.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=(0,Al.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}};Dr.BaseWS=Ni;var va=wa.globalThisShim.WebSocket||wa.globalThisShim.MozWebSocket,ba=class extends Ni{createSocket(e,t,n){return Il?new va(e,t,n):t?new va(e,t):new va(e)}doWrite(e,t){this.ws.send(t)}};Dr.WS=ba});var Ta=F(er=>{"use strict";var vm=er&&er.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),wm=er&&er.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),bm=er&&er.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&vm(e,r,t);return wm(e,r),e};Object.defineProperty(er,"__esModule",{value:!0});er.WS=void 0;var xm=bm(Rl()),Sm=xa(),Sa=class extends Sm.BaseWS{createSocket(e,t,n){var s;if(!((s=this.socket)===null||s===void 0)&&s._cookieJar){n.headers=n.headers||{},n.headers.cookie=typeof n.headers.cookie=="string"?[n.headers.cookie]:n.headers.cookie||[];for(let[i,a]of this.socket._cookieJar.cookies)n.headers.cookie.push(`${i}=${a.value}`)}return new xm.WebSocket(e,t,n)}doWrite(e,t){let n={};e.options&&(n.compress=e.options.compress),this.opts.perMessageDeflate&&(typeof t=="string"?Buffer.byteLength(t):t.length)<this.opts.perMessageDeflate.threshold&&(n.compress=!1),this.ws.send(t,n)}};er.WS=Sa});var Oa=F(Fn=>{"use strict";var Tm=Fn&&Fn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Fn,"__esModule",{value:!0});Fn.WT=void 0;var Cm=as(),Om=Xr(),Ll=xn(),km=Tm(At()),ms=(0,km.default)("engine.io-client:webtransport"),Ca=class extends Cm.Transport{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{ms("transport closed gracefully"),this.onClose()}).catch(e=>{ms("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=(0,Ll.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),s=(0,Ll.createPacketEncoderStream)();s.readable.pipeTo(e.writable),this._writer=s.writable.getWriter();let i=()=>{n.read().then(({done:c,value:u})=>{if(c){ms("session is closed");return}ms("received chunk: %o",u),this.onPacket(u),i()}).catch(c=>{ms("an error occurred while reading: %s",c)})};i();let a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],s=t===e.length-1;this._writer.write(n).then(()=>{s&&(0,Om.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};Fn.WT=Ca});var ka=F(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.transports=void 0;var Pm=Zo(),Rm=Ta(),Am=Oa();Di.transports={websocket:Rm.WS,webtransport:Am.WT,polling:Pm.XHR}});var Ra=F(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});Pa.parse=Nm;var Im=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Lm=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Nm(r){if(r.length>8e3)throw"URI too long";let e=r,t=r.indexOf("["),n=r.indexOf("]");t!=-1&&n!=-1&&(r=r.substring(0,t)+r.substring(t,n).replace(/:/g,";")+r.substring(n,r.length));let s=Im.exec(r||""),i={},a=14;for(;a--;)i[Lm[a]]=s[a]||"";return t!=-1&&n!=-1&&(i.source=e,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=Dm(i,i.path),i.queryKey=Fm(i,i.query),i}function Dm(r,e){let t=/\/{2,9}/g,n=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&n.splice(0,1),e.slice(-1)=="/"&&n.splice(n.length-1,1),n}function Fm(r,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,s,i){s&&(t[s]=i)}),t}});var Na=F(tr=>{"use strict";var Mm=tr&&tr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(tr,"__esModule",{value:!0});tr.Socket=tr.SocketWithUpgrade=tr.SocketWithoutUpgrade=void 0;var Bm=ka(),Nl=Jr(),jm=Uo(),Dl=Ra(),Um=Yr(),Fl=xn(),Aa=Xr(),qm=Mm(At()),Ne=(0,qm.default)("engine.io-client:socket"),Ia=typeof addEventListener=="function"&&typeof removeEventListener=="function",_s=[];Ia&&addEventListener("offline",()=>{Ne("closing %d connection(s) because the network was lost",_s.length),_s.forEach(r=>r())},!1);var sn=class r extends Um.Emitter{constructor(e,t){if(super(),this.binaryType=Aa.defaultBinaryType,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){let n=(0,Dl.parse)(e);t.hostname=n.host,t.secure=n.protocol==="https"||n.protocol==="wss",t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=(0,Dl.parse)(t.host).host);(0,Nl.installTimerFunctions)(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(n=>{let s=n.prototype.name;this.transports.push(s),this._transportsByName[s]=n}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=(0,jm.decode)(this.opts.query)),Ia&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(Ne("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},_s.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,Aa.createCookieJar)()),this._open()}createTransport(e){Ne('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=Fl.protocol,t.transport=e,this.id&&(t.sid=this.id);let n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return Ne("options: %j",n),new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let e=this.opts.rememberUpgrade&&r.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){Ne("setting transport %s",e.name),this.transport&&(Ne("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){Ne("socket open"),this.readyState="open",r.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(Ne('socket receive: type "%s", data "%s"',e.type,e.data),this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}else Ne('packet received with socket readyState "%s"',this.readyState)}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();Ne("flushing %d packets in socket",e.length),this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let n=0;n<this.writeBuffer.length;n++){let s=this.writeBuffer[n].data;if(s&&(t+=(0,Nl.byteLength)(s)),n>0&&t>this._maxPayload)return Ne("only send %d out of %d packets",n,this.writeBuffer.length),this.writeBuffer.slice(0,n);t+=2}return Ne("payload size is %d (max: %d)",t,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(Ne("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,Aa.nextTick)(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,s){if(typeof t=="function"&&(s=t,t=void 0),typeof n=="function"&&(s=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;let i={type:e,data:t,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),s&&this.once("flush",s),this.flush()}close(){let e=()=>{this._onClose("forced close"),Ne("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(Ne("socket error %j",e),r.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return Ne("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(Ne('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Ia&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let n=_s.indexOf(this._offlineEventListener);n!==-1&&(Ne("removing listener for the 'offline' event"),_s.splice(n,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};tr.SocketWithoutUpgrade=sn;sn.protocol=Fl.protocol;var Fi=class extends sn{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){Ne("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){Ne('probing transport "%s"',e);let t=this.createTransport(e),n=!1;sn.priorWebsocketSuccess=!1;let s=()=>{n||(Ne('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",m=>{if(!n)if(m.type==="pong"&&m.data==="probe"){if(Ne('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;sn.priorWebsocketSuccess=t.name==="websocket",Ne('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{n||this.readyState!=="closed"&&(Ne("changing transport and sending upgrade packet"),g(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{Ne('probe transport "%s" failed',e);let y=new Error("probe error");y.transport=t.name,this.emitReserved("upgradeError",y)}}))};function i(){n||(n=!0,g(),t.close(),t=null)}let a=m=>{let y=new Error("probe error: "+m);y.transport=t.name,i(),Ne('probe transport "%s" failed because of error: %s',e,m),this.emitReserved("upgradeError",y)};function c(){a("transport closed")}function u(){a("socket closed")}function d(m){t&&m.name!==t.name&&(Ne('"%s" works - aborting "%s"',m.name,t.name),i())}let g=()=>{t.removeListener("open",s),t.removeListener("error",a),t.removeListener("close",c),this.off("close",u),this.off("upgrading",d)};t.once("open",s),t.once("error",a),t.once("close",c),this.once("close",u),this.once("upgrading",d),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}};tr.SocketWithUpgrade=Fi;var La=class extends Fi{constructor(e,t={}){let n=typeof e=="object"?e:t;(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(s=>Bm.transports[s]).filter(s=>!!s)),super(e,n)}};tr.Socket=La});var Ml=F(Mi=>{"use strict";Object.defineProperty(Mi,"__esModule",{value:!0});Mi.Fetch=void 0;var Wm=zo(),Da=class extends Wm.Polling{doPoll(){this._fetch().then(e=>{if(!e.ok)return this.onError("fetch read error",e.status,e);e.text().then(t=>this.onData(t))}).catch(e=>{this.onError("fetch read error",e)})}doWrite(e,t){this._fetch(e).then(n=>{if(!n.ok)return this.onError("fetch write error",n.status,n);t()}).catch(n=>{this.onError("fetch write error",n)})}_fetch(e){var t;let n=e!==void 0,s=new Headers(this.opts.extraHeaders);return n&&s.set("content-type","text/plain;charset=UTF-8"),(t=this.socket._cookieJar)===null||t===void 0||t.appendCookies(s),fetch(this.uri(),{method:n?"POST":"GET",body:n?e:null,headers:s,credentials:this.opts.withCredentials?"include":"omit"}).then(i=>{var a;return(a=this.socket._cookieJar)===null||a===void 0||a.parseCookies(i.headers.getSetCookie()),i})}};Mi.Fetch=Da});var Bi=F(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.WebTransport=xe.WebSocket=xe.NodeWebSocket=xe.XHR=xe.NodeXHR=xe.Fetch=xe.nextTick=xe.parse=xe.installTimerFunctions=xe.transports=xe.TransportError=xe.Transport=xe.protocol=xe.SocketWithUpgrade=xe.SocketWithoutUpgrade=xe.Socket=void 0;var Bl=Na();Object.defineProperty(xe,"Socket",{enumerable:!0,get:function(){return Bl.Socket}});var jl=Na();Object.defineProperty(xe,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return jl.SocketWithoutUpgrade}});Object.defineProperty(xe,"SocketWithUpgrade",{enumerable:!0,get:function(){return jl.SocketWithUpgrade}});xe.protocol=Bl.Socket.protocol;var Ul=as();Object.defineProperty(xe,"Transport",{enumerable:!0,get:function(){return Ul.Transport}});Object.defineProperty(xe,"TransportError",{enumerable:!0,get:function(){return Ul.TransportError}});var Hm=ka();Object.defineProperty(xe,"transports",{enumerable:!0,get:function(){return Hm.transports}});var Vm=Jr();Object.defineProperty(xe,"installTimerFunctions",{enumerable:!0,get:function(){return Vm.installTimerFunctions}});var Km=Ra();Object.defineProperty(xe,"parse",{enumerable:!0,get:function(){return Km.parse}});var $m=Xr();Object.defineProperty(xe,"nextTick",{enumerable:!0,get:function(){return $m.nextTick}});var zm=Ml();Object.defineProperty(xe,"Fetch",{enumerable:!0,get:function(){return zm.Fetch}});var Gm=Zo();Object.defineProperty(xe,"NodeXHR",{enumerable:!0,get:function(){return Gm.XHR}});var Ym=Xo();Object.defineProperty(xe,"XHR",{enumerable:!0,get:function(){return Ym.XHR}});var Xm=Ta();Object.defineProperty(xe,"NodeWebSocket",{enumerable:!0,get:function(){return Xm.WS}});var Jm=xa();Object.defineProperty(xe,"WebSocket",{enumerable:!0,get:function(){return Jm.WS}});var Zm=Oa();Object.defineProperty(xe,"WebTransport",{enumerable:!0,get:function(){return Zm.WT}})});var Wl=F(ys=>{"use strict";var Qm=ys&&ys.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ys,"__esModule",{value:!0});ys.url=r_;var e_=Bi(),t_=Qm(At()),ql=(0,t_.default)("socket.io-client:url");function r_(r,e="",t){let n=r;t=t||typeof location<"u"&&location,r==null&&(r=t.protocol+"//"+t.host),typeof r=="string"&&(r.charAt(0)==="/"&&(r.charAt(1)==="/"?r=t.protocol+r:r=t.host+r),/^(https?|wss?):\/\//.test(r)||(ql("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),ql("parse %s",r),n=(0,e_.parse)(r)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";let i=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+e,n.href=n.protocol+"://"+i+(t&&t.port===n.port?"":":"+n.port),n}});var Fa=F(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.isBinary=Vl;Ui.hasBinary=ji;var n_=typeof ArrayBuffer=="function",s_=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,Hl=Object.prototype.toString,i_=typeof Blob=="function"||typeof Blob<"u"&&Hl.call(Blob)==="[object BlobConstructor]",o_=typeof File=="function"||typeof File<"u"&&Hl.call(File)==="[object FileConstructor]";function Vl(r){return n_&&(r instanceof ArrayBuffer||s_(r))||i_&&r instanceof Blob||o_&&r instanceof File}function ji(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,n=r.length;t<n;t++)if(ji(r[t]))return!0;return!1}if(Vl(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return ji(r.toJSON(),!0);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&ji(r[t]))return!0;return!1}});var Kl=F(qi=>{"use strict";Object.defineProperty(qi,"__esModule",{value:!0});qi.deconstructPacket=c_;qi.reconstructPacket=f_;var a_=Fa();function c_(r){let e=[],t=r.data,n=r;return n.data=Ma(t,e),n.attachments=e.length,{packet:n,buffers:e}}function Ma(r,e){if(!r)return r;if((0,a_.isBinary)(r)){let t={_placeholder:!0,num:e.length};return e.push(r),t}else if(Array.isArray(r)){let t=new Array(r.length);for(let n=0;n<r.length;n++)t[n]=Ma(r[n],e);return t}else if(typeof r=="object"&&!(r instanceof Date)){let t={};for(let n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=Ma(r[n],e));return t}return r}function f_(r,e){return r.data=Ba(r.data,e),delete r.attachments,r}function Ba(r,e){if(!r)return r;if(r&&r._placeholder===!0){if(typeof r.num=="number"&&r.num>=0&&r.num<e.length)return e[r.num];throw new Error("illegal attachments")}else if(Array.isArray(r))for(let t=0;t<r.length;t++)r[t]=Ba(r[t],e);else if(typeof r=="object")for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=Ba(r[t],e));return r}});var Hi=F(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.Decoder=Ut.Encoder=Ut.PacketType=Ut.protocol=void 0;Ut.isPacketValid=m_;var u_=Yr(),$l=Kl(),zl=Fa(),l_=At(),ja=(0,l_.default)("socket.io-parser"),Gl=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];Ut.protocol=5;var Le;(function(r){r[r.CONNECT=0]="CONNECT",r[r.DISCONNECT=1]="DISCONNECT",r[r.EVENT=2]="EVENT",r[r.ACK=3]="ACK",r[r.CONNECT_ERROR=4]="CONNECT_ERROR",r[r.BINARY_EVENT=5]="BINARY_EVENT",r[r.BINARY_ACK=6]="BINARY_ACK"})(Le||(Ut.PacketType=Le={}));var Ua=class{constructor(e){this.replacer=e}encode(e){return ja("encoding packet %j",e),(e.type===Le.EVENT||e.type===Le.ACK)&&(0,zl.hasBinary)(e)?this.encodeAsBinary({type:e.type===Le.EVENT?Le.BINARY_EVENT:Le.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===Le.BINARY_EVENT||e.type===Le.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),ja("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=(0,$l.deconstructPacket)(e),n=this.encodeAsString(t.packet),s=t.buffers;return s.unshift(n),s}};Ut.Encoder=Ua;var qa=class r extends u_.Emitter{constructor(e){super(),this.reviver=e}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);let n=t.type===Le.BINARY_EVENT;n||t.type===Le.BINARY_ACK?(t.type=n?Le.EVENT:Le.ACK,this.reconstructor=new Wa(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,zl.isBinary)(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0,n={type:Number(e.charAt(0))};if(Le[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===Le.BINARY_EVENT||n.type===Le.BINARY_ACK){let i=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);let a=e.substring(i,t);if(a!=Number(a)||e.charAt(t)!=="-")throw new Error("Illegal attachments");n.attachments=Number(a)}if(e.charAt(t+1)==="/"){let i=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););n.nsp=e.substring(i,t)}else n.nsp="/";let s=e.charAt(t+1);if(s!==""&&Number(s)==s){let i=t+1;for(;++t;){let a=e.charAt(t);if(a==null||Number(a)!=a){--t;break}if(t===e.length)break}n.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){let i=this.tryParse(e.substr(t));if(r.isPayloadValid(n.type,i))n.data=i;else throw new Error("invalid payload")}return ja("decoded %s as %j",e,n),n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case Le.CONNECT:return Wi(t);case Le.DISCONNECT:return t===void 0;case Le.CONNECT_ERROR:return typeof t=="string"||Wi(t);case Le.EVENT:case Le.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Gl.indexOf(t[0])===-1);case Le.ACK:case Le.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};Ut.Decoder=qa;var Wa=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let t=(0,$l.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function h_(r){return typeof r=="string"}var d_=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function p_(r){return r===void 0||d_(r)}function Wi(r){return Object.prototype.toString.call(r)==="[object Object]"}function g_(r,e){switch(r){case Le.CONNECT:return e===void 0||Wi(e);case Le.DISCONNECT:return e===void 0;case Le.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Gl.indexOf(e[0])===-1);case Le.ACK:return Array.isArray(e);case Le.CONNECT_ERROR:return typeof e=="string"||Wi(e);default:return!1}}function m_(r){return h_(r.nsp)&&p_(r.id)&&g_(r.type,r.data)}});var Va=F(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});Ha.on=__;function __(r,e,t){return r.on(e,t),function(){r.off(e,t)}}});var $a=F(Mn=>{"use strict";var y_=Mn&&Mn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Mn,"__esModule",{value:!0});Mn.Socket=void 0;var qt=Hi(),Vi=Va(),E_=Yr(),v_=y_(At()),Qe=(0,v_.default)("socket.io-client:socket"),w_=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Ka=class extends E_.Emitter{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[(0,Vi.on)(e,"open",this.onopen.bind(this)),(0,Vi.on)(e,"packet",this.onpacket.bind(this)),(0,Vi.on)(e,"error",this.onerror.bind(this)),(0,Vi.on)(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,s,i;if(w_.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let a={type:qt.PacketType.EVENT,data:t};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let g=this.ids++;Qe("emitting packet with ack id %d",g);let m=t.pop();this._registerAckCallback(g,m),a.id=g}let c=(s=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||s===void 0?void 0:s.writable,u=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!c?Qe("discard packet as the transport is not currently writable"):u?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a),this.flags={},this}_registerAckCallback(e,t){var n;let s=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(s===void 0){this.acks[e]=t;return}let i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===e&&(Qe("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(c,1));Qe("event with ack id %d has timed out after %d ms",e,s),t.call(this,new Error("operation has timed out"))},s),a=(...c)=>{this.io.clearTimeoutFn(i),t.apply(this,c)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((n,s)=>{let i=(a,c)=>a?s(a):n(c);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((s,...i)=>n!==this._queue[0]?Qe("packet [%d] already acknowledged",n.id):(s!==null?n.tryCount>this._opts.retries&&(Qe("packet [%d] is discarded after %d tries",n.id,n.tryCount),this._queue.shift(),t&&t(s)):(Qe("packet [%d] was successfully sent",n.id),this._queue.shift(),t&&t(null,...i)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(Qe("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){Qe("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,Qe("sending packet [%d] (try n\xB0%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){Qe("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:qt.PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){Qe("close (%s)",e),this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(n=>String(n.id)===e)){let n=this.acks[e];delete this.acks[e],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case qt.PacketType.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case qt.PacketType.EVENT:case qt.PacketType.BINARY_EVENT:this.onevent(e);break;case qt.PacketType.ACK:case qt.PacketType.BINARY_ACK:this.onack(e);break;case qt.PacketType.DISCONNECT:this.ondisconnect();break;case qt.PacketType.CONNECT_ERROR:this.destroy();let n=new Error(e.data.message);n.data=e.data.data,this.emitReserved("connect_error",n);break}}onevent(e){let t=e.data||[];Qe("emitting event %j",t),e.id!=null&&(Qe("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,n=!1;return function(...s){n||(n=!0,Qe("sending ack %j",s),t.packet({type:qt.PacketType.ACK,id:e,data:s}))}}onack(e){let t=this.acks[e.id];if(typeof t!="function"){Qe("bad ack %s",e.id);return}delete this.acks[e.id],Qe("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){Qe("socket connected with id %s",e),this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){Qe("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(Qe("performing disconnect (%s)",this.nsp),this.packet({type:qt.PacketType.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let n of t)n.apply(this,e.data)}}};Mn.Socket=Ka});var Yl=F(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.Backoff=Bn;function Bn(r){r=r||{},this.ms=r.min||100,this.max=r.max||1e4,this.factor=r.factor||2,this.jitter=r.jitter>0&&r.jitter<=1?r.jitter:0,this.attempts=0}Bn.prototype.duration=function(){var r=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*r);r=(Math.floor(e*10)&1)==0?r-t:r+t}return Math.min(r,this.max)|0};Bn.prototype.reset=function(){this.attempts=0};Bn.prototype.setMin=function(r){this.ms=r};Bn.prototype.setMax=function(r){this.max=r};Bn.prototype.setJitter=function(r){this.jitter=r}});var Xl=F(Nt=>{"use strict";var b_=Nt&&Nt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),x_=Nt&&Nt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),S_=Nt&&Nt.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&b_(e,r,t);return x_(e,r),e},T_=Nt&&Nt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Nt,"__esModule",{value:!0});Nt.Manager=void 0;var Ga=Bi(),C_=$a(),O_=S_(Hi()),on=Va(),k_=Yl(),P_=Yr(),R_=T_(At()),st=(0,R_.default)("socket.io-client:manager"),Ya=class extends P_.Emitter{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,(0,Ga.installTimerFunctions)(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((n=t.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new k_.Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;let s=t.parser||O_;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(st("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;st("opening %s",this.uri),this.engine=new Ga.Socket(this.uri,this.opts);let t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;let s=(0,on.on)(t,"open",function(){n.onopen(),e&&e()}),i=c=>{st("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},a=(0,on.on)(t,"error",i);if(this._timeout!==!1){let c=this._timeout;st("connect attempt will timeout after %d",c);let u=this.setTimeoutFn(()=>{st("connect attempt timed out after %d",c),s(),i(new Error("timeout")),t.close()},c);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(s),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){st("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push((0,on.on)(e,"ping",this.onping.bind(this)),(0,on.on)(e,"data",this.ondata.bind(this)),(0,on.on)(e,"error",this.onerror.bind(this)),(0,on.on)(e,"close",this.onclose.bind(this)),(0,on.on)(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){(0,Ga.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){st("error",e),this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new C_.Socket(this,e,t),this.nsps[e]=n),n}_destroy(e){let t=Object.keys(this.nsps);for(let n of t)if(this.nsps[n].active){st("socket %s is still active, skipping close",n);return}this._close()}_packet(e){st("writing packet %j",e);let t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){st("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){st("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;st("closed due to %s",e),this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)st("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();st("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(st("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(s=>{s?(st("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",s)):(st("reconnect success"),e.onreconnect())}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}};Nt.Manager=Ya});var eh=F((Fe,Ql)=>{"use strict";var A_=Fe&&Fe.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Fe,"__esModule",{value:!0});Fe.WebTransport=Fe.WebSocket=Fe.NodeWebSocket=Fe.XHR=Fe.NodeXHR=Fe.Fetch=Fe.Socket=Fe.Manager=Fe.protocol=void 0;Fe.io=an;Fe.connect=an;Fe.default=an;var I_=Wl(),Ki=Xl();Object.defineProperty(Fe,"Manager",{enumerable:!0,get:function(){return Ki.Manager}});var Zl=$a();Object.defineProperty(Fe,"Socket",{enumerable:!0,get:function(){return Zl.Socket}});var L_=A_(At()),Jl=(0,L_.default)("socket.io-client"),Es={};function an(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};let t=(0,I_.url)(r,e.path||"/socket.io"),n=t.source,s=t.id,i=t.path,a=Es[s]&&i in Es[s].nsps,c=e.forceNew||e["force new connection"]||e.multiplex===!1||a,u;return c?(Jl("ignoring socket cache for %s",n),u=new Ki.Manager(n,e)):(Es[s]||(Jl("new io instance for %s",n),Es[s]=new Ki.Manager(n,e)),u=Es[s]),t.query&&!e.query&&(e.query=t.queryKey),u.socket(t.path,e)}Object.assign(an,{Manager:Ki.Manager,Socket:Zl.Socket,io:an,connect:an});var N_=Hi();Object.defineProperty(Fe,"protocol",{enumerable:!0,get:function(){return N_.protocol}});var jn=Bi();Object.defineProperty(Fe,"Fetch",{enumerable:!0,get:function(){return jn.Fetch}});Object.defineProperty(Fe,"NodeXHR",{enumerable:!0,get:function(){return jn.NodeXHR}});Object.defineProperty(Fe,"XHR",{enumerable:!0,get:function(){return jn.XHR}});Object.defineProperty(Fe,"NodeWebSocket",{enumerable:!0,get:function(){return jn.NodeWebSocket}});Object.defineProperty(Fe,"WebSocket",{enumerable:!0,get:function(){return jn.WebSocket}});Object.defineProperty(Fe,"WebTransport",{enumerable:!0,get:function(){return jn.WebTransport}});Ql.exports=an});var sh=F($i=>{"use strict";Object.defineProperty($i,"__esModule",{value:!0});$i.WebSocketService=void 0;var D_=eh(),th=kr(),rh=$s(),nh=Hs(),Xa=class{authService;cryptoService;config;logger;notification;deviceId;platform;socket=null;inputHandler=null;createTerminalHandler=null;getBufferHandler=null;redrawHandler=null;resizeHandler=null;reconnectHandlers=[];authFailureHandler=null;fileViewRequestHandler=null;fileListRequestHandler=null;fileDownloadRequestHandler=null;statusChangeHandler=null;agentNameSyncHandler=null;clientAttachedHandler=null;clientDetachedHandler=null;agentId=null;hasConnectedOnce=!1;isRemoteRename=!1;negotiatedCapabilities=[];HEARTBEAT_INTERVAL=3e4;HEARTBEAT_TIMEOUT=1e4;heartbeatTimer=null;pongTimer=null;lastPongTime=0;isManualDisconnect=!1;reconnectAttempts=0;reconnectTimer=null;networkCheckTimer=null;isOnline=!0;lastNetworkCheck=0;rekeyingTerminals=new Set;outputBuffer=new Map;OUTPUT_BUFFER_MAX_SIZE=1e3;RECONNECT_BASE_DELAY=1e3;RECONNECT_MAX_DELAY=3e4;RECONNECT_JITTER=.2;NETWORK_CHECK_INTERVAL=5e3;constructor(e,t,n,s,i,a,c="vscode"){this.authService=e,this.cryptoService=t,this.config=n,this.logger=s,this.notification=i,this.deviceId=a,this.platform=c}async connect(){let e=await this.authService.getAccessToken();if(!e)throw new Error("No access token available");this.isManualDisconnect=!1,this.stopReconnect(),this.reconnectAttempts=0,this.agentId=await this.authService.getAgentId();let t=(0,rh.getWsUrl)(this.config);this.logger.info("Connecting to WebSocket",t),this.statusChangeHandler?.("connecting");let n=await this.cryptoService.getPublicKey();return new Promise((s,i)=>{this.socket=(0,D_.io)(`${t}/agent`,{auth:{token:e,protocolVersion:th.PROTOCOL_VERSION,deviceId:this.deviceId,platform:this.platform,capabilities:th.DEFAULT_CLIENT_CAPABILITIES,publicKey:n},transports:["websocket"],reconnection:!1}),this.socket.on("connect",()=>{if(this.logger.info("WebSocket connected"),this.reconnectAttempts=0,this.statusChangeHandler?.("connected",this.agentId??void 0),this.startHeartbeat(),this.cryptoService.cleanupAllStaleSessions(),this.hasConnectedOnce){this.logger.info("Reconnected - triggering workspace re-registration");for(let a of this.reconnectHandlers)a()}else this.hasConnectedOnce=!0,s()}),this.socket.on("error",a=>{this.logger.error(`Server error [${a.code}]: ${a.message}`),a.code==="E401"&&(this.logger.warn("Auth failure (E401)"),this.authFailureHandler?.())}),this.socket.on("disconnect",a=>{this.logger.warn("WebSocket disconnected",a),this.stopHeartbeat(),this.statusChangeHandler?.("disconnected"),this.isManualDisconnect||(a==="transport close"?(this.logger.info("Transport close - attempting immediate reconnect"),this.attemptReconnect(!0)):this.scheduleReconnect())}),this.socket.on("protocol:info",a=>{this.logger.info("Protocol info received",a.protocolVersion),this.negotiatedCapabilities=a.negotiatedCapabilities,a.agentName&&this.config.getAgentName()!==a.agentName&&(this.isRemoteRename=!0,this.config.setAgentName(a.agentName).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(a.agentName),this.logger.info("Agent name synced from server",a.agentName))}),this.socket.on("pong",()=>{this.lastPongTime=Date.now(),this.clearPongTimeout(),this.logger.debug("Heartbeat pong received")}),this.socket.on("connect_error",a=>{this.logger.error("WebSocket connection error",a),this.statusChangeHandler?.("error"),this.hasConnectedOnce||i(a),this.scheduleReconnect()}),this.socket.on("terminal:input",a=>{this.handleTerminalInput(a)}),this.socket.on("crypto:keyExchange",async(a,c)=>{this.logger.info("Received key exchange request",a.terminalId,a.sessionId),this.rekeyingTerminals.add(a.terminalId),this.outputBuffer.set(a.terminalId,[]);try{if(await this.cryptoService.handleKeyExchange(a.terminalId,a.clientPublicKey,a.sessionId)){let d=await this.cryptoService.getPublicKey();c?.({success:!0,agentPublicKey:d||void 0}),this.flushOutputBuffer(a.terminalId)}else c?.({success:!1,error:"Key exchange failed"})}catch(u){this.logger.error("Key exchange error",u),c?.({success:!1,error:String(u)})}finally{this.rekeyingTerminals.delete(a.terminalId),this.outputBuffer.delete(a.terminalId)}}),this.socket.on("crypto:sessionCleanup",a=>{this.cryptoService.removeSession(a.terminalId,a.sessionId)}),this.socket.on("agent:keyExchangeRequest",async a=>{try{let c=await this.cryptoService.handleAgentKeyExchange(a.clientPublicKey,a.sessionId),u={agentId:a.agentId,sessionId:a.sessionId,ok:c,error:c?void 0:"Key exchange failed"};this.socket?.emit("agent:keyExchangeAck",u)}catch(c){this.logger.error("Agent key exchange error",c);let u={agentId:a.agentId,sessionId:a.sessionId,ok:!1,error:String(c)};this.socket?.emit("agent:keyExchangeAck",u)}}),this.socket.on("agent:sessionEnd",a=>{this.cryptoService.removeAgentSession(a.sessionId)}),this.socket.on("agent:renamed",a=>{this.logger.info("Agent renamed from web client",a.name),this.isRemoteRename=!0,this.config.setAgentName(a.name).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(a.name)}),this.socket.on("terminal:createRequest",a=>{this.createTerminalHandler?.(a.name)}),this.socket.on("terminal:getBuffer",(a,c)=>{if(!this.getBufferHandler){c?.({success:!1,error:"Buffer handler not set"});return}let u=this.getBufferHandler(a.terminalId);if(u===null){c?.({success:!1,error:"Terminal not found"});return}let d=this.cryptoService.encryptOutput(a.terminalId,u);c?.(d?{success:!0,encrypted:d}:{success:!0,data:u}),this.redrawHandler?.(a.terminalId)}),this.socket.on("terminal:resize",a=>{this.resizeHandler?.(a.terminalId,a.cols,a.rows)}),this.socket.on("workspace:clientAttached",a=>{this.clientAttachedHandler?.(a)}),this.socket.on("workspace:clientDetached",a=>{this.clientDetachedHandler?.(a)}),this.socket.on("file:view",a=>{this.fileViewRequestHandler?.(a.terminalId,a.request)}),this.socket.on("file:list",a=>{this.fileListRequestHandler?.(a.terminalId,a.request)}),this.socket.on("file:download:request",a=>{this.fileDownloadRequestHandler?.(a.terminalId,a.path,a.requestId)})})}disconnect(){this.isManualDisconnect=!0,this.hasConnectedOnce=!1,this.stopReconnect(),this.stopHeartbeat(),this.cryptoService.clearAllSessions(),this.socket&&(this.logger.info("Disconnecting WebSocket"),this.socket.disconnect(),this.socket=null)}softDisconnect(){this.stopReconnect(),this.stopHeartbeat(),this.socket&&(this.logger.info("Soft disconnecting WebSocket (for reconnect)"),this.socket.disconnect(),this.socket=null)}getStatus(){return{connected:this.socket?.connected??!1,agentId:this.agentId}}onInput(e){this.inputHandler=e}onCreateTerminalRequest(e){this.createTerminalHandler=e}onGetBufferRequest(e){this.getBufferHandler=e}onRedrawRequest(e){this.redrawHandler=e}onResizeRequest(e){this.resizeHandler=e}onReconnect(e){this.reconnectHandlers.push(e)}onAuthFailure(e){this.authFailureHandler=e}onFileViewRequest(e){this.fileViewRequestHandler=e}onFileListRequest(e){this.fileListRequestHandler=e}onFileDownloadRequest(e){this.fileDownloadRequestHandler=e}onStatusChange(e){this.statusChangeHandler=e}onAgentNameSync(e){this.agentNameSyncHandler=e}onClientAttached(e){this.clientAttachedHandler=e}onClientDetached(e){this.clientDetachedHandler=e}async registerWorkspace(e){return this.emit("workspace:register",e)}async unregisterWorkspace(e){await this.emit("workspace:unregister",{instanceId:e})}async terminalCreated(e){return this.emit("terminal:created",e)}async terminalClosed(e){this.cryptoService.removeSession(e.terminalId),await this.emit("terminal:closed",e)}terminalNotFound(e){this.socket?.emit("terminal:notFound",{terminalId:e})}sendOutput(e,t,n){if(!this.socket?.connected)return;if(this.rekeyingTerminals.has(t)){let a=this.outputBuffer.get(t);a&&a.length<this.OUTPUT_BUFFER_MAX_SIZE&&a.push({instanceId:e,data:n});return}let s=this.cryptoService.encryptOutput(t,n),i={instanceId:e,terminalId:t,...s?{encrypted:s}:{data:n}};this.socket?.emit("terminal:output",i)}flushOutputBuffer(e){let t=this.outputBuffer.get(e);if(!(!t||t.length===0)){this.logger.info("Flushing output buffer after rekey",e,String(t.length));for(let{instanceId:n,data:s}of t){let i=this.cryptoService.encryptOutput(e,s),a={instanceId:n,terminalId:e,...i?{encrypted:i}:{data:s}};this.socket?.emit("terminal:output",a)}}}async updateStatus(e){await this.emit("terminal:status",e)}sendTerminalEvent(e,t,n){let s={instanceId:e,terminalId:t,event:n};this.socket?.emit("terminal:event",s)}hasCapability(e){return this.negotiatedCapabilities.includes(e)}sendFileChangedEvent(e,t,n){let s={instanceId:e,terminalId:t,event:n};this.socket?.emit("file:changed",s)}sendFileListResponse(e,t){let n={instanceId:e,response:t};this.socket?.emit("file:list:response",n)}sendAgentRename(e){this.socket?.emit("agent:rename",{name:e})}isRemoteRenameInProgress(){return this.isRemoteRename}getSocket(){return this.socket}emit(e,t){let n=(0,nh.generateCorrelationId)(),s=t&&typeof t=="object"&&!Array.isArray(t)?{...t,_cid:n}:t;return(0,nh.runWithCorrelation)(n,()=>new Promise((i,a)=>{if(!this.socket?.connected){a(new Error("WebSocket not connected"));return}this.socket.emit(e,s,c=>{c.success?i(c):a(new Error(c.error||"Unknown error"))})}))}startHeartbeat(){this.stopHeartbeat(),this.lastPongTime=Date.now(),this.heartbeatTimer=setInterval(()=>{if(!this.socket?.connected){this.stopHeartbeat();return}if(Date.now()-this.lastPongTime>this.HEARTBEAT_INTERVAL+this.HEARTBEAT_TIMEOUT){this.logger.warn("Heartbeat timeout"),this.socket.disconnect();return}this.socket.emit("ping"),this.pongTimer=setTimeout(()=>{this.logger.warn("Pong timeout - server not responding"),this.statusChangeHandler?.("error")},this.HEARTBEAT_TIMEOUT)},this.HEARTBEAT_INTERVAL)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.clearPongTimeout()}clearPongTimeout(){this.pongTimer&&(clearTimeout(this.pongTimer),this.pongTimer=null)}handleTerminalInput(e){let t;if(e.encrypted){let n=this.cryptoService.decryptInput(e.terminalId,e.encrypted);if(!n){this.logger.error("Failed to decrypt terminal input",e.terminalId);return}t=n}else if(e.data)t=Buffer.from(e.data,"base64").toString("utf8");else{this.logger.error("Invalid terminal input payload");return}this.inputHandler?.(e.terminalId,t,e.dbTerminalId)}hasE2ESession(e){return this.cryptoService.hasSession(e)}getReconnectDelay(){let e=Math.min(this.RECONNECT_BASE_DELAY*Math.pow(2,this.reconnectAttempts),this.RECONNECT_MAX_DELAY),t=1+(Math.random()*2-1)*this.RECONNECT_JITTER;return Math.floor(e*t)}scheduleReconnect(){if(this.isManualDisconnect)return;this.stopReconnect();let e=this.getReconnectDelay();if(this.logger.info("Scheduling reconnect",String(this.reconnectAttempts+1),"delay:",String(e)),!this.isOnline){this.statusChangeHandler?.("disconnected"),this.startNetworkCheck();return}this.statusChangeHandler?.("connecting"),this.reconnectTimer=setTimeout(()=>{this.attemptReconnect()},e)}async attemptReconnect(e=!1){if(this.isManualDisconnect||this.socket?.connected)return;let t=await this.authService.hasValidToken();if(!t){if(this.logger.info("Access token expired, attempting refresh"),!await this.authService.refreshAccessToken()){this.logger.info("Token refresh failed, stopping reconnect"),this.stopReconnect(),this.statusChangeHandler?.("disconnected"),this.notification.warn("Session expired. Please log in again."),this.authFailureHandler?.();return}t=!0}this.reconnectAttempts++;try{if(this.socket&&(this.socket.disconnect(),this.socket=null),!e&&!await this.checkNetwork()){this.isOnline=!1,this.scheduleReconnect();return}this.isOnline=!0,await this.connect(),this.reconnectAttempts=0}catch(n){this.logger.warn("Reconnect failed",n),this.statusChangeHandler?.("error"),this.scheduleReconnect()}}stopReconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stopNetworkCheck()}async checkNetwork(){let e=Date.now();if(e-this.lastNetworkCheck<1e3)return this.isOnline;this.lastNetworkCheck=e;try{let t=`${(0,rh.getApiUrl)(this.config)}/health`,n=new AbortController,s=setTimeout(()=>n.abort(),5e3),i=await fetch(t,{method:"GET",signal:n.signal});return clearTimeout(s),this.logger.debug("Network check OK",String(i.status)),!0}catch{return this.logger.debug("Network check failed (offline)"),!1}}startNetworkCheck(){this.stopNetworkCheck(),this.networkCheckTimer=setInterval(async()=>{if(this.isManualDisconnect){this.stopNetworkCheck();return}if(this.socket?.connected){this.stopNetworkCheck();return}let e=await this.checkNetwork();e&&!this.isOnline?(this.logger.info("Network restored! Triggering immediate reconnect"),this.isOnline=!0,this.stopNetworkCheck(),this.reconnectAttempts=0,this.attemptReconnect()):e&&this.isOnline?(this.stopNetworkCheck(),this.attemptReconnect()):e||(this.isOnline=!1)},this.NETWORK_CHECK_INTERVAL)}stopNetworkCheck(){this.networkCheckTimer&&(clearInterval(this.networkCheckTimer),this.networkCheckTimer=null)}};$i.WebSocketService=Xa});var oh=F(rr=>{"use strict";var F_=rr&&rr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),M_=rr&&rr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Za=rr&&rr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[n.length]=s);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),s=0;s<n.length;s++)n[s]!=="default"&&F_(t,e,n[s]);return M_(t,e),t}})();Object.defineProperty(rr,"__esModule",{value:!0});rr.FileTransferService=void 0;var zi=Za(require("fs")),B_=Za(require("path")),ih=Za(require("crypto")),Me=kr(),Ja=class{socket=null;activeTransfers=new Map;instanceId="";logger;fallbackDir;constructor(e,t="/tmp"){this.logger=e,this.fallbackDir=t}attach(e,t){this.socket=e,this.instanceId=t,this.setupEventHandlers(),this.logger.info("FileTransferService attached")}detach(){this.socket=null;for(let[e]of this.activeTransfers)this.cancelTransfer(e,"Disconnected");this.logger.info("FileTransferService detached")}async sendFile(e,t,n,s,i){let a=zi.readFileSync(t),c=t.split("/").pop()||"file";return this.initAndSendChunks(e,a,c,{mimeType:this.getMimeType(c),requestId:i,onProgress:n,onComplete:s})}async sendBuffer(e,t,n,s,i){return this.initAndSendChunks(e,t,n,{mimeType:s,purpose:i?.purpose,viewMetadata:i?.viewMetadata,requestId:i?.requestId,onProgress:i?.onProgress,onComplete:i?.onComplete})}async initAndSendChunks(e,t,n,s){if(!this.socket)throw new Error("Socket not connected");let i=t.length,a=(0,Me.calculateTotalChunks)(i),c=this.calculateChecksum(t),u=ih.randomUUID(),d={id:u,terminalId:e,filename:n,size:i,totalChunks:a,direction:Me.TransferDirection.DOWNLOAD,status:Me.TransferStatus.PENDING,deliveredChunks:new Set,pendingChunks:new Map,checksum:c,checksumAlgorithm:"sha256",onProgress:s.onProgress?(m,y)=>s.onProgress(u,m,y):void 0,onComplete:s.onComplete?(m,y)=>s.onComplete(u,m,y):void 0,ackTimeouts:new Map};d.chunks=[];for(let m=0;m<a;m++){let y=m*Me.CHUNK_SIZE,w=Math.min(y+Me.CHUNK_SIZE,i);d.chunks.push(t.subarray(y,w))}this.activeTransfers.set(u,d);let g={transferId:u,terminalId:e,filename:n,size:i,totalChunks:a,mimeType:s.mimeType||"application/octet-stream",checksum:c,direction:Me.TransferDirection.DOWNLOAD,instanceId:this.instanceId};return s.requestId&&(g.requestId=s.requestId),s.purpose&&(g.purpose=s.purpose),s.viewMetadata&&(g.viewMetadata=s.viewMetadata),new Promise((m,y)=>{this.socket.emit("file:init",g,w=>{w.accepted?(d.status=Me.TransferStatus.ACTIVE,this.startSendingChunks(u),m(u)):(this.activeTransfers.delete(u),y(new Error(w.error||"Transfer rejected")))})})}async receiveFile(e,t,n,s,i,a,c,u="sha256",d,g){let m={id:e,terminalId:t,filename:n,filePath:c,size:s,totalChunks:i,direction:Me.TransferDirection.UPLOAD,status:Me.TransferStatus.ACTIVE,deliveredChunks:new Set,pendingChunks:new Map,chunks:new Array(i).fill(null),checksum:a,checksumAlgorithm:u,onProgress:d?(y,w)=>d(e,y,w):void 0,onComplete:g?(y,w)=>g(e,y,w):void 0,ackTimeouts:new Map};this.activeTransfers.set(e,m)}cancelTransfer(e,t){let n=this.activeTransfers.get(e);if(n){for(let s of n.ackTimeouts.values())clearTimeout(s);if(n.status=Me.TransferStatus.CANCELLED,n.onComplete?.(!1,t),this.socket){let s={transferId:e,reason:t};this.socket.emit("file:cancel",s)}this.activeTransfers.delete(e)}}async resumeTransfer(e){let t=this.activeTransfers.get(e);!t||!this.socket||this.socket.emit("file:sync",{transferId:e},n=>{if(n.status===Me.TransferStatus.EXPIRED){t.onComplete?.(!1,"Transfer expired"),this.activeTransfers.delete(e);return}if(n.deliveredChunks)for(let s of n.deliveredChunks)t.deliveredChunks.add(s);if(t.direction===Me.TransferDirection.DOWNLOAD&&n.missingChunks){t.status=Me.TransferStatus.ACTIVE;for(let s of n.missingChunks)this.sendChunk(t,s)}})}getTransferStatus(e){return this.activeTransfers.get(e)?.status??null}getTransferProgress(e){let t=this.activeTransfers.get(e);return t?{delivered:t.deliveredChunks.size,total:t.totalChunks}:null}setupEventHandlers(){this.socket&&(this.socket.on("file:chunk",e=>{this.handleIncomingChunk(e)}),this.socket.on("file:chunk:ack",e=>{this.handleChunkAck(e)}),this.socket.on("file:complete",e=>{this.handleComplete(e)}),this.socket.on("file:progress",e=>{this.handleProgress(e)}),this.socket.on("file:init",(e,t)=>{this.handleIncomingFileInit(e,t)}),this.socket.on("file:cancel",e=>{let t=this.activeTransfers.get(e.transferId);if(t){for(let n of t.ackTimeouts.values())clearTimeout(n);t.status=Me.TransferStatus.CANCELLED,t.onComplete?.(!1,e.reason||"Cancelled by remote"),this.activeTransfers.delete(e.transferId)}}))}startSendingChunks(e){let t=this.activeTransfers.get(e);if(!(!t||!t.chunks))for(let n=0;n<Math.min(Me.WINDOW_SIZE,t.totalChunks);n++)t.deliveredChunks.has(n)||this.sendChunk(t,n)}sendChunk(e,t){if(!this.socket||!e.chunks)return;let n=e.chunks[t];if(!n)return;let s=e.pendingChunks.get(t),i={seq:t,data:n,retries:s?s.retries:0,sentAt:Date.now()};e.pendingChunks.set(t,i);let a={transferId:e.id,seq:t,data:n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)};this.socket.emit("file:chunk",a,u=>{u&&!u.success&&this.cancelTransfer(e.id,u.error||"Server rejected chunk")});let c=setTimeout(()=>{this.handleAckTimeout(e.id,t)},Me.ACK_TIMEOUT_MS);e.ackTimeouts.set(t,c)}handleChunkAck(e){let t=this.activeTransfers.get(e.transferId);if(!t||t.status===Me.TransferStatus.COMPLETED)return;let n=t.ackTimeouts.get(e.seq);n&&(clearTimeout(n),t.ackTimeouts.delete(e.seq)),t.deliveredChunks.add(e.seq),t.pendingChunks.delete(e.seq),t.onProgress?.(t.deliveredChunks.size,t.totalChunks);let s=e.seq+Me.WINDOW_SIZE;s<t.totalChunks&&!t.deliveredChunks.has(s)&&this.sendChunk(t,s),t.deliveredChunks.size===t.totalChunks&&this.finishSending(t)}handleAckTimeout(e,t){let n=this.activeTransfers.get(e);if(!n)return;let s=n.pendingChunks.get(t);s&&(s.retries<Me.MAX_RETRIES?(s.retries++,this.sendChunk(n,t)):this.cancelTransfer(e,"Max retries exceeded"))}finishSending(e){if(!this.socket)return;e.status=Me.TransferStatus.COMPLETED;let t={transferId:e.id,checksum:e.checksum};this.socket.emit("file:end",t)}handleIncomingChunk(e){let t=this.activeTransfers.get(e.transferId);if(!(!t||!t.chunks)){if(t.chunks[e.seq]=Buffer.from(e.data),t.deliveredChunks.add(e.seq),this.socket){let n={transferId:e.transferId,seq:e.seq};this.socket.emit("file:chunk:ack",n)}t.onProgress?.(t.deliveredChunks.size,t.totalChunks),t.deliveredChunks.size===t.totalChunks&&this.finishReceiving(t)}}finishReceiving(e){if(!e.chunks||!e.filePath)return;let t=Buffer.concat(e.chunks);if(this.calculateChecksum(t,e.checksumAlgorithm)!==e.checksum){e.status=Me.TransferStatus.FAILED,e.onComplete?.(!1,"Checksum mismatch"),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!1,error:"Checksum mismatch"});return}try{let s=B_.dirname(e.filePath);zi.existsSync(s)||zi.mkdirSync(s,{recursive:!0}),zi.writeFileSync(e.filePath,t),e.status=Me.TransferStatus.COMPLETED,e.onComplete?.(!0),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!0})}catch(s){let i=s instanceof Error?s.message:String(s);e.status=Me.TransferStatus.FAILED,e.onComplete?.(!1,`Failed to save file: ${i}`),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!1,error:`Failed to save file: ${i}`})}this.activeTransfers.delete(e.id)}handleComplete(e){let t=this.activeTransfers.get(e.transferId);if(t){e.success?(t.status=Me.TransferStatus.COMPLETED,t.onComplete?.(!0)):(t.status=Me.TransferStatus.FAILED,t.onComplete?.(!1,e.error));for(let n of t.ackTimeouts.values())clearTimeout(n);this.activeTransfers.delete(e.transferId)}}handleProgress(e){let t=this.activeTransfers.get(e.transferId);t&&t.onProgress?.(e.deliveredChunks,e.totalChunks)}handleIncomingFileInit(e,t){let s=`${e.targetPath||this.fallbackDir}/${e.filename}`;this.receiveFile(e.transferId,e.terminalId,e.filename,e.size,e.totalChunks,e.checksum,s,e.checksumAlgorithm||"sha256").then(()=>t({accepted:!0})).catch(i=>t({accepted:!1,error:i.message}))}calculateChecksum(e,t="sha256"){return t==="fnv1a"?this.fnv1aHash(e):ih.createHash("sha256").update(e).digest("hex")}fnv1aHash(e){let t=2166136261;for(let s=0;s<e.length;s++)t^=e[s],t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0").repeat(8)}getMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{txt:"text/plain",json:"application/json",js:"application/javascript",ts:"application/typescript",html:"text/html",css:"text/css",md:"text/markdown",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf",zip:"application/zip",tar:"application/x-tar",gz:"application/gzip"}[t||""]||"application/octet-stream"}};rr.FileTransferService=Ja});var ic=F((gw,Xi)=>{function fh(r){return Array.isArray(r)?r:[r]}var j_=void 0,ec="",ah=" ",Qa="\\",U_=/^\s+$/,q_=/(?:[^\\]|^)\\$/,W_=/^\\!/,H_=/^\\#/,V_=/\r?\n/g,K_=/^\.{0,2}\/|^\.{1,2}$/,$_=/\/$/,Un="/",uh="node-ignore";typeof Symbol<"u"&&(uh=Symbol.for("node-ignore"));var lh=uh,qn=(r,e,t)=>(Object.defineProperty(r,e,{value:t}),t),z_=/([0-z])-([0-z])/g,hh=()=>!1,G_=r=>r.replace(z_,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:ec),Y_=r=>{let{length:e}=r;return r.slice(0,e-e%2)},X_=[[/^\uFEFF/,()=>ec],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?ah:ec)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+ah}],[/[\\$.|*+(){^]/g,r=>`\\${r}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(r,e,t)=>e+6<t.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(r,e,t)=>{let n=t.replace(/\\\*/g,"[^\\/]*");return e+n}],[/\\\\\\(?=[$.|*+(){^])/g,()=>Qa],[/\\\\/g,()=>Qa],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,n,s)=>e===Qa?`\\[${t}${Y_(n)}${s}`:s==="]"&&n.length%2===0?`[${G_(t)}${n}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`]],J_=/(^|\\\/)?\\\*$/,vs="regex",Gi="checkRegex",ch="_",Z_={[vs](r,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[Gi](r,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},Q_=r=>X_.reduce((e,[t,n])=>e.replace(t,n.bind(r)),r),Yi=r=>typeof r=="string",ey=r=>r&&Yi(r)&&!U_.test(r)&&!q_.test(r)&&r.indexOf("#")!==0,ty=r=>r.split(V_).filter(Boolean),tc=class{constructor(e,t,n,s,i,a){this.pattern=e,this.mark=t,this.negative=i,qn(this,"body",n),qn(this,"ignoreCase",s),qn(this,"regexPrefix",a)}get regex(){let e=ch+vs;return this[e]?this[e]:this._make(vs,e)}get checkRegex(){let e=ch+Gi;return this[e]?this[e]:this._make(Gi,e)}_make(e,t){let n=this.regexPrefix.replace(J_,Z_[e]),s=this.ignoreCase?new RegExp(n,"i"):new RegExp(n);return qn(this,t,s)}},ry=({pattern:r,mark:e},t)=>{let n=!1,s=r;s.indexOf("!")===0&&(n=!0,s=s.substr(1)),s=s.replace(W_,"!").replace(H_,"#");let i=Q_(s);return new tc(r,e,s,t,n,i)},rc=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[lh]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(Yi(e)&&(e={pattern:e}),ey(e.pattern)){let t=ry(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,fh(Yi(e)?ty(e):e).forEach(this._add,this),this._added}test(e,t,n){let s=!1,i=!1,a;this._rules.forEach(u=>{let{negative:d}=u;i===d&&s!==i||d&&!s&&!i&&!t||!u[n].test(e)||(s=!d,i=d,a=d?j_:u)});let c={ignored:s,unignored:i};return a&&(c.rule=a),c}},ny=(r,e)=>{throw new e(r)},yr=(r,e,t)=>Yi(r)?r?yr.isNotRelative(r)?t(`path should be a \`path.relative()\`d string, but got "${e}"`,RangeError):!0:t("path must not be empty",TypeError):t(`path must be a string, but got \`${e}\``,TypeError),dh=r=>K_.test(r);yr.isNotRelative=dh;yr.convert=r=>r;var nc=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){qn(this,lh,!0),this._rules=new rc(t),this._strictPathCheck=!n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(e){return this._rules.add(e)&&this._initCache(),this}addPattern(e){return this.add(e)}_test(e,t,n,s){let i=e&&yr.convert(e);return yr(i,e,this._strictPathCheck?ny:hh),this._t(i,t,n,s)}checkIgnore(e){if(!$_.test(e))return this.test(e);let t=e.split(Un).filter(Boolean);if(t.pop(),t.length){let n=this._t(t.join(Un)+Un,this._testCache,!0,t);if(n.ignored)return n}return this._rules.test(e,!1,Gi)}_t(e,t,n,s){if(e in t)return t[e];if(s||(s=e.split(Un).filter(Boolean)),s.pop(),!s.length)return t[e]=this._rules.test(e,n,vs);let i=this._t(s.join(Un)+Un,t,n,s);return t[e]=i.ignored?i:this._rules.test(e,n,vs)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return fh(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},sc=r=>new nc(r),sy=r=>yr(r&&yr.convert(r),r,hh),ph=()=>{let r=t=>/^\\\\\?\\/.test(t)||/["<>|\u0000-\u001F]+/u.test(t)?t:t.replace(/\\/g,"/");yr.convert=r;let e=/^[a-z]:\//i;yr.isNotRelative=t=>e.test(t)||dh(t)};typeof process<"u"&&process.platform==="win32"&&ph();Xi.exports=sc;sc.default=sc;Xi.exports.isPathValid=sy;qn(Xi.exports,Symbol.for("setupWindows"),ph)});var mh=F(Dt=>{"use strict";var iy=Dt&&Dt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),oy=Dt&&Dt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),gh=Dt&&Dt.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[n.length]=s);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),s=0;s<n.length;s++)n[s]!=="default"&&iy(t,e,n[s]);return oy(t,e),t}})(),ay=Dt&&Dt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Dt,"__esModule",{value:!0});Dt.FileListService=void 0;var ws=gh(require("path")),oc=gh(require("fs/promises")),cy=ay(ic()),ac=kr(),fy=["node_modules",".pnpm","vendor",".git","dist","build","out",".next",".nuxt",".output",".cache",".turbo",".idea",".vscode",".DS_Store","Thumbs.db"],cc=class{ignoreFilter;workspaceRoot;onResponseCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,cy.default)(),this.ignoreFilter.add(fy),this.workspaceRoot&&this.loadGitignore(),this.logger.info("FileListService initialized",t||"null")}async loadGitignore(){if(!this.workspaceRoot)return;let e=ws.join(this.workspaceRoot,".gitignore");try{let t=await oc.readFile(e,"utf-8");this.ignoreFilter.add(t)}catch{}}onResponse(e){this.onResponseCallback=e}async handleListRequest(e){if(!this.workspaceRoot){this.sendResponse({requestId:e.requestId,path:e.path,entries:[],error:"No workspace root"});return}try{let t=this.resolvePath(e.path),n=await this.listDirectory(t,e.path);this.sendResponse({requestId:e.requestId,path:e.path,entries:n})}catch(t){this.logger.error("Failed to list directory",String(t)),this.sendResponse({requestId:e.requestId,path:e.path,entries:[],error:t instanceof Error?t.message:"Unknown error"})}}async listDirectory(e,t){let n=await oc.readdir(e,{withFileTypes:!0}),s=[];for(let i of n){let a=t==="."||t===""?i.name:ws.join(t,i.name);if(this.shouldHide(a,i.isDirectory()))continue;let c=ws.join(e,i.name),u={name:i.name,path:a,type:i.isDirectory()?ac.FileEntryType.DIRECTORY:ac.FileEntryType.FILE};if(!i.isDirectory())try{let d=await oc.stat(c);u.size=d.size,u.modified=d.mtime.toISOString()}catch{}s.push(u)}return s.sort((i,a)=>i.type!==a.type?i.type===ac.FileEntryType.DIRECTORY?-1:1:i.name.localeCompare(a.name))}shouldHide(e,t){let n=e.split(ws.sep).join("/"),s=t?`${n}/`:n;return this.ignoreFilter.ignores(s)}resolvePath(e){if(!this.workspaceRoot)throw new Error("No workspace root");if(e==="."||e==="")return this.workspaceRoot;let t=ws.join(this.workspaceRoot,e);if(!t.startsWith(this.workspaceRoot))throw new Error("Path outside workspace");return t}sendResponse(e){this.onResponseCallback?.(e)}dispose(){this.onResponseCallback=null}};Dt.FileListService=cc});var yh=F(nr=>{"use strict";var uy=nr&&nr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),ly=nr&&nr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),_h=nr&&nr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[n.length]=s);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),s=0;s<n.length;s++)n[s]!=="default"&&uy(t,e,n[s]);return ly(t,e),t}})();Object.defineProperty(nr,"__esModule",{value:!0});nr.FileTrackerService=void 0;var fc=_h(require("path")),cn=_h(require("fs/promises")),hy=require("child_process"),dy=require("util"),Wt=kr(),uc=(0,dy.promisify)(hy.exec),lc={toolStart:/⏺\s*(Write|Edit|NotebookEdit)\s*\(\s*(?:file_path|notebook_path)\s*=\s*"([^"]+)"/,toolSuccess:/[✓✔]\s*(?:Wrote|Edited|Updated|Created)\s+([^\s\n]+)/,toolError:/[✗✘]\s*(?:Failed|Error)/i},hc=class{trackedFiles=new Map;pendingToolCalls=new Map;outputBuffers=new Map;workspaceRoot;onFileChangedCallback=null;onFileViewTransferCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t}onFileChanged(e){this.onFileChangedCallback=e}onFileViewTransfer(e){this.onFileViewTransferCallback=e}async processOutput(e,t){let n=this.outputBuffers.get(e)||"";n+=t,n.length>10240&&(n=n.slice(-10240)),this.outputBuffers.set(e,n);try{await this.parseToolCalls(e,n)}catch(s){this.logger.error("Error parsing tool calls",s)}}async parseToolCalls(e,t){let n=this.stripAnsi(t),s=n.match(lc.toolStart);if(s){let a=s[1],c=s[2],u=`${a}_${Date.now()}_${c}`;this.pendingToolCalls.has(u)||await this.handleToolStart(e,u,a,{file_path:c})}let i=n.match(lc.toolSuccess);if(i){let a=i[1];for(let[c,u]of this.pendingToolCalls)if(u.filePath===a||a.endsWith(u.filePath)||u.filePath.endsWith(a)){await this.handleToolEnd(e,c,u.toolName,"success");break}}if(lc.toolError.test(n))for(let[a,c]of this.pendingToolCalls)await this.handleToolEnd(e,a,c.toolName,"error")}stripAnsi(e){return e.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g,"").replace(/\x1b\][^\x07]*\x07/g,"").replace(/\x1b[()][AB012]/g,"").replace(/\x1b[=>]/g,"").replace(/\x1b[78DMEHc]/g,"")}async handleToolStart(e,t,n,s){if(!this.isFileModifyingTool(n))return;let i=this.extractFilePath(n,s);if(!i)return;let a=this.resolveFilePath(i),c={toolId:t,toolName:n,filePath:i,timestamp:new Date().toISOString()};this.pendingToolCalls.set(t,c);let u;try{u=await cn.readFile(a,"utf-8")}catch{u=void 0}let d={path:i,changeType:u===void 0?Wt.FileChangeType.CREATE:Wt.FileChangeType.MODIFY,toolName:n,toolId:t,timestamp:c.timestamp,previousContent:u},g=this.trackedFiles.get(e)||[];g.push(d),this.trackedFiles.set(e,g)}async handleToolEnd(e,t,n,s){if(!this.isFileModifyingTool(n)||!this.pendingToolCalls.get(t))return;if(this.pendingToolCalls.delete(t),s==="error"){let g=this.trackedFiles.get(e)||[],m=g.findIndex(y=>y.toolId===t);m!==-1&&g.splice(m,1);return}let c=(this.trackedFiles.get(e)||[]).find(g=>g.toolId===t);if(!c)return;let u=this.resolveFilePath(c.path);try{let g=await cn.stat(u);c.size=g.size}catch{c.changeType=Wt.FileChangeType.DELETE,c.size=void 0}let d={path:c.path,changeType:c.changeType,timestamp:new Date().toISOString(),source:"tool-call",toolName:c.toolName,toolId:c.toolId,size:c.size};this.onFileChangedCallback?.(e,d)}async handleViewRequest(e,t){let n=this.resolveFilePath(t.path),s=this.getViewableMimeType(t.path);if(s&&this.onFileViewTransferCallback){try{let a=await cn.readFile(n),c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:s};this.onFileViewTransferCallback(e,Buffer.from(a),c)}catch(a){let c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:s,error:a instanceof Error?a.message:"Unknown error"};this.onFileViewTransferCallback(e,Buffer.alloc(0),c)}return}let i;try{t.type===Wt.FileViewType.CONTENT?i=await this.getFileContent(t,n):i=await this.getFileDiff(e,t,n)}catch(a){i={requestId:t.requestId,path:t.path,type:t.type,error:a instanceof Error?a.message:"Unknown error"}}if(this.onFileViewTransferCallback){let a={requestId:t.requestId,path:t.path,viewType:i.type===Wt.FileViewType.CONTENT?"content":"diff",language:i.language,truncated:i.truncated,error:i.error},c=Buffer.from(i.content||"","utf-8");this.onFileViewTransferCallback(e,c,a)}}getViewableMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf"}[t||""]||null}async getFileContent(e,t){let n=e.maxSize||1048576,s=await cn.stat(t),i=await cn.readFile(t,"utf-8"),a=!1,c=i;return i.length>n&&(c=i.slice(0,n),a=!0),{requestId:e.requestId,path:e.path,type:Wt.FileViewType.CONTENT,content:c,language:(0,Wt.getLanguageFromPath)(e.path),size:s.size,truncated:a}}async getFileDiff(e,t,n){let s=t.diffBase||Wt.DiffBase.GIT,i;return s===Wt.DiffBase.GIT?i=await this.getGitDiff(n):i=await this.getPreviousDiff(e,t.path,n),{requestId:t.requestId,path:t.path,type:Wt.FileViewType.DIFF,content:i,language:"diff"}}async getGitDiff(e){if(!this.workspaceRoot)throw new Error("No workspace root");try{let{stdout:t}=await uc(`git diff --cached -- "${e}"`,{cwd:this.workspaceRoot});if(t.trim())return t;let{stdout:n}=await uc(`git diff -- "${e}"`,{cwd:this.workspaceRoot});if(n.trim())return n;let{stdout:s}=await uc(`git status --porcelain -- "${e}"`,{cwd:this.workspaceRoot});if(s.startsWith("??")||s.startsWith("A ")){let a=(await cn.readFile(e,"utf-8")).split(`
|
|
27
|
+
`),c=fc.relative(this.workspaceRoot,e);return[`diff --git a/${c} b/${c}`,"new file mode 100644","--- /dev/null",`+++ b/${c}`,`@@ -0,0 +1,${a.length} @@`,...a.map(u=>`+${u}`)].join(`
|
|
28
|
+
`)}return"(no changes)"}catch{throw new Error("Git not available")}}async getPreviousDiff(e,t,n){let a=(this.trackedFiles.get(e)||[]).find(d=>d.path===t&&d.previousContent!==void 0)?.previousContent||"",c;try{c=await cn.readFile(n,"utf-8")}catch{c=""}let u=(0,Wt.createSimpleDiff)(a,c,t);return this.diffContentToUnifiedText(u)}diffContentToUnifiedText(e){let t=[];t.push(`--- a/${e.path}`),t.push(`+++ b/${e.path}`);for(let n of e.hunks){t.push(`@@ -${n.oldStart},${n.oldLines} +${n.newStart},${n.newLines} @@`);for(let s of n.lines)switch(s.type){case"add":t.push(`+${s.content}`);break;case"remove":t.push(`-${s.content}`);break;case"context":t.push(` ${s.content}`);break}}return t.join(`
|
|
29
|
+
`)}clearTerminal(e){this.trackedFiles.delete(e),this.outputBuffers.delete(e)}getChangedFiles(e){return(this.trackedFiles.get(e)||[]).map(n=>({path:n.path,changeType:n.changeType,timestamp:n.timestamp,source:"tool-call",toolName:n.toolName,toolId:n.toolId,size:n.size}))}isFileModifyingTool(e){return["Write","Edit","NotebookEdit"].includes(e)}extractFilePath(e,t){return t?e==="Write"||e==="Edit"?t.file_path||null:e==="NotebookEdit"&&t.notebook_path||null:null}resolveFilePath(e){return fc.isAbsolute(e)?e:this.workspaceRoot?fc.join(this.workspaceRoot,e):e}dispose(){this.trackedFiles.clear(),this.pendingToolCalls.clear(),this.onFileChangedCallback=null,this.onFileViewTransferCallback=null}};nr.FileTrackerService=hc});var Eh=F(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.FileTrackerService=ft.FileListService=ft.FileTransferService=ft.WebSocketService=ft.StatusDetector=ft.AuthService=ft.CryptoService=void 0;var py=Vf();Object.defineProperty(ft,"CryptoService",{enumerable:!0,get:function(){return py.CryptoService}});var gy=Kf();Object.defineProperty(ft,"AuthService",{enumerable:!0,get:function(){return gy.AuthService}});var my=$f();Object.defineProperty(ft,"StatusDetector",{enumerable:!0,get:function(){return my.StatusDetector}});var _y=sh();Object.defineProperty(ft,"WebSocketService",{enumerable:!0,get:function(){return _y.WebSocketService}});var yy=oh();Object.defineProperty(ft,"FileTransferService",{enumerable:!0,get:function(){return yy.FileTransferService}});var Ey=mh();Object.defineProperty(ft,"FileListService",{enumerable:!0,get:function(){return Ey.FileListService}});var vy=yh();Object.defineProperty(ft,"FileTrackerService",{enumerable:!0,get:function(){return vy.FileTrackerService}})});var bs=F(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.FileTrackerService=Se.FileListService=Se.FileTransferService=Se.WebSocketService=Se.StatusDetector=Se.AuthService=Se.CryptoService=Se.getCurrentCorrelationId=Se.runWithCorrelation=Se.generateCorrelationId=Se.getWsUrl=Se.getApiUrl=Se.CircularBuffer=Se.formatLogLine=Se.shouldLog=Se.LOG_LEVELS=void 0;var dc=ff();Object.defineProperty(Se,"LOG_LEVELS",{enumerable:!0,get:function(){return dc.LOG_LEVELS}});Object.defineProperty(Se,"shouldLog",{enumerable:!0,get:function(){return dc.shouldLog}});Object.defineProperty(Se,"formatLogLine",{enumerable:!0,get:function(){return dc.formatLogLine}});var Wn=hf();Object.defineProperty(Se,"CircularBuffer",{enumerable:!0,get:function(){return Wn.CircularBuffer}});Object.defineProperty(Se,"getApiUrl",{enumerable:!0,get:function(){return Wn.getApiUrl}});Object.defineProperty(Se,"getWsUrl",{enumerable:!0,get:function(){return Wn.getWsUrl}});Object.defineProperty(Se,"generateCorrelationId",{enumerable:!0,get:function(){return Wn.generateCorrelationId}});Object.defineProperty(Se,"runWithCorrelation",{enumerable:!0,get:function(){return Wn.runWithCorrelation}});Object.defineProperty(Se,"getCurrentCorrelationId",{enumerable:!0,get:function(){return Wn.getCurrentCorrelationId}});var fn=Eh();Object.defineProperty(Se,"CryptoService",{enumerable:!0,get:function(){return fn.CryptoService}});Object.defineProperty(Se,"AuthService",{enumerable:!0,get:function(){return fn.AuthService}});Object.defineProperty(Se,"StatusDetector",{enumerable:!0,get:function(){return fn.StatusDetector}});Object.defineProperty(Se,"WebSocketService",{enumerable:!0,get:function(){return fn.WebSocketService}});Object.defineProperty(Se,"FileTransferService",{enumerable:!0,get:function(){return fn.FileTransferService}});Object.defineProperty(Se,"FileListService",{enumerable:!0,get:function(){return fn.FileListService}});Object.defineProperty(Se,"FileTrackerService",{enumerable:!0,get:function(){return fn.FileTrackerService}})});var _c=F((Ss,mc)=>{(function(r,e){typeof Ss=="object"&&typeof mc=="object"?mc.exports=e(require("child_process"),require("crypto")):typeof define=="function"&&define.amd?define(["child_process","crypto"],e):typeof Ss=="object"?Ss["electron-machine-id"]=e(require("child_process"),require("crypto")):r["electron-machine-id"]=e(r.child_process,r.crypto)})(Ss,function(r,e){return(function(t){function n(i){if(s[i])return s[i].exports;var a=s[i]={exports:{},id:i,loaded:!1};return t[i].call(a.exports,a,a.exports,n),a.loaded=!0,a.exports}var s={};return n.m=t,n.c=s,n.p="",n(0)})([function(t,n,s){t.exports=s(34)},function(t,n,s){var i=s(29)("wks"),a=s(33),c=s(2).Symbol,u=typeof c=="function",d=t.exports=function(g){return i[g]||(i[g]=u&&c[g]||(u?c:a)("Symbol."+g))};d.store=i},function(t,n){var s=t.exports=typeof window<"u"&&window.Math==Math?window:typeof self<"u"&&self.Math==Math?self:Function("return this")();typeof __g=="number"&&(__g=s)},function(t,n,s){var i=s(9);t.exports=function(a){if(!i(a))throw TypeError(a+" is not an object!");return a}},function(t,n,s){t.exports=!s(24)(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7})},function(t,n,s){var i=s(12),a=s(17);t.exports=s(4)?function(c,u,d){return i.f(c,u,a(1,d))}:function(c,u,d){return c[u]=d,c}},function(t,n){var s=t.exports={version:"2.4.0"};typeof __e=="number"&&(__e=s)},function(t,n,s){var i=s(14);t.exports=function(a,c,u){if(i(a),c===void 0)return a;switch(u){case 1:return function(d){return a.call(c,d)};case 2:return function(d,g){return a.call(c,d,g)};case 3:return function(d,g,m){return a.call(c,d,g,m)}}return function(){return a.apply(c,arguments)}}},function(t,n){var s={}.hasOwnProperty;t.exports=function(i,a){return s.call(i,a)}},function(t,n){t.exports=function(s){return typeof s=="object"?s!==null:typeof s=="function"}},function(t,n){t.exports={}},function(t,n){var s={}.toString;t.exports=function(i){return s.call(i).slice(8,-1)}},function(t,n,s){var i=s(3),a=s(26),c=s(32),u=Object.defineProperty;n.f=s(4)?Object.defineProperty:function(d,g,m){if(i(d),g=c(g,!0),i(m),a)try{return u(d,g,m)}catch{}if("get"in m||"set"in m)throw TypeError("Accessors not supported!");return"value"in m&&(d[g]=m.value),d}},function(t,n,s){var i=s(42),a=s(15);t.exports=function(c){return i(a(c))}},function(t,n){t.exports=function(s){if(typeof s!="function")throw TypeError(s+" is not a function!");return s}},function(t,n){t.exports=function(s){if(s==null)throw TypeError("Can't call method on "+s);return s}},function(t,n,s){var i=s(9),a=s(2).document,c=i(a)&&i(a.createElement);t.exports=function(u){return c?a.createElement(u):{}}},function(t,n){t.exports=function(s,i){return{enumerable:!(1&s),configurable:!(2&s),writable:!(4&s),value:i}}},function(t,n,s){var i=s(12).f,a=s(8),c=s(1)("toStringTag");t.exports=function(u,d,g){u&&!a(u=g?u:u.prototype,c)&&i(u,c,{configurable:!0,value:d})}},function(t,n,s){var i=s(29)("keys"),a=s(33);t.exports=function(c){return i[c]||(i[c]=a(c))}},function(t,n){var s=Math.ceil,i=Math.floor;t.exports=function(a){return isNaN(a=+a)?0:(a>0?i:s)(a)}},function(t,n,s){var i=s(11),a=s(1)("toStringTag"),c=i((function(){return arguments})())=="Arguments",u=function(d,g){try{return d[g]}catch{}};t.exports=function(d){var g,m,y;return d===void 0?"Undefined":d===null?"Null":typeof(m=u(g=Object(d),a))=="string"?m:c?i(g):(y=i(g))=="Object"&&typeof g.callee=="function"?"Arguments":y}},function(t,n){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,n,s){var i=s(2),a=s(6),c=s(7),u=s(5),d="prototype",g=function(m,y,w){var S,C,V,de=m&g.F,B=m&g.G,P=m&g.S,L=m&g.P,Q=m&g.B,j=m&g.W,Z=B?a:a[y]||(a[y]={}),pe=Z[d],Ee=B?i:P?i[y]:(i[y]||{})[d];B&&(w=y);for(S in w)C=!de&&Ee&&Ee[S]!==void 0,C&&S in Z||(V=C?Ee[S]:w[S],Z[S]=B&&typeof Ee[S]!="function"?w[S]:Q&&C?c(V,i):j&&Ee[S]==V?(function(ve){var We=function(Ke,Te,$e){if(this instanceof ve){switch(arguments.length){case 0:return new ve;case 1:return new ve(Ke);case 2:return new ve(Ke,Te)}return new ve(Ke,Te,$e)}return ve.apply(this,arguments)};return We[d]=ve[d],We})(V):L&&typeof V=="function"?c(Function.call,V):V,L&&((Z.virtual||(Z.virtual={}))[S]=V,m&g.R&&pe&&!pe[S]&&u(pe,S,V)))};g.F=1,g.G=2,g.S=4,g.P=8,g.B=16,g.W=32,g.U=64,g.R=128,t.exports=g},function(t,n){t.exports=function(s){try{return!!s()}catch{return!0}}},function(t,n,s){t.exports=s(2).document&&document.documentElement},function(t,n,s){t.exports=!s(4)&&!s(24)(function(){return Object.defineProperty(s(16)("div"),"a",{get:function(){return 7}}).a!=7})},function(t,n,s){"use strict";var i=s(28),a=s(23),c=s(57),u=s(5),d=s(8),g=s(10),m=s(45),y=s(18),w=s(52),S=s(1)("iterator"),C=!([].keys&&"next"in[].keys()),V="@@iterator",de="keys",B="values",P=function(){return this};t.exports=function(L,Q,j,Z,pe,Ee,ve){m(j,Q,Z);var We,Ke,Te,$e=function(U){if(!C&&U in te)return te[U];switch(U){case de:return function(){return new j(this,U)};case B:return function(){return new j(this,U)}}return function(){return new j(this,U)}},He=Q+" Iterator",Ze=pe==B,G=!1,te=L.prototype,Ae=te[S]||te[V]||pe&&te[pe],Be=Ae||$e(pe),yt=pe?Ze?$e("entries"):Be:void 0,N=Q=="Array"&&te.entries||Ae;if(N&&(Te=w(N.call(new L)),Te!==Object.prototype&&(y(Te,He,!0),i||d(Te,S)||u(Te,S,P))),Ze&&Ae&&Ae.name!==B&&(G=!0,Be=function(){return Ae.call(this)}),i&&!ve||!C&&!G&&te[S]||u(te,S,Be),g[Q]=Be,g[He]=P,pe)if(We={values:Ze?Be:$e(B),keys:Ee?Be:$e(de),entries:yt},ve)for(Ke in We)Ke in te||c(te,Ke,We[Ke]);else a(a.P+a.F*(C||G),Q,We);return We}},function(t,n){t.exports=!0},function(t,n,s){var i=s(2),a="__core-js_shared__",c=i[a]||(i[a]={});t.exports=function(u){return c[u]||(c[u]={})}},function(t,n,s){var i,a,c,u=s(7),d=s(41),g=s(25),m=s(16),y=s(2),w=y.process,S=y.setImmediate,C=y.clearImmediate,V=y.MessageChannel,de=0,B={},P="onreadystatechange",L=function(){var j=+this;if(B.hasOwnProperty(j)){var Z=B[j];delete B[j],Z()}},Q=function(j){L.call(j.data)};S&&C||(S=function(j){for(var Z=[],pe=1;arguments.length>pe;)Z.push(arguments[pe++]);return B[++de]=function(){d(typeof j=="function"?j:Function(j),Z)},i(de),de},C=function(j){delete B[j]},s(11)(w)=="process"?i=function(j){w.nextTick(u(L,j,1))}:V?(a=new V,c=a.port2,a.port1.onmessage=Q,i=u(c.postMessage,c,1)):y.addEventListener&&typeof postMessage=="function"&&!y.importScripts?(i=function(j){y.postMessage(j+"","*")},y.addEventListener("message",Q,!1)):i=P in m("script")?function(j){g.appendChild(m("script"))[P]=function(){g.removeChild(this),L.call(j)}}:function(j){setTimeout(u(L,j,1),0)}),t.exports={set:S,clear:C}},function(t,n,s){var i=s(20),a=Math.min;t.exports=function(c){return c>0?a(i(c),9007199254740991):0}},function(t,n,s){var i=s(9);t.exports=function(a,c){if(!i(a))return a;var u,d;if(c&&typeof(u=a.toString)=="function"&&!i(d=u.call(a))||typeof(u=a.valueOf)=="function"&&!i(d=u.call(a))||!c&&typeof(u=a.toString)=="function"&&!i(d=u.call(a)))return d;throw TypeError("Can't convert object to primitive value")}},function(t,n){var s=0,i=Math.random();t.exports=function(a){return"Symbol(".concat(a===void 0?"":a,")_",(++s+i).toString(36))}},function(t,n,s){"use strict";function i(P){return P&&P.__esModule?P:{default:P}}function a(){return process.platform!=="win32"?"":process.arch==="ia32"&&process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432")?"mixed":"native"}function c(P){return(0,S.createHash)("sha256").update(P).digest("hex")}function u(P){switch(V){case"darwin":return P.split("IOPlatformUUID")[1].split(`
|
|
30
|
+
`)[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return P.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return P.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"freebsd":return P.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error("Unsupported platform: "+process.platform)}}function d(P){var L=u((0,w.execSync)(B[V]).toString());return P?L:c(L)}function g(P){return new y.default(function(L,Q){return(0,w.exec)(B[V],{},function(j,Z,pe){if(j)return Q(new Error("Error while obtaining machine id: "+j.stack));var Ee=u(Z.toString());return L(P?Ee:c(Ee))})})}Object.defineProperty(n,"__esModule",{value:!0});var m=s(35),y=i(m);n.machineIdSync=d,n.machineId=g;var w=s(70),S=s(71),C=process,V=C.platform,de={native:"%windir%\\System32",mixed:"%windir%\\sysnative\\cmd.exe /c %windir%\\System32"},B={darwin:"ioreg -rd1 -c IOPlatformExpertDevice",win32:de[a()]+"\\REG.exe QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",linux:"( cat /var/lib/dbus/machine-id /etc/machine-id 2> /dev/null || hostname ) | head -n 1 || :",freebsd:"kenv -q smbios.system.uuid || sysctl -n kern.hostuuid"}},function(t,n,s){t.exports={default:s(36),__esModule:!0}},function(t,n,s){s(66),s(68),s(69),s(67),t.exports=s(6).Promise},function(t,n){t.exports=function(){}},function(t,n){t.exports=function(s,i,a,c){if(!(s instanceof i)||c!==void 0&&c in s)throw TypeError(a+": incorrect invocation!");return s}},function(t,n,s){var i=s(13),a=s(31),c=s(62);t.exports=function(u){return function(d,g,m){var y,w=i(d),S=a(w.length),C=c(m,S);if(u&&g!=g){for(;S>C;)if(y=w[C++],y!=y)return!0}else for(;S>C;C++)if((u||C in w)&&w[C]===g)return u||C||0;return!u&&-1}}},function(t,w,s){var i=s(7),a=s(44),c=s(43),u=s(3),d=s(31),g=s(64),m={},y={},w=t.exports=function(S,C,V,de,B){var P,L,Q,j,Z=B?function(){return S}:g(S),pe=i(V,de,C?2:1),Ee=0;if(typeof Z!="function")throw TypeError(S+" is not iterable!");if(c(Z)){for(P=d(S.length);P>Ee;Ee++)if(j=C?pe(u(L=S[Ee])[0],L[1]):pe(S[Ee]),j===m||j===y)return j}else for(Q=Z.call(S);!(L=Q.next()).done;)if(j=a(Q,pe,L.value,C),j===m||j===y)return j};w.BREAK=m,w.RETURN=y},function(t,n){t.exports=function(s,i,a){var c=a===void 0;switch(i.length){case 0:return c?s():s.call(a);case 1:return c?s(i[0]):s.call(a,i[0]);case 2:return c?s(i[0],i[1]):s.call(a,i[0],i[1]);case 3:return c?s(i[0],i[1],i[2]):s.call(a,i[0],i[1],i[2]);case 4:return c?s(i[0],i[1],i[2],i[3]):s.call(a,i[0],i[1],i[2],i[3])}return s.apply(a,i)}},function(t,n,s){var i=s(11);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(a){return i(a)=="String"?a.split(""):Object(a)}},function(t,n,s){var i=s(10),a=s(1)("iterator"),c=Array.prototype;t.exports=function(u){return u!==void 0&&(i.Array===u||c[a]===u)}},function(t,n,s){var i=s(3);t.exports=function(a,c,u,d){try{return d?c(i(u)[0],u[1]):c(u)}catch(m){var g=a.return;throw g!==void 0&&i(g.call(a)),m}}},function(t,n,s){"use strict";var i=s(49),a=s(17),c=s(18),u={};s(5)(u,s(1)("iterator"),function(){return this}),t.exports=function(d,g,m){d.prototype=i(u,{next:a(1,m)}),c(d,g+" Iterator")}},function(t,n,s){var i=s(1)("iterator"),a=!1;try{var c=[7][i]();c.return=function(){a=!0},Array.from(c,function(){throw 2})}catch{}t.exports=function(u,d){if(!d&&!a)return!1;var g=!1;try{var m=[7],y=m[i]();y.next=function(){return{done:g=!0}},m[i]=function(){return y},u(m)}catch{}return g}},function(t,n){t.exports=function(s,i){return{value:i,done:!!s}}},function(t,n,s){var i=s(2),a=s(30).set,c=i.MutationObserver||i.WebKitMutationObserver,u=i.process,d=i.Promise,g=s(11)(u)=="process";t.exports=function(){var m,y,w,S=function(){var B,P;for(g&&(B=u.domain)&&B.exit();m;){P=m.fn,m=m.next;try{P()}catch(L){throw m?w():y=void 0,L}}y=void 0,B&&B.enter()};if(g)w=function(){u.nextTick(S)};else if(c){var C=!0,V=document.createTextNode("");new c(S).observe(V,{characterData:!0}),w=function(){V.data=C=!C}}else if(d&&d.resolve){var de=d.resolve();w=function(){de.then(S)}}else w=function(){a.call(i,S)};return function(B){var P={fn:B,next:void 0};y&&(y.next=P),m||(m=P,w()),y=P}}},function(t,n,s){var i=s(3),a=s(50),c=s(22),u=s(19)("IE_PROTO"),d=function(){},g="prototype",m=function(){var y,w=s(16)("iframe"),S=c.length,C=">";for(w.style.display="none",s(25).appendChild(w),w.src="javascript:",y=w.contentWindow.document,y.open(),y.write("<script>document.F=Object</script"+C),y.close(),m=y.F;S--;)delete m[g][c[S]];return m()};t.exports=Object.create||function(y,w){var S;return y!==null?(d[g]=i(y),S=new d,d[g]=null,S[u]=y):S=m(),w===void 0?S:a(S,w)}},function(t,n,s){var i=s(12),a=s(3),c=s(54);t.exports=s(4)?Object.defineProperties:function(u,d){a(u);for(var g,m=c(d),y=m.length,w=0;y>w;)i.f(u,g=m[w++],d[g]);return u}},function(t,n,s){var i=s(55),a=s(17),c=s(13),u=s(32),d=s(8),g=s(26),m=Object.getOwnPropertyDescriptor;n.f=s(4)?m:function(y,w){if(y=c(y),w=u(w,!0),g)try{return m(y,w)}catch{}if(d(y,w))return a(!i.f.call(y,w),y[w])}},function(t,n,s){var i=s(8),a=s(63),c=s(19)("IE_PROTO"),u=Object.prototype;t.exports=Object.getPrototypeOf||function(d){return d=a(d),i(d,c)?d[c]:typeof d.constructor=="function"&&d instanceof d.constructor?d.constructor.prototype:d instanceof Object?u:null}},function(t,n,s){var i=s(8),a=s(13),c=s(39)(!1),u=s(19)("IE_PROTO");t.exports=function(d,g){var m,y=a(d),w=0,S=[];for(m in y)m!=u&&i(y,m)&&S.push(m);for(;g.length>w;)i(y,m=g[w++])&&(~c(S,m)||S.push(m));return S}},function(t,n,s){var i=s(53),a=s(22);t.exports=Object.keys||function(c){return i(c,a)}},function(t,n){n.f={}.propertyIsEnumerable},function(t,n,s){var i=s(5);t.exports=function(a,c,u){for(var d in c)u&&a[d]?a[d]=c[d]:i(a,d,c[d]);return a}},function(t,n,s){t.exports=s(5)},function(t,n,s){var i=s(9),a=s(3),c=function(u,d){if(a(u),!i(d)&&d!==null)throw TypeError(d+": can't set as prototype!")};t.exports={set:Object.setPrototypeOf||("__proto__"in{}?(function(u,d,g){try{g=s(7)(Function.call,s(51).f(Object.prototype,"__proto__").set,2),g(u,[]),d=!(u instanceof Array)}catch{d=!0}return function(m,y){return c(m,y),d?m.__proto__=y:g(m,y),m}})({},!1):void 0),check:c}},function(t,n,s){"use strict";var i=s(2),a=s(6),c=s(12),u=s(4),d=s(1)("species");t.exports=function(g){var m=typeof a[g]=="function"?a[g]:i[g];u&&m&&!m[d]&&c.f(m,d,{configurable:!0,get:function(){return this}})}},function(t,n,s){var i=s(3),a=s(14),c=s(1)("species");t.exports=function(u,d){var g,m=i(u).constructor;return m===void 0||(g=i(m)[c])==null?d:a(g)}},function(t,n,s){var i=s(20),a=s(15);t.exports=function(c){return function(u,d){var g,m,y=String(a(u)),w=i(d),S=y.length;return w<0||w>=S?c?"":void 0:(g=y.charCodeAt(w),g<55296||g>56319||w+1===S||(m=y.charCodeAt(w+1))<56320||m>57343?c?y.charAt(w):g:c?y.slice(w,w+2):(g-55296<<10)+(m-56320)+65536)}}},function(t,n,s){var i=s(20),a=Math.max,c=Math.min;t.exports=function(u,d){return u=i(u),u<0?a(u+d,0):c(u,d)}},function(t,n,s){var i=s(15);t.exports=function(a){return Object(i(a))}},function(t,n,s){var i=s(21),a=s(1)("iterator"),c=s(10);t.exports=s(6).getIteratorMethod=function(u){if(u!=null)return u[a]||u["@@iterator"]||c[i(u)]}},function(t,n,s){"use strict";var i=s(37),a=s(47),c=s(10),u=s(13);t.exports=s(27)(Array,"Array",function(d,g){this._t=u(d),this._i=0,this._k=g},function(){var d=this._t,g=this._k,m=this._i++;return!d||m>=d.length?(this._t=void 0,a(1)):g=="keys"?a(0,m):g=="values"?a(0,d[m]):a(0,[m,d[m]])},"values"),c.Arguments=c.Array,i("keys"),i("values"),i("entries")},function(t,n){},function(t,n,s){"use strict";var i,a,c,u=s(28),d=s(2),g=s(7),m=s(21),y=s(23),w=s(9),S=(s(3),s(14)),C=s(38),V=s(40),de=(s(58).set,s(60)),B=s(30).set,P=s(48)(),L="Promise",Q=d.TypeError,Z=d.process,j=d[L],Z=d.process,pe=m(Z)=="process",Ee=function(){},ve=!!(function(){try{var N=j.resolve(1),U=(N.constructor={})[s(1)("species")]=function(A){A(Ee,Ee)};return(pe||typeof PromiseRejectionEvent=="function")&&N.then(Ee)instanceof U}catch{}})(),We=function(N,U){return N===U||N===j&&U===c},Ke=function(N){var U;return!(!w(N)||typeof(U=N.then)!="function")&&U},Te=function(N){return We(j,N)?new $e(N):new a(N)},$e=a=function(N){var U,A;this.promise=new N(function(oe,Ie){if(U!==void 0||A!==void 0)throw Q("Bad Promise constructor");U=oe,A=Ie}),this.resolve=S(U),this.reject=S(A)},He=function(N){try{N()}catch(U){return{error:U}}},Ze=function(N,U){if(!N._n){N._n=!0;var A=N._c;P(function(){for(var oe=N._v,Ie=N._s==1,ut=0,Et=function(vt){var wt,ir,wr=Ie?vt.ok:vt.fail,Wr=vt.resolve,br=vt.reject,gn=vt.domain;try{wr?(Ie||(N._h==2&&Ae(N),N._h=1),wr===!0?wt=oe:(gn&&gn.enter(),wt=wr(oe),gn&&gn.exit()),wt===vt.promise?br(Q("Promise-chain cycle")):(ir=Ke(wt))?ir.call(wt,Wr,br):Wr(wt)):br(oe)}catch(Ls){br(Ls)}};A.length>ut;)Et(A[ut++]);N._c=[],N._n=!1,U&&!N._h&&G(N)})}},G=function(N){B.call(d,function(){var U,A,oe,Ie=N._v;if(te(N)&&(U=He(function(){pe?Z.emit("unhandledRejection",Ie,N):(A=d.onunhandledrejection)?A({promise:N,reason:Ie}):(oe=d.console)&&oe.error&&oe.error("Unhandled promise rejection",Ie)}),N._h=pe||te(N)?2:1),N._a=void 0,U)throw U.error})},te=function(N){if(N._h==1)return!1;for(var U,A=N._a||N._c,oe=0;A.length>oe;)if(U=A[oe++],U.fail||!te(U.promise))return!1;return!0},Ae=function(N){B.call(d,function(){var U;pe?Z.emit("rejectionHandled",N):(U=d.onrejectionhandled)&&U({promise:N,reason:N._v})})},Be=function(N){var U=this;U._d||(U._d=!0,U=U._w||U,U._v=N,U._s=2,U._a||(U._a=U._c.slice()),Ze(U,!0))},yt=function(N){var U,A=this;if(!A._d){A._d=!0,A=A._w||A;try{if(A===N)throw Q("Promise can't be resolved itself");(U=Ke(N))?P(function(){var oe={_w:A,_d:!1};try{U.call(N,g(yt,oe,1),g(Be,oe,1))}catch(Ie){Be.call(oe,Ie)}}):(A._v=N,A._s=1,Ze(A,!1))}catch(oe){Be.call({_w:A,_d:!1},oe)}}};ve||(j=function(N){C(this,j,L,"_h"),S(N),i.call(this);try{N(g(yt,this,1),g(Be,this,1))}catch(U){Be.call(this,U)}},i=function(N){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},i.prototype=s(56)(j.prototype,{then:function(N,U){var A=Te(de(this,j));return A.ok=typeof N!="function"||N,A.fail=typeof U=="function"&&U,A.domain=pe?Z.domain:void 0,this._c.push(A),this._a&&this._a.push(A),this._s&&Ze(this,!1),A.promise},catch:function(N){return this.then(void 0,N)}}),$e=function(){var N=new i;this.promise=N,this.resolve=g(yt,N,1),this.reject=g(Be,N,1)}),y(y.G+y.W+y.F*!ve,{Promise:j}),s(18)(j,L),s(59)(L),c=s(6)[L],y(y.S+y.F*!ve,L,{reject:function(N){var U=Te(this),A=U.reject;return A(N),U.promise}}),y(y.S+y.F*(u||!ve),L,{resolve:function(N){if(N instanceof j&&We(N.constructor,this))return N;var U=Te(this),A=U.resolve;return A(N),U.promise}}),y(y.S+y.F*!(ve&&s(46)(function(N){j.all(N).catch(Ee)})),L,{all:function(N){var U=this,A=Te(U),oe=A.resolve,Ie=A.reject,ut=He(function(){var Et=[],vt=0,wt=1;V(N,!1,function(ir){var wr=vt++,Wr=!1;Et.push(void 0),wt++,U.resolve(ir).then(function(br){Wr||(Wr=!0,Et[wr]=br,--wt||oe(Et))},Ie)}),--wt||oe(Et)});return ut&&Ie(ut.error),A.promise},race:function(N){var U=this,A=Te(U),oe=A.reject,Ie=He(function(){V(N,!1,function(ut){U.resolve(ut).then(A.resolve,oe)})});return Ie&&oe(Ie.error),A.promise}})},function(t,n,s){"use strict";var i=s(61)(!0);s(27)(String,"String",function(a){this._t=String(a),this._i=0},function(){var a,c=this._t,u=this._i;return u>=c.length?{value:void 0,done:!0}:(a=i(c,u),this._i+=a.length,{value:a,done:!1})})},function(t,n,s){s(65);for(var i=s(2),a=s(5),c=s(10),u=s(1)("toStringTag"),d=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],g=0;g<5;g++){var m=d[g],y=i[m],w=y&&y.prototype;w&&!w[u]&&a(w,u,m),c[m]=c.Array}},function(t,n){t.exports=require("child_process")},function(t,n){t.exports=require("crypto")}])})});function Ty(){try{return Ec.default.statSync("/.dockerenv"),!0}catch{return!1}}function Cy(){try{return Ec.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function vc(){return yc===void 0&&(yc=Ty()||Cy()),yc}var Ec,yc,Sh=Mt(()=>{Ec=fe(require("node:fs"),1)});function Hn(){return wc===void 0&&(wc=Oy()||vc()),wc}var Th,wc,Oy,bc=Mt(()=>{Th=fe(require("node:fs"),1);Sh();Oy=()=>{try{return Th.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var xc,Oh,kh,Ch,Mr,Sc=Mt(()=>{xc=fe(require("node:process"),1),Oh=fe(require("node:os"),1),kh=fe(require("node:fs"),1);bc();Ch=()=>{if(xc.default.platform!=="linux")return!1;if(Oh.default.release().toLowerCase().includes("microsoft"))return!Hn();try{return kh.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!Hn():!1}catch{return!1}},Mr=xc.default.env.__IS_WSL_TEST__?Ch:Ch()});var Tc,Os,ky,Py,Cc,Ph=Mt(()=>{Tc=fe(require("node:process"),1),Os=fe(require("node:fs/promises"),1);Sc();Sc();ky=(()=>{let r="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",n=!1;try{await Os.default.access(t,Os.constants.F_OK),n=!0}catch{}if(!n)return r;let s=await Os.default.readFile(t,{encoding:"utf8"}),i=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(s);return i?(e=i.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):r}})(),Py=async()=>`${await ky()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Cc=async()=>Mr?Py():`${Tc.default.env.SYSTEMROOT||Tc.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function Br(r,e,t){let n=s=>Object.defineProperty(r,e,{value:s,enumerable:!0,writable:!0});return Object.defineProperty(r,e,{configurable:!0,enumerable:!0,get(){let s=t();return n(s),s},set(s){n(s)}}),r}var Rh=Mt(()=>{});async function Oc(){if(Ih.default.platform!=="darwin")throw new Error("macOS only");let{stdout:r}=await Ry("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(r)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}var Ah,Ih,Lh,Ry,Nh=Mt(()=>{Ah=require("node:util"),Ih=fe(require("node:process"),1),Lh=require("node:child_process"),Ry=(0,Ah.promisify)(Lh.execFile)});async function Mh(r,{humanReadableOutput:e=!0,signal:t}={}){if(Dh.default.platform!=="darwin")throw new Error("macOS only");let n=e?[]:["-ss"],s={};t&&(s.signal=t);let{stdout:i}=await Ay("osascript",["-e",r,n],s);return i.trim()}var Dh,Fh,kc,Ay,Bh=Mt(()=>{Dh=fe(require("node:process"),1),Fh=require("node:util"),kc=require("node:child_process"),Ay=(0,Fh.promisify)(kc.execFile)});async function Pc(r){return Mh(`tell application "Finder" to set app_path to application file id "${r}" as string
|
|
31
|
+
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var jh=Mt(()=>{Bh()});async function Ac(r=Iy){let{stdout:e}=await r("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),t=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(e);if(!t)throw new Rc(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:n}=t.groups,s=n.lastIndexOf("."),i=n.lastIndexOf("-"),a=s===-1?void 0:n.slice(0,s),c=i===-1?void 0:n.slice(0,i);return Zi[n]??Zi[a]??Zi[c]??{name:n,id:n}}var Uh,qh,Iy,Zi,Fw,Rc,Wh=Mt(()=>{Uh=require("node:util"),qh=require("node:child_process"),Iy=(0,Uh.promisify)(qh.execFile),Zi={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},Fw=new Map(Object.entries(Zi)),Rc=class extends Error{}});async function Ic(){if(Qi.default.platform==="darwin"){let r=await Oc();return{name:await Pc(r),id:r}}if(Qi.default.platform==="linux"){let{stdout:r}=await Ly("xdg-mime",["query","default","x-scheme-handler/http"]),e=r.trim();return{name:Ny(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(Qi.default.platform==="win32")return Ac();throw new Error("Only macOS, Linux, and Windows are supported")}var Hh,Qi,Vh,Ly,Ny,Kh=Mt(()=>{Hh=require("node:util"),Qi=fe(require("node:process"),1),Vh=require("node:child_process");Nh();jh();Wh();Ly=(0,Hh.promisify)(Vh.execFile),Ny=r=>r.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var Zh={};Hd(Zh,{apps:()=>jr,default:()=>jy,openApp:()=>By});async function Fy(){let r=await Cc(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=Dc.Buffer.from(e,"utf16le").toString("base64"),{stdout:n}=await Dy(r,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),s=n.trim(),i={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return i[s]?{id:i[s]}:{}}function Yh(r){if(typeof r=="string"||Array.isArray(r))return r;let{[zh]:e}=r;if(!e)throw new Error(`${zh} is not supported`);return e}function to({[Vn]:r},{wsl:e}){if(e&&Mr)return Yh(e);if(!r)throw new Error(`${Vn} is not supported`);return Yh(r)}var Nc,Dc,Fc,Xh,Jh,Mc,eo,Uy,Dy,Lc,$h,Vn,zh,Gh,ks,My,By,jr,jy,Qh=Mt(()=>{Nc=fe(require("node:process"),1),Dc=require("node:buffer"),Fc=fe(require("node:path"),1),Xh=require("node:url"),Jh=require("node:util"),Mc=fe(require("node:child_process"),1),eo=fe(require("node:fs/promises"),1);Ph();Rh();Kh();bc();Uy={},Dy=(0,Jh.promisify)(Mc.default.execFile),Lc=Fc.default.dirname((0,Xh.fileURLToPath)(Uy.url)),$h=Fc.default.join(Lc,"xdg-open"),{platform:Vn,arch:zh}=Nc.default;Gh=async(r,e)=>{let t;for(let n of r)try{return await e(n)}catch(s){t=s}throw t},ks=async r=>{if(r={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...r},Array.isArray(r.app))return Gh(r.app,c=>ks({...r,app:c}));let{name:e,arguments:t=[]}=r.app??{};if(t=[...t],Array.isArray(e))return Gh(e,c=>ks({...r,app:{name:c,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let c={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},u={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},d=Mr?await Fy():await Ic();if(d.id in c){let g=c[d.id];return e==="browserPrivate"&&t.push(u[g]),ks({...r,app:{name:jr[g],arguments:t}})}throw new Error(`${d.name} is not supported as a default browser`)}let n,s=[],i={};if(Vn==="darwin")n="open",r.wait&&s.push("--wait-apps"),r.background&&s.push("--background"),r.newInstance&&s.push("--new"),e&&s.push("-a",e);else if(Vn==="win32"||Mr&&!Hn()&&!e){n=await Cc(),s.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),Mr||(i.windowsVerbatimArguments=!0);let c=["Start"];r.wait&&c.push("-Wait"),e?(c.push(`"\`"${e}\`""`),r.target&&t.push(r.target)):r.target&&c.push(`"${r.target}"`),t.length>0&&(t=t.map(u=>`"\`"${u}\`""`),c.push("-ArgumentList",t.join(","))),r.target=Dc.Buffer.from(c.join(" "),"utf16le").toString("base64")}else{if(e)n=e;else{let c=!Lc||Lc==="/",u=!1;try{await eo.default.access($h,eo.constants.X_OK),u=!0}catch{}n=Nc.default.versions.electron??(Vn==="android"||c||!u)?"xdg-open":$h}t.length>0&&s.push(...t),r.wait||(i.stdio="ignore",i.detached=!0)}Vn==="darwin"&&t.length>0&&s.push("--args",...t),r.target&&s.push(r.target);let a=Mc.default.spawn(n,s,i);return r.wait?new Promise((c,u)=>{a.once("error",u),a.once("close",d=>{if(!r.allowNonzeroExitCode&&d>0){u(new Error(`Exited with code ${d}`));return}c(a)})}):(a.unref(),a)},My=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a `target`");return ks({...e,target:r})},By=(r,e)=>{if(typeof r!="string"&&!Array.isArray(r))throw new TypeError("Expected a valid `name`");let{arguments:t=[]}=e??{};if(t!=null&&!Array.isArray(t))throw new TypeError("Expected `appArguments` as Array type");return ks({...e,app:{name:r,arguments:t}})};jr={};Br(jr,"chrome",()=>to({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));Br(jr,"brave",()=>to({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));Br(jr,"firefox",()=>to({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Br(jr,"edge",()=>to({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Br(jr,"browser",()=>"browser");Br(jr,"browserPrivate",()=>"browserPrivate");jy=My});var ar=fe(require("fs")),qs=fe(require("path"));var nf=fe(require("os")),sf=fe(require("path")),js=fe(require("fs"));function Us(){let r=sf.join(nf.homedir(),".termiq");return js.existsSync(r)||js.mkdirSync(r,{recursive:!0,mode:448}),r}var Zn=class{filePath;data={};constructor(){this.filePath=qs.join(Us(),"credentials"),this.load()}async get(e){return this.data[e]}async set(e,t){this.data[e]=t,this.save()}async delete(e){delete this.data[e],this.save()}load(){try{if(ar.existsSync(this.filePath)){let e=ar.readFileSync(this.filePath,"utf-8");this.data=JSON.parse(e)}}catch{this.data={}}}save(){let e=qs.dirname(this.filePath);ar.existsSync(e)||ar.mkdirSync(e,{recursive:!0,mode:448}),ar.writeFileSync(this.filePath,JSON.stringify(this.data,null,2),{mode:384})}};var cr=fe(require("fs")),Ws=fe(require("path"));var Kd={serverUrl:"https://termiq.io",agentName:""},Qn=class{config;filePath;constructor(e){this.filePath=Ws.join(Us(),"config.json"),this.config={...Kd,...this.loadFromFile(),...e}}getServerUrl(){return this.config.serverUrl}getAgentName(){return this.config.agentName}isAutoConnect(){return!0}async setAgentName(e){this.config.agentName=e,this.saveToFile()}loadFromFile(){try{if(cr.existsSync(this.filePath)){let e=cr.readFileSync(this.filePath,"utf-8");return JSON.parse(e)}}catch{}return{}}saveToFile(){let e=Ws.dirname(this.filePath);cr.existsSync(e)||cr.mkdirSync(e,{recursive:!0,mode:448}),cr.writeFileSync(this.filePath,JSON.stringify(this.config,null,2))}};var dt=fe(require("fs")),gc=fe(require("path")),wh=fe(require("os")),Ji=fe(bs()),wy="cli",pc=gc.join(wh.homedir(),".termiq","logs"),Fr=gc.join(pc,"cli.log"),by=5*1024*1024,vh=3;function xy(){try{if(!dt.existsSync(Fr)||dt.statSync(Fr).size<by)return;for(let e=vh-1;e>=1;e--){let t=`${Fr}.${e}`,n=`${Fr}.${e+1}`;dt.existsSync(t)&&(e+1>vh?dt.unlinkSync(t):dt.renameSync(t,n))}dt.renameSync(Fr,`${Fr}.1`)}catch{}}function Sy(r){try{dt.existsSync(pc)||dt.mkdirSync(pc,{recursive:!0}),xy(),dt.appendFileSync(Fr,r+`
|
|
32
|
+
`,{encoding:"utf8"})}catch{}}var xs=class{level;toFile;constructor(e="silent",t=!1){typeof e=="boolean"?this.level=e?"info":"silent":this.level=e,this.toFile=t}static getLogFilePath(){return Fr}write(e,t,n){if(!(0,Ji.shouldLog)(e,this.level))return;let s=(0,Ji.formatLogLine)(e,wy,t,n);process.stderr.write(s+`
|
|
33
|
+
`),this.toFile&&Sy(s)}info(e,...t){this.write("info",e,t)}warn(e,...t){this.write("warn",e,t)}error(e,...t){this.write("error",e,t)}debug(e,...t){this.write("debug",e,t)}};var bh=fe(require("os")),xh=fe(_c()),Ts=class{cachedId=null;name;constructor(e){this.name=e||bh.hostname()||"CLI"}async getMachineId(){if(this.cachedId)return this.cachedId;try{this.cachedId=(0,xh.machineIdSync)()}catch{this.cachedId=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}return this.cachedId}getMachineName(){return this.name}};var Cs=class{info(e){process.stderr.write(`TermIQ: ${e}
|
|
34
34
|
`)}warn(e){process.stderr.write(`TermIQ [warn]: ${e}
|
|
35
35
|
`)}error(e){process.stderr.write(`TermIQ [error]: ${e}
|
|
36
|
-
`)}};var ks=class{async openUrl(e){let{default:t}=await Promise.resolve().then(()=>(Jh(),Xh));await t(e)}};var xd=me(require("path")),mt=me(vs());var Zh=me(require("os")),Qh=me(require("node-pty")),ed=me(vs()),to=class{ptyProcess=null;outputBuffer=new ed.CircularBuffer(100);logger;onOutput=null;onExit=null;constructor(e){this.logger=e}spawn(e){let t=process.env.SHELL||(Zh.platform()==="win32"?"powershell.exe":"/bin/bash"),n=process.stdout.columns||80,s=process.stdout.rows||24;this.ptyProcess=Qh.spawn(t,[],{name:"xterm-256color",cols:n,rows:s,cwd:e,env:process.env});let i=`cli_${this.ptyProcess.pid}`;return this.ptyProcess.onData(a=>{process.stdout.write(a),this.outputBuffer.append(a),this.onOutput?.(a)}),this.ptyProcess.onExit(({exitCode:a})=>{this.logger.info("Shell exited",String(a)),this.onExit?.(a)}),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",a=>{this.ptyProcess?.write(a.toString())}),process.on("SIGWINCH",()=>{let a=process.stdout.columns||80,c=process.stdout.rows||24;this.ptyProcess?.resize(a,c)}),this.logger.info("Shell spawned",t,i),i}write(e){this.ptyProcess?.write(e)}resize(e,t){this.ptyProcess?.resize(e,t)}getBuffer(){return this.outputBuffer.getContent()}getLastBytes(e){return this.outputBuffer.getLastBytes(e)}setOnOutput(e){this.onOutput=e}setOnExit(e){this.onExit=e}kill(){this.ptyProcess?.kill(),this.ptyProcess=null}dispose(){this.kill(),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause()}};var jr=me(require("path")),$n=me(require("fs"));var _d=require("node:events"),md=require("node:fs"),fo=require("node:fs/promises"),we=me(require("node:path"),1);var Er=require("node:fs/promises"),wr=require("node:path"),sd=require("node:stream"),Tt={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},Mc={root:".",fileFilter:r=>!0,directoryFilter:r=>!0,type:Tt.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(Mc);var id="READDIRP_RECURSIVE_ERROR",Fy=new Set(["ENOENT","EPERM","EACCES","ELOOP",id]),td=[Tt.DIR_TYPE,Tt.EVERYTHING_TYPE,Tt.FILE_DIR_TYPE,Tt.FILE_TYPE],My=new Set([Tt.DIR_TYPE,Tt.EVERYTHING_TYPE,Tt.FILE_DIR_TYPE]),By=new Set([Tt.EVERYTHING_TYPE,Tt.FILE_DIR_TYPE,Tt.FILE_TYPE]),jy=r=>Fy.has(r.code),Uy=process.platform==="win32",rd=r=>!0,nd=r=>{if(r===void 0)return rd;if(typeof r=="function")return r;if(typeof r=="string"){let e=r.trim();return t=>t.basename===e}if(Array.isArray(r)){let e=r.map(t=>t.trim());return t=>e.some(n=>t.basename===n)}return rd},Bc=class extends sd.Readable{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...Mc,...e},{root:n,type:s}=t;this._fileFilter=nd(t.fileFilter),this._directoryFilter=nd(t.directoryFilter);let i=t.lstat?Er.lstat:Er.stat;Uy?this._stat=a=>i(a,{bigint:!0}):this._stat=i,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:Mc.depth,this._wantsDir=s?My.has(s):!1,this._wantsFile=s?By.has(s):!1,this._wantsEverything=s===Tt.EVERYTHING_TYPE,this._root=(0,wr.resolve)(n),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:s,depth:i}=t,a=n.splice(0,e).map(u=>this._formatEntry(u,s)),c=await Promise.all(a);for(let u of c){if(!u)continue;if(this.destroyed)return;let d=await this._getEntryType(u);d==="directory"&&this._directoryFilter(u)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(u.fullPath,i+1)),this._wantsDir&&(this.push(u),e--)):(d==="file"||this._includeAsFile(u))&&this._fileFilter(u)&&this._wantsFile&&(this.push(u),e--)}}else{let s=this.parents.pop();if(!s){this.push(null);break}if(this.parent=await s,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await(0,Er.readdir)(e,this._rdOptions)}catch(s){this._onError(s)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n,s=this._isDirent?e.name:e;try{let i=(0,wr.resolve)((0,wr.join)(t,s));n={path:(0,wr.relative)(this._root,i),fullPath:i,basename:s},n[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(i){this._onError(i);return}return n}_onError(e){jy(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return"";let t=e[this._statsProp];if(t.isFile())return"file";if(t.isDirectory())return"directory";if(t&&t.isSymbolicLink()){let n=e.fullPath;try{let s=await(0,Er.realpath)(n),i=await(0,Er.lstat)(s);if(i.isFile())return"file";if(i.isDirectory()){let a=s.length;if(n.startsWith(s)&&n.substr(a,1)===wr.sep){let c=new Error(`Circular symlink detected: "${n}" points to "${s}"`);return c.code=id,this._onError(c)}return"directory"}}catch(s){return this._onError(s),""}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function od(r,e={}){let t=e.entryType||e.type;if(t==="both"&&(t=Tt.FILE_DIR_TYPE),t&&(e.type=t),r){if(typeof r!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(t&&!td.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${td.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=r,new Bc(e)}var ln=require("node:fs"),Ht=require("node:fs/promises"),cd=require("node:os"),qe=me(require("node:path"),1),qy="data",qc="end",fd="close",oo=()=>{};var ao=process.platform,Wc=ao==="win32",Wy=ao==="darwin",Hy=ao==="linux",Vy=ao==="freebsd",ud=(0,cd.type)()==="OS400",He={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},Wt=He,Ky="watch",$y={lstat:Ht.lstat,stat:Ht.stat},un="listeners",ro="errHandlers",Kn="rawEmitters",zy=[un,ro,Kn],Gy=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),Yy=r=>Gy.has(qe.extname(r).slice(1).toLowerCase()),Uc=(r,e)=>{r instanceof Set?r.forEach(e):e(r)},Ps=(r,e,t)=>{let n=r[e];n instanceof Set||(r[e]=n=new Set([n])),n.add(t)},Xy=r=>e=>{let t=r[e];t instanceof Set?t.clear():delete r[e]},Rs=(r,e,t)=>{let n=r[e];n instanceof Set?n.delete(t):n===t&&delete r[e]},ld=r=>r instanceof Set?r.size===0:!r,no=new Map;function ad(r,e,t,n,s){let i=(a,c)=>{t(r),s(a,c,{watchedPath:r}),c&&r!==c&&so(qe.resolve(r,c),un,qe.join(r,c))};try{return(0,ln.watch)(r,{persistent:e.persistent},i)}catch(a){n(a);return}}var so=(r,e,t,n,s)=>{let i=no.get(r);i&&Uc(i[e],a=>{a(t,n,s)})},Jy=(r,e,t,n)=>{let{listener:s,errHandler:i,rawEmitter:a}=n,c=no.get(e),u;if(!t.persistent)return u=ad(r,t,s,i,a),u?u.close.bind(u):void 0;if(c)Ps(c,un,s),Ps(c,ro,i),Ps(c,Kn,a);else{if(u=ad(r,t,so.bind(null,e,un),i,so.bind(null,e,Kn)),!u)return;u.on(Wt.ERROR,async d=>{let g=so.bind(null,e,ro);if(c&&(c.watcherUnusable=!0),Wc&&d.code==="EPERM")try{await(await(0,Ht.open)(r,"r")).close(),g(d)}catch{}else g(d)}),c={listeners:s,errHandlers:i,rawEmitters:a,watcher:u},no.set(e,c)}return()=>{Rs(c,un,s),Rs(c,ro,i),Rs(c,Kn,a),ld(c.listeners)&&(c.watcher.close(),no.delete(e),zy.forEach(Xy(c)),c.watcher=void 0,Object.freeze(c))}},jc=new Map,Zy=(r,e,t,n)=>{let{listener:s,rawEmitter:i}=n,a=jc.get(e),c=a&&a.options;return c&&(c.persistent<t.persistent||c.interval>t.interval)&&((0,ln.unwatchFile)(e),a=void 0),a?(Ps(a,un,s),Ps(a,Kn,i)):(a={listeners:s,rawEmitters:i,options:t,watcher:(0,ln.watchFile)(e,t,(u,d)=>{Uc(a.rawEmitters,_=>{_(Wt.CHANGE,e,{curr:u,prev:d})});let g=u.mtimeMs;(u.size!==d.size||g>d.mtimeMs||g===0)&&Uc(a.listeners,_=>_(r,u))})},jc.set(e,a)),()=>{Rs(a,un,s),Rs(a,Kn,i),ld(a.listeners)&&(jc.delete(e),(0,ln.unwatchFile)(e),a.options=a.watcher=void 0,Object.freeze(a))}},io=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,s=qe.dirname(e),i=qe.basename(e);this.fsw._getWatchedDir(s).add(i);let c=qe.resolve(e),u={persistent:n.persistent};t||(t=oo);let d;if(n.usePolling){let g=n.interval!==n.binaryInterval;u.interval=g&&Yy(i)?n.binaryInterval:n.interval,d=Zy(e,c,u,{listener:t,rawEmitter:this.fsw._emitRaw})}else d=Jy(e,c,u,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return d}_handleFile(e,t,n){if(this.fsw.closed)return;let s=qe.dirname(e),i=qe.basename(e),a=this.fsw._getWatchedDir(s),c=t;if(a.has(i))return;let u=async(g,_)=>{if(this.fsw._throttle(Ky,e,5)){if(!_||_.mtimeMs===0)try{let y=await(0,Ht.stat)(e);if(this.fsw.closed)return;let v=y.atimeMs,S=y.mtimeMs;if((!v||v<=S||S!==c.mtimeMs)&&this.fsw._emit(Wt.CHANGE,e,y),(Wy||Hy||Vy)&&c.ino!==y.ino){this.fsw._closeFile(g),c=y;let O=this._watchWithNodeFs(e,u);O&&this.fsw._addPathCloser(g,O)}else c=y}catch{this.fsw._remove(s,i)}else if(a.has(i)){let y=_.atimeMs,v=_.mtimeMs;(!y||y<=v||v!==c.mtimeMs)&&this.fsw._emit(Wt.CHANGE,e,_),c=_}}},d=this._watchWithNodeFs(e,u);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(Wt.ADD,e,0))return;this.fsw._emit(Wt.ADD,e,t)}return d}async _handleSymlink(e,t,n,s){if(this.fsw.closed)return;let i=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let c;try{c=await(0,Ht.realpath)(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(s)?this.fsw._symlinkPaths.get(i)!==c&&(this.fsw._symlinkPaths.set(i,c),this.fsw._emit(Wt.CHANGE,n,e.stats)):(a.add(s),this.fsw._symlinkPaths.set(i,c),this.fsw._emit(Wt.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,n,s,i,a,c){e=qe.join(e,"");let u=s?`${e}:${s}`:e;if(c=this.fsw._throttle("readdir",u,1e3),!c)return;let d=this.fsw._getWatchedDir(n.path),g=new Set,_=this.fsw._readdirp(e,{fileFilter:y=>n.filterPath(y),directoryFilter:y=>n.filterDir(y)});if(_)return _.on(qy,async y=>{if(this.fsw.closed){_=void 0;return}let v=y.path,S=qe.join(e,v);if(g.add(v),!(y.stats.isSymbolicLink()&&await this._handleSymlink(y,e,S,v))){if(this.fsw.closed){_=void 0;return}(v===s||!s&&!d.has(v))&&(this.fsw._incrReadyCount(),S=qe.join(i,qe.relative(i,S)),this._addToNodeFs(S,t,n,a+1))}}).on(Wt.ERROR,this._boundHandleError),new Promise((y,v)=>{if(!_)return v();_.once(qc,()=>{if(this.fsw.closed){_=void 0;return}let S=c?c.clear():!1;y(void 0),d.getChildren().filter(O=>O!==e&&!g.has(O)).forEach(O=>{this.fsw._remove(e,O)}),_=void 0,S&&this._handleRead(e,!1,n,s,i,a,c)})})}async _handleDir(e,t,n,s,i,a,c){let u=this.fsw._getWatchedDir(qe.dirname(e)),d=u.has(qe.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!d&&this.fsw._emit(Wt.ADD_DIR,e,t),u.add(qe.basename(e)),this.fsw._getWatchedDir(e);let g,_,y=this.fsw.options.depth;if((y==null||s<=y)&&!this.fsw._symlinkPaths.has(c)){if(!i&&(await this._handleRead(e,n,a,i,e,s,g),this.fsw.closed))return;_=this._watchWithNodeFs(e,(v,S)=>{S&&S.mtimeMs===0||this._handleRead(v,!1,a,i,e,s,g)})}return _}async _addToNodeFs(e,t,n,s,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let c=this.fsw._getWatchHelpers(e);n&&(c.filterPath=u=>n.filterPath(u),c.filterDir=u=>n.filterDir(u));try{let u=await $y[c.statMethod](c.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(c.watchPath,u))return a(),!1;let d=this.fsw.options.followSymlinks,g;if(u.isDirectory()){let _=qe.resolve(e),y=d?await(0,Ht.realpath)(e):e;if(this.fsw.closed||(g=await this._handleDir(c.watchPath,u,t,s,i,c,y),this.fsw.closed))return;_!==y&&y!==void 0&&this.fsw._symlinkPaths.set(_,y)}else if(u.isSymbolicLink()){let _=d?await(0,Ht.realpath)(e):e;if(this.fsw.closed)return;let y=qe.dirname(c.watchPath);if(this.fsw._getWatchedDir(y).add(c.watchPath),this.fsw._emit(Wt.ADD,c.watchPath,u),g=await this._handleDir(y,u,t,s,e,c,_),this.fsw.closed)return;_!==void 0&&this.fsw._symlinkPaths.set(qe.resolve(e),_)}else g=this._handleFile(c.watchPath,u,t);return a(),g&&this.fsw._addPathCloser(e,g),!1}catch(u){if(this.fsw._handleError(u))return a(),e}}};var Hc="/",Qy="//",yd=".",eE="..",tE="string",rE=/\\/g,Ed=/\/\//g,nE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,sE=/^\.[/\\]/;function co(r){return Array.isArray(r)?r:[r]}var Vc=r=>typeof r=="object"&&r!==null&&!(r instanceof RegExp);function iE(r){return typeof r=="function"?r:typeof r=="string"?e=>r===e:r instanceof RegExp?e=>r.test(e):typeof r=="object"&&r!==null?e=>{if(r.path===e)return!0;if(r.recursive){let t=we.relative(r.path,e);return t?!t.startsWith("..")&&!we.isAbsolute(t):!1}return!1}:()=>!1}function oE(r){if(typeof r!="string")throw new Error("string expected");r=we.normalize(r),r=r.replace(/\\/g,"/");let e=!1;return r.startsWith("//")&&(e=!0),r=r.replace(Ed,"/"),e&&(r="/"+r),r}function hd(r,e,t){let n=oE(e);for(let s=0;s<r.length;s++){let i=r[s];if(i(n,t))return!0}return!1}function aE(r,e){if(r==null)throw new TypeError("anymatch: specify first argument");let n=co(r).map(s=>iE(s));return e==null?(s,i)=>hd(n,s,i):hd(n,e)}var dd=r=>{let e=co(r).flat();if(!e.every(t=>typeof t===tE))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(wd)},pd=r=>{let e=r.replace(rE,Hc),t=!1;return e.startsWith(Qy)&&(t=!0),e=e.replace(Ed,Hc),t&&(e=Hc+e),e},wd=r=>pd(we.normalize(pd(r))),gd=(r="")=>e=>typeof e=="string"?wd(we.isAbsolute(e)?e:we.join(r,e)):e,cE=(r,e)=>we.isAbsolute(r)?r:we.join(e,r),fE=Object.freeze(new Set),Kc=class{path;_removeWatcher;items;constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==yd&&e!==eE&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await(0,fo.readdir)(n)}catch{this._removeWatcher&&this._removeWatcher(we.dirname(n),we.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=oo,this.items=fE,Object.freeze(this)}},uE="stat",lE="lstat",$c=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,t,n){this.fsw=n;let s=e;this.path=e=e.replace(sE,""),this.watchPath=s,this.fullWatchPath=we.resolve(s),this.dirParts=[],this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=t,this.statMethod=t?uE:lE}entryPath(e){return we.join(this.watchPath,we.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},zc=class extends _d.EventEmitter{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},s={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?co(e.ignored):co([]),awaitWriteFinish:t===!0?n:typeof t=="object"?{...n,...t}:!1};ud&&(s.usePolling=!0),s.atomic===void 0&&(s.atomic=!s.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let u=i.toLowerCase();u==="false"||u==="0"?s.usePolling=!1:u==="true"||u==="1"?s.usePolling=!0:s.usePolling=!!u}let a=process.env.CHOKIDAR_INTERVAL;a&&(s.interval=Number.parseInt(a,10));let c=0;this._emitReady=()=>{c++,c>=this._readyCount&&(this._emitReady=oo,this._readyEmitted=!0,process.nextTick(()=>this.emit(He.READY)))},this._emitRaw=(...u)=>this.emit(He.RAW,...u),this._boundRemove=this._remove.bind(this),this.options=s,this._nodeFsHandler=new io(this),Object.freeze(s)}_addIgnoredPath(e){if(Vc(e)){for(let t of this._ignoredPaths)if(Vc(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e=="string")for(let t of this._ignoredPaths)Vc(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:s}=this.options;this.closed=!1,this._closePromise=void 0;let i=dd(e);return s&&(i=i.map(a=>cE(a,s))),i.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=i.length,Promise.all(i.map(async a=>{let c=await this._nodeFsHandler._addToNodeFs(a,!n,void 0,0,t);return c&&this._emitReady(),c})).then(a=>{this.closed||a.forEach(c=>{c&&this.add(we.dirname(c),we.basename(t||c))})}),this}unwatch(e){if(this.closed)return this;let t=dd(e),{cwd:n}=this.options;return t.forEach(s=>{!we.isAbsolute(s)&&!this._closers.has(s)&&(n&&(s=we.join(n,s)),s=we.resolve(s)),this._closePath(s),this._addIgnoredPath(s),this._watched.has(s)&&this._addIgnoredPath({path:s,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(n=>{let s=n();s instanceof Promise&&e.push(s)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let i=(this.options.cwd?we.relative(this.options.cwd,n):n)||yd;e[i]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==He.ERROR&&this.emit(He.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let s=this.options;Wc&&(t=we.normalize(t)),s.cwd&&(t=we.relative(s.cwd,t));let i=[t];n!=null&&i.push(n);let a=s.awaitWriteFinish,c;if(a&&(c=this._pendingWrites.get(t)))return c.lastChange=new Date,this;if(s.atomic){if(e===He.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((u,d)=>{this.emit(...u),this.emit(He.ALL,...u),this._pendingUnlinks.delete(d)})},typeof s.atomic=="number"?s.atomic:100),this;e===He.ADD&&this._pendingUnlinks.has(t)&&(e=He.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===He.ADD||e===He.CHANGE)&&this._readyEmitted){let u=(d,g)=>{d?(e=He.ERROR,i[0]=d,this.emitWithAll(e,i)):g&&(i.length>1?i[1]=g:i.push(g),this.emitWithAll(e,i))};return this._awaitWriteFinish(t,a.stabilityThreshold,e,u),this}if(e===He.CHANGE&&!this._throttle(He.CHANGE,t,50))return this;if(s.alwaysStat&&n===void 0&&(e===He.ADD||e===He.ADD_DIR||e===He.CHANGE)){let u=s.cwd?we.join(s.cwd,t):t,d;try{d=await(0,fo.stat)(u)}catch{}if(!d||this.closed)return;i.push(d)}return this.emitWithAll(e,i),this}_handleError(e){let t=e&&e.code;return e&&t!=="ENOENT"&&t!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||t!=="EPERM"&&t!=="EACCES")&&this.emit(He.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let s=this._throttled.get(e);if(!s)throw new Error("invalid throttle");let i=s.get(t);if(i)return i.count++,!1;let a,c=()=>{let d=s.get(t),g=d?d.count:0;return s.delete(t),clearTimeout(a),d&&clearTimeout(d.timeoutObject),g};a=setTimeout(c,n);let u={timeoutObject:a,clear:c,count:0};return s.set(t,u),u}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,s){let i=this.options.awaitWriteFinish;if(typeof i!="object")return;let a=i.pollInterval,c,u=e;this.options.cwd&&!we.isAbsolute(e)&&(u=we.join(this.options.cwd,e));let d=new Date,g=this._pendingWrites;function _(y){(0,md.stat)(u,(v,S)=>{if(v||!g.has(e)){v&&v.code!=="ENOENT"&&s(v);return}let O=Number(new Date);y&&S.size!==y.size&&(g.get(e).lastChange=O);let H=g.get(e);O-H.lastChange>=t?(g.delete(e),s(void 0,S)):c=setTimeout(_,a,S)})}g.has(e)||(g.set(e,{lastChange:d,cancelWait:()=>(g.delete(e),clearTimeout(c),n)}),c=setTimeout(_,a))}_isIgnored(e,t){if(this.options.atomic&&nE.test(e))return!0;if(!this._userIgnored){let{cwd:n}=this.options,i=(this.options.ignored||[]).map(gd(n)),c=[...[...this._ignoredPaths].map(gd(n)),...i];this._userIgnored=aE(c,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new $c(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=we.resolve(e);return this._watched.has(t)||this._watched.set(t,new Kc(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let s=we.join(e,t),i=we.resolve(s);if(n=n??(this._watched.has(s)||this._watched.has(i)),!this._throttle("remove",s,100))return;!n&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(s).getChildren().forEach(y=>this._remove(s,y));let u=this._getWatchedDir(e),d=u.has(t);u.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let g=s;if(this.options.cwd&&(g=we.relative(this.options.cwd,s)),this.options.awaitWriteFinish&&this._pendingWrites.has(g)&&this._pendingWrites.get(g).cancelWait()===He.ADD)return;this._watched.delete(s),this._watched.delete(i);let _=n?He.UNLINK_DIR:He.UNLINK;d&&!this._isIgnored(s)&&this._emit(_,s),this._closePath(s)}_closePath(e){this._closeFile(e);let t=we.dirname(e);this._getWatchedDir(t).remove(we.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(n=>n()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n={type:He.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},s=od(e,n);return this._streams.add(s),s.once(fd,()=>{s=void 0}),s.once(qc,()=>{s&&(this._streams.delete(s),s=void 0)}),s}};function vd(r,e={}){let t=new zc(e);return t.add(r),t}var bd=me(sc()),sr=me(Gr()),hE=["**/node_modules/**","**/.git/**","**/dist/**","**/.next/**","**/.turbo/**","**/.cache/**","**/coverage/**","**/*.log"],dE=300,uo=class{watcher=null;ignoreFilter;workspaceRoot;logger;onFileChangedCallback=null;pendingEvents=new Map;pendingTypes=new Map;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,bd.default)(),this.initializeIgnoreFilter()}initializeIgnoreFilter(){this.ignoreFilter.add(hE);let e=jr.join(this.workspaceRoot,".gitignore");try{if($n.existsSync(e)){let t=$n.readFileSync(e,"utf-8");this.ignoreFilter.add(t)}}catch{}}onFileChanged(e){this.onFileChangedCallback=e}start(){this.watcher||(this.watcher=vd(this.workspaceRoot,{ignored:e=>{let t=jr.relative(this.workspaceRoot,e);if(!t||t===".")return!1;let n=t.split(jr.sep).join("/");return this.ignoreFilter.ignores(n)},persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:200,pollInterval:50}}),this.watcher.on("add",e=>this.handleEvent(e,sr.FileChangeType.CREATE)),this.watcher.on("change",e=>this.handleEvent(e,sr.FileChangeType.MODIFY)),this.watcher.on("unlink",e=>this.handleEvent(e,sr.FileChangeType.DELETE)),this.watcher.on("error",e=>this.logger.error("File watcher error",e)),this.logger.info("File watcher started"))}stop(){this.watcher?.close(),this.watcher=null;for(let e of this.pendingEvents.values())clearTimeout(e);this.pendingEvents.clear(),this.pendingTypes.clear()}handleEvent(e,t){let n=jr.relative(this.workspaceRoot,e);if(!n)return;let s=this.pendingEvents.get(n);s&&clearTimeout(s);let i=this.pendingTypes.get(n);this.pendingTypes.set(n,this.mergeTypes(i,t));let a=setTimeout(()=>{this.emit(n,this.pendingTypes.get(n)||t),this.pendingEvents.delete(n),this.pendingTypes.delete(n)},dE);this.pendingEvents.set(n,a)}mergeTypes(e,t){return e?t===sr.FileChangeType.DELETE||e===sr.FileChangeType.DELETE?sr.FileChangeType.DELETE:e===sr.FileChangeType.CREATE?sr.FileChangeType.CREATE:t:t}emit(e,t){let n={path:e,changeType:t,timestamp:new Date().toISOString(),source:"watcher"};if(t!==sr.FileChangeType.DELETE)try{let s=jr.join(this.workspaceRoot,e),i=$n.statSync(s);n.size=i.size}catch{}this.onFileChangedCallback?.(n)}dispose(){this.stop(),this.onFileChangedCallback=null}};async function lo(r,e,t,n){if(n)return process.stderr.write(`Logging in with API key...
|
|
36
|
+
`)}};var Ps=class{async openUrl(e){let{default:t}=await Promise.resolve().then(()=>(Qh(),Zh));await t(e)}};var ed=fe(require("fs")),td=fe(require("path"));function Bc(r){try{let e=r??td.join(__dirname,"..","..","package.json"),t=JSON.parse(ed.readFileSync(e,"utf8"));return typeof t.version=="string"&&t.version.length>0?t.version:"unknown"}catch{return"unknown"}}var kd=fe(require("path")),_t=fe(bs());var rd=fe(require("os")),nd=fe(require("node-pty")),sd=fe(bs()),ro=class{ptyProcess=null;outputBuffer=new sd.CircularBuffer(100);logger;onOutput=null;onExit=null;sigwinchEnabled=!0;sigwinchListener=null;constructor(e){this.logger=e}spawn(e){let t=process.env.SHELL||(rd.platform()==="win32"?"powershell.exe":"/bin/bash"),n=process.stdout.columns||80,s=process.stdout.rows||24;this.ptyProcess=nd.spawn(t,[],{name:"xterm-256color",cols:n,rows:s,cwd:e,env:process.env});let i=`cli_${this.ptyProcess.pid}`;return this.ptyProcess.onData(a=>{process.stdout.write(a),this.outputBuffer.append(a),this.onOutput?.(a)}),this.ptyProcess.onExit(({exitCode:a})=>{this.logger.info("Shell exited",String(a)),this.onExit?.(a)}),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",a=>{this.ptyProcess?.write(a.toString())}),this.sigwinchListener=()=>{if(!this.sigwinchEnabled){this.logger.debug("SIGWINCH ignored (PWA viewers attached)");return}let a=process.stdout.columns||80,c=process.stdout.rows||24;this.logger.debug("SIGWINCH applied",{cols:a,rows:c}),this.ptyProcess?.resize(a,c)},process.on("SIGWINCH",this.sigwinchListener),this.logger.info("Shell spawned",t,i),i}write(e){this.ptyProcess?.write(e)}resize(e,t){this.ptyProcess?.resize(e,t)}setSigwinchEnabled(e){this.sigwinchEnabled!==e&&(this.sigwinchEnabled=e,this.logger.info("SIGWINCH listener",{enabled:e}))}getBuffer(){return this.outputBuffer.getContent()}getLastBytes(e){return this.outputBuffer.getLastBytes(e)}setOnOutput(e){this.onOutput=e}setOnExit(e){this.onExit=e}kill(){this.ptyProcess?.kill(),this.ptyProcess=null}dispose(){this.kill(),this.sigwinchListener&&(process.removeListener("SIGWINCH",this.sigwinchListener),this.sigwinchListener=null),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause()}};var Ur=fe(require("path")),$n=fe(require("fs"));var vd=require("node:events"),wd=require("node:fs"),uo=require("node:fs/promises"),ye=fe(require("node:path"),1);var Er=require("node:fs/promises"),vr=require("node:path"),cd=require("node:stream"),Ct={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},jc={root:".",fileFilter:r=>!0,directoryFilter:r=>!0,type:Ct.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(jc);var fd="READDIRP_RECURSIVE_ERROR",qy=new Set(["ENOENT","EPERM","EACCES","ELOOP",fd]),id=[Ct.DIR_TYPE,Ct.EVERYTHING_TYPE,Ct.FILE_DIR_TYPE,Ct.FILE_TYPE],Wy=new Set([Ct.DIR_TYPE,Ct.EVERYTHING_TYPE,Ct.FILE_DIR_TYPE]),Hy=new Set([Ct.EVERYTHING_TYPE,Ct.FILE_DIR_TYPE,Ct.FILE_TYPE]),Vy=r=>qy.has(r.code),Ky=process.platform==="win32",od=r=>!0,ad=r=>{if(r===void 0)return od;if(typeof r=="function")return r;if(typeof r=="string"){let e=r.trim();return t=>t.basename===e}if(Array.isArray(r)){let e=r.map(t=>t.trim());return t=>e.some(n=>t.basename===n)}return od},Uc=class extends cd.Readable{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...jc,...e},{root:n,type:s}=t;this._fileFilter=ad(t.fileFilter),this._directoryFilter=ad(t.directoryFilter);let i=t.lstat?Er.lstat:Er.stat;Ky?this._stat=a=>i(a,{bigint:!0}):this._stat=i,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:jc.depth,this._wantsDir=s?Wy.has(s):!1,this._wantsFile=s?Hy.has(s):!1,this._wantsEverything=s===Ct.EVERYTHING_TYPE,this._root=(0,vr.resolve)(n),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:s,depth:i}=t,a=n.splice(0,e).map(u=>this._formatEntry(u,s)),c=await Promise.all(a);for(let u of c){if(!u)continue;if(this.destroyed)return;let d=await this._getEntryType(u);d==="directory"&&this._directoryFilter(u)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(u.fullPath,i+1)),this._wantsDir&&(this.push(u),e--)):(d==="file"||this._includeAsFile(u))&&this._fileFilter(u)&&this._wantsFile&&(this.push(u),e--)}}else{let s=this.parents.pop();if(!s){this.push(null);break}if(this.parent=await s,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await(0,Er.readdir)(e,this._rdOptions)}catch(s){this._onError(s)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n,s=this._isDirent?e.name:e;try{let i=(0,vr.resolve)((0,vr.join)(t,s));n={path:(0,vr.relative)(this._root,i),fullPath:i,basename:s},n[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(i){this._onError(i);return}return n}_onError(e){Vy(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return"";let t=e[this._statsProp];if(t.isFile())return"file";if(t.isDirectory())return"directory";if(t&&t.isSymbolicLink()){let n=e.fullPath;try{let s=await(0,Er.realpath)(n),i=await(0,Er.lstat)(s);if(i.isFile())return"file";if(i.isDirectory()){let a=s.length;if(n.startsWith(s)&&n.substr(a,1)===vr.sep){let c=new Error(`Circular symlink detected: "${n}" points to "${s}"`);return c.code=fd,this._onError(c)}return"directory"}}catch(s){return this._onError(s),""}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function ud(r,e={}){let t=e.entryType||e.type;if(t==="both"&&(t=Ct.FILE_DIR_TYPE),t&&(e.type=t),r){if(typeof r!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(t&&!id.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${id.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=r,new Uc(e)}var ln=require("node:fs"),Vt=require("node:fs/promises"),hd=require("node:os"),qe=fe(require("node:path"),1),$y="data",Hc="end",dd="close",ao=()=>{};var co=process.platform,Vc=co==="win32",zy=co==="darwin",Gy=co==="linux",Yy=co==="freebsd",pd=(0,hd.type)()==="OS400",Ve={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},Ht=Ve,Xy="watch",Jy={lstat:Vt.lstat,stat:Vt.stat},un="listeners",no="errHandlers",Kn="rawEmitters",Zy=[un,no,Kn],Qy=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),eE=r=>Qy.has(qe.extname(r).slice(1).toLowerCase()),Wc=(r,e)=>{r instanceof Set?r.forEach(e):e(r)},Rs=(r,e,t)=>{let n=r[e];n instanceof Set||(r[e]=n=new Set([n])),n.add(t)},tE=r=>e=>{let t=r[e];t instanceof Set?t.clear():delete r[e]},As=(r,e,t)=>{let n=r[e];n instanceof Set?n.delete(t):n===t&&delete r[e]},gd=r=>r instanceof Set?r.size===0:!r,so=new Map;function ld(r,e,t,n,s){let i=(a,c)=>{t(r),s(a,c,{watchedPath:r}),c&&r!==c&&io(qe.resolve(r,c),un,qe.join(r,c))};try{return(0,ln.watch)(r,{persistent:e.persistent},i)}catch(a){n(a);return}}var io=(r,e,t,n,s)=>{let i=so.get(r);i&&Wc(i[e],a=>{a(t,n,s)})},rE=(r,e,t,n)=>{let{listener:s,errHandler:i,rawEmitter:a}=n,c=so.get(e),u;if(!t.persistent)return u=ld(r,t,s,i,a),u?u.close.bind(u):void 0;if(c)Rs(c,un,s),Rs(c,no,i),Rs(c,Kn,a);else{if(u=ld(r,t,io.bind(null,e,un),i,io.bind(null,e,Kn)),!u)return;u.on(Ht.ERROR,async d=>{let g=io.bind(null,e,no);if(c&&(c.watcherUnusable=!0),Vc&&d.code==="EPERM")try{await(await(0,Vt.open)(r,"r")).close(),g(d)}catch{}else g(d)}),c={listeners:s,errHandlers:i,rawEmitters:a,watcher:u},so.set(e,c)}return()=>{As(c,un,s),As(c,no,i),As(c,Kn,a),gd(c.listeners)&&(c.watcher.close(),so.delete(e),Zy.forEach(tE(c)),c.watcher=void 0,Object.freeze(c))}},qc=new Map,nE=(r,e,t,n)=>{let{listener:s,rawEmitter:i}=n,a=qc.get(e),c=a&&a.options;return c&&(c.persistent<t.persistent||c.interval>t.interval)&&((0,ln.unwatchFile)(e),a=void 0),a?(Rs(a,un,s),Rs(a,Kn,i)):(a={listeners:s,rawEmitters:i,options:t,watcher:(0,ln.watchFile)(e,t,(u,d)=>{Wc(a.rawEmitters,m=>{m(Ht.CHANGE,e,{curr:u,prev:d})});let g=u.mtimeMs;(u.size!==d.size||g>d.mtimeMs||g===0)&&Wc(a.listeners,m=>m(r,u))})},qc.set(e,a)),()=>{As(a,un,s),As(a,Kn,i),gd(a.listeners)&&(qc.delete(e),(0,ln.unwatchFile)(e),a.options=a.watcher=void 0,Object.freeze(a))}},oo=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,s=qe.dirname(e),i=qe.basename(e);this.fsw._getWatchedDir(s).add(i);let c=qe.resolve(e),u={persistent:n.persistent};t||(t=ao);let d;if(n.usePolling){let g=n.interval!==n.binaryInterval;u.interval=g&&eE(i)?n.binaryInterval:n.interval,d=nE(e,c,u,{listener:t,rawEmitter:this.fsw._emitRaw})}else d=rE(e,c,u,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return d}_handleFile(e,t,n){if(this.fsw.closed)return;let s=qe.dirname(e),i=qe.basename(e),a=this.fsw._getWatchedDir(s),c=t;if(a.has(i))return;let u=async(g,m)=>{if(this.fsw._throttle(Xy,e,5)){if(!m||m.mtimeMs===0)try{let y=await(0,Vt.stat)(e);if(this.fsw.closed)return;let w=y.atimeMs,S=y.mtimeMs;if((!w||w<=S||S!==c.mtimeMs)&&this.fsw._emit(Ht.CHANGE,e,y),(zy||Gy||Yy)&&c.ino!==y.ino){this.fsw._closeFile(g),c=y;let C=this._watchWithNodeFs(e,u);C&&this.fsw._addPathCloser(g,C)}else c=y}catch{this.fsw._remove(s,i)}else if(a.has(i)){let y=m.atimeMs,w=m.mtimeMs;(!y||y<=w||w!==c.mtimeMs)&&this.fsw._emit(Ht.CHANGE,e,m),c=m}}},d=this._watchWithNodeFs(e,u);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(Ht.ADD,e,0))return;this.fsw._emit(Ht.ADD,e,t)}return d}async _handleSymlink(e,t,n,s){if(this.fsw.closed)return;let i=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let c;try{c=await(0,Vt.realpath)(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(s)?this.fsw._symlinkPaths.get(i)!==c&&(this.fsw._symlinkPaths.set(i,c),this.fsw._emit(Ht.CHANGE,n,e.stats)):(a.add(s),this.fsw._symlinkPaths.set(i,c),this.fsw._emit(Ht.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,n,s,i,a,c){e=qe.join(e,"");let u=s?`${e}:${s}`:e;if(c=this.fsw._throttle("readdir",u,1e3),!c)return;let d=this.fsw._getWatchedDir(n.path),g=new Set,m=this.fsw._readdirp(e,{fileFilter:y=>n.filterPath(y),directoryFilter:y=>n.filterDir(y)});if(m)return m.on($y,async y=>{if(this.fsw.closed){m=void 0;return}let w=y.path,S=qe.join(e,w);if(g.add(w),!(y.stats.isSymbolicLink()&&await this._handleSymlink(y,e,S,w))){if(this.fsw.closed){m=void 0;return}(w===s||!s&&!d.has(w))&&(this.fsw._incrReadyCount(),S=qe.join(i,qe.relative(i,S)),this._addToNodeFs(S,t,n,a+1))}}).on(Ht.ERROR,this._boundHandleError),new Promise((y,w)=>{if(!m)return w();m.once(Hc,()=>{if(this.fsw.closed){m=void 0;return}let S=c?c.clear():!1;y(void 0),d.getChildren().filter(C=>C!==e&&!g.has(C)).forEach(C=>{this.fsw._remove(e,C)}),m=void 0,S&&this._handleRead(e,!1,n,s,i,a,c)})})}async _handleDir(e,t,n,s,i,a,c){let u=this.fsw._getWatchedDir(qe.dirname(e)),d=u.has(qe.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!d&&this.fsw._emit(Ht.ADD_DIR,e,t),u.add(qe.basename(e)),this.fsw._getWatchedDir(e);let g,m,y=this.fsw.options.depth;if((y==null||s<=y)&&!this.fsw._symlinkPaths.has(c)){if(!i&&(await this._handleRead(e,n,a,i,e,s,g),this.fsw.closed))return;m=this._watchWithNodeFs(e,(w,S)=>{S&&S.mtimeMs===0||this._handleRead(w,!1,a,i,e,s,g)})}return m}async _addToNodeFs(e,t,n,s,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let c=this.fsw._getWatchHelpers(e);n&&(c.filterPath=u=>n.filterPath(u),c.filterDir=u=>n.filterDir(u));try{let u=await Jy[c.statMethod](c.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(c.watchPath,u))return a(),!1;let d=this.fsw.options.followSymlinks,g;if(u.isDirectory()){let m=qe.resolve(e),y=d?await(0,Vt.realpath)(e):e;if(this.fsw.closed||(g=await this._handleDir(c.watchPath,u,t,s,i,c,y),this.fsw.closed))return;m!==y&&y!==void 0&&this.fsw._symlinkPaths.set(m,y)}else if(u.isSymbolicLink()){let m=d?await(0,Vt.realpath)(e):e;if(this.fsw.closed)return;let y=qe.dirname(c.watchPath);if(this.fsw._getWatchedDir(y).add(c.watchPath),this.fsw._emit(Ht.ADD,c.watchPath,u),g=await this._handleDir(y,u,t,s,e,c,m),this.fsw.closed)return;m!==void 0&&this.fsw._symlinkPaths.set(qe.resolve(e),m)}else g=this._handleFile(c.watchPath,u,t);return a(),g&&this.fsw._addPathCloser(e,g),!1}catch(u){if(this.fsw._handleError(u))return a(),e}}};var Kc="/",sE="//",bd=".",iE="..",oE="string",aE=/\\/g,xd=/\/\//g,cE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,fE=/^\.[/\\]/;function fo(r){return Array.isArray(r)?r:[r]}var $c=r=>typeof r=="object"&&r!==null&&!(r instanceof RegExp);function uE(r){return typeof r=="function"?r:typeof r=="string"?e=>r===e:r instanceof RegExp?e=>r.test(e):typeof r=="object"&&r!==null?e=>{if(r.path===e)return!0;if(r.recursive){let t=ye.relative(r.path,e);return t?!t.startsWith("..")&&!ye.isAbsolute(t):!1}return!1}:()=>!1}function lE(r){if(typeof r!="string")throw new Error("string expected");r=ye.normalize(r),r=r.replace(/\\/g,"/");let e=!1;return r.startsWith("//")&&(e=!0),r=r.replace(xd,"/"),e&&(r="/"+r),r}function md(r,e,t){let n=lE(e);for(let s=0;s<r.length;s++){let i=r[s];if(i(n,t))return!0}return!1}function hE(r,e){if(r==null)throw new TypeError("anymatch: specify first argument");let n=fo(r).map(s=>uE(s));return e==null?(s,i)=>md(n,s,i):md(n,e)}var _d=r=>{let e=fo(r).flat();if(!e.every(t=>typeof t===oE))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Sd)},yd=r=>{let e=r.replace(aE,Kc),t=!1;return e.startsWith(sE)&&(t=!0),e=e.replace(xd,Kc),t&&(e=Kc+e),e},Sd=r=>yd(ye.normalize(yd(r))),Ed=(r="")=>e=>typeof e=="string"?Sd(ye.isAbsolute(e)?e:ye.join(r,e)):e,dE=(r,e)=>ye.isAbsolute(r)?r:ye.join(e,r),pE=Object.freeze(new Set),zc=class{path;_removeWatcher;items;constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==bd&&e!==iE&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await(0,uo.readdir)(n)}catch{this._removeWatcher&&this._removeWatcher(ye.dirname(n),ye.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=ao,this.items=pE,Object.freeze(this)}},gE="stat",mE="lstat",Gc=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,t,n){this.fsw=n;let s=e;this.path=e=e.replace(fE,""),this.watchPath=s,this.fullWatchPath=ye.resolve(s),this.dirParts=[],this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=t,this.statMethod=t?gE:mE}entryPath(e){return ye.join(this.watchPath,ye.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Yc=class extends vd.EventEmitter{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},s={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?fo(e.ignored):fo([]),awaitWriteFinish:t===!0?n:typeof t=="object"?{...n,...t}:!1};pd&&(s.usePolling=!0),s.atomic===void 0&&(s.atomic=!s.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let u=i.toLowerCase();u==="false"||u==="0"?s.usePolling=!1:u==="true"||u==="1"?s.usePolling=!0:s.usePolling=!!u}let a=process.env.CHOKIDAR_INTERVAL;a&&(s.interval=Number.parseInt(a,10));let c=0;this._emitReady=()=>{c++,c>=this._readyCount&&(this._emitReady=ao,this._readyEmitted=!0,process.nextTick(()=>this.emit(Ve.READY)))},this._emitRaw=(...u)=>this.emit(Ve.RAW,...u),this._boundRemove=this._remove.bind(this),this.options=s,this._nodeFsHandler=new oo(this),Object.freeze(s)}_addIgnoredPath(e){if($c(e)){for(let t of this._ignoredPaths)if($c(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e=="string")for(let t of this._ignoredPaths)$c(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:s}=this.options;this.closed=!1,this._closePromise=void 0;let i=_d(e);return s&&(i=i.map(a=>dE(a,s))),i.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=i.length,Promise.all(i.map(async a=>{let c=await this._nodeFsHandler._addToNodeFs(a,!n,void 0,0,t);return c&&this._emitReady(),c})).then(a=>{this.closed||a.forEach(c=>{c&&this.add(ye.dirname(c),ye.basename(t||c))})}),this}unwatch(e){if(this.closed)return this;let t=_d(e),{cwd:n}=this.options;return t.forEach(s=>{!ye.isAbsolute(s)&&!this._closers.has(s)&&(n&&(s=ye.join(n,s)),s=ye.resolve(s)),this._closePath(s),this._addIgnoredPath(s),this._watched.has(s)&&this._addIgnoredPath({path:s,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(n=>{let s=n();s instanceof Promise&&e.push(s)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let i=(this.options.cwd?ye.relative(this.options.cwd,n):n)||bd;e[i]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==Ve.ERROR&&this.emit(Ve.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let s=this.options;Vc&&(t=ye.normalize(t)),s.cwd&&(t=ye.relative(s.cwd,t));let i=[t];n!=null&&i.push(n);let a=s.awaitWriteFinish,c;if(a&&(c=this._pendingWrites.get(t)))return c.lastChange=new Date,this;if(s.atomic){if(e===Ve.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((u,d)=>{this.emit(...u),this.emit(Ve.ALL,...u),this._pendingUnlinks.delete(d)})},typeof s.atomic=="number"?s.atomic:100),this;e===Ve.ADD&&this._pendingUnlinks.has(t)&&(e=Ve.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===Ve.ADD||e===Ve.CHANGE)&&this._readyEmitted){let u=(d,g)=>{d?(e=Ve.ERROR,i[0]=d,this.emitWithAll(e,i)):g&&(i.length>1?i[1]=g:i.push(g),this.emitWithAll(e,i))};return this._awaitWriteFinish(t,a.stabilityThreshold,e,u),this}if(e===Ve.CHANGE&&!this._throttle(Ve.CHANGE,t,50))return this;if(s.alwaysStat&&n===void 0&&(e===Ve.ADD||e===Ve.ADD_DIR||e===Ve.CHANGE)){let u=s.cwd?ye.join(s.cwd,t):t,d;try{d=await(0,uo.stat)(u)}catch{}if(!d||this.closed)return;i.push(d)}return this.emitWithAll(e,i),this}_handleError(e){let t=e&&e.code;return e&&t!=="ENOENT"&&t!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||t!=="EPERM"&&t!=="EACCES")&&this.emit(Ve.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let s=this._throttled.get(e);if(!s)throw new Error("invalid throttle");let i=s.get(t);if(i)return i.count++,!1;let a,c=()=>{let d=s.get(t),g=d?d.count:0;return s.delete(t),clearTimeout(a),d&&clearTimeout(d.timeoutObject),g};a=setTimeout(c,n);let u={timeoutObject:a,clear:c,count:0};return s.set(t,u),u}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,s){let i=this.options.awaitWriteFinish;if(typeof i!="object")return;let a=i.pollInterval,c,u=e;this.options.cwd&&!ye.isAbsolute(e)&&(u=ye.join(this.options.cwd,e));let d=new Date,g=this._pendingWrites;function m(y){(0,wd.stat)(u,(w,S)=>{if(w||!g.has(e)){w&&w.code!=="ENOENT"&&s(w);return}let C=Number(new Date);y&&S.size!==y.size&&(g.get(e).lastChange=C);let V=g.get(e);C-V.lastChange>=t?(g.delete(e),s(void 0,S)):c=setTimeout(m,a,S)})}g.has(e)||(g.set(e,{lastChange:d,cancelWait:()=>(g.delete(e),clearTimeout(c),n)}),c=setTimeout(m,a))}_isIgnored(e,t){if(this.options.atomic&&cE.test(e))return!0;if(!this._userIgnored){let{cwd:n}=this.options,i=(this.options.ignored||[]).map(Ed(n)),c=[...[...this._ignoredPaths].map(Ed(n)),...i];this._userIgnored=hE(c,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new Gc(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=ye.resolve(e);return this._watched.has(t)||this._watched.set(t,new zc(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let s=ye.join(e,t),i=ye.resolve(s);if(n=n??(this._watched.has(s)||this._watched.has(i)),!this._throttle("remove",s,100))return;!n&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(s).getChildren().forEach(y=>this._remove(s,y));let u=this._getWatchedDir(e),d=u.has(t);u.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let g=s;if(this.options.cwd&&(g=ye.relative(this.options.cwd,s)),this.options.awaitWriteFinish&&this._pendingWrites.has(g)&&this._pendingWrites.get(g).cancelWait()===Ve.ADD)return;this._watched.delete(s),this._watched.delete(i);let m=n?Ve.UNLINK_DIR:Ve.UNLINK;d&&!this._isIgnored(s)&&this._emit(m,s),this._closePath(s)}_closePath(e){this._closeFile(e);let t=ye.dirname(e);this._getWatchedDir(t).remove(ye.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(n=>n()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n={type:Ve.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},s=ud(e,n);return this._streams.add(s),s.once(dd,()=>{s=void 0}),s.once(Hc,()=>{s&&(this._streams.delete(s),s=void 0)}),s}};function Td(r,e={}){let t=new Yc(e);return t.add(r),t}var Cd=fe(ic()),sr=fe(kr()),_E=["**/node_modules/**","**/.git/**","**/dist/**","**/.next/**","**/.turbo/**","**/.cache/**","**/coverage/**","**/*.log"],yE=300,lo=class{watcher=null;ignoreFilter;workspaceRoot;logger;onFileChangedCallback=null;pendingEvents=new Map;pendingTypes=new Map;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,Cd.default)(),this.initializeIgnoreFilter()}initializeIgnoreFilter(){this.ignoreFilter.add(_E);let e=Ur.join(this.workspaceRoot,".gitignore");try{if($n.existsSync(e)){let t=$n.readFileSync(e,"utf-8");this.ignoreFilter.add(t)}}catch{}}onFileChanged(e){this.onFileChangedCallback=e}start(){this.watcher||(this.watcher=Td(this.workspaceRoot,{ignored:e=>{let t=Ur.relative(this.workspaceRoot,e);if(!t||t===".")return!1;let n=t.split(Ur.sep).join("/");return this.ignoreFilter.ignores(n)},persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:200,pollInterval:50}}),this.watcher.on("add",e=>this.handleEvent(e,sr.FileChangeType.CREATE)),this.watcher.on("change",e=>this.handleEvent(e,sr.FileChangeType.MODIFY)),this.watcher.on("unlink",e=>this.handleEvent(e,sr.FileChangeType.DELETE)),this.watcher.on("error",e=>this.logger.error("File watcher error",e)),this.logger.info("File watcher started"))}stop(){this.watcher?.close(),this.watcher=null;for(let e of this.pendingEvents.values())clearTimeout(e);this.pendingEvents.clear(),this.pendingTypes.clear()}handleEvent(e,t){let n=Ur.relative(this.workspaceRoot,e);if(!n)return;let s=this.pendingEvents.get(n);s&&clearTimeout(s);let i=this.pendingTypes.get(n);this.pendingTypes.set(n,this.mergeTypes(i,t));let a=setTimeout(()=>{this.emit(n,this.pendingTypes.get(n)||t),this.pendingEvents.delete(n),this.pendingTypes.delete(n)},yE);this.pendingEvents.set(n,a)}mergeTypes(e,t){return e?t===sr.FileChangeType.DELETE||e===sr.FileChangeType.DELETE?sr.FileChangeType.DELETE:e===sr.FileChangeType.CREATE?sr.FileChangeType.CREATE:t:t}emit(e,t){let n={path:e,changeType:t,timestamp:new Date().toISOString(),source:"watcher"};if(t!==sr.FileChangeType.DELETE)try{let s=Ur.join(this.workspaceRoot,e),i=$n.statSync(s);n.size=i.size}catch{}this.onFileChangedCallback?.(n)}dispose(){this.stop(),this.onFileChangedCallback=null}};async function ho(r,e,t,n){if(n)return process.stderr.write(`Logging in with API key...
|
|
37
37
|
`),await r.loginWithApiKey(n)?(process.stderr.write(`Login successful.
|
|
38
38
|
`),!0):(process.stderr.write(`Login failed. Check your API key.
|
|
39
39
|
`),!1);try{let s=await r.startDeviceCodeFlow();process.stderr.write(`
|
|
@@ -46,18 +46,19 @@ tell application "System Events" to get value of property list item "CFBundleNam
|
|
|
46
46
|
`),!0):(process.stderr.write(` Login failed or expired.
|
|
47
47
|
|
|
48
48
|
`),!1)}catch(s){return t.error("Login error",s),process.stderr.write(`Login error: ${s instanceof Error?s.message:String(s)}
|
|
49
|
-
`),!1}}async function
|
|
50
|
-
`),await
|
|
51
|
-
`):
|
|
52
|
-
`)}),
|
|
53
|
-
`),
|
|
54
|
-
`),process.exit(1)}let
|
|
55
|
-
`)}async function
|
|
49
|
+
`),!1}}var zn=fe(kr());function EE(r){switch(r){case"numbered-choice":return"select";case"free-input":return"input";default:return"confirmation"}}function Od(r,e,t){let n=new Date().toISOString();switch(r){case"working":return e==="idle"?{type:zn.TerminalEventType.SESSION_START,timestamp:n}:null;case"waiting":return{type:zn.TerminalEventType.WAITING_INPUT,timestamp:n,promptType:EE(t?.type),question:t?.question||"Confirm action?",options:t?.choices?.map(s=>s.label)};case"completed":return{type:zn.TerminalEventType.SESSION_END,timestamp:n,status:"success"};case"error":return e==="working"?{type:zn.TerminalEventType.SESSION_END,timestamp:n,status:"error"}:{type:zn.TerminalEventType.ERROR,timestamp:n,severity:"error",message:"Command failed"};default:return null}}async function Pd(r){let{storage:e,config:t,logger:n,machineId:s,notification:i,browser:a,cwd:c,watch:u}=r,d=t.getServerUrl(),g=new URL(d).host,m=await s.getMachineId(),y=new _t.CryptoService(e,n,g,m);await y.initialize();let w=new _t.AuthService(e,y,s,t,n,i,a,g,m),S=await w.hasValidToken();S||await w.refreshAccessToken()||(process.stderr.write(`Not logged in. Starting login flow...
|
|
50
|
+
`),await ho(w,a,n)||process.exit(1),S=!0);let C;try{let{machineIdSync:G}=await Promise.resolve().then(()=>fe(_c()));C=G()}catch{C=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}let V,de=new _t.StatusDetector((G,te,Ae)=>{if(!B.getStatus().connected)return;let Be=V;V=te,B.updateStatus({instanceId:L,terminalId:G,status:te,prompt:Ae||void 0,encryptedPrompt:Ae&&y.encryptPromptInfo(Ae)||void 0}).catch(()=>{});let yt=Od(te,Be,Ae);yt&&B.sendTerminalEvent(L,G,yt)}),B=new _t.WebSocketService(w,y,t,n,i,C,"cli");B.onStatusChange(G=>{G==="connected"?process.stderr.write(`Connected to termiq.io
|
|
51
|
+
`):G==="disconnected"&&process.stderr.write(`Disconnected from termiq.io
|
|
52
|
+
`)}),B.onAuthFailure(()=>{process.stderr.write(`Session expired. Please run "termiq login" again.
|
|
53
|
+
`),Ze(),process.exit(1)});try{await B.connect()}catch(G){process.stderr.write(`Connection failed: ${G instanceof Error?G.message:String(G)}
|
|
54
|
+
`),process.exit(1)}let P=kd.basename(c),L=`cli_${Date.now()}`,Q=y.encryptWorkspaceInfo({name:P,path:c});await B.registerWorkspace({instanceId:L,name:Q?void 0:P,path:Q?void 0:c,encryptedInfo:Q||void 0});let j=new ro(n),Z=j.spawn(c),pe=`CLI: ${P}`,Ee=process.env.SHELL||"/bin/bash",ve=y.encryptTerminalInfo({name:pe,command:Ee,cwd:c});await B.terminalCreated({instanceId:L,terminalId:Z,name:ve?void 0:pe,command:ve?void 0:Ee,cwd:ve?void 0:c,encryptedInfo:ve||void 0});let We=new _t.FileTransferService(n),Ke=new _t.FileTrackerService(n,c),Te=new _t.FileListService(n,c),$e=u?new lo(n,c):null,He=B.getSocket();He&&We.attach(He,L),Ke.onFileChanged((G,te)=>{B.sendFileChangedEvent(L,G,te)}),Ke.onFileViewTransfer(async(G,te,Ae)=>{try{await We.sendBuffer(G,te,Ae.path.split("/").pop()||"view",Ae.mimeType||"text/plain",{purpose:"view",viewMetadata:Ae})}catch(Be){n.error("File view transfer failed",Be)}}),B.onFileViewRequest((G,te)=>{Ke.handleViewRequest(G,te)}),B.onFileListRequest((G,te)=>{Te.handleListRequest(te)}),Te.onResponse(G=>{B.sendFileListResponse(L,G)}),B.onFileDownloadRequest(async(G,te,Ae)=>{try{await We.sendFile(G,te,void 0,void 0,Ae)}catch(Be){n.error("File download failed",Be)}}),$e&&($e.onFileChanged(G=>{B.sendFileChangedEvent(L,Z,G)}),$e.start()),de.startTracking(Z),j.setOnOutput(G=>{B.sendOutput(L,Z,G),de.processOutput(Z,G),Ke.processOutput(Z,G)}),B.onInput((G,te)=>{G===Z&&j.write(te)}),B.onResizeRequest((G,te,Ae)=>{G===Z&&j.resize(te,Ae)}),B.onClientAttached(()=>{j.setSigwinchEnabled(!1)}),B.onClientDetached(({clientCount:G})=>{G===0&&j.setSigwinchEnabled(!0)}),B.onGetBufferRequest(G=>G===Z?j.getBuffer():null),B.onRedrawRequest(G=>{if(G===Z){let te=process.stdout.columns||80,Ae=process.stdout.rows||24;j.resize(te,Ae)}}),B.onReconnect(async()=>{try{await B.registerWorkspace({instanceId:L,name:Q?void 0:P,path:Q?void 0:c,encryptedInfo:Q||void 0}),await B.terminalCreated({instanceId:L,terminalId:Z,name:ve?void 0:pe,command:ve?void 0:Ee,cwd:ve?void 0:c,encryptedInfo:ve||void 0});let G=B.getSocket();G&&We.attach(G,L)}catch(G){n.error("Failed to re-register on reconnect",G)}});function Ze(){$e?.dispose(),We.detach(),Ke.dispose(),Te.dispose(),de.stopTracking(Z),de.dispose(),B.terminalClosed({instanceId:L,terminalId:Z}).catch(()=>{}),B.unregisterWorkspace(L).catch(()=>{}),B.disconnect(),j.dispose()}j.setOnExit(()=>{Ze(),process.exit(0)}),process.on("SIGINT",()=>{Ze(),process.exit(0)}),process.on("SIGTERM",()=>{Ze(),process.exit(0)})}async function Rd(r){await r.logout(),process.stderr.write(`Logged out.
|
|
55
|
+
`)}async function Ad(r){let e=await r.hasValidToken(),t=await r.getAgentId();e?(process.stderr.write(`Status: logged in
|
|
56
56
|
`),t&&process.stderr.write(`Agent ID: ${t}
|
|
57
57
|
`)):(process.stderr.write(`Status: not logged in
|
|
58
58
|
`),process.stderr.write(`Run 'termiq login' to authenticate.
|
|
59
|
-
`))}var
|
|
60
|
-
|
|
59
|
+
`))}var Ft=fe(bs()),Xe=process.argv.slice(2),Id=Xe.find(r=>!r.startsWith("-"))||"start",vE=Xe.includes("--verbose")||Xe.includes("-v"),wE=Xe.includes("--watch")||Xe.includes("-w"),bE=Xe.includes("--log-to-file"),xE=Xe.find(r=>r.startsWith("--token="))?.split("=")[1]||(Xe.includes("--token")?Xe[Xe.indexOf("--token")+1]:void 0),Ld=Xe.find(r=>r.startsWith("--server="))?.split("=")[1]||(Xe.includes("--server")?Xe[Xe.indexOf("--server")+1]:void 0),Xc=Xe.find(r=>r.startsWith("--log-level="))?.split("=")[1]||(Xe.includes("--log-level")?Xe[Xe.indexOf("--log-level")+1]:void 0),SE=["silent","error","warn","info","debug"],TE=Xc&&SE.includes(Xc)?Xc:vE?"info":"silent",CE=Xe.find(r=>r.startsWith("--cid="))?.split("=")[1]||(Xe.includes("--cid")?Xe[Xe.indexOf("--cid")+1]:void 0),OE=CE||(0,Ft.generateCorrelationId)(),kE=process.env.TERMIQ_TOKEN,qr=new xs(TE,bE),hn=new Zn,dn=new Qn(Ld?{serverUrl:Ld}:void 0),pn=new Ts,po=new Cs,Is=new Ps;async function PE(){switch(Id){case"start":case void 0:{await Pd({storage:hn,config:dn,logger:qr,machineId:pn,notification:po,browser:Is,cwd:process.cwd(),watch:wE});break}case"login":{let r=new URL(dn.getServerUrl()).host,e=await pn.getMachineId(),t=new Ft.CryptoService(hn,qr,r,e);await t.initialize();let n=new Ft.AuthService(hn,t,pn,dn,qr,po,Is,r,e),s=await ho(n,Is,qr,xE||kE);process.exit(s?0:1);break}case"logout":{let r=new URL(dn.getServerUrl()).host,e=await pn.getMachineId(),t=new Ft.CryptoService(hn,qr,r,e);await t.initialize();let n=new Ft.AuthService(hn,t,pn,dn,qr,po,Is,r,e);await Rd(n),process.exit(0);break}case"status":{let r=new URL(dn.getServerUrl()).host,e=await pn.getMachineId(),t=new Ft.CryptoService(hn,qr,r,e);await t.initialize();let n=new Ft.AuthService(hn,t,pn,dn,qr,po,Is,r,e);await Ad(n),process.exit(0);break}case"--version":case"-V":case"version":{process.stdout.write(`${Bc()}
|
|
60
|
+
`),process.exit(0);break}case"--help":case"-h":case"help":{process.stderr.write(`
|
|
61
|
+
termiq v${Bc()} \u2014 Access terminals from anywhere
|
|
61
62
|
|
|
62
63
|
Usage:
|
|
63
64
|
termiq Start a shell with cloud access (default)
|
|
@@ -65,20 +66,24 @@ tell application "System Events" to get value of property list item "CFBundleNam
|
|
|
65
66
|
termiq login --token KEY Login with API key
|
|
66
67
|
termiq logout Clear stored credentials
|
|
67
68
|
termiq status Show current auth state
|
|
69
|
+
termiq --version Print version and exit
|
|
68
70
|
|
|
69
71
|
Options:
|
|
70
72
|
--server URL Override server URL (default: https://termiq.io)
|
|
71
73
|
--token KEY API key for headless login
|
|
72
74
|
--watch, -w Enable file watcher (off by default)
|
|
73
75
|
--verbose, -v Verbose logging to stderr
|
|
76
|
+
--log-level L silent | error | warn | info | debug (default: silent)
|
|
77
|
+
--log-to-file Mirror logs to ~/.termiq/logs/cli.log
|
|
78
|
+
--cid ID Override session correlation ID (for support tracing)
|
|
74
79
|
--help, -h Show this help
|
|
75
80
|
|
|
76
81
|
Environment:
|
|
77
82
|
TERMIQ_TOKEN API key (equivalent to --token)
|
|
78
83
|
|
|
79
|
-
`),process.exit(0);break}default:process.stderr.write(`Unknown command: ${
|
|
84
|
+
`),process.exit(0);break}default:process.stderr.write(`Unknown command: ${Id}
|
|
80
85
|
Run 'termiq --help' for usage.
|
|
81
|
-
`),process.exit(1)}}(0,
|
|
86
|
+
`),process.exit(1)}}(0,Ft.runWithCorrelation)(OE,()=>PE().catch(r=>{process.stderr.write(`Fatal error: ${r instanceof Error?r.message:String(r)}
|
|
82
87
|
`),process.exit(1)}));
|
|
83
88
|
/*! Bundled license information:
|
|
84
89
|
|