@termiq/cli 1.16.1 → 1.17.1

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.
Files changed (2) hide show
  1. package/dist/bin.js +27 -27
  2. package/package.json +1 -1
package/dist/bin.js CHANGED
@@ -1,36 +1,36 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Yd=Object.create;var ko=Object.defineProperty;var Xd=Object.getOwnPropertyDescriptor;var Jd=Object.getOwnPropertyNames;var Zd=Object.getPrototypeOf,Qd=Object.prototype.hasOwnProperty;var Ft=(r,e)=>()=>(r&&(e=r(r=0)),e);var F=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ep=(r,e)=>{for(var t in e)ko(r,t,{get:e[t],enumerable:!0})},tp=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Jd(e))!Qd.call(r,s)&&s!==t&&ko(r,s,{get:()=>e[s],enumerable:!(i=Xd(e,s))||i.enumerable});return r};var ae=(r,e,t)=>(t=r!=null?Yd(Zd(r)):{},tp(e||!r||!r.__esModule?ko(t,"default",{value:r,enumerable:!0}):t,r));var Ws=F(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});es.generateCorrelationId=sp;es.runWithCorrelation=np;es.getCurrentCorrelationId=op;var ip=require("async_hooks");function sp(){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 hf=new ip.AsyncLocalStorage;function np(r,e){return hf.run(r,e)}function op(){return hf.getStore()}});var pf=F(_i=>{"use strict";Object.defineProperty(_i,"__esModule",{value:!0});_i.LOG_LEVELS=void 0;_i.shouldLog=cp;_i.formatLogLine=fp;var ap=Ws();_i.LOG_LEVELS=["silent","error","warn","info","debug"];var df={silent:0,error:1,warn:2,info:3,debug:4};function cp(r,e){return df[r]<=df[e]}function fp(r,e,t,i){let s={ts:new Date().toISOString(),level:r,src:e,msg:t},n=(0,ap.getCurrentCorrelationId)();n&&(s.cid=n);let a=i;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 gf=F(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.formatLogLine=Cr.shouldLog=Cr.LOG_LEVELS=void 0;var Ro=pf();Object.defineProperty(Cr,"LOG_LEVELS",{enumerable:!0,get:function(){return Ro.LOG_LEVELS}});Object.defineProperty(Cr,"shouldLog",{enumerable:!0,get:function(){return Ro.shouldLog}});Object.defineProperty(Cr,"formatLogLine",{enumerable:!0,get:function(){return Ro.formatLogLine}})});var mf=F(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});Hs.CircularBuffer=void 0;var Po=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=Po});var Ks=F(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.getApiUrl=up;Vs.getWsUrl=lp;function up(r){return`${r.getServerUrl()}/api`}function lp(r){let e=r.getServerUrl();return e.startsWith("https://")?e.replace(/^https:\/\//,"wss://"):e.replace(/^http:\/\//,"ws://")}});var yf=F(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.getCurrentCorrelationId=gt.runWithCorrelation=gt.generateCorrelationId=gt.getWsUrl=gt.getApiUrl=gt.CircularBuffer=void 0;var hp=mf();Object.defineProperty(gt,"CircularBuffer",{enumerable:!0,get:function(){return hp.CircularBuffer}});var _f=Ks();Object.defineProperty(gt,"getApiUrl",{enumerable:!0,get:function(){return _f.getApiUrl}});Object.defineProperty(gt,"getWsUrl",{enumerable:!0,get:function(){return _f.getWsUrl}});var Ao=Ws();Object.defineProperty(gt,"generateCorrelationId",{enumerable:!0,get:function(){return Ao.generateCorrelationId}});Object.defineProperty(gt,"runWithCorrelation",{enumerable:!0,get:function(){return Ao.runWithCorrelation}});Object.defineProperty(gt,"getCurrentCorrelationId",{enumerable:!0,get:function(){return Ao.getCurrentCorrelationId}})});var Ef=F(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0})});var bf=F(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0})});var xf=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 Tf=F(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0})});var Cf=F(Kt=>{"use strict";var dp=Kt&&Kt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=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,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),$s=Kt&&Kt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&dp(e,r,t)};Object.defineProperty(Kt,"__esModule",{value:!0});$s(Ef(),Kt);$s(bf(),Kt);$s(xf(),Kt);$s(Tf(),Kt)});var Of=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 kf=F(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.isMultiRecipientPayload=pp;Gs.isEncryptedPayload=gp;function pp(r){return typeof r=="object"&&r!==null&&"v"in r&&r.v===2&&"recipients"in r&&Array.isArray(r.recipients)}function gp(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 Io=F((mE,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")},i=new Uint8Array(16),s=new Uint8Array(32);s[0]=9;var n=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 b(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 T(f,h,l,o,p){var v,E=0;for(v=0;v<p;v++)E|=f[h+v]^l[o+v];return(1&E-1>>>8)-1}function C(f,h,l,o){return T(f,h,l,o,16)}function H(f,h,l,o){return T(f,h,l,o,32)}function ge(f,h,l,o){for(var p=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,v=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,E=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,R=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,B=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,G=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,Te=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,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,ie=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,ne=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,X=v,W=E,z=R,$=B,U=G,x=q,S=Te,N=V,k=te,P=re,M=ue,Z=ce,le=ie,de=ne,he=se,_,me=0;me<20;me+=2)_=K+Z|0,$^=_<<7|_>>>25,_=$+K|0,N^=_<<9|_>>>23,_=N+$|0,Z^=_<<13|_>>>19,_=Z+N|0,K^=_<<18|_>>>14,_=U+X|0,k^=_<<7|_>>>25,_=k+U|0,le^=_<<9|_>>>23,_=le+k|0,X^=_<<13|_>>>19,_=X+le|0,U^=_<<18|_>>>14,_=P+x|0,de^=_<<7|_>>>25,_=de+P|0,W^=_<<9|_>>>23,_=W+de|0,x^=_<<13|_>>>19,_=x+W|0,P^=_<<18|_>>>14,_=he+M|0,z^=_<<7|_>>>25,_=z+he|0,S^=_<<9|_>>>23,_=S+z|0,M^=_<<13|_>>>19,_=M+S|0,he^=_<<18|_>>>14,_=K+z|0,X^=_<<7|_>>>25,_=X+K|0,W^=_<<9|_>>>23,_=W+X|0,z^=_<<13|_>>>19,_=z+W|0,K^=_<<18|_>>>14,_=U+$|0,x^=_<<7|_>>>25,_=x+U|0,S^=_<<9|_>>>23,_=S+x|0,$^=_<<13|_>>>19,_=$+S|0,U^=_<<18|_>>>14,_=P+k|0,M^=_<<7|_>>>25,_=M+P|0,N^=_<<9|_>>>23,_=N+M|0,k^=_<<13|_>>>19,_=k+N|0,P^=_<<18|_>>>14,_=he+de|0,Z^=_<<7|_>>>25,_=Z+he|0,le^=_<<9|_>>>23,_=le+Z|0,de^=_<<13|_>>>19,_=de+le|0,he^=_<<18|_>>>14;K=K+p|0,X=X+v|0,W=W+E|0,z=z+R|0,$=$+B|0,U=U+G|0,x=x+q|0,S=S+Te|0,N=N+V|0,k=k+te|0,P=P+re|0,M=M+ue|0,Z=Z+ce|0,le=le+ie|0,de=de+ne|0,he=he+se|0,f[0]=K>>>0&255,f[1]=K>>>8&255,f[2]=K>>>16&255,f[3]=K>>>24&255,f[4]=X>>>0&255,f[5]=X>>>8&255,f[6]=X>>>16&255,f[7]=X>>>24&255,f[8]=W>>>0&255,f[9]=W>>>8&255,f[10]=W>>>16&255,f[11]=W>>>24&255,f[12]=z>>>0&255,f[13]=z>>>8&255,f[14]=z>>>16&255,f[15]=z>>>24&255,f[16]=$>>>0&255,f[17]=$>>>8&255,f[18]=$>>>16&255,f[19]=$>>>24&255,f[20]=U>>>0&255,f[21]=U>>>8&255,f[22]=U>>>16&255,f[23]=U>>>24&255,f[24]=x>>>0&255,f[25]=x>>>8&255,f[26]=x>>>16&255,f[27]=x>>>24&255,f[28]=S>>>0&255,f[29]=S>>>8&255,f[30]=S>>>16&255,f[31]=S>>>24&255,f[32]=N>>>0&255,f[33]=N>>>8&255,f[34]=N>>>16&255,f[35]=N>>>24&255,f[36]=k>>>0&255,f[37]=k>>>8&255,f[38]=k>>>16&255,f[39]=k>>>24&255,f[40]=P>>>0&255,f[41]=P>>>8&255,f[42]=P>>>16&255,f[43]=P>>>24&255,f[44]=M>>>0&255,f[45]=M>>>8&255,f[46]=M>>>16&255,f[47]=M>>>24&255,f[48]=Z>>>0&255,f[49]=Z>>>8&255,f[50]=Z>>>16&255,f[51]=Z>>>24&255,f[52]=le>>>0&255,f[53]=le>>>8&255,f[54]=le>>>16&255,f[55]=le>>>24&255,f[56]=de>>>0&255,f[57]=de>>>8&255,f[58]=de>>>16&255,f[59]=de>>>24&255,f[60]=he>>>0&255,f[61]=he>>>8&255,f[62]=he>>>16&255,f[63]=he>>>24&255}function Y(f,h,l,o){for(var p=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,v=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,E=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,R=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,B=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,G=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,Te=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,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,ie=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,ne=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,X=v,W=E,z=R,$=B,U=G,x=q,S=Te,N=V,k=te,P=re,M=ue,Z=ce,le=ie,de=ne,he=se,_,me=0;me<20;me+=2)_=K+Z|0,$^=_<<7|_>>>25,_=$+K|0,N^=_<<9|_>>>23,_=N+$|0,Z^=_<<13|_>>>19,_=Z+N|0,K^=_<<18|_>>>14,_=U+X|0,k^=_<<7|_>>>25,_=k+U|0,le^=_<<9|_>>>23,_=le+k|0,X^=_<<13|_>>>19,_=X+le|0,U^=_<<18|_>>>14,_=P+x|0,de^=_<<7|_>>>25,_=de+P|0,W^=_<<9|_>>>23,_=W+de|0,x^=_<<13|_>>>19,_=x+W|0,P^=_<<18|_>>>14,_=he+M|0,z^=_<<7|_>>>25,_=z+he|0,S^=_<<9|_>>>23,_=S+z|0,M^=_<<13|_>>>19,_=M+S|0,he^=_<<18|_>>>14,_=K+z|0,X^=_<<7|_>>>25,_=X+K|0,W^=_<<9|_>>>23,_=W+X|0,z^=_<<13|_>>>19,_=z+W|0,K^=_<<18|_>>>14,_=U+$|0,x^=_<<7|_>>>25,_=x+U|0,S^=_<<9|_>>>23,_=S+x|0,$^=_<<13|_>>>19,_=$+S|0,U^=_<<18|_>>>14,_=P+k|0,M^=_<<7|_>>>25,_=M+P|0,N^=_<<9|_>>>23,_=N+M|0,k^=_<<13|_>>>19,_=k+N|0,P^=_<<18|_>>>14,_=he+de|0,Z^=_<<7|_>>>25,_=Z+he|0,le^=_<<9|_>>>23,_=le+Z|0,de^=_<<13|_>>>19,_=de+le|0,he^=_<<18|_>>>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]=he>>>0&255,f[13]=he>>>8&255,f[14]=he>>>16&255,f[15]=he>>>24&255,f[16]=x>>>0&255,f[17]=x>>>8&255,f[18]=x>>>16&255,f[19]=x>>>24&255,f[20]=S>>>0&255,f[21]=S>>>8&255,f[22]=S>>>16&255,f[23]=S>>>24&255,f[24]=N>>>0&255,f[25]=N>>>8&255,f[26]=N>>>16&255,f[27]=N>>>24&255,f[28]=k>>>0&255,f[29]=k>>>8&255,f[30]=k>>>16&255,f[31]=k>>>24&255}function A(f,h,l,o){ge(f,h,l,o)}function j(f,h,l,o){Y(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 I(f,h,l,o,p,v,E){var R=new Uint8Array(16),B=new Uint8Array(64),G,q;for(q=0;q<16;q++)R[q]=0;for(q=0;q<8;q++)R[q]=v[q];for(;p>=64;){for(A(B,R,E,Q),q=0;q<64;q++)f[h+q]=l[o+q]^B[q];for(G=1,q=8;q<16;q++)G=G+(R[q]&255)|0,R[q]=G&255,G>>>=8;p-=64,h+=64,o+=64}if(p>0)for(A(B,R,E,Q),q=0;q<p;q++)f[h+q]=l[o+q]^B[q];return 0}function oe(f,h,l,o,p){var v=new Uint8Array(16),E=new Uint8Array(64),R,B;for(B=0;B<16;B++)v[B]=0;for(B=0;B<8;B++)v[B]=o[B];for(;l>=64;){for(A(E,v,p,Q),B=0;B<64;B++)f[h+B]=E[B];for(R=1,B=8;B<16;B++)R=R+(v[B]&255)|0,v[B]=R&255,R>>>=8;l-=64,h+=64}if(l>0)for(A(E,v,p,Q),B=0;B<l;B++)f[h+B]=E[B];return 0}function fe(f,h,l,o,p){var v=new Uint8Array(32);j(v,o,p,Q);for(var E=new Uint8Array(8),R=0;R<8;R++)E[R]=o[R+16];return oe(f,h,l,E,v)}function ee(f,h,l,o,p,v,E){var R=new Uint8Array(32);j(R,v,E,Q);for(var B=new Uint8Array(8),G=0;G<8;G++)B[G]=v[G+16];return I(f,h,l,o,p,B,R)}var ke=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,v,E,R,B;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,v=f[8]&255|(f[9]&255)<<8,this.r[4]=(p>>>4|v<<12)&255,this.r[5]=v>>>1&8190,E=f[10]&255|(f[11]&255)<<8,this.r[6]=(v>>>14|E<<2)&8191,R=f[12]&255|(f[13]&255)<<8,this.r[7]=(E>>>11|R<<5)&8065,B=f[14]&255|(f[15]&255)<<8,this.r[8]=(R>>>8|B<<8)&8191,this.r[9]=B>>>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};ke.prototype.blocks=function(f,h,l){for(var o=this.fin?0:2048,p,v,E,R,B,G,q,Te,V,te,re,ue,ce,ie,ne,se,K,X,W,z=this.h[0],$=this.h[1],U=this.h[2],x=this.h[3],S=this.h[4],N=this.h[5],k=this.h[6],P=this.h[7],M=this.h[8],Z=this.h[9],le=this.r[0],de=this.r[1],he=this.r[2],_=this.r[3],me=this.r[4],Ce=this.r[5],Oe=this.r[6],pe=this.r[7],ve=this.r[8],Ee=this.r[9];l>=16;)p=f[h+0]&255|(f[h+1]&255)<<8,z+=p&8191,v=f[h+2]&255|(f[h+3]&255)<<8,$+=(p>>>13|v<<3)&8191,E=f[h+4]&255|(f[h+5]&255)<<8,U+=(v>>>10|E<<6)&8191,R=f[h+6]&255|(f[h+7]&255)<<8,x+=(E>>>7|R<<9)&8191,B=f[h+8]&255|(f[h+9]&255)<<8,S+=(R>>>4|B<<12)&8191,N+=B>>>1&8191,G=f[h+10]&255|(f[h+11]&255)<<8,k+=(B>>>14|G<<2)&8191,q=f[h+12]&255|(f[h+13]&255)<<8,P+=(G>>>11|q<<5)&8191,Te=f[h+14]&255|(f[h+15]&255)<<8,M+=(q>>>8|Te<<8)&8191,Z+=Te>>>5|o,V=0,te=V,te+=z*le,te+=$*(5*Ee),te+=U*(5*ve),te+=x*(5*pe),te+=S*(5*Oe),V=te>>>13,te&=8191,te+=N*(5*Ce),te+=k*(5*me),te+=P*(5*_),te+=M*(5*he),te+=Z*(5*de),V+=te>>>13,te&=8191,re=V,re+=z*de,re+=$*le,re+=U*(5*Ee),re+=x*(5*ve),re+=S*(5*pe),V=re>>>13,re&=8191,re+=N*(5*Oe),re+=k*(5*Ce),re+=P*(5*me),re+=M*(5*_),re+=Z*(5*he),V+=re>>>13,re&=8191,ue=V,ue+=z*he,ue+=$*de,ue+=U*le,ue+=x*(5*Ee),ue+=S*(5*ve),V=ue>>>13,ue&=8191,ue+=N*(5*pe),ue+=k*(5*Oe),ue+=P*(5*Ce),ue+=M*(5*me),ue+=Z*(5*_),V+=ue>>>13,ue&=8191,ce=V,ce+=z*_,ce+=$*he,ce+=U*de,ce+=x*le,ce+=S*(5*Ee),V=ce>>>13,ce&=8191,ce+=N*(5*ve),ce+=k*(5*pe),ce+=P*(5*Oe),ce+=M*(5*Ce),ce+=Z*(5*me),V+=ce>>>13,ce&=8191,ie=V,ie+=z*me,ie+=$*_,ie+=U*he,ie+=x*de,ie+=S*le,V=ie>>>13,ie&=8191,ie+=N*(5*Ee),ie+=k*(5*ve),ie+=P*(5*pe),ie+=M*(5*Oe),ie+=Z*(5*Ce),V+=ie>>>13,ie&=8191,ne=V,ne+=z*Ce,ne+=$*me,ne+=U*_,ne+=x*he,ne+=S*de,V=ne>>>13,ne&=8191,ne+=N*le,ne+=k*(5*Ee),ne+=P*(5*ve),ne+=M*(5*pe),ne+=Z*(5*Oe),V+=ne>>>13,ne&=8191,se=V,se+=z*Oe,se+=$*Ce,se+=U*me,se+=x*_,se+=S*he,V=se>>>13,se&=8191,se+=N*de,se+=k*le,se+=P*(5*Ee),se+=M*(5*ve),se+=Z*(5*pe),V+=se>>>13,se&=8191,K=V,K+=z*pe,K+=$*Oe,K+=U*Ce,K+=x*me,K+=S*_,V=K>>>13,K&=8191,K+=N*he,K+=k*de,K+=P*le,K+=M*(5*Ee),K+=Z*(5*ve),V+=K>>>13,K&=8191,X=V,X+=z*ve,X+=$*pe,X+=U*Oe,X+=x*Ce,X+=S*me,V=X>>>13,X&=8191,X+=N*_,X+=k*he,X+=P*de,X+=M*le,X+=Z*(5*Ee),V+=X>>>13,X&=8191,W=V,W+=z*Ee,W+=$*ve,W+=U*pe,W+=x*Oe,W+=S*Ce,V=W>>>13,W&=8191,W+=N*me,W+=k*_,W+=P*he,W+=M*de,W+=Z*le,V+=W>>>13,W&=8191,V=(V<<2)+V|0,V=V+te|0,te=V&8191,V=V>>>13,re+=V,z=te,$=re,U=ue,x=ce,S=ie,N=ne,k=se,P=K,M=X,Z=W,h+=16,l-=16;this.h[0]=z,this.h[1]=$,this.h[2]=U,this.h[3]=x,this.h[4]=S,this.h[5]=N,this.h[6]=k,this.h[7]=P,this.h[8]=M,this.h[9]=Z},ke.prototype.finish=function(f,h){var l=new Uint16Array(10),o,p,v,E;if(this.leftover){for(E=this.leftover,this.buffer[E++]=1;E<16;E++)this.buffer[E]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(o=this.h[1]>>>13,this.h[1]&=8191,E=2;E<10;E++)this.h[E]+=o,o=this.h[E]>>>13,this.h[E]&=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,E=1;E<10;E++)l[E]=this.h[E]+o,o=l[E]>>>13,l[E]&=8191;for(l[9]-=8192,p=(o^1)-1,E=0;E<10;E++)l[E]&=p;for(p=~p,E=0;E<10;E++)this.h[E]=this.h[E]&p|l[E];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,v=this.h[0]+this.pad[0],this.h[0]=v&65535,E=1;E<8;E++)v=(this.h[E]+this.pad[E]|0)+(v>>>16)|0,this.h[E]=v&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},ke.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 be(f,h,l,o,p,v){var E=new ke(v);return E.update(l,o,p),E.finish(f,h),0}function xe(f,h,l,o,p,v){var E=new Uint8Array(16);return be(E,0,l,o,p,v),C(f,h,E,0)}function Se(f,h,l,o,p){var v;if(l<32)return-1;for(ee(f,0,h,0,l,o,p),be(f,16,f,32,l-32,f),v=0;v<16;v++)f[v]=0;return 0}function Ge(f,h,l,o,p){var v,E=new Uint8Array(32);if(l<32||(fe(E,0,32,o,p),xe(h,16,h,32,l-32,E)!==0))return-1;for(ee(f,0,h,0,l,o,p),v=0;v<32;v++)f[v]=0;return 0}function Ie(f,h){var l;for(l=0;l<16;l++)f[l]=h[l]|0}function Ye(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 Ue(f,h,l){for(var o,p=~(l-1),v=0;v<16;v++)o=p&(f[v]^h[v]),f[v]^=o,h[v]^=o}function Pe(f,h){var l,o,p,v=e(),E=e();for(l=0;l<16;l++)E[l]=h[l];for(Ye(E),Ye(E),Ye(E),o=0;o<2;o++){for(v[0]=E[0]-65517,l=1;l<15;l++)v[l]=E[l]-65535-(v[l-1]>>16&1),v[l-1]&=65535;v[15]=E[15]-32767-(v[14]>>16&1),p=v[15]>>16&1,v[14]&=65535,Ue(E,v,1-p)}for(l=0;l<16;l++)f[2*l]=E[l]&255,f[2*l+1]=E[l]>>8}function et(f,h){var l=new Uint8Array(32),o=new Uint8Array(32);return Pe(l,f),Pe(o,h),H(l,0,o,0)}function Xe(f){var h=new Uint8Array(32);return Pe(h,f),h[0]&1}function ut(f,h){var l;for(l=0;l<16;l++)f[l]=h[2*l]+(h[2*l+1]<<8);f[15]&=32767}function w(f,h,l){for(var o=0;o<16;o++)f[o]=h[o]+l[o]}function L(f,h,l){for(var o=0;o<16;o++)f[o]=h[o]-l[o]}function O(f,h,l){var o,p,v=0,E=0,R=0,B=0,G=0,q=0,Te=0,V=0,te=0,re=0,ue=0,ce=0,ie=0,ne=0,se=0,K=0,X=0,W=0,z=0,$=0,U=0,x=0,S=0,N=0,k=0,P=0,M=0,Z=0,le=0,de=0,he=0,_=l[0],me=l[1],Ce=l[2],Oe=l[3],pe=l[4],ve=l[5],Ee=l[6],Je=l[7],Le=l[8],Ke=l[9],ze=l[10],$e=l[11],Qe=l[12],ot=l[13],at=l[14],ct=l[15];o=h[0],v+=o*_,E+=o*me,R+=o*Ce,B+=o*Oe,G+=o*pe,q+=o*ve,Te+=o*Ee,V+=o*Je,te+=o*Le,re+=o*Ke,ue+=o*ze,ce+=o*$e,ie+=o*Qe,ne+=o*ot,se+=o*at,K+=o*ct,o=h[1],E+=o*_,R+=o*me,B+=o*Ce,G+=o*Oe,q+=o*pe,Te+=o*ve,V+=o*Ee,te+=o*Je,re+=o*Le,ue+=o*Ke,ce+=o*ze,ie+=o*$e,ne+=o*Qe,se+=o*ot,K+=o*at,X+=o*ct,o=h[2],R+=o*_,B+=o*me,G+=o*Ce,q+=o*Oe,Te+=o*pe,V+=o*ve,te+=o*Ee,re+=o*Je,ue+=o*Le,ce+=o*Ke,ie+=o*ze,ne+=o*$e,se+=o*Qe,K+=o*ot,X+=o*at,W+=o*ct,o=h[3],B+=o*_,G+=o*me,q+=o*Ce,Te+=o*Oe,V+=o*pe,te+=o*ve,re+=o*Ee,ue+=o*Je,ce+=o*Le,ie+=o*Ke,ne+=o*ze,se+=o*$e,K+=o*Qe,X+=o*ot,W+=o*at,z+=o*ct,o=h[4],G+=o*_,q+=o*me,Te+=o*Ce,V+=o*Oe,te+=o*pe,re+=o*ve,ue+=o*Ee,ce+=o*Je,ie+=o*Le,ne+=o*Ke,se+=o*ze,K+=o*$e,X+=o*Qe,W+=o*ot,z+=o*at,$+=o*ct,o=h[5],q+=o*_,Te+=o*me,V+=o*Ce,te+=o*Oe,re+=o*pe,ue+=o*ve,ce+=o*Ee,ie+=o*Je,ne+=o*Le,se+=o*Ke,K+=o*ze,X+=o*$e,W+=o*Qe,z+=o*ot,$+=o*at,U+=o*ct,o=h[6],Te+=o*_,V+=o*me,te+=o*Ce,re+=o*Oe,ue+=o*pe,ce+=o*ve,ie+=o*Ee,ne+=o*Je,se+=o*Le,K+=o*Ke,X+=o*ze,W+=o*$e,z+=o*Qe,$+=o*ot,U+=o*at,x+=o*ct,o=h[7],V+=o*_,te+=o*me,re+=o*Ce,ue+=o*Oe,ce+=o*pe,ie+=o*ve,ne+=o*Ee,se+=o*Je,K+=o*Le,X+=o*Ke,W+=o*ze,z+=o*$e,$+=o*Qe,U+=o*ot,x+=o*at,S+=o*ct,o=h[8],te+=o*_,re+=o*me,ue+=o*Ce,ce+=o*Oe,ie+=o*pe,ne+=o*ve,se+=o*Ee,K+=o*Je,X+=o*Le,W+=o*Ke,z+=o*ze,$+=o*$e,U+=o*Qe,x+=o*ot,S+=o*at,N+=o*ct,o=h[9],re+=o*_,ue+=o*me,ce+=o*Ce,ie+=o*Oe,ne+=o*pe,se+=o*ve,K+=o*Ee,X+=o*Je,W+=o*Le,z+=o*Ke,$+=o*ze,U+=o*$e,x+=o*Qe,S+=o*ot,N+=o*at,k+=o*ct,o=h[10],ue+=o*_,ce+=o*me,ie+=o*Ce,ne+=o*Oe,se+=o*pe,K+=o*ve,X+=o*Ee,W+=o*Je,z+=o*Le,$+=o*Ke,U+=o*ze,x+=o*$e,S+=o*Qe,N+=o*ot,k+=o*at,P+=o*ct,o=h[11],ce+=o*_,ie+=o*me,ne+=o*Ce,se+=o*Oe,K+=o*pe,X+=o*ve,W+=o*Ee,z+=o*Je,$+=o*Le,U+=o*Ke,x+=o*ze,S+=o*$e,N+=o*Qe,k+=o*ot,P+=o*at,M+=o*ct,o=h[12],ie+=o*_,ne+=o*me,se+=o*Ce,K+=o*Oe,X+=o*pe,W+=o*ve,z+=o*Ee,$+=o*Je,U+=o*Le,x+=o*Ke,S+=o*ze,N+=o*$e,k+=o*Qe,P+=o*ot,M+=o*at,Z+=o*ct,o=h[13],ne+=o*_,se+=o*me,K+=o*Ce,X+=o*Oe,W+=o*pe,z+=o*ve,$+=o*Ee,U+=o*Je,x+=o*Le,S+=o*Ke,N+=o*ze,k+=o*$e,P+=o*Qe,M+=o*ot,Z+=o*at,le+=o*ct,o=h[14],se+=o*_,K+=o*me,X+=o*Ce,W+=o*Oe,z+=o*pe,$+=o*ve,U+=o*Ee,x+=o*Je,S+=o*Le,N+=o*Ke,k+=o*ze,P+=o*$e,M+=o*Qe,Z+=o*ot,le+=o*at,de+=o*ct,o=h[15],K+=o*_,X+=o*me,W+=o*Ce,z+=o*Oe,$+=o*pe,U+=o*ve,x+=o*Ee,S+=o*Je,N+=o*Le,k+=o*Ke,P+=o*ze,M+=o*$e,Z+=o*Qe,le+=o*ot,de+=o*at,he+=o*ct,v+=38*X,E+=38*W,R+=38*z,B+=38*$,G+=38*U,q+=38*x,Te+=38*S,V+=38*N,te+=38*k,re+=38*P,ue+=38*M,ce+=38*Z,ie+=38*le,ne+=38*de,se+=38*he,p=1,o=v+p+65535,p=Math.floor(o/65536),v=o-p*65536,o=E+p+65535,p=Math.floor(o/65536),E=o-p*65536,o=R+p+65535,p=Math.floor(o/65536),R=o-p*65536,o=B+p+65535,p=Math.floor(o/65536),B=o-p*65536,o=G+p+65535,p=Math.floor(o/65536),G=o-p*65536,o=q+p+65535,p=Math.floor(o/65536),q=o-p*65536,o=Te+p+65535,p=Math.floor(o/65536),Te=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=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=ie+p+65535,p=Math.floor(o/65536),ie=o-p*65536,o=ne+p+65535,p=Math.floor(o/65536),ne=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,v+=p-1+37*(p-1),p=1,o=v+p+65535,p=Math.floor(o/65536),v=o-p*65536,o=E+p+65535,p=Math.floor(o/65536),E=o-p*65536,o=R+p+65535,p=Math.floor(o/65536),R=o-p*65536,o=B+p+65535,p=Math.floor(o/65536),B=o-p*65536,o=G+p+65535,p=Math.floor(o/65536),G=o-p*65536,o=q+p+65535,p=Math.floor(o/65536),q=o-p*65536,o=Te+p+65535,p=Math.floor(o/65536),Te=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=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=ie+p+65535,p=Math.floor(o/65536),ie=o-p*65536,o=ne+p+65535,p=Math.floor(o/65536),ne=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,v+=p-1+37*(p-1),f[0]=v,f[1]=E,f[2]=R,f[3]=B,f[4]=G,f[5]=q,f[6]=Te,f[7]=V,f[8]=te,f[9]=re,f[10]=ue,f[11]=ce,f[12]=ie,f[13]=ne,f[14]=se,f[15]=K}function J(f,h){O(f,h,h)}function Ae(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=253;o>=0;o--)J(l,l),o!==2&&o!==4&&O(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function lt(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=250;o>=0;o--)J(l,l),o!==1&&O(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function vt(f,h,l){var o=new Uint8Array(32),p=new Float64Array(80),v,E,R=e(),B=e(),G=e(),q=e(),Te=e(),V=e();for(E=0;E<31;E++)o[E]=h[E];for(o[31]=h[31]&127|64,o[0]&=248,ut(p,l),E=0;E<16;E++)B[E]=p[E],q[E]=R[E]=G[E]=0;for(R[0]=q[0]=1,E=254;E>=0;--E)v=o[E>>>3]>>>(E&7)&1,Ue(R,B,v),Ue(G,q,v),w(Te,R,G),L(R,R,G),w(G,B,q),L(B,B,q),J(q,Te),J(V,R),O(R,G,R),O(G,B,Te),w(Te,R,G),L(R,R,G),J(B,R),L(G,q,V),O(R,G,c),w(R,R,q),O(G,G,R),O(R,q,V),O(q,B,p),J(B,Te),Ue(R,B,v),Ue(G,q,v);for(E=0;E<16;E++)p[E+16]=R[E],p[E+32]=G[E],p[E+48]=B[E],p[E+64]=q[E];var te=p.subarray(32),re=p.subarray(16);return Ae(te,te),O(re,re,te),Pe(f,re),0}function Et(f,h){return vt(f,h,s)}function wt(f,h){return t(h,32),Et(f,h)}function nr(f,h,l){var o=new Uint8Array(32);return vt(o,l,h),j(f,i,o,Q)}var Sr=Se,Vr=Ge;function Tr(f,h,l,o,p,v){var E=new Uint8Array(32);return nr(E,p,v),Sr(f,h,l,o,E)}function pi(f,h,l,o,p,v){var E=new Uint8Array(32);return nr(E,p,v),Vr(f,h,l,o,E)}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 sf(f,h,l,o){for(var p=new Int32Array(16),v=new Int32Array(16),E,R,B,G,q,Te,V,te,re,ue,ce,ie,ne,se,K,X,W,z,$,U,x,S,N,k,P,M,Z=f[0],le=f[1],de=f[2],he=f[3],_=f[4],me=f[5],Ce=f[6],Oe=f[7],pe=h[0],ve=h[1],Ee=h[2],Je=h[3],Le=h[4],Ke=h[5],ze=h[6],$e=h[7],Qe=0;o>=128;){for($=0;$<16;$++)U=8*$+Qe,p[$]=l[U+0]<<24|l[U+1]<<16|l[U+2]<<8|l[U+3],v[$]=l[U+4]<<24|l[U+5]<<16|l[U+6]<<8|l[U+7];for($=0;$<80;$++)if(E=Z,R=le,B=de,G=he,q=_,Te=me,V=Ce,te=Oe,re=pe,ue=ve,ce=Ee,ie=Je,ne=Le,se=Ke,K=ze,X=$e,x=Oe,S=$e,N=S&65535,k=S>>>16,P=x&65535,M=x>>>16,x=(_>>>14|Le<<18)^(_>>>18|Le<<14)^(Le>>>9|_<<23),S=(Le>>>14|_<<18)^(Le>>>18|_<<14)^(_>>>9|Le<<23),N+=S&65535,k+=S>>>16,P+=x&65535,M+=x>>>16,x=_&me^~_&Ce,S=Le&Ke^~Le&ze,N+=S&65535,k+=S>>>16,P+=x&65535,M+=x>>>16,x=Is[$*2],S=Is[$*2+1],N+=S&65535,k+=S>>>16,P+=x&65535,M+=x>>>16,x=p[$%16],S=v[$%16],N+=S&65535,k+=S>>>16,P+=x&65535,M+=x>>>16,k+=N>>>16,P+=k>>>16,M+=P>>>16,W=P&65535|M<<16,z=N&65535|k<<16,x=W,S=z,N=S&65535,k=S>>>16,P=x&65535,M=x>>>16,x=(Z>>>28|pe<<4)^(pe>>>2|Z<<30)^(pe>>>7|Z<<25),S=(pe>>>28|Z<<4)^(Z>>>2|pe<<30)^(Z>>>7|pe<<25),N+=S&65535,k+=S>>>16,P+=x&65535,M+=x>>>16,x=Z&le^Z&de^le&de,S=pe&ve^pe&Ee^ve&Ee,N+=S&65535,k+=S>>>16,P+=x&65535,M+=x>>>16,k+=N>>>16,P+=k>>>16,M+=P>>>16,te=P&65535|M<<16,X=N&65535|k<<16,x=G,S=ie,N=S&65535,k=S>>>16,P=x&65535,M=x>>>16,x=W,S=z,N+=S&65535,k+=S>>>16,P+=x&65535,M+=x>>>16,k+=N>>>16,P+=k>>>16,M+=P>>>16,G=P&65535|M<<16,ie=N&65535|k<<16,le=E,de=R,he=B,_=G,me=q,Ce=Te,Oe=V,Z=te,ve=re,Ee=ue,Je=ce,Le=ie,Ke=ne,ze=se,$e=K,pe=X,$%16===15)for(U=0;U<16;U++)x=p[U],S=v[U],N=S&65535,k=S>>>16,P=x&65535,M=x>>>16,x=p[(U+9)%16],S=v[(U+9)%16],N+=S&65535,k+=S>>>16,P+=x&65535,M+=x>>>16,W=p[(U+1)%16],z=v[(U+1)%16],x=(W>>>1|z<<31)^(W>>>8|z<<24)^W>>>7,S=(z>>>1|W<<31)^(z>>>8|W<<24)^(z>>>7|W<<25),N+=S&65535,k+=S>>>16,P+=x&65535,M+=x>>>16,W=p[(U+14)%16],z=v[(U+14)%16],x=(W>>>19|z<<13)^(z>>>29|W<<3)^W>>>6,S=(z>>>19|W<<13)^(W>>>29|z<<3)^(z>>>6|W<<26),N+=S&65535,k+=S>>>16,P+=x&65535,M+=x>>>16,k+=N>>>16,P+=k>>>16,M+=P>>>16,p[U]=P&65535|M<<16,v[U]=N&65535|k<<16;x=Z,S=pe,N=S&65535,k=S>>>16,P=x&65535,M=x>>>16,x=f[0],S=h[0],N+=S&65535,k+=S>>>16,P+=x&65535,M+=x>>>16,k+=N>>>16,P+=k>>>16,M+=P>>>16,f[0]=Z=P&65535|M<<16,h[0]=pe=N&65535|k<<16,x=le,S=ve,N=S&65535,k=S>>>16,P=x&65535,M=x>>>16,x=f[1],S=h[1],N+=S&65535,k+=S>>>16,P+=x&65535,M+=x>>>16,k+=N>>>16,P+=k>>>16,M+=P>>>16,f[1]=le=P&65535|M<<16,h[1]=ve=N&65535|k<<16,x=de,S=Ee,N=S&65535,k=S>>>16,P=x&65535,M=x>>>16,x=f[2],S=h[2],N+=S&65535,k+=S>>>16,P+=x&65535,M+=x>>>16,k+=N>>>16,P+=k>>>16,M+=P>>>16,f[2]=de=P&65535|M<<16,h[2]=Ee=N&65535|k<<16,x=he,S=Je,N=S&65535,k=S>>>16,P=x&65535,M=x>>>16,x=f[3],S=h[3],N+=S&65535,k+=S>>>16,P+=x&65535,M+=x>>>16,k+=N>>>16,P+=k>>>16,M+=P>>>16,f[3]=he=P&65535|M<<16,h[3]=Je=N&65535|k<<16,x=_,S=Le,N=S&65535,k=S>>>16,P=x&65535,M=x>>>16,x=f[4],S=h[4],N+=S&65535,k+=S>>>16,P+=x&65535,M+=x>>>16,k+=N>>>16,P+=k>>>16,M+=P>>>16,f[4]=_=P&65535|M<<16,h[4]=Le=N&65535|k<<16,x=me,S=Ke,N=S&65535,k=S>>>16,P=x&65535,M=x>>>16,x=f[5],S=h[5],N+=S&65535,k+=S>>>16,P+=x&65535,M+=x>>>16,k+=N>>>16,P+=k>>>16,M+=P>>>16,f[5]=me=P&65535|M<<16,h[5]=Ke=N&65535|k<<16,x=Ce,S=ze,N=S&65535,k=S>>>16,P=x&65535,M=x>>>16,x=f[6],S=h[6],N+=S&65535,k+=S>>>16,P+=x&65535,M+=x>>>16,k+=N>>>16,P+=k>>>16,M+=P>>>16,f[6]=Ce=P&65535|M<<16,h[6]=ze=N&65535|k<<16,x=Oe,S=$e,N=S&65535,k=S>>>16,P=x&65535,M=x>>>16,x=f[7],S=h[7],N+=S&65535,k+=S>>>16,P+=x&65535,M+=x>>>16,k+=N>>>16,P+=k>>>16,M+=P>>>16,f[7]=Oe=P&65535|M<<16,h[7]=$e=N&65535|k<<16,Qe+=128,o-=128}return o}function Kr(f,h,l){var o=new Int32Array(8),p=new Int32Array(8),v=new Uint8Array(256),E,R=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,sf(o,p,h,l),l%=128,E=0;E<l;E++)v[E]=h[R-l+E];for(v[l]=128,l=256-128*(l<112?1:0),v[l-9]=0,b(v,l-8,R/536870912|0,R<<3),sf(o,p,v,l),E=0;E<8;E++)b(f,8*E,o[E],p[E]);return 0}function Ls(f,h){var l=e(),o=e(),p=e(),v=e(),E=e(),R=e(),B=e(),G=e(),q=e();L(l,f[1],f[0]),L(q,h[1],h[0]),O(l,l,q),w(o,f[0],f[1]),w(q,h[0],h[1]),O(o,o,q),O(p,f[3],h[3]),O(p,p,d),O(v,f[2],h[2]),w(v,v,v),L(E,o,l),L(R,v,p),w(B,v,p),w(G,o,l),O(f[0],E,R),O(f[1],G,B),O(f[2],B,R),O(f[3],E,G)}function nf(f,h,l){var o;for(o=0;o<4;o++)Ue(f[o],h[o],l)}function yo(f,h){var l=e(),o=e(),p=e();Ae(p,h[2]),O(l,h[0],p),O(o,h[1],p),Pe(f,o),f[31]^=Xe(l)<<7}function vo(f,h,l){var o,p;for(Ie(f[0],n),Ie(f[1],a),Ie(f[2],a),Ie(f[3],n),p=255;p>=0;--p)o=l[p/8|0]>>(p&7)&1,nf(f,h,o),Ls(h,f),Ls(f,f),nf(f,h,o)}function Ns(f,h){var l=[e(),e(),e(),e()];Ie(l[0],g),Ie(l[1],m),Ie(l[2],a),O(l[3],g,m),vo(f,l,h)}function Eo(f,h,l){var o=new Uint8Array(64),p=[e(),e(),e(),e()],v;for(l||t(h,32),Kr(o,h,32),o[0]&=248,o[31]&=127,o[31]|=64,Ns(p,o),yo(f,p),v=0;v<32;v++)h[v+32]=f[v];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 wo(f,h){var l,o,p,v;for(o=63;o>=32;--o){for(l=0,p=o-32,v=o-12;p<v;++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 bo(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;wo(f,h)}function of(f,h,l,o){var p=new Uint8Array(64),v=new Uint8Array(64),E=new Uint8Array(64),R,B,G=new Float64Array(64),q=[e(),e(),e(),e()];Kr(p,o,32),p[0]&=248,p[31]&=127,p[31]|=64;var Te=l+64;for(R=0;R<l;R++)f[64+R]=h[R];for(R=0;R<32;R++)f[32+R]=p[32+R];for(Kr(E,f.subarray(32),l+32),bo(E),Ns(q,E),yo(f,q),R=32;R<64;R++)f[R]=o[R];for(Kr(v,f,l+64),bo(v),R=0;R<64;R++)G[R]=0;for(R=0;R<32;R++)G[R]=E[R];for(R=0;R<32;R++)for(B=0;B<32;B++)G[R+B]+=v[R]*p[B];return wo(f.subarray(32),G),Te}function Kd(f,h){var l=e(),o=e(),p=e(),v=e(),E=e(),R=e(),B=e();return Ie(f[2],a),ut(f[1],h),J(p,f[1]),O(v,p,u),L(p,p,f[2]),w(v,f[2],v),J(E,v),J(R,E),O(B,R,E),O(l,B,p),O(l,l,v),lt(l,l),O(l,l,p),O(l,l,v),O(l,l,v),O(f[0],l,v),J(o,f[0]),O(o,o,v),et(o,p)&&O(f[0],f[0],y),J(o,f[0]),O(o,o,v),et(o,p)?-1:(Xe(f[0])===h[31]>>7&&L(f[0],n,f[0]),O(f[3],f[0],f[1]),0)}function xo(f,h,l,o){var p,v=new Uint8Array(32),E=new Uint8Array(64),R=[e(),e(),e(),e()],B=[e(),e(),e(),e()];if(l<64||Kd(B,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(Kr(E,f,l),bo(E),vo(R,B,E),Ns(B,h.subarray(32)),Ls(R,B),yo(v,R),l-=64,H(h,0,v,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 So=32,Ms=24,Gi=32,gi=16,Yi=32,Fs=32,Xi=32,Ji=32,To=32,af=Ms,zd=Gi,$d=gi,or=64,zr=32,mi=64,Co=32,Oo=64;r.lowlevel={crypto_core_hsalsa20:j,crypto_stream_xor:ee,crypto_stream:fe,crypto_stream_salsa20_xor:I,crypto_stream_salsa20:oe,crypto_onetimeauth:be,crypto_onetimeauth_verify:xe,crypto_verify_16:C,crypto_verify_32:H,crypto_secretbox:Se,crypto_secretbox_open:Ge,crypto_scalarmult:vt,crypto_scalarmult_base:Et,crypto_box_beforenm:nr,crypto_box_afternm:Sr,crypto_box:Tr,crypto_box_open:pi,crypto_box_keypair:wt,crypto_hash:Kr,crypto_sign:of,crypto_sign_keypair:Eo,crypto_sign_open:xo,crypto_secretbox_KEYBYTES:So,crypto_secretbox_NONCEBYTES:Ms,crypto_secretbox_ZEROBYTES:Gi,crypto_secretbox_BOXZEROBYTES:gi,crypto_scalarmult_BYTES:Yi,crypto_scalarmult_SCALARBYTES:Fs,crypto_box_PUBLICKEYBYTES:Xi,crypto_box_SECRETKEYBYTES:Ji,crypto_box_BEFORENMBYTES:To,crypto_box_NONCEBYTES:af,crypto_box_ZEROBYTES:zd,crypto_box_BOXZEROBYTES:$d,crypto_sign_BYTES:or,crypto_sign_PUBLICKEYBYTES:zr,crypto_sign_SECRETKEYBYTES:mi,crypto_sign_SEEDBYTES:Co,crypto_hash_BYTES:Oo,gf:e,D:u,L:Ds,pack25519:Pe,unpack25519:ut,M:O,A:w,S:J,Z:L,pow2523:lt,add:Ls,set25519:Ie,modL:wo,scalarmult:vo,scalarbase:Ns};function cf(f,h){if(f.length!==So)throw new Error("bad key size");if(h.length!==Ms)throw new Error("bad nonce size")}function Gd(f,h){if(f.length!==Xi)throw new Error("bad public key size");if(h.length!==Ji)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 ff(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),cf(l,h);for(var o=new Uint8Array(Gi+f.length),p=new Uint8Array(o.length),v=0;v<f.length;v++)o[v+Gi]=f[v];return Se(p,o,o.length,h,l),p.subarray(gi)},r.secretbox.open=function(f,h,l){bt(f,h,l),cf(l,h);for(var o=new Uint8Array(gi+f.length),p=new Uint8Array(o.length),v=0;v<f.length;v++)o[v+gi]=f[v];return o.length<32||Ge(p,o,o.length,h,l)!==0?null:p.subarray(Gi)},r.secretbox.keyLength=So,r.secretbox.nonceLength=Ms,r.secretbox.overheadLength=gi,r.scalarMult=function(f,h){if(bt(f,h),f.length!==Fs)throw new Error("bad n size");if(h.length!==Yi)throw new Error("bad p size");var l=new Uint8Array(Yi);return vt(l,f,h),l},r.scalarMult.base=function(f){if(bt(f),f.length!==Fs)throw new Error("bad n size");var h=new Uint8Array(Yi);return Et(h,f),h},r.scalarMult.scalarLength=Fs,r.scalarMult.groupElementLength=Yi,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),Gd(f,h);var l=new Uint8Array(To);return nr(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(Xi),h=new Uint8Array(Ji);return wt(f,h),{publicKey:f,secretKey:h}},r.box.keyPair.fromSecretKey=function(f){if(bt(f),f.length!==Ji)throw new Error("bad secret key size");var h=new Uint8Array(Xi);return Et(h,f),{publicKey:h,secretKey:new Uint8Array(f)}},r.box.publicKeyLength=Xi,r.box.secretKeyLength=Ji,r.box.sharedKeyLength=To,r.box.nonceLength=af,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(f,h){if(bt(f,h),h.length!==mi)throw new Error("bad secret key size");var l=new Uint8Array(or+f.length);return of(l,f,f.length,h),l},r.sign.open=function(f,h){if(bt(f,h),h.length!==zr)throw new Error("bad public key size");var l=new Uint8Array(f.length),o=xo(l,f,f.length,h);if(o<0)return null;for(var p=new Uint8Array(o),v=0;v<p.length;v++)p[v]=l[v];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!==zr)throw new Error("bad public key size");var o=new Uint8Array(or+f.length),p=new Uint8Array(or+f.length),v;for(v=0;v<or;v++)o[v]=h[v];for(v=0;v<f.length;v++)o[v+or]=f[v];return xo(p,o,o.length,l)>=0},r.sign.keyPair=function(){var f=new Uint8Array(zr),h=new Uint8Array(mi);return Eo(f,h),{publicKey:f,secretKey:h}},r.sign.keyPair.fromSecretKey=function(f){if(bt(f),f.length!==mi)throw new Error("bad secret key size");for(var h=new Uint8Array(zr),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!==Co)throw new Error("bad seed size");for(var h=new Uint8Array(zr),l=new Uint8Array(mi),o=0;o<32;o++)l[o]=f[o];return Eo(h,l,!0),{publicKey:h,secretKey:l}},r.sign.publicKeyLength=zr,r.sign.secretKeyLength=mi,r.sign.seedLength=Co,r.sign.signatureLength=or,r.hash=function(f){bt(f);var h=new Uint8Array(Oo);return Kr(h,f,f.length),h},r.hash.hashLength=Oo,r.verify=function(f,h){return bt(f,h),f.length===0||h.length===0||f.length!==h.length?!1:T(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,v=new Uint8Array(o);for(p=0;p<o;p+=h)f.getRandomValues(v.subarray(p,p+Math.min(o-p,h)));for(p=0;p<o;p++)l[p]=v[p];ff(v)})}else typeof require<"u"&&(f=require("crypto"),f&&f.randomBytes&&r.setPRNG(function(l,o){var p,v=f.randomBytes(o);for(p=0;p<o;p++)l[p]=v[p];ff(v)}))})()})(typeof Ys<"u"&&Ys.exports?Ys.exports:self.nacl=self.nacl||{})});var Lo=F((Rf,Xs)=>{(function(r,e){"use strict";typeof Xs<"u"&&Xs.exports?Xs.exports=e():(r.nacl||(r.nacl={}),r.nacl.util=e())})(Rf,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 i,s=unescape(encodeURIComponent(t)),n=new Uint8Array(s.length);for(i=0;i<s.length;i++)n[i]=s.charCodeAt(i);return n},r.encodeUTF8=function(t){var i,s=[];for(i=0;i<t.length;i++)s.push(String.fromCharCode(t[i]));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 i,s=[],n=t.length;for(i=0;i<n;i++)s.push(String.fromCharCode(t[i]));return btoa(s.join(""))},r.decodeBase64=function(t){e(t);var i,s=atob(t),n=new Uint8Array(s.length);for(i=0;i<s.length;i++)n[i]=s.charCodeAt(i);return n}),r})});var Pf=F(kr=>{"use strict";var mp=kr&&kr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(kr,"__esModule",{value:!0});kr.encrypt=_p;kr.decrypt=yp;kr.encryptBinary=vp;kr.decryptBinary=Ep;var fr=mp(Io()),Or=Lo();function _p(r,e,t){let i=fr.default.randomBytes(fr.default.secretbox.nonceLength),s=new TextEncoder().encode(r),n=fr.default.secretbox(s,i,e);return{v:1,sid:t,n:(0,Or.encodeBase64)(i),c:(0,Or.encodeBase64)(n)}}function yp(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Or.decodeBase64)(r.n),i=(0,Or.decodeBase64)(r.c);if(t.length!==fr.default.secretbox.nonceLength)throw new Error(`Invalid nonce length: ${t.length}`);let s=fr.default.secretbox.open(i,t,e);if(!s)throw new Error("Decryption failed: invalid ciphertext or wrong key");return new TextDecoder().decode(s)}function vp(r,e,t){let i=fr.default.randomBytes(fr.default.secretbox.nonceLength),s=fr.default.secretbox(r,i,e);return{v:1,sid:t,n:(0,Or.encodeBase64)(i),c:(0,Or.encodeBase64)(s)}}function Ep(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Or.decodeBase64)(r.n),i=(0,Or.decodeBase64)(r.c),s=fr.default.secretbox.open(i,t,e);if(!s)throw new Error("Decryption failed: invalid ciphertext or wrong key");return s}});var Af=F(zt=>{"use strict";var wp=zt&&zt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(zt,"__esModule",{value:!0});zt.generateKeyPair=bp;zt.deriveSharedSecret=xp;zt.isValidPublicKey=Sp;zt.clearKey=Tp;zt.keyToBase64=Cp;zt.base64ToKey=Op;var ts=wp(Io()),$r=Lo();function bp(){let r=ts.default.box.keyPair();return{publicKey:(0,$r.encodeBase64)(r.publicKey),secretKey:(0,$r.encodeBase64)(r.secretKey)}}function xp(r,e){let t=(0,$r.decodeBase64)(r),i=(0,$r.decodeBase64)(e);if(t.length!==ts.default.box.publicKeyLength)throw new Error(`Invalid public key length: ${t.length}`);if(i.length!==ts.default.box.secretKeyLength)throw new Error(`Invalid secret key length: ${i.length}`);return ts.default.box.before(t,i)}function Sp(r){try{return(0,$r.decodeBase64)(r).length===ts.default.box.publicKeyLength}catch{return!1}}function Tp(r){r.fill(0)}function Cp(r){return(0,$r.encodeBase64)(r)}function Op(r){return(0,$r.decodeBase64)(r)}});var Lf=F(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.base64ToKey=Fe.keyToBase64=Fe.clearKey=Fe.isValidPublicKey=Fe.deriveSharedSecret=Fe.generateKeyPair=Fe.decryptBinary=Fe.encryptBinary=Fe.decrypt=Fe.encrypt=Fe.isMultiRecipientPayload=Fe.isEncryptedPayload=void 0;var If=kf();Object.defineProperty(Fe,"isEncryptedPayload",{enumerable:!0,get:function(){return If.isEncryptedPayload}});Object.defineProperty(Fe,"isMultiRecipientPayload",{enumerable:!0,get:function(){return If.isMultiRecipientPayload}});var Js=Pf();Object.defineProperty(Fe,"encrypt",{enumerable:!0,get:function(){return Js.encrypt}});Object.defineProperty(Fe,"decrypt",{enumerable:!0,get:function(){return Js.decrypt}});Object.defineProperty(Fe,"encryptBinary",{enumerable:!0,get:function(){return Js.encryptBinary}});Object.defineProperty(Fe,"decryptBinary",{enumerable:!0,get:function(){return Js.decryptBinary}});var yi=Af();Object.defineProperty(Fe,"generateKeyPair",{enumerable:!0,get:function(){return yi.generateKeyPair}});Object.defineProperty(Fe,"deriveSharedSecret",{enumerable:!0,get:function(){return yi.deriveSharedSecret}});Object.defineProperty(Fe,"isValidPublicKey",{enumerable:!0,get:function(){return yi.isValidPublicKey}});Object.defineProperty(Fe,"clearKey",{enumerable:!0,get:function(){return yi.clearKey}});Object.defineProperty(Fe,"keyToBase64",{enumerable:!0,get:function(){return yi.keyToBase64}});Object.defineProperty(Fe,"base64ToKey",{enumerable:!0,get:function(){return yi.base64ToKey}})});var Nf=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=kp;xt.compareVersions=Rp;xt.PROTOCOL_VERSION="2.1";xt.PROTOCOL_VERSION_MAJOR=2;xt.PROTOCOL_VERSION_MINOR=1;xt.MIN_CLIENT_VERSION="2.0";function kp(r){let[e]=r.split(".").map(Number);return e===xt.PROTOCOL_VERSION_MAJOR}function Rp(r,e){let[t,i]=r.split(".").map(Number),[s,n]=e.split(".").map(Number);return t!==s?t<s?-1:1:i!==n?i<n?-1:1:0}});var Df=F($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.SERVER_CAPABILITIES=$t.DEFAULT_CLIENT_CAPABILITIES=$t.Capability=void 0;$t.hasCapability=Pp;$t.negotiateCapabilities=Ap;var vi;(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",r.RELIABLE_INPUT="reliable-input",r.MULTI_VIEWER_RENDER="multi-viewer-render"})(vi||($t.Capability=vi={}));$t.DEFAULT_CLIENT_CAPABILITIES=[vi.E2E_ENCRYPTION,vi.TERMINAL_EVENTS,vi.RELIABLE_INPUT];$t.SERVER_CAPABILITIES=Object.values(vi);function Pp(r,e){return r.includes(e)}function Ap(r,e){return r.filter(t=>e.includes(t))}});var Mf=F(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.DEFAULT_PRIORITY=ur.PRIORITY_NAMES=ur.Priority=void 0;ur.comparePriority=Ip;var Gr;(function(r){r[r.CRITICAL=0]="CRITICAL",r[r.HIGH=1]="HIGH",r[r.NORMAL=2]="NORMAL",r[r.LOW=3]="LOW"})(Gr||(ur.Priority=Gr={}));ur.PRIORITY_NAMES={[Gr.CRITICAL]:"CRITICAL",[Gr.HIGH]:"HIGH",[Gr.NORMAL]:"NORMAL",[Gr.LOW]:"LOW"};ur.DEFAULT_PRIORITY=Gr.NORMAL;function Ip(r,e){return r-e}});var Ff=F(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.DEFAULT_RELIABILITY=Gt.RELIABILITY_NAMES=Gt.Reliability=void 0;Gt.requiresAck=Lp;Gt.requiresBuffer=Np;var Rr;(function(r){r[r.FIRE_FORGET=0]="FIRE_FORGET",r[r.BUFFERED=1]="BUFFERED",r[r.GUARANTEED=2]="GUARANTEED"})(Rr||(Gt.Reliability=Rr={}));Gt.RELIABILITY_NAMES={[Rr.FIRE_FORGET]:"FIRE_FORGET",[Rr.BUFFERED]:"BUFFERED",[Rr.GUARANTEED]:"GUARANTEED"};Gt.DEFAULT_RELIABILITY=Rr.FIRE_FORGET;function Lp(r){return r===Rr.GUARANTEED}function Np(r){return r>=Rr.BUFFERED}});var Bf=F(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});No.createMessage=Dp;function Dp(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 jf=F(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.TerminalEventType=void 0;Yr.deriveStatusFromEvent=Mp;Yr.shouldTriggerPushNotification=Fp;Yr.getPushNotificationMessage=Bp;var ht;(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"})(ht||(Yr.TerminalEventType=ht={}));function Mp(r){switch(r.type){case ht.SESSION_START:case ht.TOOL_START:case ht.MESSAGE:return"working";case ht.WAITING_INPUT:return"waiting";case ht.SESSION_END:return r.status==="success"?"completed":"error";case ht.ERROR:return r.severity==="fatal"?"error":"working";case ht.TOOL_END:return r.status==="error"?"error":"working";default:return"idle"}}function Fp(r){switch(r.type){case ht.WAITING_INPUT:return!0;case ht.SESSION_END:return!0;case ht.ERROR:return r.severity!=="warning";default:return!1}}function Bp(r,e){switch(r.type){case ht.WAITING_INPUT:return{title:`${e}: Input Required`,body:r.question.slice(0,100)};case ht.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 ht.ERROR:{let t=r;return t.severity==="warning"?null:{title:`${e}: Error`,body:t.message.slice(0,100)}}default:return null}}});var Wf=F(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.TransferDirection=qe.TransferStatus=qe.CHUNK_TTL_SECONDS=qe.TRANSFER_TTL_SECONDS=qe.MAX_RETRIES=qe.ACK_TIMEOUT_MS=qe.WINDOW_SIZE=qe.DEFAULT_MAX_FILE_SIZE=qe.CHUNK_SIZE=void 0;qe.calculateTotalChunks=jp;qe.getMissingChunks=Up;qe.isTransferComplete=qp;qe.CHUNK_SIZE=64*1024;qe.DEFAULT_MAX_FILE_SIZE=100*1024*1024;qe.WINDOW_SIZE=10;qe.ACK_TIMEOUT_MS=3e4;qe.MAX_RETRIES=3;qe.TRANSFER_TTL_SECONDS=1440*60;qe.CHUNK_TTL_SECONDS=1440*60;var Uf;(function(r){r.PENDING="pending",r.ACTIVE="active",r.PAUSED="paused",r.COMPLETED="completed",r.FAILED="failed",r.CANCELLED="cancelled",r.EXPIRED="expired"})(Uf||(qe.TransferStatus=Uf={}));var qf;(function(r){r.DOWNLOAD="download",r.UPLOAD="upload"})(qf||(qe.TransferDirection=qf={}));function jp(r,e=qe.CHUNK_SIZE){return Math.ceil(r/e)}function Up(r,e){let t=new Set(e),i=[];for(let s=0;s<r;s++)t.has(s)||i.push(s);return i}function qp(r,e){return e.length===r}});var Hf=F(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.ERROR_MESSAGES=lr.ErrorCode=void 0;lr.createError=Wp;lr.isRetryableError=Hp;var Re;(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"})(Re||(lr.ErrorCode=Re={}));lr.ERROR_MESSAGES={[Re.AUTH_FAILED]:"Authentication failed",[Re.TOKEN_EXPIRED]:"Token expired",[Re.TOKEN_INVALID]:"Invalid token",[Re.NOT_FOUND]:"Resource not found",[Re.ALREADY_EXISTS]:"Resource already exists",[Re.ACCESS_DENIED]:"Access denied",[Re.FORBIDDEN]:"Operation forbidden",[Re.RATE_LIMITED]:"Rate limit exceeded",[Re.TOO_MANY_CONNECTIONS]:"Too many connections",[Re.QUOTA_EXCEEDED]:"Plan quota exceeded",[Re.FILE_TOO_LARGE]:"File size exceeds limit",[Re.QUEUE_FULL]:"Message queue is full",[Re.TRANSFERS_LIMIT]:"Daily transfers limit reached",[Re.TRANSFER_FAILED]:"File transfer failed",[Re.TRANSFER_EXPIRED]:"Transfer expired",[Re.TRANSFER_CANCELLED]:"Transfer cancelled",[Re.CHECKSUM_MISMATCH]:"File checksum mismatch",[Re.CHUNK_MISSING]:"Chunk missing or corrupted",[Re.INVALID_MESSAGE]:"Invalid message format",[Re.UNSUPPORTED_VERSION]:"Unsupported protocol version",[Re.CAPABILITY_REQUIRED]:"Required capability not supported",[Re.INVALID_STATE]:"Invalid state for this operation",[Re.TIMEOUT]:"Operation timed out",[Re.CONNECTION_LOST]:"Connection lost",[Re.INTERNAL_ERROR]:"Internal server error",[Re.SERVICE_UNAVAILABLE]:"Service temporarily unavailable"};function Wp(r,e={}){return{code:r,message:e.message||lr.ERROR_MESSAGES[r],details:e.details,retryable:e.retryable??!1,retryAfter:e.retryAfter}}function Hp(r){return[Re.RATE_LIMITED,Re.TIMEOUT,Re.CONNECTION_LOST,Re.SERVICE_UNAVAILABLE].includes(r)}});var $f=F(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.FileEntryType=St.DiffBase=St.FileViewType=St.FileChangeType=void 0;St.getLanguageFromPath=Vp;St.parseUnifiedDiff=Kp;St.createSimpleDiff=zp;var Pr;(function(r){r.CREATE="create",r.MODIFY="modify",r.DELETE="delete"})(Pr||(St.FileChangeType=Pr={}));var Vf;(function(r){r.CONTENT="content",r.DIFF="diff"})(Vf||(St.FileViewType=Vf={}));var Kf;(function(r){r.GIT="git",r.PREVIOUS="previous"})(Kf||(St.DiffBase=Kf={}));function Vp(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"},i=r.split("/").pop()?.toLowerCase()||"";return{dockerfile:"dockerfile",makefile:"makefile",".gitignore":"plaintext",".env":"plaintext",".env.local":"plaintext",".env.development":"plaintext",".env.production":"plaintext"}[i]||t[e||""]||"plaintext"}function Kp(r,e){let t=r.split(`
3
- `),i=[],s=0,n=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&&i.push(a);let y=parseInt(m[1],10),b=parseInt(m[2]||"1",10),T=parseInt(m[3],10),C=parseInt(m[4]||"1",10);a={oldStart:y,oldLines:b,newStart:T,newLines:C,lines:[]},c=y,u=T;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}),n++):(g.startsWith(" ")||g==="")&&a.lines.push({type:"context",content:g.startsWith(" ")?g.slice(1):g,oldLineNumber:c++,newLineNumber:u++}))}a&&i.push(a);let d;return n===0&&s>0&&i.length===1&&i[0].oldLines===0?d=Pr.CREATE:s===0&&n>0&&i.length===1&&i[0].newLines===0?d=Pr.DELETE:d=Pr.MODIFY,{path:e,changeType:d,hunks:i,additions:s,deletions:n,isBinary:!1}}function zp(r,e,t){let i=r.split(`
2
+ "use strict";var Yd=Object.create;var ko=Object.defineProperty;var Xd=Object.getOwnPropertyDescriptor;var Jd=Object.getOwnPropertyNames;var Zd=Object.getPrototypeOf,Qd=Object.prototype.hasOwnProperty;var Ft=(r,e)=>()=>(r&&(e=r(r=0)),e);var F=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ep=(r,e)=>{for(var t in e)ko(r,t,{get:e[t],enumerable:!0})},tp=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Jd(e))!Qd.call(r,s)&&s!==t&&ko(r,s,{get:()=>e[s],enumerable:!(i=Xd(e,s))||i.enumerable});return r};var ce=(r,e,t)=>(t=r!=null?Yd(Zd(r)):{},tp(e||!r||!r.__esModule?ko(t,"default",{value:r,enumerable:!0}):t,r));var Ws=F(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});es.generateCorrelationId=sp;es.runWithCorrelation=np;es.getCurrentCorrelationId=op;var ip=require("async_hooks");function sp(){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 hf=new ip.AsyncLocalStorage;function np(r,e){return hf.run(r,e)}function op(){return hf.getStore()}});var pf=F(_i=>{"use strict";Object.defineProperty(_i,"__esModule",{value:!0});_i.LOG_LEVELS=void 0;_i.shouldLog=cp;_i.formatLogLine=fp;var ap=Ws();_i.LOG_LEVELS=["silent","error","warn","info","debug"];var df={silent:0,error:1,warn:2,info:3,debug:4};function cp(r,e){return df[r]<=df[e]}function fp(r,e,t,i){let s={ts:new Date().toISOString(),level:r,src:e,msg:t},n=(0,ap.getCurrentCorrelationId)();n&&(s.cid=n);let a=i;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 gf=F(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.formatLogLine=Cr.shouldLog=Cr.LOG_LEVELS=void 0;var Ro=pf();Object.defineProperty(Cr,"LOG_LEVELS",{enumerable:!0,get:function(){return Ro.LOG_LEVELS}});Object.defineProperty(Cr,"shouldLog",{enumerable:!0,get:function(){return Ro.shouldLog}});Object.defineProperty(Cr,"formatLogLine",{enumerable:!0,get:function(){return Ro.formatLogLine}})});var mf=F(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});Hs.CircularBuffer=void 0;var Po=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=Po});var zs=F(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.getApiUrl=up;Vs.getWsUrl=lp;function up(r){return`${r.getServerUrl()}/api`}function lp(r){let e=r.getServerUrl();return e.startsWith("https://")?e.replace(/^https:\/\//,"wss://"):e.replace(/^http:\/\//,"ws://")}});var yf=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 hp=mf();Object.defineProperty(pt,"CircularBuffer",{enumerable:!0,get:function(){return hp.CircularBuffer}});var _f=zs();Object.defineProperty(pt,"getApiUrl",{enumerable:!0,get:function(){return _f.getApiUrl}});Object.defineProperty(pt,"getWsUrl",{enumerable:!0,get:function(){return _f.getWsUrl}});var Ao=Ws();Object.defineProperty(pt,"generateCorrelationId",{enumerable:!0,get:function(){return Ao.generateCorrelationId}});Object.defineProperty(pt,"runWithCorrelation",{enumerable:!0,get:function(){return Ao.runWithCorrelation}});Object.defineProperty(pt,"getCurrentCorrelationId",{enumerable:!0,get:function(){return Ao.getCurrentCorrelationId}})});var wf=F(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0})});var bf=F(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0})});var xf=F(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.PLAN_LIMITS=void 0;Ks.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 Tf=F(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0})});var Cf=F(zt=>{"use strict";var dp=zt&&zt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=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,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),$s=zt&&zt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&dp(e,r,t)};Object.defineProperty(zt,"__esModule",{value:!0});$s(wf(),zt);$s(bf(),zt);$s(xf(),zt);$s(Tf(),zt)});var Of=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 kf=F(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.isMultiRecipientPayload=pp;Gs.isEncryptedPayload=gp;function pp(r){return typeof r=="object"&&r!==null&&"v"in r&&r.v===2&&"recipients"in r&&Array.isArray(r.recipients)}function gp(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 Io=F((mw,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")},i=new Uint8Array(16),s=new Uint8Array(32);s[0]=9;var n=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]),p=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 E(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 T(f,h,l,o,g){var v,w=0;for(v=0;v<g;v++)w|=f[h+v]^l[o+v];return(1&w-1>>>8)-1}function O(f,h,l,o){return T(f,h,l,o,16)}function H(f,h,l,o){return T(f,h,l,o,32)}function me(f,h,l,o){for(var g=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,v=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,R=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,B=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,G=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,re=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,ie=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,le=l[16]&255|(l[17]&255)<<8|(l[18]&255)<<16|(l[19]&255)<<24,fe=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,oe=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,ne=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,z=g,J=v,W=w,K=R,$=B,U=G,b=q,x=Ce,L=V,k=re,P=ie,M=le,Z=fe,he=se,pe=oe,de=ne,_,_e=0;_e<20;_e+=2)_=z+Z|0,$^=_<<7|_>>>25,_=$+z|0,L^=_<<9|_>>>23,_=L+$|0,Z^=_<<13|_>>>19,_=Z+L|0,z^=_<<18|_>>>14,_=U+J|0,k^=_<<7|_>>>25,_=k+U|0,he^=_<<9|_>>>23,_=he+k|0,J^=_<<13|_>>>19,_=J+he|0,U^=_<<18|_>>>14,_=P+b|0,pe^=_<<7|_>>>25,_=pe+P|0,W^=_<<9|_>>>23,_=W+pe|0,b^=_<<13|_>>>19,_=b+W|0,P^=_<<18|_>>>14,_=de+M|0,K^=_<<7|_>>>25,_=K+de|0,x^=_<<9|_>>>23,_=x+K|0,M^=_<<13|_>>>19,_=M+x|0,de^=_<<18|_>>>14,_=z+K|0,J^=_<<7|_>>>25,_=J+z|0,W^=_<<9|_>>>23,_=W+J|0,K^=_<<13|_>>>19,_=K+W|0,z^=_<<18|_>>>14,_=U+$|0,b^=_<<7|_>>>25,_=b+U|0,x^=_<<9|_>>>23,_=x+b|0,$^=_<<13|_>>>19,_=$+x|0,U^=_<<18|_>>>14,_=P+k|0,M^=_<<7|_>>>25,_=M+P|0,L^=_<<9|_>>>23,_=L+M|0,k^=_<<13|_>>>19,_=k+L|0,P^=_<<18|_>>>14,_=de+pe|0,Z^=_<<7|_>>>25,_=Z+de|0,he^=_<<9|_>>>23,_=he+Z|0,pe^=_<<13|_>>>19,_=pe+he|0,de^=_<<18|_>>>14;z=z+g|0,J=J+v|0,W=W+w|0,K=K+R|0,$=$+B|0,U=U+G|0,b=b+q|0,x=x+Ce|0,L=L+V|0,k=k+re|0,P=P+ie|0,M=M+le|0,Z=Z+fe|0,he=he+se|0,pe=pe+oe|0,de=de+ne|0,f[0]=z>>>0&255,f[1]=z>>>8&255,f[2]=z>>>16&255,f[3]=z>>>24&255,f[4]=J>>>0&255,f[5]=J>>>8&255,f[6]=J>>>16&255,f[7]=J>>>24&255,f[8]=W>>>0&255,f[9]=W>>>8&255,f[10]=W>>>16&255,f[11]=W>>>24&255,f[12]=K>>>0&255,f[13]=K>>>8&255,f[14]=K>>>16&255,f[15]=K>>>24&255,f[16]=$>>>0&255,f[17]=$>>>8&255,f[18]=$>>>16&255,f[19]=$>>>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]=L>>>0&255,f[33]=L>>>8&255,f[34]=L>>>16&255,f[35]=L>>>24&255,f[36]=k>>>0&255,f[37]=k>>>8&255,f[38]=k>>>16&255,f[39]=k>>>24&255,f[40]=P>>>0&255,f[41]=P>>>8&255,f[42]=P>>>16&255,f[43]=P>>>24&255,f[44]=M>>>0&255,f[45]=M>>>8&255,f[46]=M>>>16&255,f[47]=M>>>24&255,f[48]=Z>>>0&255,f[49]=Z>>>8&255,f[50]=Z>>>16&255,f[51]=Z>>>24&255,f[52]=he>>>0&255,f[53]=he>>>8&255,f[54]=he>>>16&255,f[55]=he>>>24&255,f[56]=pe>>>0&255,f[57]=pe>>>8&255,f[58]=pe>>>16&255,f[59]=pe>>>24&255,f[60]=de>>>0&255,f[61]=de>>>8&255,f[62]=de>>>16&255,f[63]=de>>>24&255}function X(f,h,l,o){for(var g=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,v=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,R=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,B=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,G=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,re=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,ie=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,le=l[16]&255|(l[17]&255)<<8|(l[18]&255)<<16|(l[19]&255)<<24,fe=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,oe=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,ne=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,z=g,J=v,W=w,K=R,$=B,U=G,b=q,x=Ce,L=V,k=re,P=ie,M=le,Z=fe,he=se,pe=oe,de=ne,_,_e=0;_e<20;_e+=2)_=z+Z|0,$^=_<<7|_>>>25,_=$+z|0,L^=_<<9|_>>>23,_=L+$|0,Z^=_<<13|_>>>19,_=Z+L|0,z^=_<<18|_>>>14,_=U+J|0,k^=_<<7|_>>>25,_=k+U|0,he^=_<<9|_>>>23,_=he+k|0,J^=_<<13|_>>>19,_=J+he|0,U^=_<<18|_>>>14,_=P+b|0,pe^=_<<7|_>>>25,_=pe+P|0,W^=_<<9|_>>>23,_=W+pe|0,b^=_<<13|_>>>19,_=b+W|0,P^=_<<18|_>>>14,_=de+M|0,K^=_<<7|_>>>25,_=K+de|0,x^=_<<9|_>>>23,_=x+K|0,M^=_<<13|_>>>19,_=M+x|0,de^=_<<18|_>>>14,_=z+K|0,J^=_<<7|_>>>25,_=J+z|0,W^=_<<9|_>>>23,_=W+J|0,K^=_<<13|_>>>19,_=K+W|0,z^=_<<18|_>>>14,_=U+$|0,b^=_<<7|_>>>25,_=b+U|0,x^=_<<9|_>>>23,_=x+b|0,$^=_<<13|_>>>19,_=$+x|0,U^=_<<18|_>>>14,_=P+k|0,M^=_<<7|_>>>25,_=M+P|0,L^=_<<9|_>>>23,_=L+M|0,k^=_<<13|_>>>19,_=k+L|0,P^=_<<18|_>>>14,_=de+pe|0,Z^=_<<7|_>>>25,_=Z+de|0,he^=_<<9|_>>>23,_=he+Z|0,pe^=_<<13|_>>>19,_=pe+he|0,de^=_<<18|_>>>14;f[0]=z>>>0&255,f[1]=z>>>8&255,f[2]=z>>>16&255,f[3]=z>>>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]=de>>>0&255,f[13]=de>>>8&255,f[14]=de>>>16&255,f[15]=de>>>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]=L>>>0&255,f[25]=L>>>8&255,f[26]=L>>>16&255,f[27]=L>>>24&255,f[28]=k>>>0&255,f[29]=k>>>8&255,f[30]=k>>>16&255,f[31]=k>>>24&255}function A(f,h,l,o){me(f,h,l,o)}function j(f,h,l,o){X(f,h,l,o)}var te=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function I(f,h,l,o,g,v,w){var R=new Uint8Array(16),B=new Uint8Array(64),G,q;for(q=0;q<16;q++)R[q]=0;for(q=0;q<8;q++)R[q]=v[q];for(;g>=64;){for(A(B,R,w,te),q=0;q<64;q++)f[h+q]=l[o+q]^B[q];for(G=1,q=8;q<16;q++)G=G+(R[q]&255)|0,R[q]=G&255,G>>>=8;g-=64,h+=64,o+=64}if(g>0)for(A(B,R,w,te),q=0;q<g;q++)f[h+q]=l[o+q]^B[q];return 0}function ae(f,h,l,o,g){var v=new Uint8Array(16),w=new Uint8Array(64),R,B;for(B=0;B<16;B++)v[B]=0;for(B=0;B<8;B++)v[B]=o[B];for(;l>=64;){for(A(w,v,g,te),B=0;B<64;B++)f[h+B]=w[B];for(R=1,B=8;B<16;B++)R=R+(v[B]&255)|0,v[B]=R&255,R>>>=8;l-=64,h+=64}if(l>0)for(A(w,v,g,te),B=0;B<l;B++)f[h+B]=w[B];return 0}function ue(f,h,l,o,g){var v=new Uint8Array(32);j(v,o,g,te);for(var w=new Uint8Array(8),R=0;R<8;R++)w[R]=o[R+16];return ae(f,h,l,w,v)}function Q(f,h,l,o,g,v,w){var R=new Uint8Array(32);j(R,v,w,te);for(var B=new Uint8Array(8),G=0;G<8;G++)B[G]=v[G+16];return I(f,h,l,o,g,B,R)}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,g,v,w,R,B;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,g=f[6]&255|(f[7]&255)<<8,this.r[3]=(o>>>7|g<<9)&8191,v=f[8]&255|(f[9]&255)<<8,this.r[4]=(g>>>4|v<<12)&255,this.r[5]=v>>>1&8190,w=f[10]&255|(f[11]&255)<<8,this.r[6]=(v>>>14|w<<2)&8191,R=f[12]&255|(f[13]&255)<<8,this.r[7]=(w>>>11|R<<5)&8065,B=f[14]&255|(f[15]&255)<<8,this.r[8]=(R>>>8|B<<8)&8191,this.r[9]=B>>>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,g,v,w,R,B,G,q,Ce,V,re,ie,le,fe,se,oe,ne,z,J,W,K=this.h[0],$=this.h[1],U=this.h[2],b=this.h[3],x=this.h[4],L=this.h[5],k=this.h[6],P=this.h[7],M=this.h[8],Z=this.h[9],he=this.r[0],pe=this.r[1],de=this.r[2],_=this.r[3],_e=this.r[4],Oe=this.r[5],ke=this.r[6],ge=this.r[7],be=this.r[8],xe=this.r[9];l>=16;)g=f[h+0]&255|(f[h+1]&255)<<8,K+=g&8191,v=f[h+2]&255|(f[h+3]&255)<<8,$+=(g>>>13|v<<3)&8191,w=f[h+4]&255|(f[h+5]&255)<<8,U+=(v>>>10|w<<6)&8191,R=f[h+6]&255|(f[h+7]&255)<<8,b+=(w>>>7|R<<9)&8191,B=f[h+8]&255|(f[h+9]&255)<<8,x+=(R>>>4|B<<12)&8191,L+=B>>>1&8191,G=f[h+10]&255|(f[h+11]&255)<<8,k+=(B>>>14|G<<2)&8191,q=f[h+12]&255|(f[h+13]&255)<<8,P+=(G>>>11|q<<5)&8191,Ce=f[h+14]&255|(f[h+15]&255)<<8,M+=(q>>>8|Ce<<8)&8191,Z+=Ce>>>5|o,V=0,re=V,re+=K*he,re+=$*(5*xe),re+=U*(5*be),re+=b*(5*ge),re+=x*(5*ke),V=re>>>13,re&=8191,re+=L*(5*Oe),re+=k*(5*_e),re+=P*(5*_),re+=M*(5*de),re+=Z*(5*pe),V+=re>>>13,re&=8191,ie=V,ie+=K*pe,ie+=$*he,ie+=U*(5*xe),ie+=b*(5*be),ie+=x*(5*ge),V=ie>>>13,ie&=8191,ie+=L*(5*ke),ie+=k*(5*Oe),ie+=P*(5*_e),ie+=M*(5*_),ie+=Z*(5*de),V+=ie>>>13,ie&=8191,le=V,le+=K*de,le+=$*pe,le+=U*he,le+=b*(5*xe),le+=x*(5*be),V=le>>>13,le&=8191,le+=L*(5*ge),le+=k*(5*ke),le+=P*(5*Oe),le+=M*(5*_e),le+=Z*(5*_),V+=le>>>13,le&=8191,fe=V,fe+=K*_,fe+=$*de,fe+=U*pe,fe+=b*he,fe+=x*(5*xe),V=fe>>>13,fe&=8191,fe+=L*(5*be),fe+=k*(5*ge),fe+=P*(5*ke),fe+=M*(5*Oe),fe+=Z*(5*_e),V+=fe>>>13,fe&=8191,se=V,se+=K*_e,se+=$*_,se+=U*de,se+=b*pe,se+=x*he,V=se>>>13,se&=8191,se+=L*(5*xe),se+=k*(5*be),se+=P*(5*ge),se+=M*(5*ke),se+=Z*(5*Oe),V+=se>>>13,se&=8191,oe=V,oe+=K*Oe,oe+=$*_e,oe+=U*_,oe+=b*de,oe+=x*pe,V=oe>>>13,oe&=8191,oe+=L*he,oe+=k*(5*xe),oe+=P*(5*be),oe+=M*(5*ge),oe+=Z*(5*ke),V+=oe>>>13,oe&=8191,ne=V,ne+=K*ke,ne+=$*Oe,ne+=U*_e,ne+=b*_,ne+=x*de,V=ne>>>13,ne&=8191,ne+=L*pe,ne+=k*he,ne+=P*(5*xe),ne+=M*(5*be),ne+=Z*(5*ge),V+=ne>>>13,ne&=8191,z=V,z+=K*ge,z+=$*ke,z+=U*Oe,z+=b*_e,z+=x*_,V=z>>>13,z&=8191,z+=L*de,z+=k*pe,z+=P*he,z+=M*(5*xe),z+=Z*(5*be),V+=z>>>13,z&=8191,J=V,J+=K*be,J+=$*ge,J+=U*ke,J+=b*Oe,J+=x*_e,V=J>>>13,J&=8191,J+=L*_,J+=k*de,J+=P*pe,J+=M*he,J+=Z*(5*xe),V+=J>>>13,J&=8191,W=V,W+=K*xe,W+=$*be,W+=U*ge,W+=b*ke,W+=x*Oe,V=W>>>13,W&=8191,W+=L*_e,W+=k*_,W+=P*de,W+=M*pe,W+=Z*he,V+=W>>>13,W&=8191,V=(V<<2)+V|0,V=V+re|0,re=V&8191,V=V>>>13,ie+=V,K=re,$=ie,U=le,b=fe,x=se,L=oe,k=ne,P=z,M=J,Z=W,h+=16,l-=16;this.h[0]=K,this.h[1]=$,this.h[2]=U,this.h[3]=b,this.h[4]=x,this.h[5]=L,this.h[6]=k,this.h[7]=P,this.h[8]=M,this.h[9]=Z},Re.prototype.finish=function(f,h){var l=new Uint16Array(10),o,g,v,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,g=(o^1)-1,w=0;w<10;w++)l[w]&=g;for(g=~g,w=0;w<10;w++)this.h[w]=this.h[w]&g|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,v=this.h[0]+this.pad[0],this.h[0]=v&65535,w=1;w<8;w++)v=(this.h[w]+this.pad[w]|0)+(v>>>16)|0,this.h[w]=v&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,g;if(this.leftover){for(g=16-this.leftover,g>l&&(g=l),o=0;o<g;o++)this.buffer[this.leftover+o]=f[h+o];if(l-=g,h+=g,this.leftover+=g,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(l>=16&&(g=l-l%16,this.blocks(f,h,g),h+=g,l-=g),l){for(o=0;o<l;o++)this.buffer[this.leftover+o]=f[h+o];this.leftover+=l}};function Ee(f,h,l,o,g,v){var w=new Re(v);return w.update(l,o,g),w.finish(f,h),0}function Je(f,h,l,o,g,v){var w=new Uint8Array(16);return Ee(w,0,l,o,g,v),O(f,h,w,0)}function ee(f,h,l,o,g){var v;if(l<32)return-1;for(Q(f,0,h,0,l,o,g),Ee(f,16,f,32,l-32,f),v=0;v<16;v++)f[v]=0;return 0}function Ye(f,h,l,o,g){var v,w=new Uint8Array(32);if(l<32||(ue(w,0,32,o,g),Je(h,16,h,32,l-32,w)!==0))return-1;for(Q(f,0,h,0,l,o,g),v=0;v<32;v++)f[v]=0;return 0}function Be(f,h){var l;for(l=0;l<16;l++)f[l]=h[l]|0}function je(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 Ue(f,h,l){for(var o,g=~(l-1),v=0;v<16;v++)o=g&(f[v]^h[v]),f[v]^=o,h[v]^=o}function Te(f,h){var l,o,g,v=e(),w=e();for(l=0;l<16;l++)w[l]=h[l];for(je(w),je(w),je(w),o=0;o<2;o++){for(v[0]=w[0]-65517,l=1;l<15;l++)v[l]=w[l]-65535-(v[l-1]>>16&1),v[l-1]&=65535;v[15]=w[15]-32767-(v[14]>>16&1),g=v[15]>>16&1,v[14]&=65535,Ue(w,v,1-g)}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 Te(l,f),Te(o,h),H(l,0,o,0)}function Ve(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 S(f,h,l){for(var o=0;o<16;o++)f[o]=h[o]-l[o]}function C(f,h,l){var o,g,v=0,w=0,R=0,B=0,G=0,q=0,Ce=0,V=0,re=0,ie=0,le=0,fe=0,se=0,oe=0,ne=0,z=0,J=0,W=0,K=0,$=0,U=0,b=0,x=0,L=0,k=0,P=0,M=0,Z=0,he=0,pe=0,de=0,_=l[0],_e=l[1],Oe=l[2],ke=l[3],ge=l[4],be=l[5],xe=l[6],Xe=l[7],Ae=l[8],Ke=l[9],$e=l[10],Ge=l[11],Qe=l[12],at=l[13],ct=l[14],ft=l[15];o=h[0],v+=o*_,w+=o*_e,R+=o*Oe,B+=o*ke,G+=o*ge,q+=o*be,Ce+=o*xe,V+=o*Xe,re+=o*Ae,ie+=o*Ke,le+=o*$e,fe+=o*Ge,se+=o*Qe,oe+=o*at,ne+=o*ct,z+=o*ft,o=h[1],w+=o*_,R+=o*_e,B+=o*Oe,G+=o*ke,q+=o*ge,Ce+=o*be,V+=o*xe,re+=o*Xe,ie+=o*Ae,le+=o*Ke,fe+=o*$e,se+=o*Ge,oe+=o*Qe,ne+=o*at,z+=o*ct,J+=o*ft,o=h[2],R+=o*_,B+=o*_e,G+=o*Oe,q+=o*ke,Ce+=o*ge,V+=o*be,re+=o*xe,ie+=o*Xe,le+=o*Ae,fe+=o*Ke,se+=o*$e,oe+=o*Ge,ne+=o*Qe,z+=o*at,J+=o*ct,W+=o*ft,o=h[3],B+=o*_,G+=o*_e,q+=o*Oe,Ce+=o*ke,V+=o*ge,re+=o*be,ie+=o*xe,le+=o*Xe,fe+=o*Ae,se+=o*Ke,oe+=o*$e,ne+=o*Ge,z+=o*Qe,J+=o*at,W+=o*ct,K+=o*ft,o=h[4],G+=o*_,q+=o*_e,Ce+=o*Oe,V+=o*ke,re+=o*ge,ie+=o*be,le+=o*xe,fe+=o*Xe,se+=o*Ae,oe+=o*Ke,ne+=o*$e,z+=o*Ge,J+=o*Qe,W+=o*at,K+=o*ct,$+=o*ft,o=h[5],q+=o*_,Ce+=o*_e,V+=o*Oe,re+=o*ke,ie+=o*ge,le+=o*be,fe+=o*xe,se+=o*Xe,oe+=o*Ae,ne+=o*Ke,z+=o*$e,J+=o*Ge,W+=o*Qe,K+=o*at,$+=o*ct,U+=o*ft,o=h[6],Ce+=o*_,V+=o*_e,re+=o*Oe,ie+=o*ke,le+=o*ge,fe+=o*be,se+=o*xe,oe+=o*Xe,ne+=o*Ae,z+=o*Ke,J+=o*$e,W+=o*Ge,K+=o*Qe,$+=o*at,U+=o*ct,b+=o*ft,o=h[7],V+=o*_,re+=o*_e,ie+=o*Oe,le+=o*ke,fe+=o*ge,se+=o*be,oe+=o*xe,ne+=o*Xe,z+=o*Ae,J+=o*Ke,W+=o*$e,K+=o*Ge,$+=o*Qe,U+=o*at,b+=o*ct,x+=o*ft,o=h[8],re+=o*_,ie+=o*_e,le+=o*Oe,fe+=o*ke,se+=o*ge,oe+=o*be,ne+=o*xe,z+=o*Xe,J+=o*Ae,W+=o*Ke,K+=o*$e,$+=o*Ge,U+=o*Qe,b+=o*at,x+=o*ct,L+=o*ft,o=h[9],ie+=o*_,le+=o*_e,fe+=o*Oe,se+=o*ke,oe+=o*ge,ne+=o*be,z+=o*xe,J+=o*Xe,W+=o*Ae,K+=o*Ke,$+=o*$e,U+=o*Ge,b+=o*Qe,x+=o*at,L+=o*ct,k+=o*ft,o=h[10],le+=o*_,fe+=o*_e,se+=o*Oe,oe+=o*ke,ne+=o*ge,z+=o*be,J+=o*xe,W+=o*Xe,K+=o*Ae,$+=o*Ke,U+=o*$e,b+=o*Ge,x+=o*Qe,L+=o*at,k+=o*ct,P+=o*ft,o=h[11],fe+=o*_,se+=o*_e,oe+=o*Oe,ne+=o*ke,z+=o*ge,J+=o*be,W+=o*xe,K+=o*Xe,$+=o*Ae,U+=o*Ke,b+=o*$e,x+=o*Ge,L+=o*Qe,k+=o*at,P+=o*ct,M+=o*ft,o=h[12],se+=o*_,oe+=o*_e,ne+=o*Oe,z+=o*ke,J+=o*ge,W+=o*be,K+=o*xe,$+=o*Xe,U+=o*Ae,b+=o*Ke,x+=o*$e,L+=o*Ge,k+=o*Qe,P+=o*at,M+=o*ct,Z+=o*ft,o=h[13],oe+=o*_,ne+=o*_e,z+=o*Oe,J+=o*ke,W+=o*ge,K+=o*be,$+=o*xe,U+=o*Xe,b+=o*Ae,x+=o*Ke,L+=o*$e,k+=o*Ge,P+=o*Qe,M+=o*at,Z+=o*ct,he+=o*ft,o=h[14],ne+=o*_,z+=o*_e,J+=o*Oe,W+=o*ke,K+=o*ge,$+=o*be,U+=o*xe,b+=o*Xe,x+=o*Ae,L+=o*Ke,k+=o*$e,P+=o*Ge,M+=o*Qe,Z+=o*at,he+=o*ct,pe+=o*ft,o=h[15],z+=o*_,J+=o*_e,W+=o*Oe,K+=o*ke,$+=o*ge,U+=o*be,b+=o*xe,x+=o*Xe,L+=o*Ae,k+=o*Ke,P+=o*$e,M+=o*Ge,Z+=o*Qe,he+=o*at,pe+=o*ct,de+=o*ft,v+=38*J,w+=38*W,R+=38*K,B+=38*$,G+=38*U,q+=38*b,Ce+=38*x,V+=38*L,re+=38*k,ie+=38*P,le+=38*M,fe+=38*Z,se+=38*he,oe+=38*pe,ne+=38*de,g=1,o=v+g+65535,g=Math.floor(o/65536),v=o-g*65536,o=w+g+65535,g=Math.floor(o/65536),w=o-g*65536,o=R+g+65535,g=Math.floor(o/65536),R=o-g*65536,o=B+g+65535,g=Math.floor(o/65536),B=o-g*65536,o=G+g+65535,g=Math.floor(o/65536),G=o-g*65536,o=q+g+65535,g=Math.floor(o/65536),q=o-g*65536,o=Ce+g+65535,g=Math.floor(o/65536),Ce=o-g*65536,o=V+g+65535,g=Math.floor(o/65536),V=o-g*65536,o=re+g+65535,g=Math.floor(o/65536),re=o-g*65536,o=ie+g+65535,g=Math.floor(o/65536),ie=o-g*65536,o=le+g+65535,g=Math.floor(o/65536),le=o-g*65536,o=fe+g+65535,g=Math.floor(o/65536),fe=o-g*65536,o=se+g+65535,g=Math.floor(o/65536),se=o-g*65536,o=oe+g+65535,g=Math.floor(o/65536),oe=o-g*65536,o=ne+g+65535,g=Math.floor(o/65536),ne=o-g*65536,o=z+g+65535,g=Math.floor(o/65536),z=o-g*65536,v+=g-1+37*(g-1),g=1,o=v+g+65535,g=Math.floor(o/65536),v=o-g*65536,o=w+g+65535,g=Math.floor(o/65536),w=o-g*65536,o=R+g+65535,g=Math.floor(o/65536),R=o-g*65536,o=B+g+65535,g=Math.floor(o/65536),B=o-g*65536,o=G+g+65535,g=Math.floor(o/65536),G=o-g*65536,o=q+g+65535,g=Math.floor(o/65536),q=o-g*65536,o=Ce+g+65535,g=Math.floor(o/65536),Ce=o-g*65536,o=V+g+65535,g=Math.floor(o/65536),V=o-g*65536,o=re+g+65535,g=Math.floor(o/65536),re=o-g*65536,o=ie+g+65535,g=Math.floor(o/65536),ie=o-g*65536,o=le+g+65535,g=Math.floor(o/65536),le=o-g*65536,o=fe+g+65535,g=Math.floor(o/65536),fe=o-g*65536,o=se+g+65535,g=Math.floor(o/65536),se=o-g*65536,o=oe+g+65535,g=Math.floor(o/65536),oe=o-g*65536,o=ne+g+65535,g=Math.floor(o/65536),ne=o-g*65536,o=z+g+65535,g=Math.floor(o/65536),z=o-g*65536,v+=g-1+37*(g-1),f[0]=v,f[1]=w,f[2]=R,f[3]=B,f[4]=G,f[5]=q,f[6]=Ce,f[7]=V,f[8]=re,f[9]=ie,f[10]=le,f[11]=fe,f[12]=se,f[13]=oe,f[14]=ne,f[15]=z}function Y(f,h){C(f,h,h)}function ve(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=253;o>=0;o--)Y(l,l),o!==2&&o!==4&&C(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function et(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=250;o>=0;o--)Y(l,l),o!==1&&C(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function vt(f,h,l){var o=new Uint8Array(32),g=new Float64Array(80),v,w,R=e(),B=e(),G=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,yt(g,l),w=0;w<16;w++)B[w]=g[w],q[w]=R[w]=G[w]=0;for(R[0]=q[0]=1,w=254;w>=0;--w)v=o[w>>>3]>>>(w&7)&1,Ue(R,B,v),Ue(G,q,v),N(Ce,R,G),S(R,R,G),N(G,B,q),S(B,B,q),Y(q,Ce),Y(V,R),C(R,G,R),C(G,B,Ce),N(Ce,R,G),S(R,R,G),Y(B,R),S(G,q,V),C(R,G,c),N(R,R,q),C(G,G,R),C(R,q,V),C(q,B,g),Y(B,Ce),Ue(R,B,v),Ue(G,q,v);for(w=0;w<16;w++)g[w+16]=R[w],g[w+32]=G[w],g[w+48]=B[w],g[w+64]=q[w];var re=g.subarray(32),ie=g.subarray(16);return ve(re,re),C(ie,ie,re),Te(f,ie),0}function wt(f,h){return vt(f,h,s)}function Et(f,h){return t(h,32),wt(f,h)}function nr(f,h,l){var o=new Uint8Array(32);return vt(o,l,h),j(f,i,o,te)}var Sr=ee,Vr=Ye;function Tr(f,h,l,o,g,v){var w=new Uint8Array(32);return nr(w,g,v),Sr(f,h,l,o,w)}function pi(f,h,l,o,g,v){var w=new Uint8Array(32);return nr(w,g,v),Vr(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 sf(f,h,l,o){for(var g=new Int32Array(16),v=new Int32Array(16),w,R,B,G,q,Ce,V,re,ie,le,fe,se,oe,ne,z,J,W,K,$,U,b,x,L,k,P,M,Z=f[0],he=f[1],pe=f[2],de=f[3],_=f[4],_e=f[5],Oe=f[6],ke=f[7],ge=h[0],be=h[1],xe=h[2],Xe=h[3],Ae=h[4],Ke=h[5],$e=h[6],Ge=h[7],Qe=0;o>=128;){for($=0;$<16;$++)U=8*$+Qe,g[$]=l[U+0]<<24|l[U+1]<<16|l[U+2]<<8|l[U+3],v[$]=l[U+4]<<24|l[U+5]<<16|l[U+6]<<8|l[U+7];for($=0;$<80;$++)if(w=Z,R=he,B=pe,G=de,q=_,Ce=_e,V=Oe,re=ke,ie=ge,le=be,fe=xe,se=Xe,oe=Ae,ne=Ke,z=$e,J=Ge,b=ke,x=Ge,L=x&65535,k=x>>>16,P=b&65535,M=b>>>16,b=(_>>>14|Ae<<18)^(_>>>18|Ae<<14)^(Ae>>>9|_<<23),x=(Ae>>>14|_<<18)^(Ae>>>18|_<<14)^(_>>>9|Ae<<23),L+=x&65535,k+=x>>>16,P+=b&65535,M+=b>>>16,b=_&_e^~_&Oe,x=Ae&Ke^~Ae&$e,L+=x&65535,k+=x>>>16,P+=b&65535,M+=b>>>16,b=Is[$*2],x=Is[$*2+1],L+=x&65535,k+=x>>>16,P+=b&65535,M+=b>>>16,b=g[$%16],x=v[$%16],L+=x&65535,k+=x>>>16,P+=b&65535,M+=b>>>16,k+=L>>>16,P+=k>>>16,M+=P>>>16,W=P&65535|M<<16,K=L&65535|k<<16,b=W,x=K,L=x&65535,k=x>>>16,P=b&65535,M=b>>>16,b=(Z>>>28|ge<<4)^(ge>>>2|Z<<30)^(ge>>>7|Z<<25),x=(ge>>>28|Z<<4)^(Z>>>2|ge<<30)^(Z>>>7|ge<<25),L+=x&65535,k+=x>>>16,P+=b&65535,M+=b>>>16,b=Z&he^Z&pe^he&pe,x=ge&be^ge&xe^be&xe,L+=x&65535,k+=x>>>16,P+=b&65535,M+=b>>>16,k+=L>>>16,P+=k>>>16,M+=P>>>16,re=P&65535|M<<16,J=L&65535|k<<16,b=G,x=se,L=x&65535,k=x>>>16,P=b&65535,M=b>>>16,b=W,x=K,L+=x&65535,k+=x>>>16,P+=b&65535,M+=b>>>16,k+=L>>>16,P+=k>>>16,M+=P>>>16,G=P&65535|M<<16,se=L&65535|k<<16,he=w,pe=R,de=B,_=G,_e=q,Oe=Ce,ke=V,Z=re,be=ie,xe=le,Xe=fe,Ae=se,Ke=oe,$e=ne,Ge=z,ge=J,$%16===15)for(U=0;U<16;U++)b=g[U],x=v[U],L=x&65535,k=x>>>16,P=b&65535,M=b>>>16,b=g[(U+9)%16],x=v[(U+9)%16],L+=x&65535,k+=x>>>16,P+=b&65535,M+=b>>>16,W=g[(U+1)%16],K=v[(U+1)%16],b=(W>>>1|K<<31)^(W>>>8|K<<24)^W>>>7,x=(K>>>1|W<<31)^(K>>>8|W<<24)^(K>>>7|W<<25),L+=x&65535,k+=x>>>16,P+=b&65535,M+=b>>>16,W=g[(U+14)%16],K=v[(U+14)%16],b=(W>>>19|K<<13)^(K>>>29|W<<3)^W>>>6,x=(K>>>19|W<<13)^(W>>>29|K<<3)^(K>>>6|W<<26),L+=x&65535,k+=x>>>16,P+=b&65535,M+=b>>>16,k+=L>>>16,P+=k>>>16,M+=P>>>16,g[U]=P&65535|M<<16,v[U]=L&65535|k<<16;b=Z,x=ge,L=x&65535,k=x>>>16,P=b&65535,M=b>>>16,b=f[0],x=h[0],L+=x&65535,k+=x>>>16,P+=b&65535,M+=b>>>16,k+=L>>>16,P+=k>>>16,M+=P>>>16,f[0]=Z=P&65535|M<<16,h[0]=ge=L&65535|k<<16,b=he,x=be,L=x&65535,k=x>>>16,P=b&65535,M=b>>>16,b=f[1],x=h[1],L+=x&65535,k+=x>>>16,P+=b&65535,M+=b>>>16,k+=L>>>16,P+=k>>>16,M+=P>>>16,f[1]=he=P&65535|M<<16,h[1]=be=L&65535|k<<16,b=pe,x=xe,L=x&65535,k=x>>>16,P=b&65535,M=b>>>16,b=f[2],x=h[2],L+=x&65535,k+=x>>>16,P+=b&65535,M+=b>>>16,k+=L>>>16,P+=k>>>16,M+=P>>>16,f[2]=pe=P&65535|M<<16,h[2]=xe=L&65535|k<<16,b=de,x=Xe,L=x&65535,k=x>>>16,P=b&65535,M=b>>>16,b=f[3],x=h[3],L+=x&65535,k+=x>>>16,P+=b&65535,M+=b>>>16,k+=L>>>16,P+=k>>>16,M+=P>>>16,f[3]=de=P&65535|M<<16,h[3]=Xe=L&65535|k<<16,b=_,x=Ae,L=x&65535,k=x>>>16,P=b&65535,M=b>>>16,b=f[4],x=h[4],L+=x&65535,k+=x>>>16,P+=b&65535,M+=b>>>16,k+=L>>>16,P+=k>>>16,M+=P>>>16,f[4]=_=P&65535|M<<16,h[4]=Ae=L&65535|k<<16,b=_e,x=Ke,L=x&65535,k=x>>>16,P=b&65535,M=b>>>16,b=f[5],x=h[5],L+=x&65535,k+=x>>>16,P+=b&65535,M+=b>>>16,k+=L>>>16,P+=k>>>16,M+=P>>>16,f[5]=_e=P&65535|M<<16,h[5]=Ke=L&65535|k<<16,b=Oe,x=$e,L=x&65535,k=x>>>16,P=b&65535,M=b>>>16,b=f[6],x=h[6],L+=x&65535,k+=x>>>16,P+=b&65535,M+=b>>>16,k+=L>>>16,P+=k>>>16,M+=P>>>16,f[6]=Oe=P&65535|M<<16,h[6]=$e=L&65535|k<<16,b=ke,x=Ge,L=x&65535,k=x>>>16,P=b&65535,M=b>>>16,b=f[7],x=h[7],L+=x&65535,k+=x>>>16,P+=b&65535,M+=b>>>16,k+=L>>>16,P+=k>>>16,M+=P>>>16,f[7]=ke=P&65535|M<<16,h[7]=Ge=L&65535|k<<16,Qe+=128,o-=128}return o}function zr(f,h,l){var o=new Int32Array(8),g=new Int32Array(8),v=new Uint8Array(256),w,R=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,g[0]=4089235720,g[1]=2227873595,g[2]=4271175723,g[3]=1595750129,g[4]=2917565137,g[5]=725511199,g[6]=4215389547,g[7]=327033209,sf(o,g,h,l),l%=128,w=0;w<l;w++)v[w]=h[R-l+w];for(v[l]=128,l=256-128*(l<112?1:0),v[l-9]=0,E(v,l-8,R/536870912|0,R<<3),sf(o,g,v,l),w=0;w<8;w++)E(f,8*w,o[w],g[w]);return 0}function Ls(f,h){var l=e(),o=e(),g=e(),v=e(),w=e(),R=e(),B=e(),G=e(),q=e();S(l,f[1],f[0]),S(q,h[1],h[0]),C(l,l,q),N(o,f[0],f[1]),N(q,h[0],h[1]),C(o,o,q),C(g,f[3],h[3]),C(g,g,d),C(v,f[2],h[2]),N(v,v,v),S(w,o,l),S(R,v,g),N(B,v,g),N(G,o,l),C(f[0],w,R),C(f[1],G,B),C(f[2],B,R),C(f[3],w,G)}function nf(f,h,l){var o;for(o=0;o<4;o++)Ue(f[o],h[o],l)}function yo(f,h){var l=e(),o=e(),g=e();ve(g,h[2]),C(l,h[0],g),C(o,h[1],g),Te(f,o),f[31]^=Ve(l)<<7}function vo(f,h,l){var o,g;for(Be(f[0],n),Be(f[1],a),Be(f[2],a),Be(f[3],n),g=255;g>=0;--g)o=l[g/8|0]>>(g&7)&1,nf(f,h,o),Ls(h,f),Ls(f,f),nf(f,h,o)}function Ns(f,h){var l=[e(),e(),e(),e()];Be(l[0],p),Be(l[1],m),Be(l[2],a),C(l[3],p,m),vo(f,l,h)}function wo(f,h,l){var o=new Uint8Array(64),g=[e(),e(),e(),e()],v;for(l||t(h,32),zr(o,h,32),o[0]&=248,o[31]&=127,o[31]|=64,Ns(g,o),yo(f,g),v=0;v<32;v++)h[v+32]=f[v];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 Eo(f,h){var l,o,g,v;for(o=63;o>=32;--o){for(l=0,g=o-32,v=o-12;g<v;++g)h[g]+=l-16*h[o]*Ds[g-(o-32)],l=Math.floor((h[g]+128)/256),h[g]-=l*256;h[g]+=l,h[o]=0}for(l=0,g=0;g<32;g++)h[g]+=l-(h[31]>>4)*Ds[g],l=h[g]>>8,h[g]&=255;for(g=0;g<32;g++)h[g]-=l*Ds[g];for(o=0;o<32;o++)h[o+1]+=h[o]>>8,f[o]=h[o]&255}function bo(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;Eo(f,h)}function of(f,h,l,o){var g=new Uint8Array(64),v=new Uint8Array(64),w=new Uint8Array(64),R,B,G=new Float64Array(64),q=[e(),e(),e(),e()];zr(g,o,32),g[0]&=248,g[31]&=127,g[31]|=64;var Ce=l+64;for(R=0;R<l;R++)f[64+R]=h[R];for(R=0;R<32;R++)f[32+R]=g[32+R];for(zr(w,f.subarray(32),l+32),bo(w),Ns(q,w),yo(f,q),R=32;R<64;R++)f[R]=o[R];for(zr(v,f,l+64),bo(v),R=0;R<64;R++)G[R]=0;for(R=0;R<32;R++)G[R]=w[R];for(R=0;R<32;R++)for(B=0;B<32;B++)G[R+B]+=v[R]*g[B];return Eo(f.subarray(32),G),Ce}function zd(f,h){var l=e(),o=e(),g=e(),v=e(),w=e(),R=e(),B=e();return Be(f[2],a),yt(f[1],h),Y(g,f[1]),C(v,g,u),S(g,g,f[2]),N(v,f[2],v),Y(w,v),Y(R,w),C(B,R,w),C(l,B,g),C(l,l,v),et(l,l),C(l,l,g),C(l,l,v),C(l,l,v),C(f[0],l,v),Y(o,f[0]),C(o,o,v),nt(o,g)&&C(f[0],f[0],y),Y(o,f[0]),C(o,o,v),nt(o,g)?-1:(Ve(f[0])===h[31]>>7&&S(f[0],n,f[0]),C(f[3],f[0],f[1]),0)}function xo(f,h,l,o){var g,v=new Uint8Array(32),w=new Uint8Array(64),R=[e(),e(),e(),e()],B=[e(),e(),e(),e()];if(l<64||zd(B,o))return-1;for(g=0;g<l;g++)f[g]=h[g];for(g=0;g<32;g++)f[g+32]=o[g];if(zr(w,f,l),bo(w),vo(R,B,w),Ns(B,h.subarray(32)),Ls(R,B),yo(v,R),l-=64,H(h,0,v,0)){for(g=0;g<l;g++)f[g]=0;return-1}for(g=0;g<l;g++)f[g]=h[g+64];return l}var So=32,Ms=24,Gi=32,gi=16,Yi=32,Fs=32,Xi=32,Ji=32,To=32,af=Ms,Kd=Gi,$d=gi,or=64,Kr=32,mi=64,Co=32,Oo=64;r.lowlevel={crypto_core_hsalsa20:j,crypto_stream_xor:Q,crypto_stream:ue,crypto_stream_salsa20_xor:I,crypto_stream_salsa20:ae,crypto_onetimeauth:Ee,crypto_onetimeauth_verify:Je,crypto_verify_16:O,crypto_verify_32:H,crypto_secretbox:ee,crypto_secretbox_open:Ye,crypto_scalarmult:vt,crypto_scalarmult_base:wt,crypto_box_beforenm:nr,crypto_box_afternm:Sr,crypto_box:Tr,crypto_box_open:pi,crypto_box_keypair:Et,crypto_hash:zr,crypto_sign:of,crypto_sign_keypair:wo,crypto_sign_open:xo,crypto_secretbox_KEYBYTES:So,crypto_secretbox_NONCEBYTES:Ms,crypto_secretbox_ZEROBYTES:Gi,crypto_secretbox_BOXZEROBYTES:gi,crypto_scalarmult_BYTES:Yi,crypto_scalarmult_SCALARBYTES:Fs,crypto_box_PUBLICKEYBYTES:Xi,crypto_box_SECRETKEYBYTES:Ji,crypto_box_BEFORENMBYTES:To,crypto_box_NONCEBYTES:af,crypto_box_ZEROBYTES:Kd,crypto_box_BOXZEROBYTES:$d,crypto_sign_BYTES:or,crypto_sign_PUBLICKEYBYTES:Kr,crypto_sign_SECRETKEYBYTES:mi,crypto_sign_SEEDBYTES:Co,crypto_hash_BYTES:Oo,gf:e,D:u,L:Ds,pack25519:Te,unpack25519:yt,M:C,A:N,S:Y,Z:S,pow2523:et,add:Ls,set25519:Be,modL:Eo,scalarmult:vo,scalarbase:Ns};function cf(f,h){if(f.length!==So)throw new Error("bad key size");if(h.length!==Ms)throw new Error("bad nonce size")}function Gd(f,h){if(f.length!==Xi)throw new Error("bad public key size");if(h.length!==Ji)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 ff(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),cf(l,h);for(var o=new Uint8Array(Gi+f.length),g=new Uint8Array(o.length),v=0;v<f.length;v++)o[v+Gi]=f[v];return ee(g,o,o.length,h,l),g.subarray(gi)},r.secretbox.open=function(f,h,l){bt(f,h,l),cf(l,h);for(var o=new Uint8Array(gi+f.length),g=new Uint8Array(o.length),v=0;v<f.length;v++)o[v+gi]=f[v];return o.length<32||Ye(g,o,o.length,h,l)!==0?null:g.subarray(Gi)},r.secretbox.keyLength=So,r.secretbox.nonceLength=Ms,r.secretbox.overheadLength=gi,r.scalarMult=function(f,h){if(bt(f,h),f.length!==Fs)throw new Error("bad n size");if(h.length!==Yi)throw new Error("bad p size");var l=new Uint8Array(Yi);return vt(l,f,h),l},r.scalarMult.base=function(f){if(bt(f),f.length!==Fs)throw new Error("bad n size");var h=new Uint8Array(Yi);return wt(h,f),h},r.scalarMult.scalarLength=Fs,r.scalarMult.groupElementLength=Yi,r.box=function(f,h,l,o){var g=r.box.before(l,o);return r.secretbox(f,h,g)},r.box.before=function(f,h){bt(f,h),Gd(f,h);var l=new Uint8Array(To);return nr(l,f,h),l},r.box.after=r.secretbox,r.box.open=function(f,h,l,o){var g=r.box.before(l,o);return r.secretbox.open(f,h,g)},r.box.open.after=r.secretbox.open,r.box.keyPair=function(){var f=new Uint8Array(Xi),h=new Uint8Array(Ji);return Et(f,h),{publicKey:f,secretKey:h}},r.box.keyPair.fromSecretKey=function(f){if(bt(f),f.length!==Ji)throw new Error("bad secret key size");var h=new Uint8Array(Xi);return wt(h,f),{publicKey:h,secretKey:new Uint8Array(f)}},r.box.publicKeyLength=Xi,r.box.secretKeyLength=Ji,r.box.sharedKeyLength=To,r.box.nonceLength=af,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(f,h){if(bt(f,h),h.length!==mi)throw new Error("bad secret key size");var l=new Uint8Array(or+f.length);return of(l,f,f.length,h),l},r.sign.open=function(f,h){if(bt(f,h),h.length!==Kr)throw new Error("bad public key size");var l=new Uint8Array(f.length),o=xo(l,f,f.length,h);if(o<0)return null;for(var g=new Uint8Array(o),v=0;v<g.length;v++)g[v]=l[v];return g},r.sign.detached=function(f,h){for(var l=r.sign(f,h),o=new Uint8Array(or),g=0;g<o.length;g++)o[g]=l[g];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!==Kr)throw new Error("bad public key size");var o=new Uint8Array(or+f.length),g=new Uint8Array(or+f.length),v;for(v=0;v<or;v++)o[v]=h[v];for(v=0;v<f.length;v++)o[v+or]=f[v];return xo(g,o,o.length,l)>=0},r.sign.keyPair=function(){var f=new Uint8Array(Kr),h=new Uint8Array(mi);return wo(f,h),{publicKey:f,secretKey:h}},r.sign.keyPair.fromSecretKey=function(f){if(bt(f),f.length!==mi)throw new Error("bad secret key size");for(var h=new Uint8Array(Kr),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!==Co)throw new Error("bad seed size");for(var h=new Uint8Array(Kr),l=new Uint8Array(mi),o=0;o<32;o++)l[o]=f[o];return wo(h,l,!0),{publicKey:h,secretKey:l}},r.sign.publicKeyLength=Kr,r.sign.secretKeyLength=mi,r.sign.seedLength=Co,r.sign.signatureLength=or,r.hash=function(f){bt(f);var h=new Uint8Array(Oo);return zr(h,f,f.length),h},r.hash.hashLength=Oo,r.verify=function(f,h){return bt(f,h),f.length===0||h.length===0||f.length!==h.length?!1:T(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 g,v=new Uint8Array(o);for(g=0;g<o;g+=h)f.getRandomValues(v.subarray(g,g+Math.min(o-g,h)));for(g=0;g<o;g++)l[g]=v[g];ff(v)})}else typeof require<"u"&&(f=require("crypto"),f&&f.randomBytes&&r.setPRNG(function(l,o){var g,v=f.randomBytes(o);for(g=0;g<o;g++)l[g]=v[g];ff(v)}))})()})(typeof Ys<"u"&&Ys.exports?Ys.exports:self.nacl=self.nacl||{})});var Lo=F((Rf,Xs)=>{(function(r,e){"use strict";typeof Xs<"u"&&Xs.exports?Xs.exports=e():(r.nacl||(r.nacl={}),r.nacl.util=e())})(Rf,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 i,s=unescape(encodeURIComponent(t)),n=new Uint8Array(s.length);for(i=0;i<s.length;i++)n[i]=s.charCodeAt(i);return n},r.encodeUTF8=function(t){var i,s=[];for(i=0;i<t.length;i++)s.push(String.fromCharCode(t[i]));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 i,s=[],n=t.length;for(i=0;i<n;i++)s.push(String.fromCharCode(t[i]));return btoa(s.join(""))},r.decodeBase64=function(t){e(t);var i,s=atob(t),n=new Uint8Array(s.length);for(i=0;i<s.length;i++)n[i]=s.charCodeAt(i);return n}),r})});var Pf=F(kr=>{"use strict";var mp=kr&&kr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(kr,"__esModule",{value:!0});kr.encrypt=_p;kr.decrypt=yp;kr.encryptBinary=vp;kr.decryptBinary=wp;var fr=mp(Io()),Or=Lo();function _p(r,e,t){let i=fr.default.randomBytes(fr.default.secretbox.nonceLength),s=new TextEncoder().encode(r),n=fr.default.secretbox(s,i,e);return{v:1,sid:t,n:(0,Or.encodeBase64)(i),c:(0,Or.encodeBase64)(n)}}function yp(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Or.decodeBase64)(r.n),i=(0,Or.decodeBase64)(r.c);if(t.length!==fr.default.secretbox.nonceLength)throw new Error(`Invalid nonce length: ${t.length}`);let s=fr.default.secretbox.open(i,t,e);if(!s)throw new Error("Decryption failed: invalid ciphertext or wrong key");return new TextDecoder().decode(s)}function vp(r,e,t){let i=fr.default.randomBytes(fr.default.secretbox.nonceLength),s=fr.default.secretbox(r,i,e);return{v:1,sid:t,n:(0,Or.encodeBase64)(i),c:(0,Or.encodeBase64)(s)}}function wp(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Or.decodeBase64)(r.n),i=(0,Or.decodeBase64)(r.c),s=fr.default.secretbox.open(i,t,e);if(!s)throw new Error("Decryption failed: invalid ciphertext or wrong key");return s}});var Af=F(Kt=>{"use strict";var Ep=Kt&&Kt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Kt,"__esModule",{value:!0});Kt.generateKeyPair=bp;Kt.deriveSharedSecret=xp;Kt.isValidPublicKey=Sp;Kt.clearKey=Tp;Kt.keyToBase64=Cp;Kt.base64ToKey=Op;var ts=Ep(Io()),$r=Lo();function bp(){let r=ts.default.box.keyPair();return{publicKey:(0,$r.encodeBase64)(r.publicKey),secretKey:(0,$r.encodeBase64)(r.secretKey)}}function xp(r,e){let t=(0,$r.decodeBase64)(r),i=(0,$r.decodeBase64)(e);if(t.length!==ts.default.box.publicKeyLength)throw new Error(`Invalid public key length: ${t.length}`);if(i.length!==ts.default.box.secretKeyLength)throw new Error(`Invalid secret key length: ${i.length}`);return ts.default.box.before(t,i)}function Sp(r){try{return(0,$r.decodeBase64)(r).length===ts.default.box.publicKeyLength}catch{return!1}}function Tp(r){r.fill(0)}function Cp(r){return(0,$r.encodeBase64)(r)}function Op(r){return(0,$r.decodeBase64)(r)}});var Lf=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 If=kf();Object.defineProperty(De,"isEncryptedPayload",{enumerable:!0,get:function(){return If.isEncryptedPayload}});Object.defineProperty(De,"isMultiRecipientPayload",{enumerable:!0,get:function(){return If.isMultiRecipientPayload}});var Js=Pf();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 yi=Af();Object.defineProperty(De,"generateKeyPair",{enumerable:!0,get:function(){return yi.generateKeyPair}});Object.defineProperty(De,"deriveSharedSecret",{enumerable:!0,get:function(){return yi.deriveSharedSecret}});Object.defineProperty(De,"isValidPublicKey",{enumerable:!0,get:function(){return yi.isValidPublicKey}});Object.defineProperty(De,"clearKey",{enumerable:!0,get:function(){return yi.clearKey}});Object.defineProperty(De,"keyToBase64",{enumerable:!0,get:function(){return yi.keyToBase64}});Object.defineProperty(De,"base64ToKey",{enumerable:!0,get:function(){return yi.base64ToKey}})});var Nf=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=kp;xt.compareVersions=Rp;xt.PROTOCOL_VERSION="2.1";xt.PROTOCOL_VERSION_MAJOR=2;xt.PROTOCOL_VERSION_MINOR=1;xt.MIN_CLIENT_VERSION="2.0";function kp(r){let[e]=r.split(".").map(Number);return e===xt.PROTOCOL_VERSION_MAJOR}function Rp(r,e){let[t,i]=r.split(".").map(Number),[s,n]=e.split(".").map(Number);return t!==s?t<s?-1:1:i!==n?i<n?-1:1:0}});var Df=F($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.SERVER_CAPABILITIES=$t.DEFAULT_CLIENT_CAPABILITIES=$t.Capability=void 0;$t.hasCapability=Pp;$t.negotiateCapabilities=Ap;var vi;(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",r.RELIABLE_INPUT="reliable-input",r.MULTI_VIEWER_RENDER="multi-viewer-render"})(vi||($t.Capability=vi={}));$t.DEFAULT_CLIENT_CAPABILITIES=[vi.E2E_ENCRYPTION,vi.TERMINAL_EVENTS,vi.RELIABLE_INPUT];$t.SERVER_CAPABILITIES=Object.values(vi);function Pp(r,e){return r.includes(e)}function Ap(r,e){return r.filter(t=>e.includes(t))}});var Mf=F(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.DEFAULT_PRIORITY=ur.PRIORITY_NAMES=ur.Priority=void 0;ur.comparePriority=Ip;var Gr;(function(r){r[r.CRITICAL=0]="CRITICAL",r[r.HIGH=1]="HIGH",r[r.NORMAL=2]="NORMAL",r[r.LOW=3]="LOW"})(Gr||(ur.Priority=Gr={}));ur.PRIORITY_NAMES={[Gr.CRITICAL]:"CRITICAL",[Gr.HIGH]:"HIGH",[Gr.NORMAL]:"NORMAL",[Gr.LOW]:"LOW"};ur.DEFAULT_PRIORITY=Gr.NORMAL;function Ip(r,e){return r-e}});var Ff=F(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.DEFAULT_RELIABILITY=Gt.RELIABILITY_NAMES=Gt.Reliability=void 0;Gt.requiresAck=Lp;Gt.requiresBuffer=Np;var Rr;(function(r){r[r.FIRE_FORGET=0]="FIRE_FORGET",r[r.BUFFERED=1]="BUFFERED",r[r.GUARANTEED=2]="GUARANTEED"})(Rr||(Gt.Reliability=Rr={}));Gt.RELIABILITY_NAMES={[Rr.FIRE_FORGET]:"FIRE_FORGET",[Rr.BUFFERED]:"BUFFERED",[Rr.GUARANTEED]:"GUARANTEED"};Gt.DEFAULT_RELIABILITY=Rr.FIRE_FORGET;function Lp(r){return r===Rr.GUARANTEED}function Np(r){return r>=Rr.BUFFERED}});var Bf=F(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});No.createMessage=Dp;function Dp(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 jf=F(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.TerminalEventType=void 0;Yr.deriveStatusFromEvent=Mp;Yr.shouldTriggerPushNotification=Fp;Yr.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||(Yr.TerminalEventType=lt={}));function Mp(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 Fp(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 Wf=F(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.TransferDirection=qe.TransferStatus=qe.CHUNK_TTL_SECONDS=qe.TRANSFER_TTL_SECONDS=qe.MAX_RETRIES=qe.ACK_TIMEOUT_MS=qe.WINDOW_SIZE=qe.DEFAULT_MAX_FILE_SIZE=qe.CHUNK_SIZE=void 0;qe.calculateTotalChunks=jp;qe.getMissingChunks=Up;qe.isTransferComplete=qp;qe.CHUNK_SIZE=64*1024;qe.DEFAULT_MAX_FILE_SIZE=100*1024*1024;qe.WINDOW_SIZE=10;qe.ACK_TIMEOUT_MS=3e4;qe.MAX_RETRIES=3;qe.TRANSFER_TTL_SECONDS=1440*60;qe.CHUNK_TTL_SECONDS=1440*60;var Uf;(function(r){r.PENDING="pending",r.ACTIVE="active",r.PAUSED="paused",r.COMPLETED="completed",r.FAILED="failed",r.CANCELLED="cancelled",r.EXPIRED="expired"})(Uf||(qe.TransferStatus=Uf={}));var qf;(function(r){r.DOWNLOAD="download",r.UPLOAD="upload"})(qf||(qe.TransferDirection=qf={}));function jp(r,e=qe.CHUNK_SIZE){return Math.ceil(r/e)}function Up(r,e){let t=new Set(e),i=[];for(let s=0;s<r;s++)t.has(s)||i.push(s);return i}function qp(r,e){return e.length===r}});var Hf=F(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.ERROR_MESSAGES=lr.ErrorCode=void 0;lr.createError=Wp;lr.isRetryableError=Hp;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 Wp(r,e={}){return{code:r,message:e.message||lr.ERROR_MESSAGES[r],details:e.details,retryable:e.retryable??!1,retryAfter:e.retryAfter}}function Hp(r){return[Pe.RATE_LIMITED,Pe.TIMEOUT,Pe.CONNECTION_LOST,Pe.SERVICE_UNAVAILABLE].includes(r)}});var $f=F(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.FileEntryType=St.DiffBase=St.FileViewType=St.FileChangeType=void 0;St.getLanguageFromPath=Vp;St.parseUnifiedDiff=zp;St.createSimpleDiff=Kp;var Pr;(function(r){r.CREATE="create",r.MODIFY="modify",r.DELETE="delete"})(Pr||(St.FileChangeType=Pr={}));var Vf;(function(r){r.CONTENT="content",r.DIFF="diff"})(Vf||(St.FileViewType=Vf={}));var zf;(function(r){r.GIT="git",r.PREVIOUS="previous"})(zf||(St.DiffBase=zf={}));function Vp(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"},i=r.split("/").pop()?.toLowerCase()||"";return{dockerfile:"dockerfile",makefile:"makefile",".gitignore":"plaintext",".env":"plaintext",".env.local":"plaintext",".env.development":"plaintext",".env.production":"plaintext"}[i]||t[e||""]||"plaintext"}function zp(r,e){let t=r.split(`
3
+ `),i=[],s=0,n=0,a=null,c=0,u=0;for(let p of t){if(p.startsWith("diff ")||p.startsWith("index ")||p.startsWith("---")||p.startsWith("+++"))continue;let m=p.match(/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@/);if(m){a&&i.push(a);let y=parseInt(m[1],10),E=parseInt(m[2]||"1",10),T=parseInt(m[3],10),O=parseInt(m[4]||"1",10);a={oldStart:y,oldLines:E,newStart:T,newLines:O,lines:[]},c=y,u=T;continue}a&&(p.startsWith("+")?(a.lines.push({type:"add",content:p.slice(1),oldLineNumber:null,newLineNumber:u++}),s++):p.startsWith("-")?(a.lines.push({type:"remove",content:p.slice(1),oldLineNumber:c++,newLineNumber:null}),n++):(p.startsWith(" ")||p==="")&&a.lines.push({type:"context",content:p.startsWith(" ")?p.slice(1):p,oldLineNumber:c++,newLineNumber:u++}))}a&&i.push(a);let d;return n===0&&s>0&&i.length===1&&i[0].oldLines===0?d=Pr.CREATE:s===0&&n>0&&i.length===1&&i[0].newLines===0?d=Pr.DELETE:d=Pr.MODIFY,{path:e,changeType:d,hunks:i,additions:s,deletions:n,isBinary:!1}}function Kp(r,e,t){let i=r.split(`
4
4
  `),s=e.split(`
5
- `),n=[],a=0,c=0,u=Math.max(i.length,s.length);for(let g=0;g<u;g++){let m=i[g],y=s[g];m===y?m!==void 0&&n.push({type:"context",content:m,oldLineNumber:g+1,newLineNumber:g+1}):(m!==void 0&&(n.push({type:"remove",content:m,oldLineNumber:g+1,newLineNumber:null}),c++),y!==void 0&&(n.push({type:"add",content:y,oldLineNumber:null,newLineNumber:g+1}),a++))}let d;return r===""?d=Pr.CREATE:e===""?d=Pr.DELETE:d=Pr.MODIFY,{path:t,changeType:d,hunks:[{oldStart:1,oldLines:i.length,newStart:1,newLines:s.length,lines:n}],additions:a,deletions:c,isBinary:!1}}var zf;(function(r){r.FILE="file",r.DIRECTORY="directory"})(zf||(St.FileEntryType=zf={}))});var Gf=F(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.createSimpleDiff=D.parseUnifiedDiff=D.getLanguageFromPath=D.FileEntryType=D.DiffBase=D.FileViewType=D.FileChangeType=D.isRetryableError=D.createError=D.ERROR_MESSAGES=D.ErrorCode=D.isTransferComplete=D.getMissingChunks=D.calculateTotalChunks=D.TransferDirection=D.TransferStatus=D.CHUNK_TTL_SECONDS=D.TRANSFER_TTL_SECONDS=D.MAX_RETRIES=D.ACK_TIMEOUT_MS=D.WINDOW_SIZE=D.DEFAULT_MAX_FILE_SIZE=D.CHUNK_SIZE=D.getPushNotificationMessage=D.shouldTriggerPushNotification=D.deriveStatusFromEvent=D.TerminalEventType=D.createMessage=D.requiresBuffer=D.requiresAck=D.DEFAULT_RELIABILITY=D.RELIABILITY_NAMES=D.Reliability=D.comparePriority=D.DEFAULT_PRIORITY=D.PRIORITY_NAMES=D.Priority=D.negotiateCapabilities=D.hasCapability=D.SERVER_CAPABILITIES=D.DEFAULT_CLIENT_CAPABILITIES=D.Capability=D.compareVersions=D.isCompatibleVersion=D.MIN_CLIENT_VERSION=D.PROTOCOL_VERSION_MINOR=D.PROTOCOL_VERSION_MAJOR=D.PROTOCOL_VERSION=void 0;var Ei=Nf();Object.defineProperty(D,"PROTOCOL_VERSION",{enumerable:!0,get:function(){return Ei.PROTOCOL_VERSION}});Object.defineProperty(D,"PROTOCOL_VERSION_MAJOR",{enumerable:!0,get:function(){return Ei.PROTOCOL_VERSION_MAJOR}});Object.defineProperty(D,"PROTOCOL_VERSION_MINOR",{enumerable:!0,get:function(){return Ei.PROTOCOL_VERSION_MINOR}});Object.defineProperty(D,"MIN_CLIENT_VERSION",{enumerable:!0,get:function(){return Ei.MIN_CLIENT_VERSION}});Object.defineProperty(D,"isCompatibleVersion",{enumerable:!0,get:function(){return Ei.isCompatibleVersion}});Object.defineProperty(D,"compareVersions",{enumerable:!0,get:function(){return Ei.compareVersions}});var rs=Df();Object.defineProperty(D,"Capability",{enumerable:!0,get:function(){return rs.Capability}});Object.defineProperty(D,"DEFAULT_CLIENT_CAPABILITIES",{enumerable:!0,get:function(){return rs.DEFAULT_CLIENT_CAPABILITIES}});Object.defineProperty(D,"SERVER_CAPABILITIES",{enumerable:!0,get:function(){return rs.SERVER_CAPABILITIES}});Object.defineProperty(D,"hasCapability",{enumerable:!0,get:function(){return rs.hasCapability}});Object.defineProperty(D,"negotiateCapabilities",{enumerable:!0,get:function(){return rs.negotiateCapabilities}});var Zs=Mf();Object.defineProperty(D,"Priority",{enumerable:!0,get:function(){return Zs.Priority}});Object.defineProperty(D,"PRIORITY_NAMES",{enumerable:!0,get:function(){return Zs.PRIORITY_NAMES}});Object.defineProperty(D,"DEFAULT_PRIORITY",{enumerable:!0,get:function(){return Zs.DEFAULT_PRIORITY}});Object.defineProperty(D,"comparePriority",{enumerable:!0,get:function(){return Zs.comparePriority}});var is=Ff();Object.defineProperty(D,"Reliability",{enumerable:!0,get:function(){return is.Reliability}});Object.defineProperty(D,"RELIABILITY_NAMES",{enumerable:!0,get:function(){return is.RELIABILITY_NAMES}});Object.defineProperty(D,"DEFAULT_RELIABILITY",{enumerable:!0,get:function(){return is.DEFAULT_RELIABILITY}});Object.defineProperty(D,"requiresAck",{enumerable:!0,get:function(){return is.requiresAck}});Object.defineProperty(D,"requiresBuffer",{enumerable:!0,get:function(){return is.requiresBuffer}});var $p=Bf();Object.defineProperty(D,"createMessage",{enumerable:!0,get:function(){return $p.createMessage}});var Qs=jf();Object.defineProperty(D,"TerminalEventType",{enumerable:!0,get:function(){return Qs.TerminalEventType}});Object.defineProperty(D,"deriveStatusFromEvent",{enumerable:!0,get:function(){return Qs.deriveStatusFromEvent}});Object.defineProperty(D,"shouldTriggerPushNotification",{enumerable:!0,get:function(){return Qs.shouldTriggerPushNotification}});Object.defineProperty(D,"getPushNotificationMessage",{enumerable:!0,get:function(){return Qs.getPushNotificationMessage}});var kt=Wf();Object.defineProperty(D,"CHUNK_SIZE",{enumerable:!0,get:function(){return kt.CHUNK_SIZE}});Object.defineProperty(D,"DEFAULT_MAX_FILE_SIZE",{enumerable:!0,get:function(){return kt.DEFAULT_MAX_FILE_SIZE}});Object.defineProperty(D,"WINDOW_SIZE",{enumerable:!0,get:function(){return kt.WINDOW_SIZE}});Object.defineProperty(D,"ACK_TIMEOUT_MS",{enumerable:!0,get:function(){return kt.ACK_TIMEOUT_MS}});Object.defineProperty(D,"MAX_RETRIES",{enumerable:!0,get:function(){return kt.MAX_RETRIES}});Object.defineProperty(D,"TRANSFER_TTL_SECONDS",{enumerable:!0,get:function(){return kt.TRANSFER_TTL_SECONDS}});Object.defineProperty(D,"CHUNK_TTL_SECONDS",{enumerable:!0,get:function(){return kt.CHUNK_TTL_SECONDS}});Object.defineProperty(D,"TransferStatus",{enumerable:!0,get:function(){return kt.TransferStatus}});Object.defineProperty(D,"TransferDirection",{enumerable:!0,get:function(){return kt.TransferDirection}});Object.defineProperty(D,"calculateTotalChunks",{enumerable:!0,get:function(){return kt.calculateTotalChunks}});Object.defineProperty(D,"getMissingChunks",{enumerable:!0,get:function(){return kt.getMissingChunks}});Object.defineProperty(D,"isTransferComplete",{enumerable:!0,get:function(){return kt.isTransferComplete}});var en=Hf();Object.defineProperty(D,"ErrorCode",{enumerable:!0,get:function(){return en.ErrorCode}});Object.defineProperty(D,"ERROR_MESSAGES",{enumerable:!0,get:function(){return en.ERROR_MESSAGES}});Object.defineProperty(D,"createError",{enumerable:!0,get:function(){return en.createError}});Object.defineProperty(D,"isRetryableError",{enumerable:!0,get:function(){return en.isRetryableError}});var Xr=$f();Object.defineProperty(D,"FileChangeType",{enumerable:!0,get:function(){return Xr.FileChangeType}});Object.defineProperty(D,"FileViewType",{enumerable:!0,get:function(){return Xr.FileViewType}});Object.defineProperty(D,"DiffBase",{enumerable:!0,get:function(){return Xr.DiffBase}});Object.defineProperty(D,"FileEntryType",{enumerable:!0,get:function(){return Xr.FileEntryType}});Object.defineProperty(D,"getLanguageFromPath",{enumerable:!0,get:function(){return Xr.getLanguageFromPath}});Object.defineProperty(D,"parseUnifiedDiff",{enumerable:!0,get:function(){return Xr.parseUnifiedDiff}});Object.defineProperty(D,"createSimpleDiff",{enumerable:!0,get:function(){return Xr.createSimpleDiff}})});var hr=F(Yt=>{"use strict";var Gp=Yt&&Yt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=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,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),tn=Yt&&Yt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Gp(e,r,t)};Object.defineProperty(Yt,"__esModule",{value:!0});tn(Cf(),Yt);tn(Of(),Yt);tn(Lf(),Yt);tn(Gf(),Yt)});var Xf=F(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.CryptoService=void 0;var ft=hr(),Yp=3600*1e3,Yf=10,Do=class{storage;logger;sessions=new Map;agentSessions=new Map;keyPair=null;publicKeyKey;secretKeyKey;keyVersionKey;constructor(e,t,i,s){this.storage=e,this.logger=t;let n=`termiq.${i}.${s}`;this.publicKeyKey=`${n}.crypto.publicKey`,this.secretKeyKey=`${n}.crypto.secretKey`,this.keyVersionKey=`${n}.crypto.keyVersion`,this.logger.info("CryptoService namespace",i,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,ft.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,i){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,i);try{let s=this.sessions.get(e);s||(s=new Map,this.sessions.set(e,s));let n=(0,ft.deriveSharedSecret)(t,this.keyPair.secretKey),a={terminalId:e,clientPublicKey:t,sharedSecret:n,createdAt:Date.now(),sessionId:i};return s.set(i,a),this.logger.info("Key exchange completed",e,i,"total:",s.size),!0}catch(s){return this.logger.error("Key exchange failed",s),!1}}encryptOutput(e,t){let i=this.sessions.get(e);if(!i||i.size===0)return null;try{if(i.size===1){let n=i.values().next().value;return n?(0,ft.encrypt)(t,n.sharedSecret,n.sessionId):null}let s=[];for(let n of i.values()){let a=(0,ft.encrypt)(t,n.sharedSecret,n.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 i=this.sessions.get(e);if(!i)return this.logger.error("No sessions for terminal",e),null;let s=i.get(t.sid);if(!s)return this.logger.error("No session for sessionId",t.sid),null;try{return(0,ft.decrypt)(t,s.sharedSecret)}catch(n){return this.logger.error("Decryption failed",n),null}}hasSession(e){let t=this.sessions.get(e);return t!==void 0&&t.size>0}removeSession(e,t){let i=this.sessions.get(e);if(i)if(t){let s=i.get(t);s&&((0,ft.clearKey)(s.sharedSecret),i.delete(t),this.logger.info("Session removed",e,t)),i.size===0&&this.sessions.delete(e)}else{for(let s of i.values())(0,ft.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,ft.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 i=Date.now(),s=[];for(let[n,a]of t)i-a.createdAt>Yp&&s.push(n);for(let n of s){let a=t.get(n);a&&((0,ft.clearKey)(a.sharedSecret),t.delete(n))}if(t.size>Yf){let a=Array.from(t.entries()).sort((c,u)=>c[1].createdAt-u[1].createdAt).slice(0,t.size-Yf);for(let[,c]of a)(0,ft.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,i]of this.sessions.entries())for(let s of i.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 i=this.agentSessions.get(t);i&&(this.logger.info("Rekeying existing agent session",t),(0,ft.clearKey)(i.sharedSecret));let s=(0,ft.deriveSharedSecret)(e,this.keyPair.secretKey),n={sessionId:t,clientPublicKey:e,sharedSecret:s,createdAt:Date.now()};return this.agentSessions.set(t,n),this.logger.info("Agent key exchange completed",t,"total:",this.agentSessions.size),!0}catch(i){return this.logger.error("Agent key exchange failed",i),!1}}removeAgentSession(e){let t=this.agentSessions.get(e);t&&((0,ft.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),i=this.encryptForAllAgentSessions(t);return i?{encrypted:i}:null}encryptTerminalInfo(e){if(this.agentSessions.size===0)return null;let t=JSON.stringify(e),i=this.encryptForAllAgentSessions(t);return i?{encrypted:i}:null}encryptPromptInfo(e){if(this.agentSessions.size===0)return null;let t=JSON.stringify(e),i=this.encryptForAllAgentSessions(t);return i?{encrypted:i}:null}encryptForAllAgentSessions(e){if(this.agentSessions.size===0)return null;try{if(this.agentSessions.size===1){let i=this.agentSessions.values().next().value;return i?(0,ft.encrypt)(e,i.sharedSecret,i.sessionId):null}let t=[];for(let i of this.agentSessions.values()){let s=(0,ft.encrypt)(e,i.sharedSecret,i.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,ft.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")}};rn.CryptoService=Do});var Jf=F(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.AuthService=void 0;var ss=Ks(),Mo=class{storage;cryptoService;machineId;config;logger;notification;browser;pollingAbortController=null;tokenKey;refreshTokenKey;agentIdKey;constructor(e,t,i,s,n,a,c,u,d){this.storage=e,this.cryptoService=t,this.machineId=i,this.config=s,this.logger=n,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(),i=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,i);let n=await fetch(`${e}/auth/device/code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machineId:t,machineName:i,publicKey:s})});if(!n.ok){let a=await n.text();throw new Error(`Failed to get device code: ${a}`)}return n.json()}async pollForToken(e){this.cancelPolling();let t=(0,ss.getApiUrl)(this.config),i=5e3,s=60;this.pollingAbortController=new AbortController;let n=this.pollingAbortController.signal;this.logger.info("Starting token polling");for(let a=0;a<s;a++){if(n.aborted)return this.logger.info("Polling was cancelled"),null;if(await this.sleep(i),n.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:n});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(n.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),i=await this.machineId.getMachineId(),s=this.machineId.getMachineName(),n=await this.cryptoService.getPublicKey();n||(await this.cryptoService.generateIdentityKeyPair(),n=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:i,machineName:s,publicKey:n})});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 i=JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()).exp*1e3;return Date.now()<i}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 i=await fetch(`${t}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!i.ok)return this.logger.warn("Token refresh failed",String(i.status)),i.status===401&&await this.storage.delete(this.refreshTokenKey),null;let s=await i.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(i){return this.logger.warn("Token refresh error",i),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 i=await fetch(`${t}/users/me/limits`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});return i.ok?await i.json():(this.logger.error("Failed to fetch limits",String(i.status)),null)}catch(i){let s=i instanceof Error?i.message:String(i);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))}};sn.AuthService=Mo});var Zf=F(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.StatusDetector=void 0;var nn={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]},ns={IDLE_TIMEOUT_MS:5e3,DEBOUNCE_MS:500,BUFFER_SIZE:2e3,WORKING_TIMEOUT_MS:3e4},Fo=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 i=this.states.get(e);if(!i)return;i.lastOutput=Date.now(),i.outputBuffer+=t,i.outputBuffer.length>ns.BUFFER_SIZE&&(i.outputBuffer=i.outputBuffer.slice(-ns.BUFFER_SIZE));let s=this.analyzeOutput(i.outputBuffer);s&&this.scheduleStatusUpdate(e,s),this.resetWorkingTimeout(e,i)}onCommandStart(e){let t=this.states.get(e);t&&(t.outputBuffer="",this.scheduleStatusUpdate(e,"working"),this.resetWorkingTimeout(e,t))}onCommandEnd(e,t){let i=this.states.get(e);if(!i)return;i.workingTimeout&&(clearTimeout(i.workingTimeout),i.workingTimeout=null);let s;if(t!==void 0&&t!==0)s="error";else{let n=this.analyzeOutput(i.outputBuffer);n==="waiting"?s="waiting":n==="error"?s="error":n==="completed"?s="completed":s="idle"}this.scheduleStatusUpdate(e,s),(s==="completed"||s==="error")&&setTimeout(()=>{let n=this.states.get(e);n&&(n.status==="completed"||n.status==="error")&&this.scheduleStatusUpdate(e,"idle")},ns.IDLE_TIMEOUT_MS)}analyzeOutput(e){let t=e.split(`
5
+ `),n=[],a=0,c=0,u=Math.max(i.length,s.length);for(let p=0;p<u;p++){let m=i[p],y=s[p];m===y?m!==void 0&&n.push({type:"context",content:m,oldLineNumber:p+1,newLineNumber:p+1}):(m!==void 0&&(n.push({type:"remove",content:m,oldLineNumber:p+1,newLineNumber:null}),c++),y!==void 0&&(n.push({type:"add",content:y,oldLineNumber:null,newLineNumber:p+1}),a++))}let d;return r===""?d=Pr.CREATE:e===""?d=Pr.DELETE:d=Pr.MODIFY,{path:t,changeType:d,hunks:[{oldStart:1,oldLines:i.length,newStart:1,newLines:s.length,lines:n}],additions:a,deletions:c,isBinary:!1}}var Kf;(function(r){r.FILE="file",r.DIRECTORY="directory"})(Kf||(St.FileEntryType=Kf={}))});var Gf=F(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.createSimpleDiff=D.parseUnifiedDiff=D.getLanguageFromPath=D.FileEntryType=D.DiffBase=D.FileViewType=D.FileChangeType=D.isRetryableError=D.createError=D.ERROR_MESSAGES=D.ErrorCode=D.isTransferComplete=D.getMissingChunks=D.calculateTotalChunks=D.TransferDirection=D.TransferStatus=D.CHUNK_TTL_SECONDS=D.TRANSFER_TTL_SECONDS=D.MAX_RETRIES=D.ACK_TIMEOUT_MS=D.WINDOW_SIZE=D.DEFAULT_MAX_FILE_SIZE=D.CHUNK_SIZE=D.getPushNotificationMessage=D.shouldTriggerPushNotification=D.deriveStatusFromEvent=D.TerminalEventType=D.createMessage=D.requiresBuffer=D.requiresAck=D.DEFAULT_RELIABILITY=D.RELIABILITY_NAMES=D.Reliability=D.comparePriority=D.DEFAULT_PRIORITY=D.PRIORITY_NAMES=D.Priority=D.negotiateCapabilities=D.hasCapability=D.SERVER_CAPABILITIES=D.DEFAULT_CLIENT_CAPABILITIES=D.Capability=D.compareVersions=D.isCompatibleVersion=D.MIN_CLIENT_VERSION=D.PROTOCOL_VERSION_MINOR=D.PROTOCOL_VERSION_MAJOR=D.PROTOCOL_VERSION=void 0;var wi=Nf();Object.defineProperty(D,"PROTOCOL_VERSION",{enumerable:!0,get:function(){return wi.PROTOCOL_VERSION}});Object.defineProperty(D,"PROTOCOL_VERSION_MAJOR",{enumerable:!0,get:function(){return wi.PROTOCOL_VERSION_MAJOR}});Object.defineProperty(D,"PROTOCOL_VERSION_MINOR",{enumerable:!0,get:function(){return wi.PROTOCOL_VERSION_MINOR}});Object.defineProperty(D,"MIN_CLIENT_VERSION",{enumerable:!0,get:function(){return wi.MIN_CLIENT_VERSION}});Object.defineProperty(D,"isCompatibleVersion",{enumerable:!0,get:function(){return wi.isCompatibleVersion}});Object.defineProperty(D,"compareVersions",{enumerable:!0,get:function(){return wi.compareVersions}});var rs=Df();Object.defineProperty(D,"Capability",{enumerable:!0,get:function(){return rs.Capability}});Object.defineProperty(D,"DEFAULT_CLIENT_CAPABILITIES",{enumerable:!0,get:function(){return rs.DEFAULT_CLIENT_CAPABILITIES}});Object.defineProperty(D,"SERVER_CAPABILITIES",{enumerable:!0,get:function(){return rs.SERVER_CAPABILITIES}});Object.defineProperty(D,"hasCapability",{enumerable:!0,get:function(){return rs.hasCapability}});Object.defineProperty(D,"negotiateCapabilities",{enumerable:!0,get:function(){return rs.negotiateCapabilities}});var Zs=Mf();Object.defineProperty(D,"Priority",{enumerable:!0,get:function(){return Zs.Priority}});Object.defineProperty(D,"PRIORITY_NAMES",{enumerable:!0,get:function(){return Zs.PRIORITY_NAMES}});Object.defineProperty(D,"DEFAULT_PRIORITY",{enumerable:!0,get:function(){return Zs.DEFAULT_PRIORITY}});Object.defineProperty(D,"comparePriority",{enumerable:!0,get:function(){return Zs.comparePriority}});var is=Ff();Object.defineProperty(D,"Reliability",{enumerable:!0,get:function(){return is.Reliability}});Object.defineProperty(D,"RELIABILITY_NAMES",{enumerable:!0,get:function(){return is.RELIABILITY_NAMES}});Object.defineProperty(D,"DEFAULT_RELIABILITY",{enumerable:!0,get:function(){return is.DEFAULT_RELIABILITY}});Object.defineProperty(D,"requiresAck",{enumerable:!0,get:function(){return is.requiresAck}});Object.defineProperty(D,"requiresBuffer",{enumerable:!0,get:function(){return is.requiresBuffer}});var $p=Bf();Object.defineProperty(D,"createMessage",{enumerable:!0,get:function(){return $p.createMessage}});var Qs=jf();Object.defineProperty(D,"TerminalEventType",{enumerable:!0,get:function(){return Qs.TerminalEventType}});Object.defineProperty(D,"deriveStatusFromEvent",{enumerable:!0,get:function(){return Qs.deriveStatusFromEvent}});Object.defineProperty(D,"shouldTriggerPushNotification",{enumerable:!0,get:function(){return Qs.shouldTriggerPushNotification}});Object.defineProperty(D,"getPushNotificationMessage",{enumerable:!0,get:function(){return Qs.getPushNotificationMessage}});var kt=Wf();Object.defineProperty(D,"CHUNK_SIZE",{enumerable:!0,get:function(){return kt.CHUNK_SIZE}});Object.defineProperty(D,"DEFAULT_MAX_FILE_SIZE",{enumerable:!0,get:function(){return kt.DEFAULT_MAX_FILE_SIZE}});Object.defineProperty(D,"WINDOW_SIZE",{enumerable:!0,get:function(){return kt.WINDOW_SIZE}});Object.defineProperty(D,"ACK_TIMEOUT_MS",{enumerable:!0,get:function(){return kt.ACK_TIMEOUT_MS}});Object.defineProperty(D,"MAX_RETRIES",{enumerable:!0,get:function(){return kt.MAX_RETRIES}});Object.defineProperty(D,"TRANSFER_TTL_SECONDS",{enumerable:!0,get:function(){return kt.TRANSFER_TTL_SECONDS}});Object.defineProperty(D,"CHUNK_TTL_SECONDS",{enumerable:!0,get:function(){return kt.CHUNK_TTL_SECONDS}});Object.defineProperty(D,"TransferStatus",{enumerable:!0,get:function(){return kt.TransferStatus}});Object.defineProperty(D,"TransferDirection",{enumerable:!0,get:function(){return kt.TransferDirection}});Object.defineProperty(D,"calculateTotalChunks",{enumerable:!0,get:function(){return kt.calculateTotalChunks}});Object.defineProperty(D,"getMissingChunks",{enumerable:!0,get:function(){return kt.getMissingChunks}});Object.defineProperty(D,"isTransferComplete",{enumerable:!0,get:function(){return kt.isTransferComplete}});var en=Hf();Object.defineProperty(D,"ErrorCode",{enumerable:!0,get:function(){return en.ErrorCode}});Object.defineProperty(D,"ERROR_MESSAGES",{enumerable:!0,get:function(){return en.ERROR_MESSAGES}});Object.defineProperty(D,"createError",{enumerable:!0,get:function(){return en.createError}});Object.defineProperty(D,"isRetryableError",{enumerable:!0,get:function(){return en.isRetryableError}});var Xr=$f();Object.defineProperty(D,"FileChangeType",{enumerable:!0,get:function(){return Xr.FileChangeType}});Object.defineProperty(D,"FileViewType",{enumerable:!0,get:function(){return Xr.FileViewType}});Object.defineProperty(D,"DiffBase",{enumerable:!0,get:function(){return Xr.DiffBase}});Object.defineProperty(D,"FileEntryType",{enumerable:!0,get:function(){return Xr.FileEntryType}});Object.defineProperty(D,"getLanguageFromPath",{enumerable:!0,get:function(){return Xr.getLanguageFromPath}});Object.defineProperty(D,"parseUnifiedDiff",{enumerable:!0,get:function(){return Xr.parseUnifiedDiff}});Object.defineProperty(D,"createSimpleDiff",{enumerable:!0,get:function(){return Xr.createSimpleDiff}})});var hr=F(Yt=>{"use strict";var Gp=Yt&&Yt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=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,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),tn=Yt&&Yt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Gp(e,r,t)};Object.defineProperty(Yt,"__esModule",{value:!0});tn(Cf(),Yt);tn(Of(),Yt);tn(Lf(),Yt);tn(Gf(),Yt)});var Xf=F(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.CryptoService=void 0;var ut=hr(),Yp=3600*1e3,Yf=10,Do=class{storage;logger;sessions=new Map;agentSessions=new Map;keyPair=null;publicKeyKey;secretKeyKey;keyVersionKey;constructor(e,t,i,s){this.storage=e,this.logger=t;let n=`termiq.${i}.${s}`;this.publicKeyKey=`${n}.crypto.publicKey`,this.secretKeyKey=`${n}.crypto.secretKey`,this.keyVersionKey=`${n}.crypto.keyVersion`,this.logger.info("CryptoService namespace",i,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,ut.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,i){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,i);try{let s=this.sessions.get(e);s||(s=new Map,this.sessions.set(e,s));let n=(0,ut.deriveSharedSecret)(t,this.keyPair.secretKey),a={terminalId:e,clientPublicKey:t,sharedSecret:n,createdAt:Date.now(),sessionId:i};return s.set(i,a),this.logger.info("Key exchange completed",e,i,"total:",s.size),!0}catch(s){return this.logger.error("Key exchange failed",s),!1}}encryptOutput(e,t){let i=this.sessions.get(e);if(!i||i.size===0)return null;try{if(i.size===1){let n=i.values().next().value;return n?(0,ut.encrypt)(t,n.sharedSecret,n.sessionId):null}let s=[];for(let n of i.values()){let a=(0,ut.encrypt)(t,n.sharedSecret,n.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 i=this.sessions.get(e);if(!i)return this.logger.error("No sessions for terminal",e),null;let s=i.get(t.sid);if(!s)return this.logger.error("No session for sessionId",t.sid),null;try{return(0,ut.decrypt)(t,s.sharedSecret)}catch(n){return this.logger.error("Decryption failed",n),null}}hasSession(e){let t=this.sessions.get(e);return t!==void 0&&t.size>0}removeSession(e,t){let i=this.sessions.get(e);if(i)if(t){let s=i.get(t);s&&((0,ut.clearKey)(s.sharedSecret),i.delete(t),this.logger.info("Session removed",e,t)),i.size===0&&this.sessions.delete(e)}else{for(let s of i.values())(0,ut.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,ut.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 i=Date.now(),s=[];for(let[n,a]of t)i-a.createdAt>Yp&&s.push(n);for(let n of s){let a=t.get(n);a&&((0,ut.clearKey)(a.sharedSecret),t.delete(n))}if(t.size>Yf){let a=Array.from(t.entries()).sort((c,u)=>c[1].createdAt-u[1].createdAt).slice(0,t.size-Yf);for(let[,c]of a)(0,ut.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,i]of this.sessions.entries())for(let s of i.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 i=this.agentSessions.get(t);i&&(this.logger.info("Rekeying existing agent session",t),(0,ut.clearKey)(i.sharedSecret));let s=(0,ut.deriveSharedSecret)(e,this.keyPair.secretKey),n={sessionId:t,clientPublicKey:e,sharedSecret:s,createdAt:Date.now()};return this.agentSessions.set(t,n),this.logger.info("Agent key exchange completed",t,"total:",this.agentSessions.size),!0}catch(i){return this.logger.error("Agent key exchange failed",i),!1}}removeAgentSession(e){let t=this.agentSessions.get(e);t&&((0,ut.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),i=this.encryptForAllAgentSessions(t);return i?{encrypted:i}:null}encryptTerminalInfo(e){if(this.agentSessions.size===0)return null;let t=JSON.stringify(e),i=this.encryptForAllAgentSessions(t);return i?{encrypted:i}:null}encryptPromptInfo(e){if(this.agentSessions.size===0)return null;let t=JSON.stringify(e),i=this.encryptForAllAgentSessions(t);return i?{encrypted:i}:null}encryptForAllAgentSessions(e){if(this.agentSessions.size===0)return null;try{if(this.agentSessions.size===1){let i=this.agentSessions.values().next().value;return i?(0,ut.encrypt)(e,i.sharedSecret,i.sessionId):null}let t=[];for(let i of this.agentSessions.values()){let s=(0,ut.encrypt)(e,i.sharedSecret,i.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,ut.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")}};rn.CryptoService=Do});var Jf=F(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.AuthService=void 0;var ss=zs(),Mo=class{storage;cryptoService;machineId;config;logger;notification;browser;pollingAbortController=null;tokenKey;refreshTokenKey;agentIdKey;constructor(e,t,i,s,n,a,c,u,d){this.storage=e,this.cryptoService=t,this.machineId=i,this.config=s,this.logger=n,this.notification=a,this.browser=c;let p=`termiq.${u}.${d}`;this.tokenKey=`${p}.accessToken`,this.refreshTokenKey=`${p}.refreshToken`,this.agentIdKey=`${p}.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(),i=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,i);let n=await fetch(`${e}/auth/device/code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machineId:t,machineName:i,publicKey:s})});if(!n.ok){let a=await n.text();throw new Error(`Failed to get device code: ${a}`)}return n.json()}async pollForToken(e){this.cancelPolling();let t=(0,ss.getApiUrl)(this.config),i=5e3,s=60;this.pollingAbortController=new AbortController;let n=this.pollingAbortController.signal;this.logger.info("Starting token polling");for(let a=0;a<s;a++){if(n.aborted)return this.logger.info("Polling was cancelled"),null;if(await this.sleep(i),n.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:n});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(n.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),i=await this.machineId.getMachineId(),s=this.machineId.getMachineName(),n=await this.cryptoService.getPublicKey();n||(await this.cryptoService.generateIdentityKeyPair(),n=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:i,machineName:s,publicKey:n})});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 i=JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()).exp*1e3;return Date.now()<i}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 i=await fetch(`${t}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!i.ok)return this.logger.warn("Token refresh failed",String(i.status)),i.status===401&&await this.storage.delete(this.refreshTokenKey),null;let s=await i.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(i){return this.logger.warn("Token refresh error",i),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 i=await fetch(`${t}/users/me/limits`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});return i.ok?await i.json():(this.logger.error("Failed to fetch limits",String(i.status)),null)}catch(i){let s=i instanceof Error?i.message:String(i);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))}};sn.AuthService=Mo});var Zf=F(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.StatusDetector=void 0;var nn={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]},ns={IDLE_TIMEOUT_MS:5e3,DEBOUNCE_MS:500,BUFFER_SIZE:2e3,WORKING_TIMEOUT_MS:3e4},Fo=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 i=this.states.get(e);if(!i)return;i.lastOutput=Date.now(),i.outputBuffer+=t,i.outputBuffer.length>ns.BUFFER_SIZE&&(i.outputBuffer=i.outputBuffer.slice(-ns.BUFFER_SIZE));let s=this.analyzeOutput(i.outputBuffer);s&&this.scheduleStatusUpdate(e,s),this.resetWorkingTimeout(e,i)}onCommandStart(e){let t=this.states.get(e);t&&(t.outputBuffer="",this.scheduleStatusUpdate(e,"working"),this.resetWorkingTimeout(e,t))}onCommandEnd(e,t){let i=this.states.get(e);if(!i)return;i.workingTimeout&&(clearTimeout(i.workingTimeout),i.workingTimeout=null);let s;if(t!==void 0&&t!==0)s="error";else{let n=this.analyzeOutput(i.outputBuffer);n==="waiting"?s="waiting":n==="error"?s="error":n==="completed"?s="completed":s="idle"}this.scheduleStatusUpdate(e,s),(s==="completed"||s==="error")&&setTimeout(()=>{let n=this.states.get(e);n&&(n.status==="completed"||n.status==="error")&&this.scheduleStatusUpdate(e,"idle")},ns.IDLE_TIMEOUT_MS)}analyzeOutput(e){let t=e.split(`
6
6
  `).slice(-10),i=t.join(`
7
7
  `),s=t[t.length-1]||"";for(let n of nn.waiting)if(n.test(i))return"waiting";for(let n of nn.working)if(n.test(s))return"working";for(let n of nn.completed)if(n.test(i))return"completed";for(let n of nn.idle)if(n.test(s))return"idle";return null}detectPrompt(e){let s=this.normalizeBuffer(this.stripAnsi(e)).split(`
8
8
  `).slice(-20),n=s.join(`
9
- `),a=s[s.length-1]||"",c=this.extractNumberedChoices(e);if(c.length>=2)return{type:"numbered-choice",question:this.extractQuestion(n)||"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(n))return{type:"yes-no",question:this.extractQuestion(n)||"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(n))return{type:"enter",question:this.extractQuestion(n)||"Press Enter to continue"};let g=[/Press any key/i,/press a key/i];for(let m of g)if(m.test(n))return{type:"any-key",question:this.extractQuestion(n)||"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
- `),n=/^\s*[❯>*]?\s*(?:(\d+)[.)]\s*|\[(\d+)\]\s*)(.+)$/;for(let a of s){let c=a.match(n);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(`
9
+ `),a=s[s.length-1]||"",c=this.extractNumberedChoices(e);if(c.length>=2)return{type:"numbered-choice",question:this.extractQuestion(n)||"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(n))return{type:"yes-no",question:this.extractQuestion(n)||"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(n))return{type:"enter",question:this.extractQuestion(n)||"Press Enter to continue"};let p=[/Press any key/i,/press a key/i];for(let m of p)if(m.test(n))return{type:"any-key",question:this.extractQuestion(n)||"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
+ `),n=/^\s*[❯>*]?\s*(?:(\d+)[.)]\s*|\[(\d+)\]\s*)(.+)$/;for(let a of s){let c=a.match(n);if(c){let u=c[1]||c[2],d=c[3].trim();if(u&&d&&d.length<100&&!d.includes("error")){let p=t.length+1;parseInt(u)===p&&t.push({key:u,label:d})}}}return t}extractQuestion(e){let t=e.split(`
11
11
  `).filter(i=>i.trim());for(let i=t.length-1;i>=Math.max(0,t.length-5);i--){let s=t[i].trim();if(!s||/^\s*\d+[.)]\s/.test(s)||/^\s*\[/.test(s))continue;let n=this.stripAnsi(s);if(n.endsWith("?")||n.endsWith(":"))return n.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 i=this.states.get(e);i&&i.status!==t&&(i.pendingUpdate&&clearTimeout(i.pendingUpdate),i.pendingUpdate=setTimeout(()=>{this.emitStatus(e,t),i.pendingUpdate=null},ns.DEBOUNCE_MS))}emitStatus(e,t){let i=this.states.get(e);if(!i||i.status===t)return;i.status=t,i.lastUpdate=Date.now();let s;t==="waiting"&&(s=this.detectPrompt(i.outputBuffer)||void 0),this.onStatusChange(e,t,s)}resetWorkingTimeout(e,t){t.workingTimeout&&clearTimeout(t.workingTimeout),t.status==="working"&&(t.workingTimeout=setTimeout(()=>{let i=this.states.get(e);i&&i.status==="working"&&(this.analyzeOutput(i.outputBuffer)==="waiting"?this.emitStatus(e,"waiting"):this.onStatusChange(e,"working",void 0))},ns.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)}};on.StatusDetector=Fo});var tu=F((NE,eu)=>{var wi=require("fs"),Qf=require("url"),Xp=require("child_process").spawn;eu.exports=Bo;Bo.XMLHttpRequest=Bo;function Bo(r){"use strict";r=r||{};var e=this,t=require("http"),i=require("https"),s,n,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,b=!1,T=!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 H=function(A){return c||A&&g.indexOf(A.toLowerCase())===-1},ge=function(A){return A&&m.indexOf(A)===-1};this.open=function(A,j,Q,I,oe){if(this.abort(),b=!1,T=!1,!ge(A))throw new Error("SecurityError: Request method not allowed");a={method:A,url:j.toString(),async:typeof Q!="boolean"?!0:Q,user:I||null,password:oe||null},Y(this.OPENED)},this.setDisableHeaderCheck=function(A){c=A},this.setRequestHeader=function(A,j){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");if(!H(A))return console.warn('Refused to set unsafe header "'+A+'"'),!1;if(y)throw new Error("INVALID_STATE_ERR: send flag is true");return d[A]=j,!0},this.getResponseHeader=function(A){return typeof A=="string"&&this.readyState>this.OPENED&&n.headers[A.toLowerCase()]&&!b?n.headers[A.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||b)return"";var A="";for(var j in n.headers)j!=="set-cookie"&&j!=="set-cookie2"&&(A+=j+": "+n.headers[j]+`\r
16
- `);return A.substr(0,A.length-2)},this.getRequestHeader=function(A){return typeof A=="string"&&d[A]?d[A]:""},this.send=function(A){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 j=!1,Q=!1,I=Qf.parse(a.url),oe;switch(I.protocol){case"https:":j=!0;case"http:":oe=I.hostname;break;case"file:":Q=!0;break;case void 0:case"":oe="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)wi.readFile(unescape(I.pathname),function(O,J){O?e.handleError(O,O.errno||-1):(e.status=200,e.responseText=J.toString("utf8"),e.response=J,Y(e.DONE))});else try{this.response=wi.readFileSync(unescape(I.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,Y(e.DONE)}catch(O){this.handleError(O,O.errno||-1)}return}var fe=I.port||(j?443:80),ee=I.pathname+(I.search?I.search:"");if(d.Host=oe,j&&fe===443||fe===80||(d.Host+=":"+I.port),a.user){typeof a.password>"u"&&(a.password="");var ke=new Buffer(a.user+":"+a.password);d.Authorization="Basic "+ke.toString("base64")}if(a.method==="GET"||a.method==="HEAD")A=null;else if(A){d["Content-Length"]=Buffer.isBuffer(A)?A.length:Buffer.byteLength(A);var be=Object.keys(d);be.some(function(O){return O.toLowerCase()==="content-type"})||(d["Content-Type"]="text/plain;charset=UTF-8")}else a.method==="POST"&&(d["Content-Length"]=0);var xe=r.agent||!1,Se={host:oe,port:fe,path:ee,method:a.method,headers:d,agent:xe};if(j&&(Se.pfx=r.pfx,Se.key=r.key,Se.passphrase=r.passphrase,Se.cert=r.cert,Se.ca=r.ca,Se.ciphers=r.ciphers,Se.rejectUnauthorized=r.rejectUnauthorized!==!1),b=!1,a.async){var Ge=j?i.request:t.request;y=!0,e.dispatchEvent("readystatechange");var Ie=function(O){if(n=O,n.statusCode===302||n.statusCode===303||n.statusCode===307){a.url=n.headers.location;var J=Qf.parse(a.url);oe=J.hostname;var Ae={hostname:J.hostname,port:J.port,path:J.path,method:n.statusCode===303?"GET":a.method,headers:d};j&&(Ae.pfx=r.pfx,Ae.key=r.key,Ae.passphrase=r.passphrase,Ae.cert=r.cert,Ae.ca=r.ca,Ae.ciphers=r.ciphers,Ae.rejectUnauthorized=r.rejectUnauthorized!==!1),s=Ge(Ae,Ie).on("error",Ye),s.end();return}Y(e.HEADERS_RECEIVED),e.status=n.statusCode,n.on("data",function(lt){if(lt){var vt=Buffer.from(lt);e.response=Buffer.concat([e.response,vt])}y&&Y(e.LOADING)}),n.on("end",function(){y&&(y=!1,Y(e.DONE),e.responseText=e.response.toString("utf8"))}),n.on("error",function(lt){e.handleError(lt)})},Ye=function(O){if(s.reusedSocket&&O.code==="ECONNRESET")return Ge(Se,Ie).on("error",Ye);e.handleError(O)};s=Ge(Se,Ie).on("error",Ye),r.autoUnref&&s.on("socket",O=>{O.unref()}),A&&s.write(A),s.end(),e.dispatchEvent("loadstart")}else{var Ue=".node-xmlhttprequest-content-"+process.pid,Pe=".node-xmlhttprequest-sync-"+process.pid;wi.writeFileSync(Pe,"","utf8");for(var et="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(j?"s":"")+".request;var options = "+JSON.stringify(Se)+";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('"+Ue+"', 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('"+Ue+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Pe+"');});}).on('error', function(error) {fs.writeFileSync('"+Ue+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Pe+"');});"+(A?"req.write('"+JSON.stringify(A).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",Xe=Xp(process.argv[0],["-e",et]),ut;wi.existsSync(Pe););if(e.responseText=wi.readFileSync(Ue,"utf8"),Xe.stdin.end(),wi.unlinkSync(Ue),e.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var w=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,""));e.handleError(w,503)}else{e.status=e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/,"$1");var L=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"));n={statusCode:e.status,headers:L.data.headers},e.responseText=L.data.text,e.response=Buffer.from(L.data.data,"base64"),Y(e.DONE,!0)}}},this.handleError=function(A,j){this.status=j||0,this.statusText=A,this.responseText=A.stack,b=!0,Y(this.DONE)},this.abort=function(){s&&(s.abort(),s=null),d=Object.assign({},u),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),b=T=!0,this.readyState!==this.UNSENT&&(this.readyState!==this.OPENED||y)&&this.readyState!==this.DONE&&(y=!1,Y(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(A,j){A in C||(C[A]=[]),C[A].push(j)},this.removeEventListener=function(A,j){A in C&&(C[A]=C[A].filter(function(Q){return Q!==j}))},this.dispatchEvent=function(A){if(typeof e["on"+A]=="function"&&(this.readyState===this.DONE&&a.async?setTimeout(function(){e["on"+A]()},0):e["on"+A]()),A in C)for(let j=0,Q=C[A].length;j<Q;j++)this.readyState===this.DONE?setTimeout(function(){C[A][j].call(e)},0):C[A][j].call(e)};var Y=function(A){if(!(e.readyState===A||e.readyState===e.UNSENT&&T)&&(e.readyState=A,(a.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let j;T?j="abort":b?j="error":j="load",e.dispatchEvent(j),e.dispatchEvent("loadend")}}}});var an=F(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.ERROR_PACKET=Ar.PACKET_TYPES_REVERSE=Ar.PACKET_TYPES=void 0;var Xt=Object.create(null);Ar.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 ru=Object.create(null);Ar.PACKET_TYPES_REVERSE=ru;Object.keys(Xt).forEach(r=>{ru[Xt[r]]=r});var Jp={type:"error",data:"parser error"};Ar.ERROR_PACKET=Jp});var su=F(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});bi.encodePacket=void 0;bi.encodePacketToBinary=eg;var Zp=an(),Qp=({type:r,data:e},t,i)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?i(t?e:"b"+iu(e,!0).toString("base64")):i(Zp.PACKET_TYPES[r]+(e||""));bi.encodePacket=Qp;var iu=(r,e)=>Buffer.isBuffer(r)||r instanceof Uint8Array&&!e?r:r instanceof ArrayBuffer?Buffer.from(r):Buffer.from(r.buffer,r.byteOffset,r.byteLength),jo;function eg(r,e){if(r.data instanceof ArrayBuffer||ArrayBuffer.isView(r.data))return e(iu(r.data,!1));(0,bi.encodePacket)(r,!0,t=>{jo||(jo=new TextEncoder),e(jo.encode(t))})}});var ou=F(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.decodePacket=void 0;var cn=an(),tg=(r,e)=>{if(typeof r!="string")return{type:"message",data:nu(r,e)};let t=r.charAt(0);if(t==="b"){let i=Buffer.from(r.substring(1),"base64");return{type:"message",data:nu(i,e)}}return cn.PACKET_TYPES_REVERSE[t]?r.length>1?{type:cn.PACKET_TYPES_REVERSE[t],data:r.substring(1)}:{type:cn.PACKET_TYPES_REVERSE[t]}:cn.ERROR_PACKET};fn.decodePacket=tg;var nu=(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 xi=F(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.decodePayload=mt.decodePacket=mt.encodePayload=mt.encodePacket=mt.protocol=void 0;mt.createPacketEncoderStream=sg;mt.createPacketDecoderStream=ng;var qo=su();Object.defineProperty(mt,"encodePacket",{enumerable:!0,get:function(){return qo.encodePacket}});var Wo=ou();Object.defineProperty(mt,"decodePacket",{enumerable:!0,get:function(){return Wo.decodePacket}});var au=an(),cu="",rg=(r,e)=>{let t=r.length,i=new Array(t),s=0;r.forEach((n,a)=>{(0,qo.encodePacket)(n,!1,c=>{i[a]=c,++s===t&&e(i.join(cu))})})};mt.encodePayload=rg;var ig=(r,e)=>{let t=r.split(cu),i=[];for(let s=0;s<t.length;s++){let n=(0,Wo.decodePacket)(t[s],e);if(i.push(n),n.type==="error")break}return i};mt.decodePayload=ig;function sg(){return new TransformStream({transform(r,e){(0,qo.encodePacketToBinary)(r,t=>{let i=t.length,s;if(i<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,i);else if(i<65536){s=new Uint8Array(3);let n=new DataView(s.buffer);n.setUint8(0,126),n.setUint16(1,i)}else{s=new Uint8Array(9);let n=new DataView(s.buffer);n.setUint8(0,127),n.setBigUint64(1,BigInt(i))}r.data&&typeof r.data!="string"&&(s[0]|=128),e.enqueue(s),e.enqueue(t)})}})}var Uo;function un(r){return r.reduce((e,t)=>e+t.length,0)}function ln(r,e){if(r[0].length===e)return r.shift();let t=new Uint8Array(e),i=0;for(let s=0;s<e;s++)t[s]=r[0][i++],i===r[0].length&&(r.shift(),i=0);return r.length&&i<r[0].length&&(r[0]=r[0].slice(i)),t}function ng(r,e){Uo||(Uo=new TextDecoder);let t=[],i=0,s=-1,n=!1;return new TransformStream({transform(a,c){for(t.push(a);;){if(i===0){if(un(t)<1)break;let u=ln(t,1);n=(u[0]&128)===128,s=u[0]&127,s<126?i=3:s===126?i=1:i=2}else if(i===1){if(un(t)<2)break;let u=ln(t,2);s=new DataView(u.buffer,u.byteOffset,u.length).getUint16(0),i=3}else if(i===2){if(un(t)<8)break;let u=ln(t,8),d=new DataView(u.buffer,u.byteOffset,u.length),g=d.getUint32(0);if(g>Math.pow(2,21)-1){c.enqueue(au.ERROR_PACKET);break}s=g*Math.pow(2,32)+d.getUint32(4),i=3}else{if(un(t)<s)break;let u=ln(t,s);c.enqueue((0,Wo.decodePacket)(n?u:Uo.decode(u),e)),i=0}if(s===0||s>r){c.enqueue(au.ERROR_PACKET);break}}}})}mt.protocol=4});var Jr=F(fu=>{fu.Emitter=dt;function dt(r){if(r)return og(r)}function og(r){for(var e in dt.prototype)r[e]=dt.prototype[e];return r}dt.prototype.on=dt.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this};dt.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this};dt.prototype.off=dt.prototype.removeListener=dt.prototype.removeAllListeners=dt.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 i,s=0;s<t.length;s++)if(i=t[s],i===e||i.fn===e){t.splice(s,1);break}return t.length===0&&delete this._callbacks["$"+r],this};dt.prototype.emit=function(r){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+r],i=1;i<arguments.length;i++)e[i-1]=arguments[i];if(t){t=t.slice(0);for(var i=0,s=t.length;i<s;++i)t[i].apply(this,e)}return this};dt.prototype.emitReserved=dt.prototype.emit;dt.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};dt.prototype.hasListeners=function(r){return!!this.listeners(r).length}});var Zr=F(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.CookieJar=Rt.defaultBinaryType=Rt.globalThisShim=Rt.nextTick=void 0;Rt.createCookieJar=ag;Rt.parse=uu;Rt.nextTick=process.nextTick;Rt.globalThisShim=global;Rt.defaultBinaryType="nodebuffer";function ag(){return new hn}function uu(r){let e=r.split("; "),t=e[0].indexOf("=");if(t===-1)return;let i=e[0].substring(0,t).trim();if(!i.length)return;let s=e[0].substring(t+1).trim();s.charCodeAt(0)===34&&(s=s.slice(1,-1));let n={name:i,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":n.expires=new Date(d);break;case"Max-Age":let g=new Date;g.setUTCSeconds(g.getUTCSeconds()+parseInt(d,10)),n.expires=g;break;default:}}return n}var hn=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let i=uu(t);i&&this._cookies.set(i.name,i)})}get cookies(){let e=Date.now();return this._cookies.forEach((t,i)=>{var s;((s=t.expires)===null||s===void 0?void 0:s.getTime())<e&&this._cookies.delete(i)}),this._cookies.entries()}addCookies(e){let t=[];for(let[i,s]of this.cookies)t.push(`${i}=${s.value}`);t.length&&(e.setDisableHeaderCheck(!0),e.setRequestHeader("cookie",t.join("; ")))}appendCookies(e){for(let[t,i]of this.cookies)e.append("cookie",`${t}=${i.value}`)}};Rt.CookieJar=hn});var Qr=F(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});Si.pick=cg;Si.installTimerFunctions=lg;Si.byteLength=dg;Si.randomString=gg;var Ir=Zr();function cg(r,...e){return e.reduce((t,i)=>(r.hasOwnProperty(i)&&(t[i]=r[i]),t),{})}var fg=Ir.globalThisShim.setTimeout,ug=Ir.globalThisShim.clearTimeout;function lg(r,e){e.useNativeTimers?(r.setTimeoutFn=fg.bind(Ir.globalThisShim),r.clearTimeoutFn=ug.bind(Ir.globalThisShim)):(r.setTimeoutFn=Ir.globalThisShim.setTimeout.bind(Ir.globalThisShim),r.clearTimeoutFn=Ir.globalThisShim.clearTimeout.bind(Ir.globalThisShim))}var hg=1.33;function dg(r){return typeof r=="string"?pg(r):Math.ceil((r.byteLength||r.size)*hg)}function pg(r){let e=0,t=0;for(let i=0,s=r.length;i<s;i++)e=r.charCodeAt(i),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(i++,t+=4);return t}function gg(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}});var Ho=F(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.encode=mg;dn.decode=_g;function mg(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function _g(r){let e={},t=r.split("&");for(let i=0,s=t.length;i<s;i++){let n=t[i].split("=");e[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return e}});var hu=F((HE,lu)=>{var Ti=1e3,Ci=Ti*60,Oi=Ci*60,ei=Oi*24,yg=ei*7,vg=ei*365.25;lu.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return Eg(r);if(t==="number"&&isFinite(r))return e.long?bg(r):wg(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function Eg(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]),i=(e[2]||"ms").toLowerCase();switch(i){case"years":case"year":case"yrs":case"yr":case"y":return t*vg;case"weeks":case"week":case"w":return t*yg;case"days":case"day":case"d":return t*ei;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Oi;case"minutes":case"minute":case"mins":case"min":case"m":return t*Ci;case"seconds":case"second":case"secs":case"sec":case"s":return t*Ti;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function wg(r){var e=Math.abs(r);return e>=ei?Math.round(r/ei)+"d":e>=Oi?Math.round(r/Oi)+"h":e>=Ci?Math.round(r/Ci)+"m":e>=Ti?Math.round(r/Ti)+"s":r+"ms"}function bg(r){var e=Math.abs(r);return e>=ei?pn(r,e,ei,"day"):e>=Oi?pn(r,e,Oi,"hour"):e>=Ci?pn(r,e,Ci,"minute"):e>=Ti?pn(r,e,Ti,"second"):r+" ms"}function pn(r,e,t,i){var s=e>=t*1.5;return Math.round(r/t)+" "+i+(s?"s":"")}});var Vo=F((VE,du)=>{function xg(r){t.debug=t,t.default=t,t.coerce=u,t.disable=a,t.enable=s,t.enabled=c,t.humanize=hu(),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,b,T;function C(...H){if(!C.enabled)return;let ge=C,Y=Number(new Date),A=Y-(m||Y);ge.diff=A,ge.prev=m,ge.curr=Y,m=Y,H[0]=t.coerce(H[0]),typeof H[0]!="string"&&H.unshift("%O");let j=0;H[0]=H[0].replace(/%([a-zA-Z%])/g,(I,oe)=>{if(I==="%%")return"%";j++;let fe=t.formatters[oe];if(typeof fe=="function"){let ee=H[j];I=fe.call(ge,ee),H.splice(j,1),j--}return I}),t.formatArgs.call(ge,H),(ge.log||t.log).apply(ge,H)}return C.namespace=g,C.useColors=t.useColors(),C.color=t.selectColor(g),C.extend=i,C.destroy=t.destroy,Object.defineProperty(C,"enabled",{enumerable:!0,configurable:!1,get:()=>y!==null?y:(b!==t.namespaces&&(b=t.namespaces,T=t.enabled(g)),T),set:H=>{y=H}}),typeof t.init=="function"&&t.init(C),C}function i(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 n(g,m){let y=0,b=0,T=-1,C=0;for(;y<g.length;)if(b<m.length&&(m[b]===g[y]||m[b]==="*"))m[b]==="*"?(T=b,C=y,b++):(y++,b++);else if(T!==-1)b=T+1,C++,y=C;else return!1;for(;b<m.length&&m[b]==="*";)b++;return b===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(n(g,m))return!1;for(let m of t.names)if(n(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}du.exports=xg});var pu=F((_t,gn)=>{_t.formatArgs=Tg;_t.save=Cg;_t.load=Og;_t.useColors=Sg;_t.storage=kg();_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 Sg(){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 Tg(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+gn.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,i=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(i=t))}),r.splice(i,0,e)}_t.log=console.debug||console.log||(()=>{});function Cg(r){try{r?_t.storage.setItem("debug",r):_t.storage.removeItem("debug")}catch{}}function Og(){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 kg(){try{return localStorage}catch{}}gn.exports=Vo()(_t);var{formatters:Rg}=gn.exports;Rg.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var mu=F((KE,gu)=>{"use strict";gu.exports=(r,e=process.argv)=>{let t=r.startsWith("-")?"":r.length===1?"-":"--",i=e.indexOf(t+r),s=e.indexOf("--");return i!==-1&&(s===-1||i<s)}});var vu=F((zE,yu)=>{"use strict";var Pg=require("os"),_u=require("tty"),Pt=mu(),{env:tt}=process,Lr;Pt("no-color")||Pt("no-colors")||Pt("color=false")||Pt("color=never")?Lr=0:(Pt("color")||Pt("colors")||Pt("color=true")||Pt("color=always"))&&(Lr=1);"FORCE_COLOR"in tt&&(tt.FORCE_COLOR==="true"?Lr=1:tt.FORCE_COLOR==="false"?Lr=0:Lr=tt.FORCE_COLOR.length===0?1:Math.min(parseInt(tt.FORCE_COLOR,10),3));function Ko(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function zo(r,e){if(Lr===0)return 0;if(Pt("color=16m")||Pt("color=full")||Pt("color=truecolor"))return 3;if(Pt("color=256"))return 2;if(r&&!e&&Lr===void 0)return 0;let t=Lr||0;if(tt.TERM==="dumb")return t;if(process.platform==="win32"){let i=Pg.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in tt)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(i=>i 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 i=parseInt((tt.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(tt.TERM_PROGRAM){case"iTerm.app":return i>=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 Ag(r){let e=zo(r,r&&r.isTTY);return Ko(e)}yu.exports={supportsColor:Ag,stdout:Ko(zo(!0,_u.isatty(1))),stderr:Ko(zo(!0,_u.isatty(2)))}});var wu=F((rt,_n)=>{var Ig=require("tty"),mn=require("util");rt.init=jg;rt.log=Mg;rt.formatArgs=Ng;rt.save=Fg;rt.load=Bg;rt.useColors=Lg;rt.destroy=mn.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=vu();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,n)=>n.toUpperCase()),i=process.env[e];return/^(yes|on|true|enabled)$/i.test(i)?i=!0:/^(no|off|false|disabled)$/i.test(i)?i=!1:i==="null"?i=null:i=Number(i),r[t]=i,r},{});function Lg(){return"colors"in rt.inspectOpts?!!rt.inspectOpts.colors:Ig.isatty(process.stderr.fd)}function Ng(r){let{namespace:e,useColors:t}=this;if(t){let i=this.color,s="\x1B[3"+(i<8?i:"8;5;"+i),n=` ${s};1m${e} \x1B[0m`;r[0]=n+r[0].split(`
15
+ `)}scheduleStatusUpdate(e,t){let i=this.states.get(e);i&&i.status!==t&&(i.pendingUpdate&&clearTimeout(i.pendingUpdate),i.pendingUpdate=setTimeout(()=>{this.emitStatus(e,t),i.pendingUpdate=null},ns.DEBOUNCE_MS))}emitStatus(e,t){let i=this.states.get(e);if(!i||i.status===t)return;i.status=t,i.lastUpdate=Date.now();let s;t==="waiting"&&(s=this.detectPrompt(i.outputBuffer)||void 0),this.onStatusChange(e,t,s)}resetWorkingTimeout(e,t){t.workingTimeout&&clearTimeout(t.workingTimeout),t.status==="working"&&(t.workingTimeout=setTimeout(()=>{let i=this.states.get(e);i&&i.status==="working"&&(this.analyzeOutput(i.outputBuffer)==="waiting"?this.emitStatus(e,"waiting"):this.onStatusChange(e,"working",void 0))},ns.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)}};on.StatusDetector=Fo});var tu=F((Nw,eu)=>{var Ei=require("fs"),Qf=require("url"),Xp=require("child_process").spawn;eu.exports=Bo;Bo.XMLHttpRequest=Bo;function Bo(r){"use strict";r=r||{};var e=this,t=require("http"),i=require("https"),s,n,a={},c=!1,u={"User-Agent":"node-XMLHttpRequest",Accept:"*/*"},d=Object.assign({},u),p=["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,E=!1,T=!1,O={};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 H=function(A){return c||A&&p.indexOf(A.toLowerCase())===-1},me=function(A){return A&&m.indexOf(A)===-1};this.open=function(A,j,te,I,ae){if(this.abort(),E=!1,T=!1,!me(A))throw new Error("SecurityError: Request method not allowed");a={method:A,url:j.toString(),async:typeof te!="boolean"?!0:te,user:I||null,password:ae||null},X(this.OPENED)},this.setDisableHeaderCheck=function(A){c=A},this.setRequestHeader=function(A,j){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");if(!H(A))return console.warn('Refused to set unsafe header "'+A+'"'),!1;if(y)throw new Error("INVALID_STATE_ERR: send flag is true");return d[A]=j,!0},this.getResponseHeader=function(A){return typeof A=="string"&&this.readyState>this.OPENED&&n.headers[A.toLowerCase()]&&!E?n.headers[A.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||E)return"";var A="";for(var j in n.headers)j!=="set-cookie"&&j!=="set-cookie2"&&(A+=j+": "+n.headers[j]+`\r
16
+ `);return A.substr(0,A.length-2)},this.getRequestHeader=function(A){return typeof A=="string"&&d[A]?d[A]:""},this.send=function(A){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 j=!1,te=!1,I=Qf.parse(a.url),ae;switch(I.protocol){case"https:":j=!0;case"http:":ae=I.hostname;break;case"file:":te=!0;break;case void 0:case"":ae="localhost";break;default:throw new Error("Protocol not supported.")}if(te){if(a.method!=="GET")throw new Error("XMLHttpRequest: Only GET method is supported");if(a.async)Ei.readFile(unescape(I.pathname),function(C,Y){C?e.handleError(C,C.errno||-1):(e.status=200,e.responseText=Y.toString("utf8"),e.response=Y,X(e.DONE))});else try{this.response=Ei.readFileSync(unescape(I.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,X(e.DONE)}catch(C){this.handleError(C,C.errno||-1)}return}var ue=I.port||(j?443:80),Q=I.pathname+(I.search?I.search:"");if(d.Host=ae,j&&ue===443||ue===80||(d.Host+=":"+I.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")A=null;else if(A){d["Content-Length"]=Buffer.isBuffer(A)?A.length:Buffer.byteLength(A);var Ee=Object.keys(d);Ee.some(function(C){return C.toLowerCase()==="content-type"})||(d["Content-Type"]="text/plain;charset=UTF-8")}else a.method==="POST"&&(d["Content-Length"]=0);var Je=r.agent||!1,ee={host:ae,port:ue,path:Q,method:a.method,headers:d,agent:Je};if(j&&(ee.pfx=r.pfx,ee.key=r.key,ee.passphrase=r.passphrase,ee.cert=r.cert,ee.ca=r.ca,ee.ciphers=r.ciphers,ee.rejectUnauthorized=r.rejectUnauthorized!==!1),E=!1,a.async){var Ye=j?i.request:t.request;y=!0,e.dispatchEvent("readystatechange");var Be=function(C){if(n=C,n.statusCode===302||n.statusCode===303||n.statusCode===307){a.url=n.headers.location;var Y=Qf.parse(a.url);ae=Y.hostname;var ve={hostname:Y.hostname,port:Y.port,path:Y.path,method:n.statusCode===303?"GET":a.method,headers:d};j&&(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),s=Ye(ve,Be).on("error",je),s.end();return}X(e.HEADERS_RECEIVED),e.status=n.statusCode,n.on("data",function(et){if(et){var vt=Buffer.from(et);e.response=Buffer.concat([e.response,vt])}y&&X(e.LOADING)}),n.on("end",function(){y&&(y=!1,X(e.DONE),e.responseText=e.response.toString("utf8"))}),n.on("error",function(et){e.handleError(et)})},je=function(C){if(s.reusedSocket&&C.code==="ECONNRESET")return Ye(ee,Be).on("error",je);e.handleError(C)};s=Ye(ee,Be).on("error",je),r.autoUnref&&s.on("socket",C=>{C.unref()}),A&&s.write(A),s.end(),e.dispatchEvent("loadstart")}else{var Ue=".node-xmlhttprequest-content-"+process.pid,Te=".node-xmlhttprequest-sync-"+process.pid;Ei.writeFileSync(Te,"","utf8");for(var nt="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(j?"s":"")+".request;var options = "+JSON.stringify(ee)+";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('"+Ue+"', 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('"+Ue+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Te+"');});}).on('error', function(error) {fs.writeFileSync('"+Ue+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Te+"');});"+(A?"req.write('"+JSON.stringify(A).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",Ve=Xp(process.argv[0],["-e",nt]),yt;Ei.existsSync(Te););if(e.responseText=Ei.readFileSync(Ue,"utf8"),Ve.stdin.end(),Ei.unlinkSync(Ue),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 S=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"));n={statusCode:e.status,headers:S.data.headers},e.responseText=S.data.text,e.response=Buffer.from(S.data.data,"base64"),X(e.DONE,!0)}}},this.handleError=function(A,j){this.status=j||0,this.statusText=A,this.responseText=A.stack,E=!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),E=T=!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(A,j){A in O||(O[A]=[]),O[A].push(j)},this.removeEventListener=function(A,j){A in O&&(O[A]=O[A].filter(function(te){return te!==j}))},this.dispatchEvent=function(A){if(typeof e["on"+A]=="function"&&(this.readyState===this.DONE&&a.async?setTimeout(function(){e["on"+A]()},0):e["on"+A]()),A in O)for(let j=0,te=O[A].length;j<te;j++)this.readyState===this.DONE?setTimeout(function(){O[A][j].call(e)},0):O[A][j].call(e)};var X=function(A){if(!(e.readyState===A||e.readyState===e.UNSENT&&T)&&(e.readyState=A,(a.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let j;T?j="abort":E?j="error":j="load",e.dispatchEvent(j),e.dispatchEvent("loadend")}}}});var an=F(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.ERROR_PACKET=Ar.PACKET_TYPES_REVERSE=Ar.PACKET_TYPES=void 0;var Xt=Object.create(null);Ar.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 ru=Object.create(null);Ar.PACKET_TYPES_REVERSE=ru;Object.keys(Xt).forEach(r=>{ru[Xt[r]]=r});var Jp={type:"error",data:"parser error"};Ar.ERROR_PACKET=Jp});var su=F(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});bi.encodePacket=void 0;bi.encodePacketToBinary=eg;var Zp=an(),Qp=({type:r,data:e},t,i)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?i(t?e:"b"+iu(e,!0).toString("base64")):i(Zp.PACKET_TYPES[r]+(e||""));bi.encodePacket=Qp;var iu=(r,e)=>Buffer.isBuffer(r)||r instanceof Uint8Array&&!e?r:r instanceof ArrayBuffer?Buffer.from(r):Buffer.from(r.buffer,r.byteOffset,r.byteLength),jo;function eg(r,e){if(r.data instanceof ArrayBuffer||ArrayBuffer.isView(r.data))return e(iu(r.data,!1));(0,bi.encodePacket)(r,!0,t=>{jo||(jo=new TextEncoder),e(jo.encode(t))})}});var ou=F(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.decodePacket=void 0;var cn=an(),tg=(r,e)=>{if(typeof r!="string")return{type:"message",data:nu(r,e)};let t=r.charAt(0);if(t==="b"){let i=Buffer.from(r.substring(1),"base64");return{type:"message",data:nu(i,e)}}return cn.PACKET_TYPES_REVERSE[t]?r.length>1?{type:cn.PACKET_TYPES_REVERSE[t],data:r.substring(1)}:{type:cn.PACKET_TYPES_REVERSE[t]}:cn.ERROR_PACKET};fn.decodePacket=tg;var nu=(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 xi=F(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.decodePayload=gt.decodePacket=gt.encodePayload=gt.encodePacket=gt.protocol=void 0;gt.createPacketEncoderStream=sg;gt.createPacketDecoderStream=ng;var qo=su();Object.defineProperty(gt,"encodePacket",{enumerable:!0,get:function(){return qo.encodePacket}});var Wo=ou();Object.defineProperty(gt,"decodePacket",{enumerable:!0,get:function(){return Wo.decodePacket}});var au=an(),cu="",rg=(r,e)=>{let t=r.length,i=new Array(t),s=0;r.forEach((n,a)=>{(0,qo.encodePacket)(n,!1,c=>{i[a]=c,++s===t&&e(i.join(cu))})})};gt.encodePayload=rg;var ig=(r,e)=>{let t=r.split(cu),i=[];for(let s=0;s<t.length;s++){let n=(0,Wo.decodePacket)(t[s],e);if(i.push(n),n.type==="error")break}return i};gt.decodePayload=ig;function sg(){return new TransformStream({transform(r,e){(0,qo.encodePacketToBinary)(r,t=>{let i=t.length,s;if(i<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,i);else if(i<65536){s=new Uint8Array(3);let n=new DataView(s.buffer);n.setUint8(0,126),n.setUint16(1,i)}else{s=new Uint8Array(9);let n=new DataView(s.buffer);n.setUint8(0,127),n.setBigUint64(1,BigInt(i))}r.data&&typeof r.data!="string"&&(s[0]|=128),e.enqueue(s),e.enqueue(t)})}})}var Uo;function un(r){return r.reduce((e,t)=>e+t.length,0)}function ln(r,e){if(r[0].length===e)return r.shift();let t=new Uint8Array(e),i=0;for(let s=0;s<e;s++)t[s]=r[0][i++],i===r[0].length&&(r.shift(),i=0);return r.length&&i<r[0].length&&(r[0]=r[0].slice(i)),t}function ng(r,e){Uo||(Uo=new TextDecoder);let t=[],i=0,s=-1,n=!1;return new TransformStream({transform(a,c){for(t.push(a);;){if(i===0){if(un(t)<1)break;let u=ln(t,1);n=(u[0]&128)===128,s=u[0]&127,s<126?i=3:s===126?i=1:i=2}else if(i===1){if(un(t)<2)break;let u=ln(t,2);s=new DataView(u.buffer,u.byteOffset,u.length).getUint16(0),i=3}else if(i===2){if(un(t)<8)break;let u=ln(t,8),d=new DataView(u.buffer,u.byteOffset,u.length),p=d.getUint32(0);if(p>Math.pow(2,21)-1){c.enqueue(au.ERROR_PACKET);break}s=p*Math.pow(2,32)+d.getUint32(4),i=3}else{if(un(t)<s)break;let u=ln(t,s);c.enqueue((0,Wo.decodePacket)(n?u:Uo.decode(u),e)),i=0}if(s===0||s>r){c.enqueue(au.ERROR_PACKET);break}}}})}gt.protocol=4});var Jr=F(fu=>{fu.Emitter=ht;function ht(r){if(r)return og(r)}function og(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 i,s=0;s<t.length;s++)if(i=t[s],i===e||i.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],i=1;i<arguments.length;i++)e[i-1]=arguments[i];if(t){t=t.slice(0);for(var i=0,s=t.length;i<s;++i)t[i].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 Zr=F(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.CookieJar=Rt.defaultBinaryType=Rt.globalThisShim=Rt.nextTick=void 0;Rt.createCookieJar=ag;Rt.parse=uu;Rt.nextTick=process.nextTick;Rt.globalThisShim=global;Rt.defaultBinaryType="nodebuffer";function ag(){return new hn}function uu(r){let e=r.split("; "),t=e[0].indexOf("=");if(t===-1)return;let i=e[0].substring(0,t).trim();if(!i.length)return;let s=e[0].substring(t+1).trim();s.charCodeAt(0)===34&&(s=s.slice(1,-1));let n={name:i,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":n.expires=new Date(d);break;case"Max-Age":let p=new Date;p.setUTCSeconds(p.getUTCSeconds()+parseInt(d,10)),n.expires=p;break;default:}}return n}var hn=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let i=uu(t);i&&this._cookies.set(i.name,i)})}get cookies(){let e=Date.now();return this._cookies.forEach((t,i)=>{var s;((s=t.expires)===null||s===void 0?void 0:s.getTime())<e&&this._cookies.delete(i)}),this._cookies.entries()}addCookies(e){let t=[];for(let[i,s]of this.cookies)t.push(`${i}=${s.value}`);t.length&&(e.setDisableHeaderCheck(!0),e.setRequestHeader("cookie",t.join("; ")))}appendCookies(e){for(let[t,i]of this.cookies)e.append("cookie",`${t}=${i.value}`)}};Rt.CookieJar=hn});var Qr=F(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});Si.pick=cg;Si.installTimerFunctions=lg;Si.byteLength=dg;Si.randomString=gg;var Ir=Zr();function cg(r,...e){return e.reduce((t,i)=>(r.hasOwnProperty(i)&&(t[i]=r[i]),t),{})}var fg=Ir.globalThisShim.setTimeout,ug=Ir.globalThisShim.clearTimeout;function lg(r,e){e.useNativeTimers?(r.setTimeoutFn=fg.bind(Ir.globalThisShim),r.clearTimeoutFn=ug.bind(Ir.globalThisShim)):(r.setTimeoutFn=Ir.globalThisShim.setTimeout.bind(Ir.globalThisShim),r.clearTimeoutFn=Ir.globalThisShim.clearTimeout.bind(Ir.globalThisShim))}var hg=1.33;function dg(r){return typeof r=="string"?pg(r):Math.ceil((r.byteLength||r.size)*hg)}function pg(r){let e=0,t=0;for(let i=0,s=r.length;i<s;i++)e=r.charCodeAt(i),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(i++,t+=4);return t}function gg(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}});var Ho=F(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.encode=mg;dn.decode=_g;function mg(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function _g(r){let e={},t=r.split("&");for(let i=0,s=t.length;i<s;i++){let n=t[i].split("=");e[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return e}});var hu=F((Hw,lu)=>{var Ti=1e3,Ci=Ti*60,Oi=Ci*60,ei=Oi*24,yg=ei*7,vg=ei*365.25;lu.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return wg(r);if(t==="number"&&isFinite(r))return e.long?bg(r):Eg(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function wg(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]),i=(e[2]||"ms").toLowerCase();switch(i){case"years":case"year":case"yrs":case"yr":case"y":return t*vg;case"weeks":case"week":case"w":return t*yg;case"days":case"day":case"d":return t*ei;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Oi;case"minutes":case"minute":case"mins":case"min":case"m":return t*Ci;case"seconds":case"second":case"secs":case"sec":case"s":return t*Ti;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Eg(r){var e=Math.abs(r);return e>=ei?Math.round(r/ei)+"d":e>=Oi?Math.round(r/Oi)+"h":e>=Ci?Math.round(r/Ci)+"m":e>=Ti?Math.round(r/Ti)+"s":r+"ms"}function bg(r){var e=Math.abs(r);return e>=ei?pn(r,e,ei,"day"):e>=Oi?pn(r,e,Oi,"hour"):e>=Ci?pn(r,e,Ci,"minute"):e>=Ti?pn(r,e,Ti,"second"):r+" ms"}function pn(r,e,t,i){var s=e>=t*1.5;return Math.round(r/t)+" "+i+(s?"s":"")}});var Vo=F((Vw,du)=>{function xg(r){t.debug=t,t.default=t,t.coerce=u,t.disable=a,t.enable=s,t.enabled=c,t.humanize=hu(),t.destroy=d,Object.keys(r).forEach(p=>{t[p]=r[p]}),t.names=[],t.skips=[],t.formatters={};function e(p){let m=0;for(let y=0;y<p.length;y++)m=(m<<5)-m+p.charCodeAt(y),m|=0;return t.colors[Math.abs(m)%t.colors.length]}t.selectColor=e;function t(p){let m,y=null,E,T;function O(...H){if(!O.enabled)return;let me=O,X=Number(new Date),A=X-(m||X);me.diff=A,me.prev=m,me.curr=X,m=X,H[0]=t.coerce(H[0]),typeof H[0]!="string"&&H.unshift("%O");let j=0;H[0]=H[0].replace(/%([a-zA-Z%])/g,(I,ae)=>{if(I==="%%")return"%";j++;let ue=t.formatters[ae];if(typeof ue=="function"){let Q=H[j];I=ue.call(me,Q),H.splice(j,1),j--}return I}),t.formatArgs.call(me,H),(me.log||t.log).apply(me,H)}return O.namespace=p,O.useColors=t.useColors(),O.color=t.selectColor(p),O.extend=i,O.destroy=t.destroy,Object.defineProperty(O,"enabled",{enumerable:!0,configurable:!1,get:()=>y!==null?y:(E!==t.namespaces&&(E=t.namespaces,T=t.enabled(p)),T),set:H=>{y=H}}),typeof t.init=="function"&&t.init(O),O}function i(p,m){let y=t(this.namespace+(typeof m>"u"?":":m)+p);return y.log=this.log,y}function s(p){t.save(p),t.namespaces=p,t.names=[],t.skips=[];let m=(typeof p=="string"?p:"").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 n(p,m){let y=0,E=0,T=-1,O=0;for(;y<p.length;)if(E<m.length&&(m[E]===p[y]||m[E]==="*"))m[E]==="*"?(T=E,O=y,E++):(y++,E++);else if(T!==-1)E=T+1,O++,y=O;else return!1;for(;E<m.length&&m[E]==="*";)E++;return E===m.length}function a(){let p=[...t.names,...t.skips.map(m=>"-"+m)].join(",");return t.enable(""),p}function c(p){for(let m of t.skips)if(n(p,m))return!1;for(let m of t.names)if(n(p,m))return!0;return!1}function u(p){return p instanceof Error?p.stack||p.message:p}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}du.exports=xg});var pu=F((mt,gn)=>{mt.formatArgs=Tg;mt.save=Cg;mt.load=Og;mt.useColors=Sg;mt.storage=kg();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 Sg(){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 Tg(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+gn.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,i=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(i=t))}),r.splice(i,0,e)}mt.log=console.debug||console.log||(()=>{});function Cg(r){try{r?mt.storage.setItem("debug",r):mt.storage.removeItem("debug")}catch{}}function Og(){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 kg(){try{return localStorage}catch{}}gn.exports=Vo()(mt);var{formatters:Rg}=gn.exports;Rg.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var mu=F((zw,gu)=>{"use strict";gu.exports=(r,e=process.argv)=>{let t=r.startsWith("-")?"":r.length===1?"-":"--",i=e.indexOf(t+r),s=e.indexOf("--");return i!==-1&&(s===-1||i<s)}});var vu=F((Kw,yu)=>{"use strict";var Pg=require("os"),_u=require("tty"),Pt=mu(),{env:tt}=process,Lr;Pt("no-color")||Pt("no-colors")||Pt("color=false")||Pt("color=never")?Lr=0:(Pt("color")||Pt("colors")||Pt("color=true")||Pt("color=always"))&&(Lr=1);"FORCE_COLOR"in tt&&(tt.FORCE_COLOR==="true"?Lr=1:tt.FORCE_COLOR==="false"?Lr=0:Lr=tt.FORCE_COLOR.length===0?1:Math.min(parseInt(tt.FORCE_COLOR,10),3));function zo(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function Ko(r,e){if(Lr===0)return 0;if(Pt("color=16m")||Pt("color=full")||Pt("color=truecolor"))return 3;if(Pt("color=256"))return 2;if(r&&!e&&Lr===void 0)return 0;let t=Lr||0;if(tt.TERM==="dumb")return t;if(process.platform==="win32"){let i=Pg.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in tt)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(i=>i 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 i=parseInt((tt.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(tt.TERM_PROGRAM){case"iTerm.app":return i>=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 Ag(r){let e=Ko(r,r&&r.isTTY);return zo(e)}yu.exports={supportsColor:Ag,stdout:zo(Ko(!0,_u.isatty(1))),stderr:zo(Ko(!0,_u.isatty(2)))}});var Eu=F((rt,_n)=>{var Ig=require("tty"),mn=require("util");rt.init=jg;rt.log=Mg;rt.formatArgs=Ng;rt.save=Fg;rt.load=Bg;rt.useColors=Lg;rt.destroy=mn.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=vu();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,n)=>n.toUpperCase()),i=process.env[e];return/^(yes|on|true|enabled)$/i.test(i)?i=!0:/^(no|off|false|disabled)$/i.test(i)?i=!1:i==="null"?i=null:i=Number(i),r[t]=i,r},{});function Lg(){return"colors"in rt.inspectOpts?!!rt.inspectOpts.colors:Ig.isatty(process.stderr.fd)}function Ng(r){let{namespace:e,useColors:t}=this;if(t){let i=this.color,s="\x1B[3"+(i<8?i:"8;5;"+i),n=` ${s};1m${e} \x1B[0m`;r[0]=n+r[0].split(`
17
17
  `).join(`
18
18
  `+n),r.push(s+"m+"+_n.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=Dg()+e+" "+r[0]}function Dg(){return rt.inspectOpts.hideDate?"":new Date().toISOString()+" "}function Mg(...r){return process.stderr.write(mn.formatWithOptions(rt.inspectOpts,...r)+`
19
- `)}function Fg(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function Bg(){return process.env.DEBUG}function jg(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]]}_n.exports=Vo()(rt);var{formatters:Eu}=_n.exports;Eu.o=function(r){return this.inspectOpts.colors=this.useColors,mn.inspect(r,this.inspectOpts).split(`
20
- `).map(e=>e.trim()).join(" ")};Eu.O=function(r){return this.inspectOpts.colors=this.useColors,mn.inspect(r,this.inspectOpts)}});var At=F(($E,$o)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?$o.exports=pu():$o.exports=wu()});var os=F(Nr=>{"use strict";var Ug=Nr&&Nr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Nr,"__esModule",{value:!0});Nr.Transport=Nr.TransportError=void 0;var qg=xi(),Wg=Jr(),Hg=Qr(),Vg=Ho(),Kg=Ug(At()),zg=(0,Kg.default)("engine.io-client:transport"),yn=class extends Error{constructor(e,t,i){super(e),this.description=t,this.context=i,this.type="TransportError"}};Nr.TransportError=yn;var Go=class extends Wg.Emitter{constructor(e){super(),this.writable=!1,(0,Hg.installTimerFunctions)(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,i){return super.emitReserved("error",new yn(e,t,i)),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):zg("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=(0,qg.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,Vg.encode)(e);return t.length?"?"+t:""}};Nr.Transport=Go});var Xo=F(ki=>{"use strict";var $g=ki&&ki.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ki,"__esModule",{value:!0});ki.Polling=void 0;var Gg=os(),Yg=Qr(),bu=xi(),Xg=$g(At()),Bt=(0,Xg.default)("engine.io-client:polling"),Yo=class extends Gg.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 i=0;this._polling&&(Bt("we are currently polling - waiting to pause"),i++,this.once("pollComplete",function(){Bt("pre-pause polling complete"),--i||t()})),this.writable||(Bt("we are currently writing - waiting to pause"),i++,this.once("drain",function(){Bt("pre-pause writing complete"),--i||t()}))}else t()}_poll(){Bt("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){Bt("polling got data %s",e);let t=i=>{if(this.readyState==="opening"&&i.type==="open"&&this.onOpen(),i.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(i)};(0,bu.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,bu.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,Yg.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}};ki.Polling=Yo});var Su=F(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.hasCORS=void 0;var xu=!1;try{xu=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}vn.hasCORS=xu});var Qo=F(Jt=>{"use strict";var Jg=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 Zg=Xo(),Qg=Jr(),Tu=Qr(),Ou=Zr(),em=Su(),tm=Jg(At()),Jo=(0,tm.default)("engine.io-client:polling");function rm(){}var En=class extends Zg.Polling{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",i=location.port;i||(i=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||i!==e.port}}doWrite(e,t){let i=this.request({method:"POST",data:e});i.on("success",t),i.on("error",(s,n)=>{this.onError("xhr post error",s,n)})}doPoll(){Jo("xhr poll");let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,i)=>{this.onError("xhr poll error",t,i)}),this.pollXhr=e}};Jt.BaseXHR=En;var dr=class r extends Qg.Emitter{constructor(e,t,i){super(),this.createRequest=e,(0,Tu.installTimerFunctions)(this,i),this._opts=i,this._method=i.method||"GET",this._uri=t,this._data=i.data!==void 0?i.data:null,this._create()}_create(){var e;let t=(0,Tu.pick)(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let i=this._xhr=this.createRequest(t);try{Jo("xhr open %s: %s",this._method,this._uri),i.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0);for(let s in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(s)&&i.setRequestHeader(s,this._opts.extraHeaders[s])}}catch{}if(this._method==="POST")try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{i.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(i),"withCredentials"in i&&(i.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(i.timeout=this._opts.requestTimeout),i.onreadystatechange=()=>{var s;i.readyState===3&&((s=this._opts.cookieJar)===null||s===void 0||s.parseCookies(i.getResponseHeader("set-cookie"))),i.readyState===4&&(i.status===200||i.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof i.status=="number"?i.status:0)},0))},Jo("xhr data %s",this._data),i.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=rm,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=dr;dr.requestsCount=0;dr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Cu);else if(typeof addEventListener=="function"){let r="onpagehide"in Ou.globalThisShim?"pagehide":"unload";addEventListener(r,Cu,!1)}}function Cu(){for(let r in dr.requests)dr.requests.hasOwnProperty(r)&&dr.requests[r].abort()}var im=(function(){let r=ku({xdomain:!1});return r&&r.responseType!==null})(),Zo=class extends En{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=im&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new dr(ku,this.uri(),e)}};Jt.XHR=Zo;function ku(r){let e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||em.hasCORS))return new XMLHttpRequest}catch{}if(!e)try{return new Ou.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}});var ta=F(Zt=>{"use strict";var sm=Zt&&Zt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=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,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),nm=Zt&&Zt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),om=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)&&sm(e,r,t);return nm(e,r),e};Object.defineProperty(Zt,"__esModule",{value:!0});Zt.XHR=void 0;var Ru=om(tu()),Pu=Qo(),am=Ru.default||Ru,ea=class extends Pu.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 Pu.Request(i=>new am(i),this.uri(),e)}};Zt.XHR=ea});var pr=F((QE,Lu)=>{"use strict";var Au=["nodebuffer","arraybuffer","fragments"],Iu=typeof Blob<"u";Iu&&Au.push("blob");Lu.exports={BINARY_TYPES:Au,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Iu,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var as=F((ew,wn)=>{"use strict";var{EMPTY_BUFFER:cm}=pr(),ra=Buffer[Symbol.species];function fm(r,e){if(r.length===0)return cm;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),i=0;for(let s=0;s<r.length;s++){let n=r[s];t.set(n,i),i+=n.length}return i<e?new ra(t.buffer,t.byteOffset,i):t}function Nu(r,e,t,i,s){for(let n=0;n<s;n++)t[i+n]=r[n]^e[n&3]}function Du(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function um(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function ia(r){if(ia.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new ra(r):ArrayBuffer.isView(r)?e=new ra(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),ia.readOnly=!1),e}wn.exports={concat:fm,mask:Nu,toArrayBuffer:um,toBuffer:ia,unmask:Du};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");wn.exports.mask=function(e,t,i,s,n){n<48?Nu(e,t,i,s,n):r.mask(e,t,i,s,n)},wn.exports.unmask=function(e,t){e.length<32?Du(e,t):r.unmask(e,t)}}catch{}});var Bu=F((tw,Fu)=>{"use strict";var Mu=Symbol("kDone"),sa=Symbol("kRun"),na=class{constructor(e){this[Mu]=()=>{this.pending--,this[sa]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[sa]()}[sa](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Mu])}}};Fu.exports=na});var fs=F((rw,Wu)=>{"use strict";var cs=require("zlib"),ju=as(),lm=Bu(),{kStatusCode:Uu}=pr(),hm=Buffer[Symbol.species],dm=Buffer.from([0,0,255,255]),xn=Symbol("permessage-deflate"),gr=Symbol("total-length"),Ri=Symbol("callback"),Dr=Symbol("buffers"),Pi=Symbol("error"),bn,oa=class{constructor(e,t,i){if(this._maxPayload=i|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,!bn){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;bn=new lm(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[Ri];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,i=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(!i)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(i.server_no_context_takeover=!0),t.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(i.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?i.client_max_window_bits=t.clientMaxWindowBits:(i.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}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(i=>{let s=t[i];if(s.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(s=s[0],i==="client_max_window_bits"){if(s!==!0){let n=+s;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${i}": ${s}`);s=n}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${s}`)}else if(i==="server_max_window_bits"){let n=+s;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${i}": ${s}`);s=n}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${s}`)}else throw new Error(`Unknown parameter "${i}"`);t[i]=s})}),e}decompress(e,t,i){bn.add(s=>{this._decompress(e,t,(n,a)=>{s(),i(n,a)})})}compress(e,t,i){bn.add(s=>{this._compress(e,t,(n,a)=>{s(),i(n,a)})})}_decompress(e,t,i){let s=this._isServer?"client":"server";if(!this._inflate){let n=`${s}_max_window_bits`,a=typeof this.params[n]!="number"?cs.Z_DEFAULT_WINDOWBITS:this.params[n];this._inflate=cs.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[xn]=this,this._inflate[gr]=0,this._inflate[Dr]=[],this._inflate.on("error",gm),this._inflate.on("data",qu)}this._inflate[Ri]=i,this._inflate.write(e),t&&this._inflate.write(dm),this._inflate.flush(()=>{let n=this._inflate[Pi];if(n){this._inflate.close(),this._inflate=null,i(n);return}let a=ju.concat(this._inflate[Dr],this._inflate[gr]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[gr]=0,this._inflate[Dr]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),i(null,a)})}_compress(e,t,i){let s=this._isServer?"server":"client";if(!this._deflate){let n=`${s}_max_window_bits`,a=typeof this.params[n]!="number"?cs.Z_DEFAULT_WINDOWBITS:this.params[n];this._deflate=cs.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[gr]=0,this._deflate[Dr]=[],this._deflate.on("data",pm)}this._deflate[Ri]=i,this._deflate.write(e),this._deflate.flush(cs.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let n=ju.concat(this._deflate[Dr],this._deflate[gr]);t&&(n=new hm(n.buffer,n.byteOffset,n.length-4)),this._deflate[Ri]=null,this._deflate[gr]=0,this._deflate[Dr]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),i(null,n)})}};Wu.exports=oa;function pm(r){this[Dr].push(r),this[gr]+=r.length}function qu(r){if(this[gr]+=r.length,this[xn]._maxPayload<1||this[gr]<=this[xn]._maxPayload){this[Dr].push(r);return}this[Pi]=new RangeError("Max payload size exceeded"),this[Pi].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Pi][Uu]=1009,this.removeListener("data",qu),this.reset()}function gm(r){if(this[xn]._inflate=null,this[Pi]){this[Ri](this[Pi]);return}r[Uu]=1007,this[Ri](r)}});var Ai=F((iw,Sn)=>{"use strict";var{isUtf8:Hu}=require("buffer"),{hasBlob:mm}=pr(),_m=[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 ym(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function aa(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 vm(r){return mm&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}Sn.exports={isBlob:vm,isValidStatusCode:ym,isValidUTF8:aa,tokenChars:_m};if(Hu)Sn.exports.isValidUTF8=function(r){return r.length<24?aa(r):Hu(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");Sn.exports.isValidUTF8=function(e){return e.length<32?aa(e):r(e)}}catch{}});var ha=F((sw,Xu)=>{"use strict";var{Writable:Em}=require("stream"),Vu=fs(),{BINARY_TYPES:wm,EMPTY_BUFFER:Ku,kStatusCode:bm,kWebSocket:xm}=pr(),{concat:ca,toArrayBuffer:Sm,unmask:Tm}=as(),{isValidStatusCode:Cm,isValidUTF8:zu}=Ai(),Tn=Buffer[Symbol.species],It=0,$u=1,Gu=2,Yu=3,fa=4,ua=5,Cn=6,la=class extends Em{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||wm[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[xm]=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,i){if(this._opcode===8&&this._state==It)return i();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new Tn(i.buffer,i.byteOffset+e,i.length-e),new Tn(i.buffer,i.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let i=this._buffers[0],s=t.length-e;e>=i.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(i.buffer,i.byteOffset,e),s),this._buffers[0]=new Tn(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case It:this.getInfo(e);break;case $u:this.getPayloadLength16(e);break;case Gu:this.getPayloadLength64(e);break;case Yu:this.getMask();break;case fa:this.getData(e);break;case ua:case Cn: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 i=(t[0]&64)===64;if(i&&!this._extensions[Vu.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(i){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=i}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(i){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=$u:this._payloadLength===127?this._state=Gu: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),i=t.readUInt32BE(0);if(i>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=i*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=Yu:this._state=fa}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=fa}getData(e){let t=Ku;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&&Tm(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=ua,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Vu.extensionName].decompress(e,this._fin,(s,n)=>{if(s)return t(s);if(n.length){if(this._messageLength+=n.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(n)}this.dataMessage(t),this._state===It&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=It;return}let t=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=ca(i,t):this._binaryType==="arraybuffer"?s=Sm(ca(i,t)):this._binaryType==="blob"?s=new Blob(i):s=i,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=It):(this._state=Cn,setImmediate(()=>{this.emit("message",s,!0),this._state=It,this.startLoop(e)}))}else{let s=ca(i,t);if(!this._skipUTF8Validation&&!zu(s)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(n);return}this._state===ua||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=It):(this._state=Cn,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,Ku),this.end();else{let i=e.readUInt16BE(0);if(!Cm(i)){let n=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(n);return}let s=new Tn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!zu(s)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(n);return}this._loop=!1,this.emit("conclude",i,s),this.end()}this._state=It;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=It):(this._state=Cn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=It,this.startLoop(t)}))}createError(e,t,i,s,n){this._loop=!1,this._errored=!0;let a=new e(i?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=n,a[bm]=s,a}};Xu.exports=la});var ga=F((ow,Qu)=>{"use strict";var{Duplex:nw}=require("stream"),{randomFillSync:Om}=require("crypto"),Ju=fs(),{EMPTY_BUFFER:km,kWebSocket:Rm,NOOP:Pm}=pr(),{isBlob:Ii,isValidStatusCode:Am}=Ai(),{mask:Zu,toBuffer:ti}=as(),Lt=Symbol("kByteLength"),Im=Buffer.alloc(4),On=8*1024,ri,Li=On,jt=0,Lm=1,Nm=2,da=class r{constructor(e,t,i){this._extensions=t||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=jt,this.onerror=Pm,this[Rm]=void 0}static frame(e,t){let i,s=!1,n=2,a=!1;t.mask&&(i=t.maskBuffer||Im,t.generateMask?t.generateMask(i):(Li===On&&(ri===void 0&&(ri=Buffer.alloc(On)),Om(ri,0,On),Li=0),i[0]=ri[Li++],i[1]=ri[Li++],i[2]=ri[Li++],i[3]=ri[Li++]),a=(i[0]|i[1]|i[2]|i[3])===0,n=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?(n+=8,u=127):c>125&&(n+=2,u=126);let d=Buffer.allocUnsafe(s?c+n:n);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[n-4]=i[0],d[n-3]=i[1],d[n-2]=i[2],d[n-1]=i[3],a?[d,e]:s?(Zu(e,i,d,n,c),[d]):(Zu(e,i,e,0,c),[d,e])):[d,e]}close(e,t,i,s){let n;if(e===void 0)n=km;else{if(typeof e!="number"||!Am(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)n=Buffer.allocUnsafe(2),n.writeUInt16BE(e,0);else{let c=Buffer.byteLength(t);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");n=Buffer.allocUnsafe(2+c),n.writeUInt16BE(e,0),typeof t=="string"?n.write(t,2):n.set(t,2)}}let a={[Lt]:n.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==jt?this.enqueue([this.dispatch,n,!1,a,s]):this.sendFrame(r.frame(n,a),s)}ping(e,t,i){let s,n;if(typeof e=="string"?(s=Buffer.byteLength(e),n=!1):Ii(e)?(s=e.size,n=!1):(e=ti(e),s=e.length,n=ti.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:n,rsv1:!1};Ii(e)?this._state!==jt?this.enqueue([this.getBlobData,e,!1,a,i]):this.getBlobData(e,!1,a,i):this._state!==jt?this.enqueue([this.dispatch,e,!1,a,i]):this.sendFrame(r.frame(e,a),i)}pong(e,t,i){let s,n;if(typeof e=="string"?(s=Buffer.byteLength(e),n=!1):Ii(e)?(s=e.size,n=!1):(e=ti(e),s=e.length,n=ti.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:n,rsv1:!1};Ii(e)?this._state!==jt?this.enqueue([this.getBlobData,e,!1,a,i]):this.getBlobData(e,!1,a,i):this._state!==jt?this.enqueue([this.dispatch,e,!1,a,i]):this.sendFrame(r.frame(e,a),i)}send(e,t,i){let s=this._extensions[Ju.extensionName],n=t.binary?2:1,a=t.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):Ii(e)?(c=e.size,u=!1):(e=ti(e),c=e.length,u=ti.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,n=0),t.fin&&(this._firstFragment=!0);let d={[Lt]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:n,readOnly:u,rsv1:a};Ii(e)?this._state!==jt?this.enqueue([this.getBlobData,e,this._compress,d,i]):this.getBlobData(e,this._compress,d,i):this._state!==jt?this.enqueue([this.dispatch,e,this._compress,d,i]):this.dispatch(e,this._compress,d,i)}getBlobData(e,t,i,s){this._bufferedBytes+=i[Lt],this._state=Nm,e.arrayBuffer().then(n=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(pa,this,c,s);return}this._bufferedBytes-=i[Lt];let a=ti(n);t?this.dispatch(a,t,i,s):(this._state=jt,this.sendFrame(r.frame(a,i),s),this.dequeue())}).catch(n=>{process.nextTick(Dm,this,n,s)})}dispatch(e,t,i,s){if(!t){this.sendFrame(r.frame(e,i),s);return}let n=this._extensions[Ju.extensionName];this._bufferedBytes+=i[Lt],this._state=Lm,n.compress(e,i.fin,(a,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");pa(this,u,s);return}this._bufferedBytes-=i[Lt],this._state=jt,i.readOnly=!1,this.sendFrame(r.frame(c,i),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)}};Qu.exports=da;function pa(r,e,t){typeof t=="function"&&t(e);for(let i=0;i<r._queue.length;i++){let s=r._queue[i],n=s[s.length-1];typeof n=="function"&&n(e)}}function Dm(r,e,t){pa(r,e,t),r.onerror(e)}});var cl=F((aw,al)=>{"use strict";var{kForOnEventAttribute:us,kListener:ma}=pr(),el=Symbol("kCode"),tl=Symbol("kData"),rl=Symbol("kError"),il=Symbol("kMessage"),sl=Symbol("kReason"),Ni=Symbol("kTarget"),nl=Symbol("kType"),ol=Symbol("kWasClean"),mr=class{constructor(e){this[Ni]=null,this[nl]=e}get target(){return this[Ni]}get type(){return this[nl]}};Object.defineProperty(mr.prototype,"target",{enumerable:!0});Object.defineProperty(mr.prototype,"type",{enumerable:!0});var ii=class extends mr{constructor(e,t={}){super(e),this[el]=t.code===void 0?0:t.code,this[sl]=t.reason===void 0?"":t.reason,this[ol]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[el]}get reason(){return this[sl]}get wasClean(){return this[ol]}};Object.defineProperty(ii.prototype,"code",{enumerable:!0});Object.defineProperty(ii.prototype,"reason",{enumerable:!0});Object.defineProperty(ii.prototype,"wasClean",{enumerable:!0});var Di=class extends mr{constructor(e,t={}){super(e),this[rl]=t.error===void 0?null:t.error,this[il]=t.message===void 0?"":t.message}get error(){return this[rl]}get message(){return this[il]}};Object.defineProperty(Di.prototype,"error",{enumerable:!0});Object.defineProperty(Di.prototype,"message",{enumerable:!0});var ls=class extends mr{constructor(e,t={}){super(e),this[tl]=t.data===void 0?null:t.data}get data(){return this[tl]}};Object.defineProperty(ls.prototype,"data",{enumerable:!0});var Mm={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[us]&&s[ma]===e&&!s[us])return;let i;if(r==="message")i=function(n,a){let c=new ls("message",{data:a?n:n.toString()});c[Ni]=this,kn(e,this,c)};else if(r==="close")i=function(n,a){let c=new ii("close",{code:n,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[Ni]=this,kn(e,this,c)};else if(r==="error")i=function(n){let a=new Di("error",{error:n,message:n.message});a[Ni]=this,kn(e,this,a)};else if(r==="open")i=function(){let n=new mr("open");n[Ni]=this,kn(e,this,n)};else return;i[us]=!!t[us],i[ma]=e,t.once?this.once(r,i):this.on(r,i)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[ma]===e&&!t[us]){this.removeListener(r,t);break}}};al.exports={CloseEvent:ii,ErrorEvent:Di,Event:mr,EventTarget:Mm,MessageEvent:ls};function kn(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var _a=F((cw,fl)=>{"use strict";var{tokenChars:hs}=Ai();function Qt(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function Fm(r){let e=Object.create(null),t=Object.create(null),i=!1,s=!1,n=!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&&hs[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 b=r.slice(u,g);d===44?(Qt(e,b,t),t=Object.create(null)):a=b,u=g=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);else if(c===void 0)if(g===-1&&hs[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(hs[d]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);u===-1?u=m:i||(i=!0),s=!1}else if(n)if(hs[d]===1)u===-1&&(u=m);else if(d===34&&u!==-1)n=!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)n=!0;else if(g===-1&&hs[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 b=r.slice(u,g);i&&(b=b.replace(/\\/g,""),i=!1),Qt(t,c,b),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||n||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):i?Qt(t,c,y.replace(/\\/g,"")):Qt(t,c,y),Qt(e,a,t)),e}function Bm(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(i=>[e].concat(Object.keys(i).map(s=>{let n=i[s];return Array.isArray(n)||(n=[n]),n.map(a=>a===!0?s:`${s}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}fl.exports={format:Bm,parse:Fm}});var In=F((lw,wl)=>{"use strict";var jm=require("events"),Um=require("https"),qm=require("http"),hl=require("net"),Wm=require("tls"),{randomBytes:Hm,createHash:Vm}=require("crypto"),{Duplex:fw,Readable:uw}=require("stream"),{URL:ya}=require("url"),Mr=fs(),Km=ha(),zm=ga(),{isBlob:$m}=Ai(),{BINARY_TYPES:ul,EMPTY_BUFFER:Rn,GUID:Gm,kForOnEventAttribute:va,kListener:Ym,kStatusCode:Xm,kWebSocket:it,NOOP:dl}=pr(),{EventTarget:{addEventListener:Jm,removeEventListener:Zm}}=cl(),{format:Qm,parse:e0}=_a(),{toBuffer:t0}=as(),r0=30*1e3,pl=Symbol("kAborted"),Ea=[8,13],_r=["CONNECTING","OPEN","CLOSING","CLOSED"],i0=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,We=class r extends jm{constructor(e,t,i){super(),this._binaryType=ul[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Rn,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?(i=t,t=[]):t=[t]),gl(this,e,t,i)):(this._autoPong=i.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ul.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,i){let s=new Km({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),n=new zm(e,this._extensions,i.generateMask);this._receiver=s,this._sender=n,this._socket=e,s[it]=this,n[it]=this,e[it]=this,s.on("conclude",o0),s.on("drain",a0),s.on("error",c0),s.on("message",f0),s.on("ping",u0),s.on("pong",l0),n.onerror=h0,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",yl),e.on("data",An),e.on("end",vl),e.on("error",El),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[Mr.extensionName]&&this._extensions[Mr.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,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),_l(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,i){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=t=void 0):typeof t=="function"&&(i=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){wa(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Rn,t,i)}pong(e,t,i){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=t=void 0):typeof t=="function"&&(i=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){wa(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Rn,t,i)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,i){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(i=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){wa(this,e,i);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Mr.extensionName]||(s.compress=!1),this._sender.send(e||Rn,s,i)}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(We,"CONNECTING",{enumerable:!0,value:_r.indexOf("CONNECTING")});Object.defineProperty(We.prototype,"CONNECTING",{enumerable:!0,value:_r.indexOf("CONNECTING")});Object.defineProperty(We,"OPEN",{enumerable:!0,value:_r.indexOf("OPEN")});Object.defineProperty(We.prototype,"OPEN",{enumerable:!0,value:_r.indexOf("OPEN")});Object.defineProperty(We,"CLOSING",{enumerable:!0,value:_r.indexOf("CLOSING")});Object.defineProperty(We.prototype,"CLOSING",{enumerable:!0,value:_r.indexOf("CLOSING")});Object.defineProperty(We,"CLOSED",{enumerable:!0,value:_r.indexOf("CLOSED")});Object.defineProperty(We.prototype,"CLOSED",{enumerable:!0,value:_r.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(We.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(We.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[va])return e[Ym];return null},set(e){for(let t of this.listeners(r))if(t[va]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[va]:!0})}})});We.prototype.addEventListener=Jm;We.prototype.removeEventListener=Zm;wl.exports=We;function gl(r,e,t,i){let s={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:Ea[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,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,!Ea.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Ea.join(", ")})`);let n;if(e instanceof ya)n=e;else try{n=new ya(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),r._url=n.href;let a=n.protocol==="wss:",c=n.protocol==="ws+unix:",u;if(n.protocol!=="ws:"&&!a&&!c?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!n.pathname?u="The URL's pathname is empty":n.hash&&(u="The URL contains a fragment identifier"),u){let C=new SyntaxError(u);if(r._redirects===0)throw C;Pn(r,C);return}let d=a?443:80,g=Hm(16).toString("base64"),m=a?Um.request:qm.request,y=new Set,b;if(s.createConnection=s.createConnection||(a?n0:s0),s.defaultPort=s.defaultPort||d,s.port=n.port||d,s.host=n.hostname.startsWith("[")?n.hostname.slice(1,-1):n.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":g,Connection:"Upgrade",Upgrade:"websocket"},s.path=n.pathname+n.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(b=new Mr(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Qm({[Mr.extensionName]:b.offer()})),t.length){for(let C of t){if(typeof C!="string"||!i0.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),(n.username||n.password)&&(s.auth=`${n.username}:${n.password}`),c){let C=s.path.split(":");s.socketPath=C[0],s.path=C[1]}let T;if(s.followRedirects){if(r._redirects===0){r._originalIpc=c,r._originalSecure=a,r._originalHostOrSocketPath=c?s.socketPath:n.host;let C=i&&i.headers;if(i={...i,headers:{}},C)for(let[H,ge]of Object.entries(C))i.headers[H.toLowerCase()]=ge}else if(r.listenerCount("redirect")===0){let C=c?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:n.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&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),T=r._req=m(s),r._redirects&&r.emit("redirect",r.url,T)}else T=r._req=m(s);s.timeout&&T.on("timeout",()=>{Tt(r,T,"Opening handshake has timed out")}),T.on("error",C=>{T===null||T[pl]||(T=r._req=null,Pn(r,C))}),T.on("response",C=>{let H=C.headers.location,ge=C.statusCode;if(H&&s.followRedirects&&ge>=300&&ge<400){if(++r._redirects>s.maxRedirects){Tt(r,T,"Maximum redirects exceeded");return}T.abort();let Y;try{Y=new ya(H,e)}catch{let j=new SyntaxError(`Invalid URL: ${H}`);Pn(r,j);return}gl(r,Y,t,i)}else r.emit("unexpected-response",T,C)||Tt(r,T,`Unexpected server response: ${C.statusCode}`)}),T.on("upgrade",(C,H,ge)=>{if(r.emit("upgrade",C),r.readyState!==We.CONNECTING)return;T=r._req=null;let Y=C.headers.upgrade;if(Y===void 0||Y.toLowerCase()!=="websocket"){Tt(r,H,"Invalid Upgrade header");return}let A=Vm("sha1").update(g+Gm).digest("base64");if(C.headers["sec-websocket-accept"]!==A){Tt(r,H,"Invalid Sec-WebSocket-Accept header");return}let j=C.headers["sec-websocket-protocol"],Q;if(j!==void 0?y.size?y.has(j)||(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,H,Q);return}j&&(r._protocol=j);let I=C.headers["sec-websocket-extensions"];if(I!==void 0){if(!b){Tt(r,H,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let oe;try{oe=e0(I)}catch{Tt(r,H,"Invalid Sec-WebSocket-Extensions header");return}let fe=Object.keys(oe);if(fe.length!==1||fe[0]!==Mr.extensionName){Tt(r,H,"Server indicated an extension that was not requested");return}try{b.accept(oe[Mr.extensionName])}catch{Tt(r,H,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Mr.extensionName]=b}r.setSocket(H,ge,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(T,r):T.end()}function Pn(r,e){r._readyState=We.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function s0(r){return r.path=r.socketPath,hl.connect(r)}function n0(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=hl.isIP(r.host)?"":r.host),Wm.connect(r)}function Tt(r,e,t){r._readyState=We.CLOSING;let i=new Error(t);Error.captureStackTrace(i,Tt),e.setHeader?(e[pl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Pn,r,i)):(e.destroy(i),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function wa(r,e,t){if(e){let i=$m(e)?e.size:t0(e).length;r._socket?r._sender._bufferedBytes+=i:r._bufferedAmount+=i}if(t){let i=new Error(`WebSocket is not open: readyState ${r.readyState} (${_r[r.readyState]})`);process.nextTick(t,i)}}function o0(r,e){let t=this[it];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[it]!==void 0&&(t._socket.removeListener("data",An),process.nextTick(ml,t._socket),r===1005?t.close():t.close(r,e))}function a0(){let r=this[it];r.isPaused||r._socket.resume()}function c0(r){let e=this[it];e._socket[it]!==void 0&&(e._socket.removeListener("data",An),process.nextTick(ml,e._socket),e.close(r[Xm])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function ll(){this[it].emitClose()}function f0(r,e){this[it].emit("message",r,e)}function u0(r){let e=this[it];e._autoPong&&e.pong(r,!this._isServer,dl),e.emit("ping",r)}function l0(r){this[it].emit("pong",r)}function ml(r){r.resume()}function h0(r){let e=this[it];e.readyState!==We.CLOSED&&(e.readyState===We.OPEN&&(e._readyState=We.CLOSING,_l(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function _l(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r0)}function yl(){let r=this[it];this.removeListener("close",yl),this.removeListener("data",An),this.removeListener("end",vl),r._readyState=We.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[it]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",ll),r._receiver.on("finish",ll))}function An(r){this[it]._receiver.write(r)||this.pause()}function vl(){let r=this[it];r._readyState=We.CLOSING,r._receiver.end(),this.end()}function El(){let r=this[it];this.removeListener("error",El),this.on("error",dl),r&&(r._readyState=We.CLOSING,this.destroy())}});var Tl=F((dw,Sl)=>{"use strict";var hw=In(),{Duplex:d0}=require("stream");function bl(r){r.emit("close")}function p0(){!this.destroyed&&this._writableState.finished&&this.destroy()}function xl(r){this.removeListener("error",xl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function g0(r,e){let t=!0,i=new d0({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(n,a){let c=!a&&i._readableState.objectMode?n.toString():n;i.push(c)||r.pause()}),r.once("error",function(n){i.destroyed||(t=!1,i.destroy(n))}),r.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(s,n){if(r.readyState===r.CLOSED){n(s),process.nextTick(bl,i);return}let a=!1;r.once("error",function(u){a=!0,n(u)}),r.once("close",function(){a||n(s),process.nextTick(bl,i)}),t&&r.terminate()},i._final=function(s){if(r.readyState===r.CONNECTING){r.once("open",function(){i._final(s)});return}r._socket!==null&&(r._socket._writableState.finished?(s(),i._readableState.endEmitted&&i.destroy()):(r._socket.once("finish",function(){s()}),r.close()))},i._read=function(){r.isPaused&&r.resume()},i._write=function(s,n,a){if(r.readyState===r.CONNECTING){r.once("open",function(){i._write(s,n,a)});return}r.send(s,a)},i.on("end",p0),i.on("error",xl),i}Sl.exports=g0});var Ol=F((pw,Cl)=>{"use strict";var{tokenChars:m0}=Ai();function _0(r){let e=new Set,t=-1,i=-1,s=0;for(s;s<r.length;s++){let a=r.charCodeAt(s);if(i===-1&&m0[a]===1)t===-1&&(t=s);else if(s!==0&&(a===32||a===9))i===-1&&t!==-1&&(i=s);else if(a===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);i===-1&&(i=s);let c=r.slice(t,i);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);e.add(c),t=i=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let n=r.slice(t,s);if(e.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);return e.add(n),e}Cl.exports={parse:_0}});var Nl=F((mw,Ll)=>{"use strict";var y0=require("events"),Ln=require("http"),{Duplex:gw}=require("stream"),{createHash:v0}=require("crypto"),kl=_a(),si=fs(),E0=Ol(),w0=In(),{GUID:b0,kWebSocket:x0}=pr(),S0=/^[+/0-9A-Za-z]{22}==$/,Rl=0,Pl=1,Il=2,ba=class extends y0{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:w0,...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=Ln.createServer((i,s)=>{let n=Ln.STATUS_CODES[426];s.writeHead(426,{"Content-Length":n.length,"Content-Type":"text/plain"}),s.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=T0(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,n,a)=>{this.handleUpgrade(s,n,a,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Rl}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===Il){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!==Pl)if(this._state=Pl,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,i,s){t.on("error",Al);let n=e.headers["sec-websocket-key"],a=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){ni(this,e,t,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){ni(this,e,t,400,"Invalid Upgrade header");return}if(n===void 0||!S0.test(n)){ni(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){ni(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=E0.parse(u)}catch{ni(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 si(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let b=kl.parse(g);b[si.extensionName]&&(y.accept(b[si.extensionName]),m[si.extensionName]=y)}catch{ni(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,(b,T,C,H)=>{if(!b)return ps(t,T||401,C,H);this.completeUpgrade(m,n,d,e,t,i,s)});return}if(!this.options.verifyClient(y))return ps(t,401)}this.completeUpgrade(m,n,d,e,t,i,s)}completeUpgrade(e,t,i,s,n,a,c){if(!n.readable||!n.writable)return n.destroy();if(n[x0])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Rl)return ps(n,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${v0("sha1").update(t+b0).digest("base64")}`],g=new this.options.WebSocket(null,void 0,this.options);if(i.size){let m=this.options.handleProtocols?this.options.handleProtocols(i,s):i.values().next().value;m&&(d.push(`Sec-WebSocket-Protocol: ${m}`),g._protocol=m)}if(e[si.extensionName]){let m=e[si.extensionName].params,y=kl.format({[si.extensionName]:[m]});d.push(`Sec-WebSocket-Extensions: ${y}`),g._extensions=e}this.emit("headers",d,s),n.write(d.concat(`\r
19
+ `)}function Fg(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function Bg(){return process.env.DEBUG}function jg(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]]}_n.exports=Vo()(rt);var{formatters:wu}=_n.exports;wu.o=function(r){return this.inspectOpts.colors=this.useColors,mn.inspect(r,this.inspectOpts).split(`
20
+ `).map(e=>e.trim()).join(" ")};wu.O=function(r){return this.inspectOpts.colors=this.useColors,mn.inspect(r,this.inspectOpts)}});var At=F(($w,$o)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?$o.exports=pu():$o.exports=Eu()});var os=F(Nr=>{"use strict";var Ug=Nr&&Nr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Nr,"__esModule",{value:!0});Nr.Transport=Nr.TransportError=void 0;var qg=xi(),Wg=Jr(),Hg=Qr(),Vg=Ho(),zg=Ug(At()),Kg=(0,zg.default)("engine.io-client:transport"),yn=class extends Error{constructor(e,t,i){super(e),this.description=t,this.context=i,this.type="TransportError"}};Nr.TransportError=yn;var Go=class extends Wg.Emitter{constructor(e){super(),this.writable=!1,(0,Hg.installTimerFunctions)(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,i){return super.emitReserved("error",new yn(e,t,i)),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):Kg("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=(0,qg.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,Vg.encode)(e);return t.length?"?"+t:""}};Nr.Transport=Go});var Xo=F(ki=>{"use strict";var $g=ki&&ki.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ki,"__esModule",{value:!0});ki.Polling=void 0;var Gg=os(),Yg=Qr(),bu=xi(),Xg=$g(At()),Bt=(0,Xg.default)("engine.io-client:polling"),Yo=class extends Gg.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 i=0;this._polling&&(Bt("we are currently polling - waiting to pause"),i++,this.once("pollComplete",function(){Bt("pre-pause polling complete"),--i||t()})),this.writable||(Bt("we are currently writing - waiting to pause"),i++,this.once("drain",function(){Bt("pre-pause writing complete"),--i||t()}))}else t()}_poll(){Bt("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){Bt("polling got data %s",e);let t=i=>{if(this.readyState==="opening"&&i.type==="open"&&this.onOpen(),i.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(i)};(0,bu.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,bu.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,Yg.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}};ki.Polling=Yo});var Su=F(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.hasCORS=void 0;var xu=!1;try{xu=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}vn.hasCORS=xu});var Qo=F(Jt=>{"use strict";var Jg=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 Zg=Xo(),Qg=Jr(),Tu=Qr(),Ou=Zr(),em=Su(),tm=Jg(At()),Jo=(0,tm.default)("engine.io-client:polling");function rm(){}var wn=class extends Zg.Polling{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",i=location.port;i||(i=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||i!==e.port}}doWrite(e,t){let i=this.request({method:"POST",data:e});i.on("success",t),i.on("error",(s,n)=>{this.onError("xhr post error",s,n)})}doPoll(){Jo("xhr poll");let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,i)=>{this.onError("xhr poll error",t,i)}),this.pollXhr=e}};Jt.BaseXHR=wn;var dr=class r extends Qg.Emitter{constructor(e,t,i){super(),this.createRequest=e,(0,Tu.installTimerFunctions)(this,i),this._opts=i,this._method=i.method||"GET",this._uri=t,this._data=i.data!==void 0?i.data:null,this._create()}_create(){var e;let t=(0,Tu.pick)(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let i=this._xhr=this.createRequest(t);try{Jo("xhr open %s: %s",this._method,this._uri),i.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0);for(let s in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(s)&&i.setRequestHeader(s,this._opts.extraHeaders[s])}}catch{}if(this._method==="POST")try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{i.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(i),"withCredentials"in i&&(i.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(i.timeout=this._opts.requestTimeout),i.onreadystatechange=()=>{var s;i.readyState===3&&((s=this._opts.cookieJar)===null||s===void 0||s.parseCookies(i.getResponseHeader("set-cookie"))),i.readyState===4&&(i.status===200||i.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof i.status=="number"?i.status:0)},0))},Jo("xhr data %s",this._data),i.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=rm,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=dr;dr.requestsCount=0;dr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Cu);else if(typeof addEventListener=="function"){let r="onpagehide"in Ou.globalThisShim?"pagehide":"unload";addEventListener(r,Cu,!1)}}function Cu(){for(let r in dr.requests)dr.requests.hasOwnProperty(r)&&dr.requests[r].abort()}var im=(function(){let r=ku({xdomain:!1});return r&&r.responseType!==null})(),Zo=class extends wn{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=im&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new dr(ku,this.uri(),e)}};Jt.XHR=Zo;function ku(r){let e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||em.hasCORS))return new XMLHttpRequest}catch{}if(!e)try{return new Ou.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}});var ta=F(Zt=>{"use strict";var sm=Zt&&Zt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=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,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),nm=Zt&&Zt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),om=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)&&sm(e,r,t);return nm(e,r),e};Object.defineProperty(Zt,"__esModule",{value:!0});Zt.XHR=void 0;var Ru=om(tu()),Pu=Qo(),am=Ru.default||Ru,ea=class extends Pu.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 Pu.Request(i=>new am(i),this.uri(),e)}};Zt.XHR=ea});var pr=F((Qw,Lu)=>{"use strict";var Au=["nodebuffer","arraybuffer","fragments"],Iu=typeof Blob<"u";Iu&&Au.push("blob");Lu.exports={BINARY_TYPES:Au,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Iu,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var as=F((eE,En)=>{"use strict";var{EMPTY_BUFFER:cm}=pr(),ra=Buffer[Symbol.species];function fm(r,e){if(r.length===0)return cm;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),i=0;for(let s=0;s<r.length;s++){let n=r[s];t.set(n,i),i+=n.length}return i<e?new ra(t.buffer,t.byteOffset,i):t}function Nu(r,e,t,i,s){for(let n=0;n<s;n++)t[i+n]=r[n]^e[n&3]}function Du(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function um(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function ia(r){if(ia.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new ra(r):ArrayBuffer.isView(r)?e=new ra(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),ia.readOnly=!1),e}En.exports={concat:fm,mask:Nu,toArrayBuffer:um,toBuffer:ia,unmask:Du};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");En.exports.mask=function(e,t,i,s,n){n<48?Nu(e,t,i,s,n):r.mask(e,t,i,s,n)},En.exports.unmask=function(e,t){e.length<32?Du(e,t):r.unmask(e,t)}}catch{}});var Bu=F((tE,Fu)=>{"use strict";var Mu=Symbol("kDone"),sa=Symbol("kRun"),na=class{constructor(e){this[Mu]=()=>{this.pending--,this[sa]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[sa]()}[sa](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Mu])}}};Fu.exports=na});var fs=F((rE,Wu)=>{"use strict";var cs=require("zlib"),ju=as(),lm=Bu(),{kStatusCode:Uu}=pr(),hm=Buffer[Symbol.species],dm=Buffer.from([0,0,255,255]),xn=Symbol("permessage-deflate"),gr=Symbol("total-length"),Ri=Symbol("callback"),Dr=Symbol("buffers"),Pi=Symbol("error"),bn,oa=class{constructor(e,t,i){if(this._maxPayload=i|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,!bn){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;bn=new lm(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[Ri];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,i=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(!i)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(i.server_no_context_takeover=!0),t.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(i.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?i.client_max_window_bits=t.clientMaxWindowBits:(i.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}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(i=>{let s=t[i];if(s.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(s=s[0],i==="client_max_window_bits"){if(s!==!0){let n=+s;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${i}": ${s}`);s=n}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${s}`)}else if(i==="server_max_window_bits"){let n=+s;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${i}": ${s}`);s=n}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${s}`)}else throw new Error(`Unknown parameter "${i}"`);t[i]=s})}),e}decompress(e,t,i){bn.add(s=>{this._decompress(e,t,(n,a)=>{s(),i(n,a)})})}compress(e,t,i){bn.add(s=>{this._compress(e,t,(n,a)=>{s(),i(n,a)})})}_decompress(e,t,i){let s=this._isServer?"client":"server";if(!this._inflate){let n=`${s}_max_window_bits`,a=typeof this.params[n]!="number"?cs.Z_DEFAULT_WINDOWBITS:this.params[n];this._inflate=cs.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[xn]=this,this._inflate[gr]=0,this._inflate[Dr]=[],this._inflate.on("error",gm),this._inflate.on("data",qu)}this._inflate[Ri]=i,this._inflate.write(e),t&&this._inflate.write(dm),this._inflate.flush(()=>{let n=this._inflate[Pi];if(n){this._inflate.close(),this._inflate=null,i(n);return}let a=ju.concat(this._inflate[Dr],this._inflate[gr]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[gr]=0,this._inflate[Dr]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),i(null,a)})}_compress(e,t,i){let s=this._isServer?"server":"client";if(!this._deflate){let n=`${s}_max_window_bits`,a=typeof this.params[n]!="number"?cs.Z_DEFAULT_WINDOWBITS:this.params[n];this._deflate=cs.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[gr]=0,this._deflate[Dr]=[],this._deflate.on("data",pm)}this._deflate[Ri]=i,this._deflate.write(e),this._deflate.flush(cs.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let n=ju.concat(this._deflate[Dr],this._deflate[gr]);t&&(n=new hm(n.buffer,n.byteOffset,n.length-4)),this._deflate[Ri]=null,this._deflate[gr]=0,this._deflate[Dr]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),i(null,n)})}};Wu.exports=oa;function pm(r){this[Dr].push(r),this[gr]+=r.length}function qu(r){if(this[gr]+=r.length,this[xn]._maxPayload<1||this[gr]<=this[xn]._maxPayload){this[Dr].push(r);return}this[Pi]=new RangeError("Max payload size exceeded"),this[Pi].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Pi][Uu]=1009,this.removeListener("data",qu),this.reset()}function gm(r){if(this[xn]._inflate=null,this[Pi]){this[Ri](this[Pi]);return}r[Uu]=1007,this[Ri](r)}});var Ai=F((iE,Sn)=>{"use strict";var{isUtf8:Hu}=require("buffer"),{hasBlob:mm}=pr(),_m=[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 ym(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function aa(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 vm(r){return mm&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}Sn.exports={isBlob:vm,isValidStatusCode:ym,isValidUTF8:aa,tokenChars:_m};if(Hu)Sn.exports.isValidUTF8=function(r){return r.length<24?aa(r):Hu(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");Sn.exports.isValidUTF8=function(e){return e.length<32?aa(e):r(e)}}catch{}});var ha=F((sE,Xu)=>{"use strict";var{Writable:wm}=require("stream"),Vu=fs(),{BINARY_TYPES:Em,EMPTY_BUFFER:zu,kStatusCode:bm,kWebSocket:xm}=pr(),{concat:ca,toArrayBuffer:Sm,unmask:Tm}=as(),{isValidStatusCode:Cm,isValidUTF8:Ku}=Ai(),Tn=Buffer[Symbol.species],It=0,$u=1,Gu=2,Yu=3,fa=4,ua=5,Cn=6,la=class extends wm{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Em[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[xm]=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,i){if(this._opcode===8&&this._state==It)return i();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new Tn(i.buffer,i.byteOffset+e,i.length-e),new Tn(i.buffer,i.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let i=this._buffers[0],s=t.length-e;e>=i.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(i.buffer,i.byteOffset,e),s),this._buffers[0]=new Tn(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case It:this.getInfo(e);break;case $u:this.getPayloadLength16(e);break;case Gu:this.getPayloadLength64(e);break;case Yu:this.getMask();break;case fa:this.getData(e);break;case ua:case Cn: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 i=(t[0]&64)===64;if(i&&!this._extensions[Vu.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(i){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=i}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(i){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=$u:this._payloadLength===127?this._state=Gu: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),i=t.readUInt32BE(0);if(i>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=i*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=Yu:this._state=fa}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=fa}getData(e){let t=zu;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&&Tm(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=ua,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Vu.extensionName].decompress(e,this._fin,(s,n)=>{if(s)return t(s);if(n.length){if(this._messageLength+=n.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(n)}this.dataMessage(t),this._state===It&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=It;return}let t=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=ca(i,t):this._binaryType==="arraybuffer"?s=Sm(ca(i,t)):this._binaryType==="blob"?s=new Blob(i):s=i,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=It):(this._state=Cn,setImmediate(()=>{this.emit("message",s,!0),this._state=It,this.startLoop(e)}))}else{let s=ca(i,t);if(!this._skipUTF8Validation&&!Ku(s)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(n);return}this._state===ua||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=It):(this._state=Cn,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,zu),this.end();else{let i=e.readUInt16BE(0);if(!Cm(i)){let n=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(n);return}let s=new Tn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ku(s)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(n);return}this._loop=!1,this.emit("conclude",i,s),this.end()}this._state=It;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=It):(this._state=Cn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=It,this.startLoop(t)}))}createError(e,t,i,s,n){this._loop=!1,this._errored=!0;let a=new e(i?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=n,a[bm]=s,a}};Xu.exports=la});var ga=F((oE,Qu)=>{"use strict";var{Duplex:nE}=require("stream"),{randomFillSync:Om}=require("crypto"),Ju=fs(),{EMPTY_BUFFER:km,kWebSocket:Rm,NOOP:Pm}=pr(),{isBlob:Ii,isValidStatusCode:Am}=Ai(),{mask:Zu,toBuffer:ti}=as(),Lt=Symbol("kByteLength"),Im=Buffer.alloc(4),On=8*1024,ri,Li=On,jt=0,Lm=1,Nm=2,da=class r{constructor(e,t,i){this._extensions=t||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=jt,this.onerror=Pm,this[Rm]=void 0}static frame(e,t){let i,s=!1,n=2,a=!1;t.mask&&(i=t.maskBuffer||Im,t.generateMask?t.generateMask(i):(Li===On&&(ri===void 0&&(ri=Buffer.alloc(On)),Om(ri,0,On),Li=0),i[0]=ri[Li++],i[1]=ri[Li++],i[2]=ri[Li++],i[3]=ri[Li++]),a=(i[0]|i[1]|i[2]|i[3])===0,n=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?(n+=8,u=127):c>125&&(n+=2,u=126);let d=Buffer.allocUnsafe(s?c+n:n);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[n-4]=i[0],d[n-3]=i[1],d[n-2]=i[2],d[n-1]=i[3],a?[d,e]:s?(Zu(e,i,d,n,c),[d]):(Zu(e,i,e,0,c),[d,e])):[d,e]}close(e,t,i,s){let n;if(e===void 0)n=km;else{if(typeof e!="number"||!Am(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)n=Buffer.allocUnsafe(2),n.writeUInt16BE(e,0);else{let c=Buffer.byteLength(t);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");n=Buffer.allocUnsafe(2+c),n.writeUInt16BE(e,0),typeof t=="string"?n.write(t,2):n.set(t,2)}}let a={[Lt]:n.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==jt?this.enqueue([this.dispatch,n,!1,a,s]):this.sendFrame(r.frame(n,a),s)}ping(e,t,i){let s,n;if(typeof e=="string"?(s=Buffer.byteLength(e),n=!1):Ii(e)?(s=e.size,n=!1):(e=ti(e),s=e.length,n=ti.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:n,rsv1:!1};Ii(e)?this._state!==jt?this.enqueue([this.getBlobData,e,!1,a,i]):this.getBlobData(e,!1,a,i):this._state!==jt?this.enqueue([this.dispatch,e,!1,a,i]):this.sendFrame(r.frame(e,a),i)}pong(e,t,i){let s,n;if(typeof e=="string"?(s=Buffer.byteLength(e),n=!1):Ii(e)?(s=e.size,n=!1):(e=ti(e),s=e.length,n=ti.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:n,rsv1:!1};Ii(e)?this._state!==jt?this.enqueue([this.getBlobData,e,!1,a,i]):this.getBlobData(e,!1,a,i):this._state!==jt?this.enqueue([this.dispatch,e,!1,a,i]):this.sendFrame(r.frame(e,a),i)}send(e,t,i){let s=this._extensions[Ju.extensionName],n=t.binary?2:1,a=t.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):Ii(e)?(c=e.size,u=!1):(e=ti(e),c=e.length,u=ti.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,n=0),t.fin&&(this._firstFragment=!0);let d={[Lt]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:n,readOnly:u,rsv1:a};Ii(e)?this._state!==jt?this.enqueue([this.getBlobData,e,this._compress,d,i]):this.getBlobData(e,this._compress,d,i):this._state!==jt?this.enqueue([this.dispatch,e,this._compress,d,i]):this.dispatch(e,this._compress,d,i)}getBlobData(e,t,i,s){this._bufferedBytes+=i[Lt],this._state=Nm,e.arrayBuffer().then(n=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(pa,this,c,s);return}this._bufferedBytes-=i[Lt];let a=ti(n);t?this.dispatch(a,t,i,s):(this._state=jt,this.sendFrame(r.frame(a,i),s),this.dequeue())}).catch(n=>{process.nextTick(Dm,this,n,s)})}dispatch(e,t,i,s){if(!t){this.sendFrame(r.frame(e,i),s);return}let n=this._extensions[Ju.extensionName];this._bufferedBytes+=i[Lt],this._state=Lm,n.compress(e,i.fin,(a,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");pa(this,u,s);return}this._bufferedBytes-=i[Lt],this._state=jt,i.readOnly=!1,this.sendFrame(r.frame(c,i),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)}};Qu.exports=da;function pa(r,e,t){typeof t=="function"&&t(e);for(let i=0;i<r._queue.length;i++){let s=r._queue[i],n=s[s.length-1];typeof n=="function"&&n(e)}}function Dm(r,e,t){pa(r,e,t),r.onerror(e)}});var cl=F((aE,al)=>{"use strict";var{kForOnEventAttribute:us,kListener:ma}=pr(),el=Symbol("kCode"),tl=Symbol("kData"),rl=Symbol("kError"),il=Symbol("kMessage"),sl=Symbol("kReason"),Ni=Symbol("kTarget"),nl=Symbol("kType"),ol=Symbol("kWasClean"),mr=class{constructor(e){this[Ni]=null,this[nl]=e}get target(){return this[Ni]}get type(){return this[nl]}};Object.defineProperty(mr.prototype,"target",{enumerable:!0});Object.defineProperty(mr.prototype,"type",{enumerable:!0});var ii=class extends mr{constructor(e,t={}){super(e),this[el]=t.code===void 0?0:t.code,this[sl]=t.reason===void 0?"":t.reason,this[ol]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[el]}get reason(){return this[sl]}get wasClean(){return this[ol]}};Object.defineProperty(ii.prototype,"code",{enumerable:!0});Object.defineProperty(ii.prototype,"reason",{enumerable:!0});Object.defineProperty(ii.prototype,"wasClean",{enumerable:!0});var Di=class extends mr{constructor(e,t={}){super(e),this[rl]=t.error===void 0?null:t.error,this[il]=t.message===void 0?"":t.message}get error(){return this[rl]}get message(){return this[il]}};Object.defineProperty(Di.prototype,"error",{enumerable:!0});Object.defineProperty(Di.prototype,"message",{enumerable:!0});var ls=class extends mr{constructor(e,t={}){super(e),this[tl]=t.data===void 0?null:t.data}get data(){return this[tl]}};Object.defineProperty(ls.prototype,"data",{enumerable:!0});var Mm={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[us]&&s[ma]===e&&!s[us])return;let i;if(r==="message")i=function(n,a){let c=new ls("message",{data:a?n:n.toString()});c[Ni]=this,kn(e,this,c)};else if(r==="close")i=function(n,a){let c=new ii("close",{code:n,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[Ni]=this,kn(e,this,c)};else if(r==="error")i=function(n){let a=new Di("error",{error:n,message:n.message});a[Ni]=this,kn(e,this,a)};else if(r==="open")i=function(){let n=new mr("open");n[Ni]=this,kn(e,this,n)};else return;i[us]=!!t[us],i[ma]=e,t.once?this.once(r,i):this.on(r,i)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[ma]===e&&!t[us]){this.removeListener(r,t);break}}};al.exports={CloseEvent:ii,ErrorEvent:Di,Event:mr,EventTarget:Mm,MessageEvent:ls};function kn(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var _a=F((cE,fl)=>{"use strict";var{tokenChars:hs}=Ai();function Qt(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function Fm(r){let e=Object.create(null),t=Object.create(null),i=!1,s=!1,n=!1,a,c,u=-1,d=-1,p=-1,m=0;for(;m<r.length;m++)if(d=r.charCodeAt(m),a===void 0)if(p===-1&&hs[d]===1)u===-1&&(u=m);else if(m!==0&&(d===32||d===9))p===-1&&u!==-1&&(p=m);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m);let E=r.slice(u,p);d===44?(Qt(e,E,t),t=Object.create(null)):a=E,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);else if(c===void 0)if(p===-1&&hs[d]===1)u===-1&&(u=m);else if(d===32||d===9)p===-1&&u!==-1&&(p=m);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m),Qt(t,r.slice(u,p),!0),d===44&&(Qt(e,a,t),t=Object.create(null),a=void 0),u=p=-1}else if(d===61&&u!==-1&&p===-1)c=r.slice(u,m),u=p=-1;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(s){if(hs[d]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);u===-1?u=m:i||(i=!0),s=!1}else if(n)if(hs[d]===1)u===-1&&(u=m);else if(d===34&&u!==-1)n=!1,p=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)n=!0;else if(p===-1&&hs[d]===1)u===-1&&(u=m);else if(u!==-1&&(d===32||d===9))p===-1&&(p=m);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m);let E=r.slice(u,p);i&&(E=E.replace(/\\/g,""),i=!1),Qt(t,c,E),d===44&&(Qt(e,a,t),t=Object.create(null),a=void 0),c=void 0,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);if(u===-1||n||d===32||d===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=m);let y=r.slice(u,p);return a===void 0?Qt(e,y,t):(c===void 0?Qt(t,y,!0):i?Qt(t,c,y.replace(/\\/g,"")):Qt(t,c,y),Qt(e,a,t)),e}function Bm(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(i=>[e].concat(Object.keys(i).map(s=>{let n=i[s];return Array.isArray(n)||(n=[n]),n.map(a=>a===!0?s:`${s}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}fl.exports={format:Bm,parse:Fm}});var In=F((lE,El)=>{"use strict";var jm=require("events"),Um=require("https"),qm=require("http"),hl=require("net"),Wm=require("tls"),{randomBytes:Hm,createHash:Vm}=require("crypto"),{Duplex:fE,Readable:uE}=require("stream"),{URL:ya}=require("url"),Mr=fs(),zm=ha(),Km=ga(),{isBlob:$m}=Ai(),{BINARY_TYPES:ul,EMPTY_BUFFER:Rn,GUID:Gm,kForOnEventAttribute:va,kListener:Ym,kStatusCode:Xm,kWebSocket:it,NOOP:dl}=pr(),{EventTarget:{addEventListener:Jm,removeEventListener:Zm}}=cl(),{format:Qm,parse:e0}=_a(),{toBuffer:t0}=as(),r0=30*1e3,pl=Symbol("kAborted"),wa=[8,13],_r=["CONNECTING","OPEN","CLOSING","CLOSED"],i0=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,We=class r extends jm{constructor(e,t,i){super(),this._binaryType=ul[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Rn,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?(i=t,t=[]):t=[t]),gl(this,e,t,i)):(this._autoPong=i.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ul.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,i){let s=new zm({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),n=new Km(e,this._extensions,i.generateMask);this._receiver=s,this._sender=n,this._socket=e,s[it]=this,n[it]=this,e[it]=this,s.on("conclude",o0),s.on("drain",a0),s.on("error",c0),s.on("message",f0),s.on("ping",u0),s.on("pong",l0),n.onerror=h0,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",yl),e.on("data",An),e.on("end",vl),e.on("error",wl),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[Mr.extensionName]&&this._extensions[Mr.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,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),_l(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,i){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=t=void 0):typeof t=="function"&&(i=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ea(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Rn,t,i)}pong(e,t,i){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=t=void 0):typeof t=="function"&&(i=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ea(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Rn,t,i)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,i){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(i=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ea(this,e,i);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Mr.extensionName]||(s.compress=!1),this._sender.send(e||Rn,s,i)}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(We,"CONNECTING",{enumerable:!0,value:_r.indexOf("CONNECTING")});Object.defineProperty(We.prototype,"CONNECTING",{enumerable:!0,value:_r.indexOf("CONNECTING")});Object.defineProperty(We,"OPEN",{enumerable:!0,value:_r.indexOf("OPEN")});Object.defineProperty(We.prototype,"OPEN",{enumerable:!0,value:_r.indexOf("OPEN")});Object.defineProperty(We,"CLOSING",{enumerable:!0,value:_r.indexOf("CLOSING")});Object.defineProperty(We.prototype,"CLOSING",{enumerable:!0,value:_r.indexOf("CLOSING")});Object.defineProperty(We,"CLOSED",{enumerable:!0,value:_r.indexOf("CLOSED")});Object.defineProperty(We.prototype,"CLOSED",{enumerable:!0,value:_r.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(We.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(We.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[va])return e[Ym];return null},set(e){for(let t of this.listeners(r))if(t[va]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[va]:!0})}})});We.prototype.addEventListener=Jm;We.prototype.removeEventListener=Zm;El.exports=We;function gl(r,e,t,i){let s={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:wa[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,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,!wa.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${wa.join(", ")})`);let n;if(e instanceof ya)n=e;else try{n=new ya(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),r._url=n.href;let a=n.protocol==="wss:",c=n.protocol==="ws+unix:",u;if(n.protocol!=="ws:"&&!a&&!c?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!n.pathname?u="The URL's pathname is empty":n.hash&&(u="The URL contains a fragment identifier"),u){let O=new SyntaxError(u);if(r._redirects===0)throw O;Pn(r,O);return}let d=a?443:80,p=Hm(16).toString("base64"),m=a?Um.request:qm.request,y=new Set,E;if(s.createConnection=s.createConnection||(a?n0:s0),s.defaultPort=s.defaultPort||d,s.port=n.port||d,s.host=n.hostname.startsWith("[")?n.hostname.slice(1,-1):n.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},s.path=n.pathname+n.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(E=new Mr(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Qm({[Mr.extensionName]:E.offer()})),t.length){for(let O of t){if(typeof O!="string"||!i0.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),(n.username||n.password)&&(s.auth=`${n.username}:${n.password}`),c){let O=s.path.split(":");s.socketPath=O[0],s.path=O[1]}let T;if(s.followRedirects){if(r._redirects===0){r._originalIpc=c,r._originalSecure=a,r._originalHostOrSocketPath=c?s.socketPath:n.host;let O=i&&i.headers;if(i={...i,headers:{}},O)for(let[H,me]of Object.entries(O))i.headers[H.toLowerCase()]=me}else if(r.listenerCount("redirect")===0){let O=c?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:n.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&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),T=r._req=m(s),r._redirects&&r.emit("redirect",r.url,T)}else T=r._req=m(s);s.timeout&&T.on("timeout",()=>{Tt(r,T,"Opening handshake has timed out")}),T.on("error",O=>{T===null||T[pl]||(T=r._req=null,Pn(r,O))}),T.on("response",O=>{let H=O.headers.location,me=O.statusCode;if(H&&s.followRedirects&&me>=300&&me<400){if(++r._redirects>s.maxRedirects){Tt(r,T,"Maximum redirects exceeded");return}T.abort();let X;try{X=new ya(H,e)}catch{let j=new SyntaxError(`Invalid URL: ${H}`);Pn(r,j);return}gl(r,X,t,i)}else r.emit("unexpected-response",T,O)||Tt(r,T,`Unexpected server response: ${O.statusCode}`)}),T.on("upgrade",(O,H,me)=>{if(r.emit("upgrade",O),r.readyState!==We.CONNECTING)return;T=r._req=null;let X=O.headers.upgrade;if(X===void 0||X.toLowerCase()!=="websocket"){Tt(r,H,"Invalid Upgrade header");return}let A=Vm("sha1").update(p+Gm).digest("base64");if(O.headers["sec-websocket-accept"]!==A){Tt(r,H,"Invalid Sec-WebSocket-Accept header");return}let j=O.headers["sec-websocket-protocol"],te;if(j!==void 0?y.size?y.has(j)||(te="Server sent an invalid subprotocol"):te="Server sent a subprotocol but none was requested":y.size&&(te="Server sent no subprotocol"),te){Tt(r,H,te);return}j&&(r._protocol=j);let I=O.headers["sec-websocket-extensions"];if(I!==void 0){if(!E){Tt(r,H,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ae;try{ae=e0(I)}catch{Tt(r,H,"Invalid Sec-WebSocket-Extensions header");return}let ue=Object.keys(ae);if(ue.length!==1||ue[0]!==Mr.extensionName){Tt(r,H,"Server indicated an extension that was not requested");return}try{E.accept(ae[Mr.extensionName])}catch{Tt(r,H,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Mr.extensionName]=E}r.setSocket(H,me,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(T,r):T.end()}function Pn(r,e){r._readyState=We.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function s0(r){return r.path=r.socketPath,hl.connect(r)}function n0(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=hl.isIP(r.host)?"":r.host),Wm.connect(r)}function Tt(r,e,t){r._readyState=We.CLOSING;let i=new Error(t);Error.captureStackTrace(i,Tt),e.setHeader?(e[pl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Pn,r,i)):(e.destroy(i),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function Ea(r,e,t){if(e){let i=$m(e)?e.size:t0(e).length;r._socket?r._sender._bufferedBytes+=i:r._bufferedAmount+=i}if(t){let i=new Error(`WebSocket is not open: readyState ${r.readyState} (${_r[r.readyState]})`);process.nextTick(t,i)}}function o0(r,e){let t=this[it];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[it]!==void 0&&(t._socket.removeListener("data",An),process.nextTick(ml,t._socket),r===1005?t.close():t.close(r,e))}function a0(){let r=this[it];r.isPaused||r._socket.resume()}function c0(r){let e=this[it];e._socket[it]!==void 0&&(e._socket.removeListener("data",An),process.nextTick(ml,e._socket),e.close(r[Xm])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function ll(){this[it].emitClose()}function f0(r,e){this[it].emit("message",r,e)}function u0(r){let e=this[it];e._autoPong&&e.pong(r,!this._isServer,dl),e.emit("ping",r)}function l0(r){this[it].emit("pong",r)}function ml(r){r.resume()}function h0(r){let e=this[it];e.readyState!==We.CLOSED&&(e.readyState===We.OPEN&&(e._readyState=We.CLOSING,_l(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function _l(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r0)}function yl(){let r=this[it];this.removeListener("close",yl),this.removeListener("data",An),this.removeListener("end",vl),r._readyState=We.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[it]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",ll),r._receiver.on("finish",ll))}function An(r){this[it]._receiver.write(r)||this.pause()}function vl(){let r=this[it];r._readyState=We.CLOSING,r._receiver.end(),this.end()}function wl(){let r=this[it];this.removeListener("error",wl),this.on("error",dl),r&&(r._readyState=We.CLOSING,this.destroy())}});var Tl=F((dE,Sl)=>{"use strict";var hE=In(),{Duplex:d0}=require("stream");function bl(r){r.emit("close")}function p0(){!this.destroyed&&this._writableState.finished&&this.destroy()}function xl(r){this.removeListener("error",xl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function g0(r,e){let t=!0,i=new d0({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(n,a){let c=!a&&i._readableState.objectMode?n.toString():n;i.push(c)||r.pause()}),r.once("error",function(n){i.destroyed||(t=!1,i.destroy(n))}),r.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(s,n){if(r.readyState===r.CLOSED){n(s),process.nextTick(bl,i);return}let a=!1;r.once("error",function(u){a=!0,n(u)}),r.once("close",function(){a||n(s),process.nextTick(bl,i)}),t&&r.terminate()},i._final=function(s){if(r.readyState===r.CONNECTING){r.once("open",function(){i._final(s)});return}r._socket!==null&&(r._socket._writableState.finished?(s(),i._readableState.endEmitted&&i.destroy()):(r._socket.once("finish",function(){s()}),r.close()))},i._read=function(){r.isPaused&&r.resume()},i._write=function(s,n,a){if(r.readyState===r.CONNECTING){r.once("open",function(){i._write(s,n,a)});return}r.send(s,a)},i.on("end",p0),i.on("error",xl),i}Sl.exports=g0});var Ol=F((pE,Cl)=>{"use strict";var{tokenChars:m0}=Ai();function _0(r){let e=new Set,t=-1,i=-1,s=0;for(s;s<r.length;s++){let a=r.charCodeAt(s);if(i===-1&&m0[a]===1)t===-1&&(t=s);else if(s!==0&&(a===32||a===9))i===-1&&t!==-1&&(i=s);else if(a===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);i===-1&&(i=s);let c=r.slice(t,i);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);e.add(c),t=i=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let n=r.slice(t,s);if(e.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);return e.add(n),e}Cl.exports={parse:_0}});var Nl=F((mE,Ll)=>{"use strict";var y0=require("events"),Ln=require("http"),{Duplex:gE}=require("stream"),{createHash:v0}=require("crypto"),kl=_a(),si=fs(),w0=Ol(),E0=In(),{GUID:b0,kWebSocket:x0}=pr(),S0=/^[+/0-9A-Za-z]{22}==$/,Rl=0,Pl=1,Il=2,ba=class extends y0{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:E0,...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=Ln.createServer((i,s)=>{let n=Ln.STATUS_CODES[426];s.writeHead(426,{"Content-Length":n.length,"Content-Type":"text/plain"}),s.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=T0(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,n,a)=>{this.handleUpgrade(s,n,a,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Rl}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===Il){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!==Pl)if(this._state=Pl,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,i,s){t.on("error",Al);let n=e.headers["sec-websocket-key"],a=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){ni(this,e,t,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){ni(this,e,t,400,"Invalid Upgrade header");return}if(n===void 0||!S0.test(n)){ni(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){ni(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=w0.parse(u)}catch{ni(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],m={};if(this.options.perMessageDeflate&&p!==void 0){let y=new si(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let E=kl.parse(p);E[si.extensionName]&&(y.accept(E[si.extensionName]),m[si.extensionName]=y)}catch{ni(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,(E,T,O,H)=>{if(!E)return ps(t,T||401,O,H);this.completeUpgrade(m,n,d,e,t,i,s)});return}if(!this.options.verifyClient(y))return ps(t,401)}this.completeUpgrade(m,n,d,e,t,i,s)}completeUpgrade(e,t,i,s,n,a,c){if(!n.readable||!n.writable)return n.destroy();if(n[x0])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Rl)return ps(n,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${v0("sha1").update(t+b0).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(i.size){let m=this.options.handleProtocols?this.options.handleProtocols(i,s):i.values().next().value;m&&(d.push(`Sec-WebSocket-Protocol: ${m}`),p._protocol=m)}if(e[si.extensionName]){let m=e[si.extensionName].params,y=kl.format({[si.extensionName]:[m]});d.push(`Sec-WebSocket-Extensions: ${y}`),p._extensions=e}this.emit("headers",d,s),n.write(d.concat(`\r
21
21
  `).join(`\r
22
- `)),n.removeListener("error",Al),g.setSocket(n,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(ds,this)})),c(g,s)}};Ll.exports=ba;function T0(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let i of Object.keys(e))r.removeListener(i,e[i])}}function ds(r){r._state=Il,r.emit("close")}function Al(){this.destroy()}function ps(r,e,t,i){t=t||Ln.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...i},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${Ln.STATUS_CODES[e]}\r
22
+ `)),n.removeListener("error",Al),p.setSocket(n,a,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on("close",()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(ds,this)})),c(p,s)}};Ll.exports=ba;function T0(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let i of Object.keys(e))r.removeListener(i,e[i])}}function ds(r){r._state=Il,r.emit("close")}function Al(){this.destroy()}function ps(r,e,t,i){t=t||Ln.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...i},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${Ln.STATUS_CODES[e]}\r
23
23
  `+Object.keys(i).map(s=>`${s}: ${i[s]}`).join(`\r
24
24
  `)+`\r
25
25
  \r
26
- `+t)}function ni(r,e,t,i,s,n){if(r.listenerCount("wsClientError")){let a=new Error(s);Error.captureStackTrace(a,ni),r.emit("wsClientError",a,t,e)}else ps(t,i,s,n)}});var Ml=F((_w,Dl)=>{"use strict";var yr=In();yr.createWebSocketStream=Tl();yr.Server=Nl();yr.Receiver=ha();yr.Sender=ga();yr.WebSocket=yr;yr.WebSocketServer=yr.Server;Dl.exports=yr});var Ca=F(Fr=>{"use strict";var C0=Fr&&Fr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Fr,"__esModule",{value:!0});Fr.WS=Fr.BaseWS=void 0;var O0=os(),Fl=Qr(),k0=xi(),Sa=Zr(),R0=C0(At()),P0=(0,R0.default)("engine.io-client:websocket"),Bl=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Nn=class extends O0.Transport{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,i=Bl?{}:(0,Fl.pick)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(i.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,i)}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 i=e[t],s=t===e.length-1;(0,k0.encodePacket)(i,this.supportsBinary,n=>{try{this.doWrite(i,n)}catch{P0("websocket closed before onclose event")}s&&(0,Sa.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,Fl.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}};Fr.BaseWS=Nn;var xa=Sa.globalThisShim.WebSocket||Sa.globalThisShim.MozWebSocket,Ta=class extends Nn{createSocket(e,t,i){return Bl?new xa(e,t,i):t?new xa(e,t):new xa(e)}doWrite(e,t){this.ws.send(t)}};Fr.WS=Ta});var ka=F(er=>{"use strict";var A0=er&&er.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=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,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),I0=er&&er.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),L0=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)&&A0(e,r,t);return I0(e,r),e};Object.defineProperty(er,"__esModule",{value:!0});er.WS=void 0;var N0=L0(Ml()),D0=Ca(),Oa=class extends D0.BaseWS{createSocket(e,t,i){var s;if(!((s=this.socket)===null||s===void 0)&&s._cookieJar){i.headers=i.headers||{},i.headers.cookie=typeof i.headers.cookie=="string"?[i.headers.cookie]:i.headers.cookie||[];for(let[n,a]of this.socket._cookieJar.cookies)i.headers.cookie.push(`${n}=${a.value}`)}return new N0.WebSocket(e,t,i)}doWrite(e,t){let i={};e.options&&(i.compress=e.options.compress),this.opts.perMessageDeflate&&(typeof t=="string"?Buffer.byteLength(t):t.length)<this.opts.perMessageDeflate.threshold&&(i.compress=!1),this.ws.send(t,i)}};er.WS=Oa});var Pa=F(Mi=>{"use strict";var M0=Mi&&Mi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Mi,"__esModule",{value:!0});Mi.WT=void 0;var F0=os(),B0=Zr(),jl=xi(),j0=M0(At()),gs=(0,j0.default)("engine.io-client:webtransport"),Ra=class extends F0.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,jl.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=e.readable.pipeThrough(t).getReader(),s=(0,jl.createPacketEncoderStream)();s.readable.pipeTo(e.writable),this._writer=s.writable.getWriter();let n=()=>{i.read().then(({done:c,value:u})=>{if(c){gs("session is closed");return}gs("received chunk: %o",u),this.onPacket(u),n()}).catch(c=>{gs("an error occurred while reading: %s",c)})};n();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 i=e[t],s=t===e.length-1;this._writer.write(i).then(()=>{s&&(0,B0.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};Mi.WT=Ra});var Aa=F(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.transports=void 0;var U0=ta(),q0=ka(),W0=Pa();Dn.transports={websocket:q0.WS,webtransport:W0.WT,polling:U0.XHR}});var La=F(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});Ia.parse=K0;var H0=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,V0=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function K0(r){if(r.length>8e3)throw"URI too long";let e=r,t=r.indexOf("["),i=r.indexOf("]");t!=-1&&i!=-1&&(r=r.substring(0,t)+r.substring(t,i).replace(/:/g,";")+r.substring(i,r.length));let s=H0.exec(r||""),n={},a=14;for(;a--;)n[V0[a]]=s[a]||"";return t!=-1&&i!=-1&&(n.source=e,n.host=n.host.substring(1,n.host.length-1).replace(/;/g,":"),n.authority=n.authority.replace("[","").replace("]","").replace(/;/g,":"),n.ipv6uri=!0),n.pathNames=z0(n,n.path),n.queryKey=$0(n,n.query),n}function z0(r,e){let t=/\/{2,9}/g,i=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&i.splice(0,1),e.slice(-1)=="/"&&i.splice(i.length-1,1),i}function $0(r,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(i,s,n){s&&(t[s]=n)}),t}});var Fa=F(tr=>{"use strict";var G0=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 Y0=Aa(),Ul=Qr(),X0=Ho(),ql=La(),J0=Jr(),Wl=xi(),Na=Zr(),Z0=G0(At()),Me=(0,Z0.default)("engine.io-client:socket"),Da=typeof addEventListener=="function"&&typeof removeEventListener=="function",ms=[];Da&&addEventListener("offline",()=>{Me("closing %d connection(s) because the network was lost",ms.length),ms.forEach(r=>r())},!1);var oi=class r extends J0.Emitter{constructor(e,t){if(super(),this.binaryType=Na.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 i=(0,ql.parse)(e);t.hostname=i.host,t.secure=i.protocol==="https"||i.protocol==="wss",t.port=i.port,i.query&&(t.query=i.query)}else t.host&&(t.hostname=(0,ql.parse)(t.host).host);(0,Ul.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(i=>{let s=i.prototype.name;this.transports.push(s),this._transportsByName[s]=i}),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,X0.decode)(this.opts.query)),Da&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(Me("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},ms.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,Na.createCookieJar)()),this._open()}createTransport(e){Me('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=Wl.protocol,t.transport=e,this.id&&(t.sid=this.id);let i=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return Me("options: %j",i),new this._transportsByName[e](i)}_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){Me("setting transport %s",e.name),this.transport&&(Me("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(){Me("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(Me('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 Me('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();Me("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 i=0;i<this.writeBuffer.length;i++){let s=this.writeBuffer[i].data;if(s&&(t+=(0,Ul.byteLength)(s)),i>0&&t>this._maxPayload)return Me("only send %d out of %d packets",i,this.writeBuffer.length),this.writeBuffer.slice(0,i);t+=2}return Me("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&&(Me("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,Na.nextTick)(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,i){return this._sendPacket("message",e,t,i),this}send(e,t,i){return this._sendPacket("message",e,t,i),this}_sendPacket(e,t,i,s){if(typeof t=="function"&&(s=t,t=void 0),typeof i=="function"&&(s=i,i=null),this.readyState==="closing"||this.readyState==="closed")return;i=i||{},i.compress=i.compress!==!1;let n={type:e,data:t,options:i};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),s&&this.once("flush",s),this.flush()}close(){let e=()=>{this._onClose("forced close"),Me("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},i=()=>{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?i():e()}):this.upgrading?i():e()),this}_onError(e){if(Me("socket error %j",e),r.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return Me("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(Me('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Da&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let i=ms.indexOf(this._offlineEventListener);i!==-1&&(Me("removing listener for the 'offline' event"),ms.splice(i,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};tr.SocketWithoutUpgrade=oi;oi.protocol=Wl.protocol;var Mn=class extends oi{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){Me("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){Me('probing transport "%s"',e);let t=this.createTransport(e),i=!1;oi.priorWebsocketSuccess=!1;let s=()=>{i||(Me('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",m=>{if(!i)if(m.type==="pong"&&m.data==="probe"){if(Me('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;oi.priorWebsocketSuccess=t.name==="websocket",Me('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{i||this.readyState!=="closed"&&(Me("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{Me('probe transport "%s" failed',e);let y=new Error("probe error");y.transport=t.name,this.emitReserved("upgradeError",y)}}))};function n(){i||(i=!0,g(),t.close(),t=null)}let a=m=>{let y=new Error("probe error: "+m);y.transport=t.name,n(),Me('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&&(Me('"%s" works - aborting "%s"',m.name,t.name),n())}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(()=>{i||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let i=0;i<e.length;i++)~this.transports.indexOf(e[i])&&t.push(e[i]);return t}};tr.SocketWithUpgrade=Mn;var Ma=class extends Mn{constructor(e,t={}){let i=typeof e=="object"?e:t;(!i.transports||i.transports&&typeof i.transports[0]=="string")&&(i.transports=(i.transports||["polling","websocket","webtransport"]).map(s=>Y0.transports[s]).filter(s=>!!s)),super(e,i)}};tr.Socket=Ma});var Hl=F(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.Fetch=void 0;var Q0=Xo(),Ba=class extends Q0.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(i=>{if(!i.ok)return this.onError("fetch write error",i.status,i);t()}).catch(i=>{this.onError("fetch write error",i)})}_fetch(e){var t;let i=e!==void 0,s=new Headers(this.opts.extraHeaders);return i&&s.set("content-type","text/plain;charset=UTF-8"),(t=this.socket._cookieJar)===null||t===void 0||t.appendCookies(s),fetch(this.uri(),{method:i?"POST":"GET",body:i?e:null,headers:s,credentials:this.opts.withCredentials?"include":"omit"}).then(n=>{var a;return(a=this.socket._cookieJar)===null||a===void 0||a.parseCookies(n.headers.getSetCookie()),n})}};Fn.Fetch=Ba});var Bn=F(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.WebTransport=we.WebSocket=we.NodeWebSocket=we.XHR=we.NodeXHR=we.Fetch=we.nextTick=we.parse=we.installTimerFunctions=we.transports=we.TransportError=we.Transport=we.protocol=we.SocketWithUpgrade=we.SocketWithoutUpgrade=we.Socket=void 0;var Vl=Fa();Object.defineProperty(we,"Socket",{enumerable:!0,get:function(){return Vl.Socket}});var Kl=Fa();Object.defineProperty(we,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return Kl.SocketWithoutUpgrade}});Object.defineProperty(we,"SocketWithUpgrade",{enumerable:!0,get:function(){return Kl.SocketWithUpgrade}});we.protocol=Vl.Socket.protocol;var zl=os();Object.defineProperty(we,"Transport",{enumerable:!0,get:function(){return zl.Transport}});Object.defineProperty(we,"TransportError",{enumerable:!0,get:function(){return zl.TransportError}});var e_=Aa();Object.defineProperty(we,"transports",{enumerable:!0,get:function(){return e_.transports}});var t_=Qr();Object.defineProperty(we,"installTimerFunctions",{enumerable:!0,get:function(){return t_.installTimerFunctions}});var r_=La();Object.defineProperty(we,"parse",{enumerable:!0,get:function(){return r_.parse}});var i_=Zr();Object.defineProperty(we,"nextTick",{enumerable:!0,get:function(){return i_.nextTick}});var s_=Hl();Object.defineProperty(we,"Fetch",{enumerable:!0,get:function(){return s_.Fetch}});var n_=ta();Object.defineProperty(we,"NodeXHR",{enumerable:!0,get:function(){return n_.XHR}});var o_=Qo();Object.defineProperty(we,"XHR",{enumerable:!0,get:function(){return o_.XHR}});var a_=ka();Object.defineProperty(we,"NodeWebSocket",{enumerable:!0,get:function(){return a_.WS}});var c_=Ca();Object.defineProperty(we,"WebSocket",{enumerable:!0,get:function(){return c_.WS}});var f_=Pa();Object.defineProperty(we,"WebTransport",{enumerable:!0,get:function(){return f_.WT}})});var Gl=F(_s=>{"use strict";var u_=_s&&_s.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(_s,"__esModule",{value:!0});_s.url=d_;var l_=Bn(),h_=u_(At()),$l=(0,h_.default)("socket.io-client:url");function d_(r,e="",t){let i=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)||($l("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),$l("parse %s",r),i=(0,l_.parse)(r)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";let n=i.host.indexOf(":")!==-1?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+n+":"+i.port+e,i.href=i.protocol+"://"+n+(t&&t.port===i.port?"":":"+i.port),i}});var ja=F(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.isBinary=Xl;Un.hasBinary=jn;var p_=typeof ArrayBuffer=="function",g_=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,Yl=Object.prototype.toString,m_=typeof Blob=="function"||typeof Blob<"u"&&Yl.call(Blob)==="[object BlobConstructor]",__=typeof File=="function"||typeof File<"u"&&Yl.call(File)==="[object FileConstructor]";function Xl(r){return p_&&(r instanceof ArrayBuffer||g_(r))||m_&&r instanceof Blob||__&&r instanceof File}function jn(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,i=r.length;t<i;t++)if(jn(r[t]))return!0;return!1}if(Xl(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return jn(r.toJSON(),!0);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&jn(r[t]))return!0;return!1}});var Jl=F(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.deconstructPacket=v_;qn.reconstructPacket=E_;var y_=ja();function v_(r){let e=[],t=r.data,i=r;return i.data=Ua(t,e),i.attachments=e.length,{packet:i,buffers:e}}function Ua(r,e){if(!r)return r;if((0,y_.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 i=0;i<r.length;i++)t[i]=Ua(r[i],e);return t}else if(typeof r=="object"&&!(r instanceof Date)){let t={};for(let i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=Ua(r[i],e));return t}return r}function E_(r,e){return r.data=qa(r.data,e),delete r.attachments,r}function qa(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]=qa(r[t],e);else if(typeof r=="object")for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=qa(r[t],e));return r}});var Hn=F(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.Decoder=Ut.Encoder=Ut.PacketType=Ut.protocol=void 0;Ut.isPacketValid=O_;var w_=Jr(),Zl=Jl(),Ql=ja(),b_=At(),Wa=(0,b_.default)("socket.io-parser"),eh=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];Ut.protocol=5;var De;(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"})(De||(Ut.PacketType=De={}));var Ha=class{constructor(e){this.replacer=e}encode(e){return Wa("encoding packet %j",e),(e.type===De.EVENT||e.type===De.ACK)&&(0,Ql.hasBinary)(e)?this.encodeAsBinary({type:e.type===De.EVENT?De.BINARY_EVENT:De.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===De.BINARY_EVENT||e.type===De.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)),Wa("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=(0,Zl.deconstructPacket)(e),i=this.encodeAsString(t.packet),s=t.buffers;return s.unshift(i),s}};Ut.Encoder=Ha;var Va=class r extends w_.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 i=t.type===De.BINARY_EVENT;i||t.type===De.BINARY_ACK?(t.type=i?De.EVENT:De.ACK,this.reconstructor=new Ka(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,Ql.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,i={type:Number(e.charAt(0))};if(De[i.type]===void 0)throw new Error("unknown packet type "+i.type);if(i.type===De.BINARY_EVENT||i.type===De.BINARY_ACK){let n=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);let a=e.substring(n,t);if(a!=Number(a)||e.charAt(t)!=="-")throw new Error("Illegal attachments");i.attachments=Number(a)}if(e.charAt(t+1)==="/"){let n=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););i.nsp=e.substring(n,t)}else i.nsp="/";let s=e.charAt(t+1);if(s!==""&&Number(s)==s){let n=t+1;for(;++t;){let a=e.charAt(t);if(a==null||Number(a)!=a){--t;break}if(t===e.length)break}i.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){let n=this.tryParse(e.substr(t));if(r.isPayloadValid(i.type,n))i.data=n;else throw new Error("invalid payload")}return Wa("decoded %s as %j",e,i),i}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case De.CONNECT:return Wn(t);case De.DISCONNECT:return t===void 0;case De.CONNECT_ERROR:return typeof t=="string"||Wn(t);case De.EVENT:case De.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&eh.indexOf(t[0])===-1);case De.ACK:case De.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};Ut.Decoder=Va;var Ka=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,Zl.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function x_(r){return typeof r=="string"}var S_=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function T_(r){return r===void 0||S_(r)}function Wn(r){return Object.prototype.toString.call(r)==="[object Object]"}function C_(r,e){switch(r){case De.CONNECT:return e===void 0||Wn(e);case De.DISCONNECT:return e===void 0;case De.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&eh.indexOf(e[0])===-1);case De.ACK:return Array.isArray(e);case De.CONNECT_ERROR:return typeof e=="string"||Wn(e);default:return!1}}function O_(r){return x_(r.nsp)&&T_(r.id)&&C_(r.type,r.data)}});var $a=F(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.on=k_;function k_(r,e,t){return r.on(e,t),function(){r.off(e,t)}}});var Ya=F(Fi=>{"use strict";var R_=Fi&&Fi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Fi,"__esModule",{value:!0});Fi.Socket=void 0;var qt=Hn(),Vn=$a(),P_=Jr(),A_=R_(At()),Ze=(0,A_.default)("socket.io-client:socket"),I_=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Ga=class extends P_.Emitter{constructor(e,t,i){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,i&&i.auth&&(this.auth=i.auth),this._opts=Object.assign({},i),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[(0,Vn.on)(e,"open",this.onopen.bind(this)),(0,Vn.on)(e,"packet",this.onpacket.bind(this)),(0,Vn.on)(e,"error",this.onerror.bind(this)),(0,Vn.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 i,s,n;if(I_.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++;Ze("emitting packet with ack id %d",g);let m=t.pop();this._registerAckCallback(g,m),a.id=g}let c=(s=(i=this.io.engine)===null||i===void 0?void 0:i.transport)===null||s===void 0?void 0:s.writable,u=this.connected&&!(!((n=this.io.engine)===null||n===void 0)&&n._hasPingExpired());return this.flags.volatile&&!c?Ze("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 i;let s=(i=this.flags.timeout)!==null&&i!==void 0?i:this._opts.ackTimeout;if(s===void 0){this.acks[e]=t;return}let n=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===e&&(Ze("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(c,1));Ze("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(n),t.apply(this,c)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((i,s)=>{let n=(a,c)=>a?s(a):i(c);n.withError=!0,t.push(n),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let i={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((s,...n)=>i!==this._queue[0]?Ze("packet [%d] already acknowledged",i.id):(s!==null?i.tryCount>this._opts.retries&&(Ze("packet [%d] is discarded after %d tries",i.id,i.tryCount),this._queue.shift(),t&&t(s)):(Ze("packet [%d] was successfully sent",i.id),this._queue.shift(),t&&t(null,...n)),i.pending=!1,this._drainQueue())),this._queue.push(i),this._drainQueue()}_drainQueue(e=!1){if(Ze("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){Ze("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,Ze("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(){Ze("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){Ze("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(i=>String(i.id)===e)){let i=this.acks[e];delete this.acks[e],i.withError&&i.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 i=new Error(e.data.message);i.data=e.data.data,this.emitReserved("connect_error",i);break}}onevent(e){let t=e.data||[];Ze("emitting event %j",t),e.id!=null&&(Ze("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 i of t)i.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,i=!1;return function(...s){i||(i=!0,Ze("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"){Ze("bad ack %s",e.id);return}delete this.acks[e.id],Ze("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){Ze("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(){Ze("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&&(Ze("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 i=0;i<t.length;i++)if(e===t[i])return t.splice(i,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 i=0;i<t.length;i++)if(e===t[i])return t.splice(i,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 i of t)i.apply(this,e.data)}}};Fi.Socket=Ga});var th=F(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.Backoff=Bi;function Bi(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}Bi.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};Bi.prototype.reset=function(){this.attempts=0};Bi.prototype.setMin=function(r){this.ms=r};Bi.prototype.setMax=function(r){this.max=r};Bi.prototype.setJitter=function(r){this.jitter=r}});var rh=F(Nt=>{"use strict";var L_=Nt&&Nt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=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,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),N_=Nt&&Nt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),D_=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)&&L_(e,r,t);return N_(e,r),e},M_=Nt&&Nt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Nt,"__esModule",{value:!0});Nt.Manager=void 0;var Ja=Bn(),F_=Ya(),B_=D_(Hn()),ai=$a(),j_=th(),U_=Jr(),q_=M_(At()),nt=(0,q_.default)("socket.io-client:manager"),Za=class extends U_.Emitter{constructor(e,t){var i;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,Ja.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((i=t.randomizationFactor)!==null&&i!==void 0?i:.5),this.backoff=new j_.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||B_;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(nt("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;nt("opening %s",this.uri),this.engine=new Ja.Socket(this.uri,this.opts);let t=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;let s=(0,ai.on)(t,"open",function(){i.onopen(),e&&e()}),n=c=>{nt("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},a=(0,ai.on)(t,"error",n);if(this._timeout!==!1){let c=this._timeout;nt("connect attempt will timeout after %d",c);let u=this.setTimeoutFn(()=>{nt("connect attempt timed out after %d",c),s(),n(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(){nt("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push((0,ai.on)(e,"ping",this.onping.bind(this)),(0,ai.on)(e,"data",this.ondata.bind(this)),(0,ai.on)(e,"error",this.onerror.bind(this)),(0,ai.on)(e,"close",this.onclose.bind(this)),(0,ai.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,Ja.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){nt("error",e),this.emitReserved("error",e)}socket(e,t){let i=this.nsps[e];return i?this._autoConnect&&!i.active&&i.connect():(i=new F_.Socket(this,e,t),this.nsps[e]=i),i}_destroy(e){let t=Object.keys(this.nsps);for(let i of t)if(this.nsps[i].active){nt("socket %s is still active, skipping close",i);return}this._close()}_packet(e){nt("writing packet %j",e);let t=this.encoder.encode(e);for(let i=0;i<t.length;i++)this.engine.write(t[i],e.options)}cleanup(){nt("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){nt("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var i;nt("closed due to %s",e),this.cleanup(),(i=this.engine)===null||i===void 0||i.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)nt("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();nt("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let i=this.setTimeoutFn(()=>{e.skipReconnect||(nt("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(s=>{s?(nt("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",s)):(nt("reconnect success"),e.onreconnect())}))},t);this.opts.autoUnref&&i.unref(),this.subs.push(()=>{this.clearTimeoutFn(i)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}};Nt.Manager=Za});var oh=F((Be,nh)=>{"use strict";var W_=Be&&Be.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Be,"__esModule",{value:!0});Be.WebTransport=Be.WebSocket=Be.NodeWebSocket=Be.XHR=Be.NodeXHR=Be.Fetch=Be.Socket=Be.Manager=Be.protocol=void 0;Be.io=ci;Be.connect=ci;Be.default=ci;var H_=Gl(),Kn=rh();Object.defineProperty(Be,"Manager",{enumerable:!0,get:function(){return Kn.Manager}});var sh=Ya();Object.defineProperty(Be,"Socket",{enumerable:!0,get:function(){return sh.Socket}});var V_=W_(At()),ih=(0,V_.default)("socket.io-client"),ys={};function ci(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};let t=(0,H_.url)(r,e.path||"/socket.io"),i=t.source,s=t.id,n=t.path,a=ys[s]&&n in ys[s].nsps,c=e.forceNew||e["force new connection"]||e.multiplex===!1||a,u;return c?(ih("ignoring socket cache for %s",i),u=new Kn.Manager(i,e)):(ys[s]||(ih("new io instance for %s",i),ys[s]=new Kn.Manager(i,e)),u=ys[s]),t.query&&!e.query&&(e.query=t.queryKey),u.socket(t.path,e)}Object.assign(ci,{Manager:Kn.Manager,Socket:sh.Socket,io:ci,connect:ci});var K_=Hn();Object.defineProperty(Be,"protocol",{enumerable:!0,get:function(){return K_.protocol}});var ji=Bn();Object.defineProperty(Be,"Fetch",{enumerable:!0,get:function(){return ji.Fetch}});Object.defineProperty(Be,"NodeXHR",{enumerable:!0,get:function(){return ji.NodeXHR}});Object.defineProperty(Be,"XHR",{enumerable:!0,get:function(){return ji.XHR}});Object.defineProperty(Be,"NodeWebSocket",{enumerable:!0,get:function(){return ji.NodeWebSocket}});Object.defineProperty(Be,"WebSocket",{enumerable:!0,get:function(){return ji.WebSocket}});Object.defineProperty(Be,"WebTransport",{enumerable:!0,get:function(){return ji.WebTransport}});nh.exports=ci});var ec=F(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.InputStreamReceiver=void 0;var z_=64,$_=30,G_=4,Y_=256,X_=16,Qa=class{streamId;lastAppliedSeq=0;cb;windowSize;ackThrottleMs;ackTimer=null;framesSinceAck=0;lastResendFrom=0;resendSuppressed=0;constructor(e,t,i={}){this.streamId=e,this.cb=t,this.windowSize=Math.max(1,i.windowSize??z_),this.ackThrottleMs=Math.max(0,i.ackThrottleMs??$_)}get appliedSeq(){return this.lastAppliedSeq}receive(e,t,i){if(e<=this.lastAppliedSeq){this.flushAck();return}if(e===this.lastAppliedSeq+1){try{this.cb.onApply(t,i)}catch{}this.lastAppliedSeq=e,this.scheduleAck();return}this.flushAck();let s=Math.max(this.windowSize*G_,Y_);e-this.lastAppliedSeq>s||this.maybeResend(this.lastAppliedSeq+1)}maybeResend(e){if(e===this.lastResendFrom){if(++this.resendSuppressed<X_)return;this.resendSuppressed=0}else this.lastResendFrom=e,this.resendSuppressed=0;this.cb.onResend(e)}resumeState(){return{streamId:this.streamId,lastAckSeq:this.lastAppliedSeq}}dispose(){this.ackTimer&&(clearTimeout(this.ackTimer),this.ackTimer=null)}scheduleAck(){this.framesSinceAck++;let e=Math.max(1,Math.floor(this.windowSize/4));if(this.windowSize===1||this.framesSinceAck>=e){this.flushAck();return}this.ackTimer||(this.ackTimer=setTimeout(()=>this.flushAck(),this.ackThrottleMs))}flushAck(){this.ackTimer&&(clearTimeout(this.ackTimer),this.ackTimer=null),this.framesSinceAck=0,this.cb.onAck(this.lastAppliedSeq)}};zn.InputStreamReceiver=Qa});var uh=F($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.WebSocketService=void 0;var J_=oh(),ah=hr(),ch=Ks(),fh=Ws(),Z_=ec(),tc=class{authService;cryptoService;config;logger;notification;deviceId;platform;extraCapabilities;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;inputReceivers=new Map;terminalActiveCheck=null;MAX_INPUT_RECEIVERS=512;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,i,s,n,a,c="vscode",u=[]){this.authService=e,this.cryptoService=t,this.config=i,this.logger=s,this.notification=n,this.deviceId=a,this.platform=c,this.extraCapabilities=u}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,ch.getWsUrl)(this.config);this.logger.info("Connecting to WebSocket",t),this.statusChangeHandler?.("connecting");let i=await this.cryptoService.getPublicKey();return new Promise((s,n)=>{let a=Array.from(new Set([...ah.DEFAULT_CLIENT_CAPABILITIES,...this.extraCapabilities]));this.socket=(0,J_.io)(`${t}/agent`,{auth:{token:e,protocolVersion:ah.PROTOCOL_VERSION,deviceId:this.deviceId,platform:this.platform,capabilities:a,publicKey:i},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 c of this.reconnectHandlers)c()}else this.hasConnectedOnce=!0,s()}),this.socket.on("error",c=>{this.logger.error(`Server error [${c.code}]: ${c.message}`),c.code==="E401"&&(this.logger.warn("Auth failure (E401)"),this.authFailureHandler?.())}),this.socket.on("disconnect",c=>{this.logger.warn("WebSocket disconnected",c),this.stopHeartbeat(),this.statusChangeHandler?.("disconnected"),this.isManualDisconnect||(c==="transport close"?(this.logger.info("Transport close - attempting immediate reconnect"),this.attemptReconnect(!0)):this.scheduleReconnect())}),this.socket.on("protocol:info",c=>{this.logger.info("Protocol info received",c.protocolVersion),this.negotiatedCapabilities=c.negotiatedCapabilities,c.agentName&&this.config.getAgentName()!==c.agentName&&(this.isRemoteRename=!0,this.config.setAgentName(c.agentName).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(c.agentName),this.logger.info("Agent name synced from server",c.agentName))}),this.socket.on("pong",()=>{this.lastPongTime=Date.now(),this.clearPongTimeout(),this.logger.debug("Heartbeat pong received")}),this.socket.on("connect_error",c=>{this.logger.error("WebSocket connection error",c),this.statusChangeHandler?.("error"),this.hasConnectedOnce||n(c),this.scheduleReconnect()}),this.socket.on("terminal:input",c=>{this.handleTerminalInput(c)}),this.socket.on("crypto:keyExchange",async(c,u)=>{this.logger.info("Received key exchange request",c.terminalId,c.sessionId),this.rekeyingTerminals.add(c.terminalId),this.outputBuffer.set(c.terminalId,[]);try{if(await this.cryptoService.handleKeyExchange(c.terminalId,c.clientPublicKey,c.sessionId)){let g=await this.cryptoService.getPublicKey();u?.({success:!0,agentPublicKey:g||void 0}),this.flushOutputBuffer(c.terminalId)}else u?.({success:!1,error:"Key exchange failed"})}catch(d){this.logger.error("Key exchange error",d),u?.({success:!1,error:String(d)})}finally{this.rekeyingTerminals.delete(c.terminalId),this.outputBuffer.delete(c.terminalId)}}),this.socket.on("crypto:sessionCleanup",c=>{this.cryptoService.removeSession(c.terminalId,c.sessionId)}),this.socket.on("agent:keyExchangeRequest",async c=>{try{let u=await this.cryptoService.handleAgentKeyExchange(c.clientPublicKey,c.sessionId),d={agentId:c.agentId,sessionId:c.sessionId,ok:u,error:u?void 0:"Key exchange failed"};this.socket?.emit("agent:keyExchangeAck",d)}catch(u){this.logger.error("Agent key exchange error",u);let d={agentId:c.agentId,sessionId:c.sessionId,ok:!1,error:String(u)};this.socket?.emit("agent:keyExchangeAck",d)}}),this.socket.on("agent:sessionEnd",c=>{this.cryptoService.removeAgentSession(c.sessionId)}),this.socket.on("agent:renamed",c=>{this.logger.info("Agent renamed from web client",c.name),this.isRemoteRename=!0,this.config.setAgentName(c.name).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(c.name)}),this.socket.on("terminal:createRequest",c=>{this.createTerminalHandler?.(c.name)}),this.socket.on("terminal:getBuffer",(c,u)=>{if(!this.getBufferHandler){u?.({success:!1,error:"Buffer handler not set"});return}let d=this.getBufferHandler(c.terminalId);if(d===null){u?.({success:!1,error:"Terminal not found"});return}let g=this.cryptoService.encryptOutput(c.terminalId,d);u?.(g?{success:!0,encrypted:g}:{success:!0,data:d}),this.redrawHandler?.(c.terminalId)}),this.socket.on("terminal:resize",c=>{this.resizeHandler?.(c.terminalId,c.cols,c.rows)}),this.socket.on("workspace:clientAttached",c=>{this.clientAttachedHandler?.(c)}),this.socket.on("workspace:clientDetached",c=>{this.clientDetachedHandler?.(c)}),this.socket.on("file:view",c=>{this.fileViewRequestHandler?.(c.terminalId,c.request)}),this.socket.on("file:list",c=>{this.fileListRequestHandler?.(c.terminalId,c.request)}),this.socket.on("file:download:request",c=>{this.fileDownloadRequestHandler?.(c.terminalId,c.path,c.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,i){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:i});return}let s=this.cryptoService.encryptOutput(t,i),n={instanceId:e,terminalId:t,...s?{encrypted:s}:{data:i}};this.socket?.emit("terminal:output",n)}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:i,data:s}of t){let n=this.cryptoService.encryptOutput(e,s),a={instanceId:i,terminalId:e,...n?{encrypted:n}:{data:s}};this.socket?.emit("terminal:output",a)}}}async updateStatus(e){await this.emit("terminal:status",e)}sendTerminalEvent(e,t,i){let s={instanceId:e,terminalId:t,event:i};this.socket?.emit("terminal:event",s)}hasCapability(e){return this.negotiatedCapabilities.includes(e)}sendFileChangedEvent(e,t,i){let s={instanceId:e,terminalId:t,event:i};this.socket?.emit("file:changed",s)}sendFileListResponse(e,t){let i={instanceId:e,response:t};this.socket?.emit("file:list:response",i)}sendAgentRename(e){this.socket?.emit("agent:rename",{name:e})}isRemoteRenameInProgress(){return this.isRemoteRename}getSocket(){return this.socket}emit(e,t){let i=(0,fh.generateCorrelationId)(),s=t&&typeof t=="object"&&!Array.isArray(t)?{...t,_cid:i}:t;return(0,fh.runWithCorrelation)(i,()=>new Promise((n,a)=>{if(!this.socket?.connected){a(new Error("WebSocket not connected"));return}this.socket.emit(e,s,c=>{c.success?n(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 i=this.cryptoService.decryptInput(e.terminalId,e.encrypted);if(!i){this.logger.error("Failed to decrypt terminal input",e.terminalId);return}t=i}else if(e.data)t=Buffer.from(e.data,"base64").toString("utf8");else{this.logger.error("Invalid terminal input payload");return}if(e.streamId&&typeof e.seq=="number"){let i=this.getOrCreateInputReceiver(e.terminalId,e.streamId,e.instanceId,e.dbTerminalId);if(!i)return;i.receive(e.seq,t,e.paste);return}this.inputHandler?.(e.terminalId,t,e.dbTerminalId)}getOrCreateInputReceiver(e,t,i,s){let n=this.inputReceivers.get(e);if(this.terminalActiveCheck&&!this.terminalActiveCheck(e))return n&&this.disposeInputStream(e),null;if(n&&n.receiver.streamId===t)return s&&(n.routeId=s),i&&(n.instanceId=i),n.receiver;if(n&&n.receiver.dispose(),!n&&this.inputReceivers.size>=this.MAX_INPUT_RECEIVERS)return this.logger.error("inputReceivers map at cap, dropping frame",e),null;let a=new Z_.InputStreamReceiver(t,{onApply:(c,u)=>this.inputHandler?.(e,c,this.routeIdFor(e),u),onAck:c=>this.sendInputAck(e,t,c),onResend:c=>this.sendInputResend(e,t,c)});return this.inputReceivers.set(e,{receiver:a,routeId:s??e,instanceId:i??""}),a}setTerminalActiveCheck(e){this.terminalActiveCheck=e}routeIdFor(e){return this.inputReceivers.get(e)?.routeId??e}sendInputAck(e,t,i){let s=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:ack",{instanceId:s,terminalId:e,streamId:t,ackSeq:i})}sendInputResend(e,t,i){let s=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:resend",{instanceId:s,terminalId:e,streamId:t,fromSeq:i})}sendInputResume(e){let t=this.inputReceivers.get(e);if(!t)return;let{streamId:i,lastAckSeq:s}=t.receiver.resumeState();this.socket?.emit("input:resume",{instanceId:t.instanceId,terminalId:e,streamId:i,lastAckSeq:s})}disposeInputStream(e){this.inputReceivers.get(e)?.receiver.dispose(),this.inputReceivers.delete(e)}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(i){this.logger.warn("Reconnect failed",i),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,ch.getApiUrl)(this.config)}/health`,i=new AbortController,s=setTimeout(()=>i.abort(),5e3),n=await fetch(t,{method:"GET",signal:i.signal});return clearTimeout(s),this.logger.debug("Network check OK",String(n.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)}};$n.WebSocketService=tc});var hh=F(rr=>{"use strict";var Q_=rr&&rr.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=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,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),ey=rr&&rr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),ic=rr&&rr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(i[i.length]=s);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),s=0;s<i.length;s++)i[s]!=="default"&&Q_(t,e,i[s]);return ey(t,e),t}})();Object.defineProperty(rr,"__esModule",{value:!0});rr.FileTransferService=void 0;var Gn=ic(require("fs")),ty=ic(require("path")),lh=ic(require("crypto")),je=hr(),rc=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,i,s,n){let a=Gn.readFileSync(t),c=t.split("/").pop()||"file";return this.initAndSendChunks(e,a,c,{mimeType:this.getMimeType(c),requestId:n,onProgress:i,onComplete:s})}async sendBuffer(e,t,i,s,n){return this.initAndSendChunks(e,t,i,{mimeType:s,purpose:n?.purpose,viewMetadata:n?.viewMetadata,requestId:n?.requestId,onProgress:n?.onProgress,onComplete:n?.onComplete})}async initAndSendChunks(e,t,i,s){if(!this.socket)throw new Error("Socket not connected");let n=t.length,a=(0,je.calculateTotalChunks)(n),c=this.calculateChecksum(t),u=lh.randomUUID(),d={id:u,terminalId:e,filename:i,size:n,totalChunks:a,direction:je.TransferDirection.DOWNLOAD,status:je.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*je.CHUNK_SIZE,b=Math.min(y+je.CHUNK_SIZE,n);d.chunks.push(t.subarray(y,b))}this.activeTransfers.set(u,d);let g={transferId:u,terminalId:e,filename:i,size:n,totalChunks:a,mimeType:s.mimeType||"application/octet-stream",checksum:c,direction:je.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,b=>{b.accepted?(d.status=je.TransferStatus.ACTIVE,this.startSendingChunks(u),m(u)):(this.activeTransfers.delete(u),y(new Error(b.error||"Transfer rejected")))})})}async receiveFile(e,t,i,s,n,a,c,u="sha256",d,g){let m={id:e,terminalId:t,filename:i,filePath:c,size:s,totalChunks:n,direction:je.TransferDirection.UPLOAD,status:je.TransferStatus.ACTIVE,deliveredChunks:new Set,pendingChunks:new Map,chunks:new Array(n).fill(null),checksum:a,checksumAlgorithm:u,onProgress:d?(y,b)=>d(e,y,b):void 0,onComplete:g?(y,b)=>g(e,y,b):void 0,ackTimeouts:new Map};this.activeTransfers.set(e,m)}cancelTransfer(e,t){let i=this.activeTransfers.get(e);if(i){for(let s of i.ackTimeouts.values())clearTimeout(s);if(i.status=je.TransferStatus.CANCELLED,i.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},i=>{if(i.status===je.TransferStatus.EXPIRED){t.onComplete?.(!1,"Transfer expired"),this.activeTransfers.delete(e);return}if(i.deliveredChunks)for(let s of i.deliveredChunks)t.deliveredChunks.add(s);if(t.direction===je.TransferDirection.DOWNLOAD&&i.missingChunks){t.status=je.TransferStatus.ACTIVE;for(let s of i.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 i of t.ackTimeouts.values())clearTimeout(i);t.status=je.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 i=0;i<Math.min(je.WINDOW_SIZE,t.totalChunks);i++)t.deliveredChunks.has(i)||this.sendChunk(t,i)}sendChunk(e,t){if(!this.socket||!e.chunks)return;let i=e.chunks[t];if(!i)return;let s=e.pendingChunks.get(t),n={seq:t,data:i,retries:s?s.retries:0,sentAt:Date.now()};e.pendingChunks.set(t,n);let a={transferId:e.id,seq:t,data:i.buffer.slice(i.byteOffset,i.byteOffset+i.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)},je.ACK_TIMEOUT_MS);e.ackTimeouts.set(t,c)}handleChunkAck(e){let t=this.activeTransfers.get(e.transferId);if(!t||t.status===je.TransferStatus.COMPLETED)return;let i=t.ackTimeouts.get(e.seq);i&&(clearTimeout(i),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+je.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 i=this.activeTransfers.get(e);if(!i)return;let s=i.pendingChunks.get(t);s&&(s.retries<je.MAX_RETRIES?(s.retries++,this.sendChunk(i,t)):this.cancelTransfer(e,"Max retries exceeded"))}finishSending(e){if(!this.socket)return;e.status=je.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 i={transferId:e.transferId,seq:e.seq};this.socket.emit("file:chunk:ack",i)}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=je.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=ty.dirname(e.filePath);Gn.existsSync(s)||Gn.mkdirSync(s,{recursive:!0}),Gn.writeFileSync(e.filePath,t),e.status=je.TransferStatus.COMPLETED,e.onComplete?.(!0),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!0})}catch(s){let n=s instanceof Error?s.message:String(s);e.status=je.TransferStatus.FAILED,e.onComplete?.(!1,`Failed to save file: ${n}`),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!1,error:`Failed to save file: ${n}`})}this.activeTransfers.delete(e.id)}handleComplete(e){let t=this.activeTransfers.get(e.transferId);if(t){e.success?(t.status=je.TransferStatus.COMPLETED,t.onComplete?.(!0)):(t.status=je.TransferStatus.FAILED,t.onComplete?.(!1,e.error));for(let i of t.ackTimeouts.values())clearTimeout(i);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(n=>t({accepted:!1,error:n.message}))}calculateChecksum(e,t="sha256"){return t==="fnv1a"?this.fnv1aHash(e):lh.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=rc});var uc=F((Fw,Jn)=>{function gh(r){return Array.isArray(r)?r:[r]}var ry=void 0,nc="",dh=" ",sc="\\",iy=/^\s+$/,sy=/(?:[^\\]|^)\\$/,ny=/^\\!/,oy=/^\\#/,ay=/\r?\n/g,cy=/^\.{0,2}\/|^\.{1,2}$/,fy=/\/$/,Ui="/",mh="node-ignore";typeof Symbol<"u"&&(mh=Symbol.for("node-ignore"));var _h=mh,qi=(r,e,t)=>(Object.defineProperty(r,e,{value:t}),t),uy=/([0-z])-([0-z])/g,yh=()=>!1,ly=r=>r.replace(uy,(e,t,i)=>t.charCodeAt(0)<=i.charCodeAt(0)?e:nc),hy=r=>{let{length:e}=r;return r.slice(0,e-e%2)},dy=[[/^\uFEFF/,()=>nc],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?dh:nc)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+dh}],[/[\\$.|*+(){^]/g,r=>`\\${r}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(r,e,t)=>e+6<t.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(r,e,t)=>{let i=t.replace(/\\\*/g,"[^\\/]*");return e+i}],[/\\\\\\(?=[$.|*+(){^])/g,()=>sc],[/\\\\/g,()=>sc],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,i,s)=>e===sc?`\\[${t}${hy(i)}${s}`:s==="]"&&i.length%2===0?`[${ly(t)}${i}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`]],py=/(^|\\\/)?\\\*$/,vs="regex",Yn="checkRegex",ph="_",gy={[vs](r,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[Yn](r,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},my=r=>dy.reduce((e,[t,i])=>e.replace(t,i.bind(r)),r),Xn=r=>typeof r=="string",_y=r=>r&&Xn(r)&&!iy.test(r)&&!sy.test(r)&&r.indexOf("#")!==0,yy=r=>r.split(ay).filter(Boolean),oc=class{constructor(e,t,i,s,n,a){this.pattern=e,this.mark=t,this.negative=n,qi(this,"body",i),qi(this,"ignoreCase",s),qi(this,"regexPrefix",a)}get regex(){let e=ph+vs;return this[e]?this[e]:this._make(vs,e)}get checkRegex(){let e=ph+Yn;return this[e]?this[e]:this._make(Yn,e)}_make(e,t){let i=this.regexPrefix.replace(py,gy[e]),s=this.ignoreCase?new RegExp(i,"i"):new RegExp(i);return qi(this,t,s)}},vy=({pattern:r,mark:e},t)=>{let i=!1,s=r;s.indexOf("!")===0&&(i=!0,s=s.substr(1)),s=s.replace(ny,"!").replace(oy,"#");let n=my(s);return new oc(r,e,s,t,i,n)},ac=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[_h]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(Xn(e)&&(e={pattern:e}),_y(e.pattern)){let t=vy(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,gh(Xn(e)?yy(e):e).forEach(this._add,this),this._added}test(e,t,i){let s=!1,n=!1,a;this._rules.forEach(u=>{let{negative:d}=u;n===d&&s!==n||d&&!s&&!n&&!t||!u[i].test(e)||(s=!d,n=d,a=d?ry:u)});let c={ignored:s,unignored:n};return a&&(c.rule=a),c}},Ey=(r,e)=>{throw new e(r)},vr=(r,e,t)=>Xn(r)?r?vr.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),vh=r=>cy.test(r);vr.isNotRelative=vh;vr.convert=r=>r;var cc=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:i=!1}={}){qi(this,_h,!0),this._rules=new ac(t),this._strictPathCheck=!i,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,i,s){let n=e&&vr.convert(e);return vr(n,e,this._strictPathCheck?Ey:yh),this._t(n,t,i,s)}checkIgnore(e){if(!fy.test(e))return this.test(e);let t=e.split(Ui).filter(Boolean);if(t.pop(),t.length){let i=this._t(t.join(Ui)+Ui,this._testCache,!0,t);if(i.ignored)return i}return this._rules.test(e,!1,Yn)}_t(e,t,i,s){if(e in t)return t[e];if(s||(s=e.split(Ui).filter(Boolean)),s.pop(),!s.length)return t[e]=this._rules.test(e,i,vs);let n=this._t(s.join(Ui)+Ui,t,i,s);return t[e]=n.ignored?n:this._rules.test(e,i,vs)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return gh(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},fc=r=>new cc(r),wy=r=>vr(r&&vr.convert(r),r,yh),Eh=()=>{let r=t=>/^\\\\\?\\/.test(t)||/["<>|\u0000-\u001F]+/u.test(t)?t:t.replace(/\\/g,"/");vr.convert=r;let e=/^[a-z]:\//i;vr.isNotRelative=t=>e.test(t)||vh(t)};typeof process<"u"&&process.platform==="win32"&&Eh();Jn.exports=fc;fc.default=fc;Jn.exports.isPathValid=wy;qi(Jn.exports,Symbol.for("setupWindows"),Eh)});var bh=F(Dt=>{"use strict";var by=Dt&&Dt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=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,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),xy=Dt&&Dt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),wh=Dt&&Dt.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(i[i.length]=s);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),s=0;s<i.length;s++)i[s]!=="default"&&by(t,e,i[s]);return xy(t,e),t}})(),Sy=Dt&&Dt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Dt,"__esModule",{value:!0});Dt.FileListService=void 0;var Es=wh(require("path")),lc=wh(require("fs/promises")),Ty=Sy(uc()),hc=hr(),Cy=["node_modules",".pnpm","vendor",".git","dist","build","out",".next",".nuxt",".output",".cache",".turbo",".idea",".vscode",".DS_Store","Thumbs.db"],dc=class{ignoreFilter;workspaceRoot;onResponseCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,Ty.default)(),this.ignoreFilter.add(Cy),this.workspaceRoot&&this.loadGitignore(),this.logger.info("FileListService initialized",t||"null")}async loadGitignore(){if(!this.workspaceRoot)return;let e=Es.join(this.workspaceRoot,".gitignore");try{let t=await lc.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),i=await this.listDirectory(t,e.path);this.sendResponse({requestId:e.requestId,path:e.path,entries:i})}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 i=await lc.readdir(e,{withFileTypes:!0}),s=[];for(let n of i){let a=t==="."||t===""?n.name:Es.join(t,n.name);if(this.shouldHide(a,n.isDirectory()))continue;let c=Es.join(e,n.name),u={name:n.name,path:a,type:n.isDirectory()?hc.FileEntryType.DIRECTORY:hc.FileEntryType.FILE};if(!n.isDirectory())try{let d=await lc.stat(c);u.size=d.size,u.modified=d.mtime.toISOString()}catch{}s.push(u)}return s.sort((n,a)=>n.type!==a.type?n.type===hc.FileEntryType.DIRECTORY?-1:1:n.name.localeCompare(a.name))}shouldHide(e,t){let i=e.split(Es.sep).join("/"),s=t?`${i}/`:i;return this.ignoreFilter.ignores(s)}resolvePath(e){if(!this.workspaceRoot)throw new Error("No workspace root");if(e==="."||e==="")return this.workspaceRoot;let t=Es.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=dc});var Sh=F(ir=>{"use strict";var Oy=ir&&ir.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=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,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),ky=ir&&ir.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),xh=ir&&ir.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(i[i.length]=s);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),s=0;s<i.length;s++)i[s]!=="default"&&Oy(t,e,i[s]);return ky(t,e),t}})();Object.defineProperty(ir,"__esModule",{value:!0});ir.FileTrackerService=void 0;var pc=xh(require("path")),fi=xh(require("fs/promises")),Ry=require("child_process"),Py=require("util"),Wt=hr(),gc=(0,Py.promisify)(Ry.exec),mc={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},_c=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 i=this.outputBuffers.get(e)||"";i+=t,i.length>10240&&(i=i.slice(-10240)),this.outputBuffers.set(e,i);try{await this.parseToolCalls(e,i)}catch(s){this.logger.error("Error parsing tool calls",s)}}async parseToolCalls(e,t){let i=this.stripAnsi(t),s=i.match(mc.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 n=i.match(mc.toolSuccess);if(n){let a=n[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(mc.toolError.test(i))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,i,s){if(!this.isFileModifyingTool(i))return;let n=this.extractFilePath(i,s);if(!n)return;let a=this.resolveFilePath(n),c={toolId:t,toolName:i,filePath:n,timestamp:new Date().toISOString()};this.pendingToolCalls.set(t,c);let u;try{u=await fi.readFile(a,"utf-8")}catch{u=void 0}let d={path:n,changeType:u===void 0?Wt.FileChangeType.CREATE:Wt.FileChangeType.MODIFY,toolName:i,toolId:t,timestamp:c.timestamp,previousContent:u},g=this.trackedFiles.get(e)||[];g.push(d),this.trackedFiles.set(e,g)}async handleToolEnd(e,t,i,s){if(!this.isFileModifyingTool(i)||!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 fi.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 i=this.resolveFilePath(t.path),s=this.getViewableMimeType(t.path);if(s&&this.onFileViewTransferCallback){try{let a=await fi.readFile(i),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 n;try{t.type===Wt.FileViewType.CONTENT?n=await this.getFileContent(t,i):n=await this.getFileDiff(e,t,i)}catch(a){n={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:n.type===Wt.FileViewType.CONTENT?"content":"diff",language:n.language,truncated:n.truncated,error:n.error},c=Buffer.from(n.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 i=e.maxSize||1048576,s=await fi.stat(t),n=await fi.readFile(t,"utf-8"),a=!1,c=n;return n.length>i&&(c=n.slice(0,i),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,i){let s=t.diffBase||Wt.DiffBase.GIT,n;return s===Wt.DiffBase.GIT?n=await this.getGitDiff(i):n=await this.getPreviousDiff(e,t.path,i),{requestId:t.requestId,path:t.path,type:Wt.FileViewType.DIFF,content:n,language:"diff"}}async getGitDiff(e){if(!this.workspaceRoot)throw new Error("No workspace root");try{let{stdout:t}=await gc(`git diff --cached -- "${e}"`,{cwd:this.workspaceRoot});if(t.trim())return t;let{stdout:i}=await gc(`git diff -- "${e}"`,{cwd:this.workspaceRoot});if(i.trim())return i;let{stdout:s}=await gc(`git status --porcelain -- "${e}"`,{cwd:this.workspaceRoot});if(s.startsWith("??")||s.startsWith("A ")){let a=(await fi.readFile(e,"utf-8")).split(`
26
+ `+t)}function ni(r,e,t,i,s,n){if(r.listenerCount("wsClientError")){let a=new Error(s);Error.captureStackTrace(a,ni),r.emit("wsClientError",a,t,e)}else ps(t,i,s,n)}});var Ml=F((_E,Dl)=>{"use strict";var yr=In();yr.createWebSocketStream=Tl();yr.Server=Nl();yr.Receiver=ha();yr.Sender=ga();yr.WebSocket=yr;yr.WebSocketServer=yr.Server;Dl.exports=yr});var Ca=F(Fr=>{"use strict";var C0=Fr&&Fr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Fr,"__esModule",{value:!0});Fr.WS=Fr.BaseWS=void 0;var O0=os(),Fl=Qr(),k0=xi(),Sa=Zr(),R0=C0(At()),P0=(0,R0.default)("engine.io-client:websocket"),Bl=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Nn=class extends O0.Transport{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,i=Bl?{}:(0,Fl.pick)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(i.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,i)}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 i=e[t],s=t===e.length-1;(0,k0.encodePacket)(i,this.supportsBinary,n=>{try{this.doWrite(i,n)}catch{P0("websocket closed before onclose event")}s&&(0,Sa.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,Fl.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}};Fr.BaseWS=Nn;var xa=Sa.globalThisShim.WebSocket||Sa.globalThisShim.MozWebSocket,Ta=class extends Nn{createSocket(e,t,i){return Bl?new xa(e,t,i):t?new xa(e,t):new xa(e)}doWrite(e,t){this.ws.send(t)}};Fr.WS=Ta});var ka=F(er=>{"use strict";var A0=er&&er.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=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,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),I0=er&&er.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),L0=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)&&A0(e,r,t);return I0(e,r),e};Object.defineProperty(er,"__esModule",{value:!0});er.WS=void 0;var N0=L0(Ml()),D0=Ca(),Oa=class extends D0.BaseWS{createSocket(e,t,i){var s;if(!((s=this.socket)===null||s===void 0)&&s._cookieJar){i.headers=i.headers||{},i.headers.cookie=typeof i.headers.cookie=="string"?[i.headers.cookie]:i.headers.cookie||[];for(let[n,a]of this.socket._cookieJar.cookies)i.headers.cookie.push(`${n}=${a.value}`)}return new N0.WebSocket(e,t,i)}doWrite(e,t){let i={};e.options&&(i.compress=e.options.compress),this.opts.perMessageDeflate&&(typeof t=="string"?Buffer.byteLength(t):t.length)<this.opts.perMessageDeflate.threshold&&(i.compress=!1),this.ws.send(t,i)}};er.WS=Oa});var Pa=F(Mi=>{"use strict";var M0=Mi&&Mi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Mi,"__esModule",{value:!0});Mi.WT=void 0;var F0=os(),B0=Zr(),jl=xi(),j0=M0(At()),gs=(0,j0.default)("engine.io-client:webtransport"),Ra=class extends F0.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,jl.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=e.readable.pipeThrough(t).getReader(),s=(0,jl.createPacketEncoderStream)();s.readable.pipeTo(e.writable),this._writer=s.writable.getWriter();let n=()=>{i.read().then(({done:c,value:u})=>{if(c){gs("session is closed");return}gs("received chunk: %o",u),this.onPacket(u),n()}).catch(c=>{gs("an error occurred while reading: %s",c)})};n();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 i=e[t],s=t===e.length-1;this._writer.write(i).then(()=>{s&&(0,B0.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};Mi.WT=Ra});var Aa=F(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.transports=void 0;var U0=ta(),q0=ka(),W0=Pa();Dn.transports={websocket:q0.WS,webtransport:W0.WT,polling:U0.XHR}});var La=F(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});Ia.parse=z0;var H0=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,V0=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function z0(r){if(r.length>8e3)throw"URI too long";let e=r,t=r.indexOf("["),i=r.indexOf("]");t!=-1&&i!=-1&&(r=r.substring(0,t)+r.substring(t,i).replace(/:/g,";")+r.substring(i,r.length));let s=H0.exec(r||""),n={},a=14;for(;a--;)n[V0[a]]=s[a]||"";return t!=-1&&i!=-1&&(n.source=e,n.host=n.host.substring(1,n.host.length-1).replace(/;/g,":"),n.authority=n.authority.replace("[","").replace("]","").replace(/;/g,":"),n.ipv6uri=!0),n.pathNames=K0(n,n.path),n.queryKey=$0(n,n.query),n}function K0(r,e){let t=/\/{2,9}/g,i=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&i.splice(0,1),e.slice(-1)=="/"&&i.splice(i.length-1,1),i}function $0(r,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(i,s,n){s&&(t[s]=n)}),t}});var Fa=F(tr=>{"use strict";var G0=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 Y0=Aa(),Ul=Qr(),X0=Ho(),ql=La(),J0=Jr(),Wl=xi(),Na=Zr(),Z0=G0(At()),Ne=(0,Z0.default)("engine.io-client:socket"),Da=typeof addEventListener=="function"&&typeof removeEventListener=="function",ms=[];Da&&addEventListener("offline",()=>{Ne("closing %d connection(s) because the network was lost",ms.length),ms.forEach(r=>r())},!1);var oi=class r extends J0.Emitter{constructor(e,t){if(super(),this.binaryType=Na.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 i=(0,ql.parse)(e);t.hostname=i.host,t.secure=i.protocol==="https"||i.protocol==="wss",t.port=i.port,i.query&&(t.query=i.query)}else t.host&&(t.hostname=(0,ql.parse)(t.host).host);(0,Ul.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(i=>{let s=i.prototype.name;this.transports.push(s),this._transportsByName[s]=i}),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,X0.decode)(this.opts.query)),Da&&(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"})},ms.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,Na.createCookieJar)()),this._open()}createTransport(e){Ne('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=Wl.protocol,t.transport=e,this.id&&(t.sid=this.id);let i=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",i),new this._transportsByName[e](i)}_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 i=0;i<this.writeBuffer.length;i++){let s=this.writeBuffer[i].data;if(s&&(t+=(0,Ul.byteLength)(s)),i>0&&t>this._maxPayload)return Ne("only send %d out of %d packets",i,this.writeBuffer.length),this.writeBuffer.slice(0,i);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,Na.nextTick)(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,i){return this._sendPacket("message",e,t,i),this}send(e,t,i){return this._sendPacket("message",e,t,i),this}_sendPacket(e,t,i,s){if(typeof t=="function"&&(s=t,t=void 0),typeof i=="function"&&(s=i,i=null),this.readyState==="closing"||this.readyState==="closed")return;i=i||{},i.compress=i.compress!==!1;let n={type:e,data:t,options:i};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),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()},i=()=>{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?i():e()}):this.upgrading?i():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(),Da&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let i=ms.indexOf(this._offlineEventListener);i!==-1&&(Ne("removing listener for the 'offline' event"),ms.splice(i,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};tr.SocketWithoutUpgrade=oi;oi.protocol=Wl.protocol;var Mn=class extends oi{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),i=!1;oi.priorWebsocketSuccess=!1;let s=()=>{i||(Ne('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",m=>{if(!i)if(m.type==="pong"&&m.data==="probe"){if(Ne('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;oi.priorWebsocketSuccess=t.name==="websocket",Ne('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{i||this.readyState!=="closed"&&(Ne("changing transport and sending upgrade packet"),p(),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 n(){i||(i=!0,p(),t.close(),t=null)}let a=m=>{let y=new Error("probe error: "+m);y.transport=t.name,n(),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),n())}let p=()=>{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(()=>{i||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let i=0;i<e.length;i++)~this.transports.indexOf(e[i])&&t.push(e[i]);return t}};tr.SocketWithUpgrade=Mn;var Ma=class extends Mn{constructor(e,t={}){let i=typeof e=="object"?e:t;(!i.transports||i.transports&&typeof i.transports[0]=="string")&&(i.transports=(i.transports||["polling","websocket","webtransport"]).map(s=>Y0.transports[s]).filter(s=>!!s)),super(e,i)}};tr.Socket=Ma});var Hl=F(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.Fetch=void 0;var Q0=Xo(),Ba=class extends Q0.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(i=>{if(!i.ok)return this.onError("fetch write error",i.status,i);t()}).catch(i=>{this.onError("fetch write error",i)})}_fetch(e){var t;let i=e!==void 0,s=new Headers(this.opts.extraHeaders);return i&&s.set("content-type","text/plain;charset=UTF-8"),(t=this.socket._cookieJar)===null||t===void 0||t.appendCookies(s),fetch(this.uri(),{method:i?"POST":"GET",body:i?e:null,headers:s,credentials:this.opts.withCredentials?"include":"omit"}).then(n=>{var a;return(a=this.socket._cookieJar)===null||a===void 0||a.parseCookies(n.headers.getSetCookie()),n})}};Fn.Fetch=Ba});var Bn=F(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 Vl=Fa();Object.defineProperty(Se,"Socket",{enumerable:!0,get:function(){return Vl.Socket}});var zl=Fa();Object.defineProperty(Se,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return zl.SocketWithoutUpgrade}});Object.defineProperty(Se,"SocketWithUpgrade",{enumerable:!0,get:function(){return zl.SocketWithUpgrade}});Se.protocol=Vl.Socket.protocol;var Kl=os();Object.defineProperty(Se,"Transport",{enumerable:!0,get:function(){return Kl.Transport}});Object.defineProperty(Se,"TransportError",{enumerable:!0,get:function(){return Kl.TransportError}});var e_=Aa();Object.defineProperty(Se,"transports",{enumerable:!0,get:function(){return e_.transports}});var t_=Qr();Object.defineProperty(Se,"installTimerFunctions",{enumerable:!0,get:function(){return t_.installTimerFunctions}});var r_=La();Object.defineProperty(Se,"parse",{enumerable:!0,get:function(){return r_.parse}});var i_=Zr();Object.defineProperty(Se,"nextTick",{enumerable:!0,get:function(){return i_.nextTick}});var s_=Hl();Object.defineProperty(Se,"Fetch",{enumerable:!0,get:function(){return s_.Fetch}});var n_=ta();Object.defineProperty(Se,"NodeXHR",{enumerable:!0,get:function(){return n_.XHR}});var o_=Qo();Object.defineProperty(Se,"XHR",{enumerable:!0,get:function(){return o_.XHR}});var a_=ka();Object.defineProperty(Se,"NodeWebSocket",{enumerable:!0,get:function(){return a_.WS}});var c_=Ca();Object.defineProperty(Se,"WebSocket",{enumerable:!0,get:function(){return c_.WS}});var f_=Pa();Object.defineProperty(Se,"WebTransport",{enumerable:!0,get:function(){return f_.WT}})});var Gl=F(_s=>{"use strict";var u_=_s&&_s.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(_s,"__esModule",{value:!0});_s.url=d_;var l_=Bn(),h_=u_(At()),$l=(0,h_.default)("socket.io-client:url");function d_(r,e="",t){let i=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)||($l("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),$l("parse %s",r),i=(0,l_.parse)(r)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";let n=i.host.indexOf(":")!==-1?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+n+":"+i.port+e,i.href=i.protocol+"://"+n+(t&&t.port===i.port?"":":"+i.port),i}});var ja=F(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.isBinary=Xl;Un.hasBinary=jn;var p_=typeof ArrayBuffer=="function",g_=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,Yl=Object.prototype.toString,m_=typeof Blob=="function"||typeof Blob<"u"&&Yl.call(Blob)==="[object BlobConstructor]",__=typeof File=="function"||typeof File<"u"&&Yl.call(File)==="[object FileConstructor]";function Xl(r){return p_&&(r instanceof ArrayBuffer||g_(r))||m_&&r instanceof Blob||__&&r instanceof File}function jn(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,i=r.length;t<i;t++)if(jn(r[t]))return!0;return!1}if(Xl(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return jn(r.toJSON(),!0);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&jn(r[t]))return!0;return!1}});var Jl=F(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.deconstructPacket=v_;qn.reconstructPacket=w_;var y_=ja();function v_(r){let e=[],t=r.data,i=r;return i.data=Ua(t,e),i.attachments=e.length,{packet:i,buffers:e}}function Ua(r,e){if(!r)return r;if((0,y_.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 i=0;i<r.length;i++)t[i]=Ua(r[i],e);return t}else if(typeof r=="object"&&!(r instanceof Date)){let t={};for(let i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=Ua(r[i],e));return t}return r}function w_(r,e){return r.data=qa(r.data,e),delete r.attachments,r}function qa(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]=qa(r[t],e);else if(typeof r=="object")for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=qa(r[t],e));return r}});var Hn=F(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.Decoder=Ut.Encoder=Ut.PacketType=Ut.protocol=void 0;Ut.isPacketValid=O_;var E_=Jr(),Zl=Jl(),Ql=ja(),b_=At(),Wa=(0,b_.default)("socket.io-parser"),eh=["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 Ha=class{constructor(e){this.replacer=e}encode(e){return Wa("encoding packet %j",e),(e.type===Le.EVENT||e.type===Le.ACK)&&(0,Ql.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)),Wa("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=(0,Zl.deconstructPacket)(e),i=this.encodeAsString(t.packet),s=t.buffers;return s.unshift(i),s}};Ut.Encoder=Ha;var Va=class r extends E_.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 i=t.type===Le.BINARY_EVENT;i||t.type===Le.BINARY_ACK?(t.type=i?Le.EVENT:Le.ACK,this.reconstructor=new za(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,Ql.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,i={type:Number(e.charAt(0))};if(Le[i.type]===void 0)throw new Error("unknown packet type "+i.type);if(i.type===Le.BINARY_EVENT||i.type===Le.BINARY_ACK){let n=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);let a=e.substring(n,t);if(a!=Number(a)||e.charAt(t)!=="-")throw new Error("Illegal attachments");i.attachments=Number(a)}if(e.charAt(t+1)==="/"){let n=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););i.nsp=e.substring(n,t)}else i.nsp="/";let s=e.charAt(t+1);if(s!==""&&Number(s)==s){let n=t+1;for(;++t;){let a=e.charAt(t);if(a==null||Number(a)!=a){--t;break}if(t===e.length)break}i.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){let n=this.tryParse(e.substr(t));if(r.isPayloadValid(i.type,n))i.data=n;else throw new Error("invalid payload")}return Wa("decoded %s as %j",e,i),i}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case Le.CONNECT:return Wn(t);case Le.DISCONNECT:return t===void 0;case Le.CONNECT_ERROR:return typeof t=="string"||Wn(t);case Le.EVENT:case Le.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&eh.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=Va;var za=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,Zl.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function x_(r){return typeof r=="string"}var S_=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function T_(r){return r===void 0||S_(r)}function Wn(r){return Object.prototype.toString.call(r)==="[object Object]"}function C_(r,e){switch(r){case Le.CONNECT:return e===void 0||Wn(e);case Le.DISCONNECT:return e===void 0;case Le.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&eh.indexOf(e[0])===-1);case Le.ACK:return Array.isArray(e);case Le.CONNECT_ERROR:return typeof e=="string"||Wn(e);default:return!1}}function O_(r){return x_(r.nsp)&&T_(r.id)&&C_(r.type,r.data)}});var $a=F(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.on=k_;function k_(r,e,t){return r.on(e,t),function(){r.off(e,t)}}});var Ya=F(Fi=>{"use strict";var R_=Fi&&Fi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Fi,"__esModule",{value:!0});Fi.Socket=void 0;var qt=Hn(),Vn=$a(),P_=Jr(),A_=R_(At()),Ze=(0,A_.default)("socket.io-client:socket"),I_=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Ga=class extends P_.Emitter{constructor(e,t,i){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,i&&i.auth&&(this.auth=i.auth),this._opts=Object.assign({},i),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[(0,Vn.on)(e,"open",this.onopen.bind(this)),(0,Vn.on)(e,"packet",this.onpacket.bind(this)),(0,Vn.on)(e,"error",this.onerror.bind(this)),(0,Vn.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 i,s,n;if(I_.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 p=this.ids++;Ze("emitting packet with ack id %d",p);let m=t.pop();this._registerAckCallback(p,m),a.id=p}let c=(s=(i=this.io.engine)===null||i===void 0?void 0:i.transport)===null||s===void 0?void 0:s.writable,u=this.connected&&!(!((n=this.io.engine)===null||n===void 0)&&n._hasPingExpired());return this.flags.volatile&&!c?Ze("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 i;let s=(i=this.flags.timeout)!==null&&i!==void 0?i:this._opts.ackTimeout;if(s===void 0){this.acks[e]=t;return}let n=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===e&&(Ze("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(c,1));Ze("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(n),t.apply(this,c)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((i,s)=>{let n=(a,c)=>a?s(a):i(c);n.withError=!0,t.push(n),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let i={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((s,...n)=>i!==this._queue[0]?Ze("packet [%d] already acknowledged",i.id):(s!==null?i.tryCount>this._opts.retries&&(Ze("packet [%d] is discarded after %d tries",i.id,i.tryCount),this._queue.shift(),t&&t(s)):(Ze("packet [%d] was successfully sent",i.id),this._queue.shift(),t&&t(null,...n)),i.pending=!1,this._drainQueue())),this._queue.push(i),this._drainQueue()}_drainQueue(e=!1){if(Ze("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){Ze("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,Ze("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(){Ze("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){Ze("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(i=>String(i.id)===e)){let i=this.acks[e];delete this.acks[e],i.withError&&i.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 i=new Error(e.data.message);i.data=e.data.data,this.emitReserved("connect_error",i);break}}onevent(e){let t=e.data||[];Ze("emitting event %j",t),e.id!=null&&(Ze("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 i of t)i.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,i=!1;return function(...s){i||(i=!0,Ze("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"){Ze("bad ack %s",e.id);return}delete this.acks[e.id],Ze("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){Ze("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(){Ze("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&&(Ze("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 i=0;i<t.length;i++)if(e===t[i])return t.splice(i,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 i=0;i<t.length;i++)if(e===t[i])return t.splice(i,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 i of t)i.apply(this,e.data)}}};Fi.Socket=Ga});var th=F(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.Backoff=Bi;function Bi(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}Bi.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};Bi.prototype.reset=function(){this.attempts=0};Bi.prototype.setMin=function(r){this.ms=r};Bi.prototype.setMax=function(r){this.max=r};Bi.prototype.setJitter=function(r){this.jitter=r}});var rh=F(Nt=>{"use strict";var L_=Nt&&Nt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=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,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),N_=Nt&&Nt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),D_=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)&&L_(e,r,t);return N_(e,r),e},M_=Nt&&Nt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Nt,"__esModule",{value:!0});Nt.Manager=void 0;var Ja=Bn(),F_=Ya(),B_=D_(Hn()),ai=$a(),j_=th(),U_=Jr(),q_=M_(At()),ot=(0,q_.default)("socket.io-client:manager"),Za=class extends U_.Emitter{constructor(e,t){var i;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,Ja.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((i=t.randomizationFactor)!==null&&i!==void 0?i:.5),this.backoff=new j_.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||B_;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(ot("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;ot("opening %s",this.uri),this.engine=new Ja.Socket(this.uri,this.opts);let t=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;let s=(0,ai.on)(t,"open",function(){i.onopen(),e&&e()}),n=c=>{ot("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},a=(0,ai.on)(t,"error",n);if(this._timeout!==!1){let c=this._timeout;ot("connect attempt will timeout after %d",c);let u=this.setTimeoutFn(()=>{ot("connect attempt timed out after %d",c),s(),n(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(){ot("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push((0,ai.on)(e,"ping",this.onping.bind(this)),(0,ai.on)(e,"data",this.ondata.bind(this)),(0,ai.on)(e,"error",this.onerror.bind(this)),(0,ai.on)(e,"close",this.onclose.bind(this)),(0,ai.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,Ja.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){ot("error",e),this.emitReserved("error",e)}socket(e,t){let i=this.nsps[e];return i?this._autoConnect&&!i.active&&i.connect():(i=new F_.Socket(this,e,t),this.nsps[e]=i),i}_destroy(e){let t=Object.keys(this.nsps);for(let i of t)if(this.nsps[i].active){ot("socket %s is still active, skipping close",i);return}this._close()}_packet(e){ot("writing packet %j",e);let t=this.encoder.encode(e);for(let i=0;i<t.length;i++)this.engine.write(t[i],e.options)}cleanup(){ot("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){ot("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var i;ot("closed due to %s",e),this.cleanup(),(i=this.engine)===null||i===void 0||i.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)ot("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();ot("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let i=this.setTimeoutFn(()=>{e.skipReconnect||(ot("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(s=>{s?(ot("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",s)):(ot("reconnect success"),e.onreconnect())}))},t);this.opts.autoUnref&&i.unref(),this.subs.push(()=>{this.clearTimeoutFn(i)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}};Nt.Manager=Za});var oh=F((Me,nh)=>{"use strict";var W_=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=ci;Me.connect=ci;Me.default=ci;var H_=Gl(),zn=rh();Object.defineProperty(Me,"Manager",{enumerable:!0,get:function(){return zn.Manager}});var sh=Ya();Object.defineProperty(Me,"Socket",{enumerable:!0,get:function(){return sh.Socket}});var V_=W_(At()),ih=(0,V_.default)("socket.io-client"),ys={};function ci(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};let t=(0,H_.url)(r,e.path||"/socket.io"),i=t.source,s=t.id,n=t.path,a=ys[s]&&n in ys[s].nsps,c=e.forceNew||e["force new connection"]||e.multiplex===!1||a,u;return c?(ih("ignoring socket cache for %s",i),u=new zn.Manager(i,e)):(ys[s]||(ih("new io instance for %s",i),ys[s]=new zn.Manager(i,e)),u=ys[s]),t.query&&!e.query&&(e.query=t.queryKey),u.socket(t.path,e)}Object.assign(ci,{Manager:zn.Manager,Socket:sh.Socket,io:ci,connect:ci});var z_=Hn();Object.defineProperty(Me,"protocol",{enumerable:!0,get:function(){return z_.protocol}});var ji=Bn();Object.defineProperty(Me,"Fetch",{enumerable:!0,get:function(){return ji.Fetch}});Object.defineProperty(Me,"NodeXHR",{enumerable:!0,get:function(){return ji.NodeXHR}});Object.defineProperty(Me,"XHR",{enumerable:!0,get:function(){return ji.XHR}});Object.defineProperty(Me,"NodeWebSocket",{enumerable:!0,get:function(){return ji.NodeWebSocket}});Object.defineProperty(Me,"WebSocket",{enumerable:!0,get:function(){return ji.WebSocket}});Object.defineProperty(Me,"WebTransport",{enumerable:!0,get:function(){return ji.WebTransport}});nh.exports=ci});var ec=F(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.InputStreamReceiver=void 0;var K_=64,$_=30,G_=4,Y_=256,X_=16,Qa=class{streamId;lastAppliedSeq=0;cb;windowSize;ackThrottleMs;ackTimer=null;framesSinceAck=0;lastResendFrom=0;resendSuppressed=0;constructor(e,t,i={}){this.streamId=e,this.cb=t,this.windowSize=Math.max(1,i.windowSize??K_),this.ackThrottleMs=Math.max(0,i.ackThrottleMs??$_)}get appliedSeq(){return this.lastAppliedSeq}receive(e,t,i){if(e<=this.lastAppliedSeq){this.flushAck();return}if(e===this.lastAppliedSeq+1){try{this.cb.onApply(t,i)}catch{}this.lastAppliedSeq=e,this.scheduleAck();return}this.flushAck();let s=Math.max(this.windowSize*G_,Y_);e-this.lastAppliedSeq>s||this.maybeResend(this.lastAppliedSeq+1)}maybeResend(e){if(e===this.lastResendFrom){if(++this.resendSuppressed<X_)return;this.resendSuppressed=0}else this.lastResendFrom=e,this.resendSuppressed=0;this.cb.onResend(e)}resumeState(){return{streamId:this.streamId,lastAckSeq:this.lastAppliedSeq}}dispose(){this.ackTimer&&(clearTimeout(this.ackTimer),this.ackTimer=null)}scheduleAck(){this.framesSinceAck++;let e=Math.max(1,Math.floor(this.windowSize/4));if(this.windowSize===1||this.framesSinceAck>=e){this.flushAck();return}this.ackTimer||(this.ackTimer=setTimeout(()=>this.flushAck(),this.ackThrottleMs))}flushAck(){this.ackTimer&&(clearTimeout(this.ackTimer),this.ackTimer=null),this.framesSinceAck=0,this.cb.onAck(this.lastAppliedSeq)}};Kn.InputStreamReceiver=Qa});var uh=F($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.WebSocketService=void 0;var J_=oh(),ah=hr(),ch=zs(),fh=Ws(),Z_=ec(),tc=class{authService;cryptoService;config;logger;notification;deviceId;platform;extraCapabilities;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;inputReceivers=new Map;terminalActiveCheck=null;MAX_INPUT_RECEIVERS=512;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,i,s,n,a,c="vscode",u=[]){this.authService=e,this.cryptoService=t,this.config=i,this.logger=s,this.notification=n,this.deviceId=a,this.platform=c,this.extraCapabilities=u}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,ch.getWsUrl)(this.config);this.logger.info("Connecting to WebSocket",t),this.statusChangeHandler?.("connecting");let i=await this.cryptoService.getPublicKey();return new Promise((s,n)=>{let a=Array.from(new Set([...ah.DEFAULT_CLIENT_CAPABILITIES,...this.extraCapabilities]));this.socket=(0,J_.io)(`${t}/agent`,{auth:{token:e,protocolVersion:ah.PROTOCOL_VERSION,deviceId:this.deviceId,platform:this.platform,capabilities:a,publicKey:i},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 c of this.reconnectHandlers)c()}else this.hasConnectedOnce=!0,s()}),this.socket.on("error",c=>{this.logger.error(`Server error [${c.code}]: ${c.message}`),c.code==="E401"&&(this.logger.warn("Auth failure (E401)"),this.authFailureHandler?.())}),this.socket.on("disconnect",c=>{this.logger.warn("WebSocket disconnected",c),this.stopHeartbeat(),this.statusChangeHandler?.("disconnected"),this.isManualDisconnect||(c==="transport close"?(this.logger.info("Transport close - attempting immediate reconnect"),this.attemptReconnect(!0)):this.scheduleReconnect())}),this.socket.on("protocol:info",c=>{this.logger.info("Protocol info received",c.protocolVersion),this.negotiatedCapabilities=c.negotiatedCapabilities,c.agentName&&this.config.getAgentName()!==c.agentName&&(this.isRemoteRename=!0,this.config.setAgentName(c.agentName).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(c.agentName),this.logger.info("Agent name synced from server",c.agentName))}),this.socket.on("pong",()=>{this.lastPongTime=Date.now(),this.clearPongTimeout(),this.logger.debug("Heartbeat pong received")}),this.socket.on("connect_error",c=>{this.logger.error("WebSocket connection error",c),this.statusChangeHandler?.("error"),this.hasConnectedOnce||n(c),this.scheduleReconnect()}),this.socket.on("terminal:input",c=>{this.handleTerminalInput(c)}),this.socket.on("crypto:keyExchange",async(c,u)=>{this.logger.info("Received key exchange request",c.terminalId,c.sessionId),this.rekeyingTerminals.add(c.terminalId),this.outputBuffer.set(c.terminalId,[]);try{if(await this.cryptoService.handleKeyExchange(c.terminalId,c.clientPublicKey,c.sessionId)){let p=await this.cryptoService.getPublicKey();u?.({success:!0,agentPublicKey:p||void 0}),this.flushOutputBuffer(c.terminalId)}else u?.({success:!1,error:"Key exchange failed"})}catch(d){this.logger.error("Key exchange error",d),u?.({success:!1,error:String(d)})}finally{this.rekeyingTerminals.delete(c.terminalId),this.outputBuffer.delete(c.terminalId)}}),this.socket.on("crypto:sessionCleanup",c=>{this.cryptoService.removeSession(c.terminalId,c.sessionId)}),this.socket.on("agent:keyExchangeRequest",async c=>{try{let u=await this.cryptoService.handleAgentKeyExchange(c.clientPublicKey,c.sessionId),d={agentId:c.agentId,sessionId:c.sessionId,ok:u,error:u?void 0:"Key exchange failed"};this.socket?.emit("agent:keyExchangeAck",d)}catch(u){this.logger.error("Agent key exchange error",u);let d={agentId:c.agentId,sessionId:c.sessionId,ok:!1,error:String(u)};this.socket?.emit("agent:keyExchangeAck",d)}}),this.socket.on("agent:sessionEnd",c=>{this.cryptoService.removeAgentSession(c.sessionId)}),this.socket.on("agent:renamed",c=>{this.logger.info("Agent renamed from web client",c.name),this.isRemoteRename=!0,this.config.setAgentName(c.name).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(c.name)}),this.socket.on("terminal:createRequest",c=>{this.createTerminalHandler?.(c.name)}),this.socket.on("terminal:getBuffer",(c,u)=>{if(!this.getBufferHandler){u?.({success:!1,error:"Buffer handler not set"});return}let d=this.getBufferHandler(c.terminalId);if(d===null){u?.({success:!1,error:"Terminal not found"});return}let p=this.cryptoService.encryptOutput(c.terminalId,d);u?.(p?{success:!0,encrypted:p}:{success:!0,data:d}),this.redrawHandler?.(c.terminalId)}),this.socket.on("terminal:resize",c=>{this.resizeHandler?.(c.terminalId,c.cols,c.rows)}),this.socket.on("workspace:clientAttached",c=>{this.clientAttachedHandler?.(c)}),this.socket.on("workspace:clientDetached",c=>{this.clientDetachedHandler?.(c)}),this.socket.on("file:view",c=>{this.fileViewRequestHandler?.(c.terminalId,c.request)}),this.socket.on("file:list",c=>{this.fileListRequestHandler?.(c.terminalId,c.request)}),this.socket.on("file:download:request",c=>{this.fileDownloadRequestHandler?.(c.terminalId,c.path,c.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})}sendPtyResized(e,t,i,s){this.socket?.connected&&this.socket.emit("agent:ptyResized",{instanceId:e,terminalId:t,cols:i,rows:s})}sendOutput(e,t,i){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:i});return}let s=this.cryptoService.encryptOutput(t,i),n={instanceId:e,terminalId:t,...s?{encrypted:s}:{data:i}};this.socket?.emit("terminal:output",n)}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:i,data:s}of t){let n=this.cryptoService.encryptOutput(e,s),a={instanceId:i,terminalId:e,...n?{encrypted:n}:{data:s}};this.socket?.emit("terminal:output",a)}}}async updateStatus(e){await this.emit("terminal:status",e)}sendTerminalEvent(e,t,i){let s={instanceId:e,terminalId:t,event:i};this.socket?.emit("terminal:event",s)}hasCapability(e){return this.negotiatedCapabilities.includes(e)}sendFileChangedEvent(e,t,i){let s={instanceId:e,terminalId:t,event:i};this.socket?.emit("file:changed",s)}sendFileListResponse(e,t){let i={instanceId:e,response:t};this.socket?.emit("file:list:response",i)}sendAgentRename(e){this.socket?.emit("agent:rename",{name:e})}isRemoteRenameInProgress(){return this.isRemoteRename}getSocket(){return this.socket}emit(e,t){let i=(0,fh.generateCorrelationId)(),s=t&&typeof t=="object"&&!Array.isArray(t)?{...t,_cid:i}:t;return(0,fh.runWithCorrelation)(i,()=>new Promise((n,a)=>{if(!this.socket?.connected){a(new Error("WebSocket not connected"));return}this.socket.emit(e,s,c=>{c.success?n(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 i=this.cryptoService.decryptInput(e.terminalId,e.encrypted);if(!i){this.logger.error("Failed to decrypt terminal input",e.terminalId);return}t=i}else if(e.data)t=Buffer.from(e.data,"base64").toString("utf8");else{this.logger.error("Invalid terminal input payload");return}if(e.streamId&&typeof e.seq=="number"){let i=this.getOrCreateInputReceiver(e.terminalId,e.streamId,e.instanceId,e.dbTerminalId);if(!i)return;i.receive(e.seq,t,e.paste);return}this.inputHandler?.(e.terminalId,t,e.dbTerminalId)}getOrCreateInputReceiver(e,t,i,s){let n=this.inputReceivers.get(e);if(this.terminalActiveCheck&&!this.terminalActiveCheck(e))return n&&this.disposeInputStream(e),null;if(n&&n.receiver.streamId===t)return s&&(n.routeId=s),i&&(n.instanceId=i),n.receiver;if(n&&n.receiver.dispose(),!n&&this.inputReceivers.size>=this.MAX_INPUT_RECEIVERS)return this.logger.error("inputReceivers map at cap, dropping frame",e),null;let a=new Z_.InputStreamReceiver(t,{onApply:(c,u)=>this.inputHandler?.(e,c,this.routeIdFor(e),u),onAck:c=>this.sendInputAck(e,t,c),onResend:c=>this.sendInputResend(e,t,c)});return this.inputReceivers.set(e,{receiver:a,routeId:s??e,instanceId:i??""}),a}setTerminalActiveCheck(e){this.terminalActiveCheck=e}routeIdFor(e){return this.inputReceivers.get(e)?.routeId??e}sendInputAck(e,t,i){let s=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:ack",{instanceId:s,terminalId:e,streamId:t,ackSeq:i})}sendInputResend(e,t,i){let s=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:resend",{instanceId:s,terminalId:e,streamId:t,fromSeq:i})}sendInputResume(e){let t=this.inputReceivers.get(e);if(!t)return;let{streamId:i,lastAckSeq:s}=t.receiver.resumeState();this.socket?.emit("input:resume",{instanceId:t.instanceId,terminalId:e,streamId:i,lastAckSeq:s})}disposeInputStream(e){this.inputReceivers.get(e)?.receiver.dispose(),this.inputReceivers.delete(e)}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(i){this.logger.warn("Reconnect failed",i),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,ch.getApiUrl)(this.config)}/health`,i=new AbortController,s=setTimeout(()=>i.abort(),5e3),n=await fetch(t,{method:"GET",signal:i.signal});return clearTimeout(s),this.logger.debug("Network check OK",String(n.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)}};$n.WebSocketService=tc});var hh=F(rr=>{"use strict";var Q_=rr&&rr.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=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,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),ey=rr&&rr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),ic=rr&&rr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(i[i.length]=s);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),s=0;s<i.length;s++)i[s]!=="default"&&Q_(t,e,i[s]);return ey(t,e),t}})();Object.defineProperty(rr,"__esModule",{value:!0});rr.FileTransferService=void 0;var Gn=ic(require("fs")),ty=ic(require("path")),lh=ic(require("crypto")),Fe=hr(),rc=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,i,s,n){let a=Gn.readFileSync(t),c=t.split("/").pop()||"file";return this.initAndSendChunks(e,a,c,{mimeType:this.getMimeType(c),requestId:n,onProgress:i,onComplete:s})}async sendBuffer(e,t,i,s,n){return this.initAndSendChunks(e,t,i,{mimeType:s,purpose:n?.purpose,viewMetadata:n?.viewMetadata,requestId:n?.requestId,onProgress:n?.onProgress,onComplete:n?.onComplete})}async initAndSendChunks(e,t,i,s){if(!this.socket)throw new Error("Socket not connected");let n=t.length,a=(0,Fe.calculateTotalChunks)(n),c=this.calculateChecksum(t),u=lh.randomUUID(),d={id:u,terminalId:e,filename:i,size:n,totalChunks:a,direction:Fe.TransferDirection.DOWNLOAD,status:Fe.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*Fe.CHUNK_SIZE,E=Math.min(y+Fe.CHUNK_SIZE,n);d.chunks.push(t.subarray(y,E))}this.activeTransfers.set(u,d);let p={transferId:u,terminalId:e,filename:i,size:n,totalChunks:a,mimeType:s.mimeType||"application/octet-stream",checksum:c,direction:Fe.TransferDirection.DOWNLOAD,instanceId:this.instanceId};return s.requestId&&(p.requestId=s.requestId),s.purpose&&(p.purpose=s.purpose),s.viewMetadata&&(p.viewMetadata=s.viewMetadata),new Promise((m,y)=>{this.socket.emit("file:init",p,E=>{E.accepted?(d.status=Fe.TransferStatus.ACTIVE,this.startSendingChunks(u),m(u)):(this.activeTransfers.delete(u),y(new Error(E.error||"Transfer rejected")))})})}async receiveFile(e,t,i,s,n,a,c,u="sha256",d,p){let m={id:e,terminalId:t,filename:i,filePath:c,size:s,totalChunks:n,direction:Fe.TransferDirection.UPLOAD,status:Fe.TransferStatus.ACTIVE,deliveredChunks:new Set,pendingChunks:new Map,chunks:new Array(n).fill(null),checksum:a,checksumAlgorithm:u,onProgress:d?(y,E)=>d(e,y,E):void 0,onComplete:p?(y,E)=>p(e,y,E):void 0,ackTimeouts:new Map};this.activeTransfers.set(e,m)}cancelTransfer(e,t){let i=this.activeTransfers.get(e);if(i){for(let s of i.ackTimeouts.values())clearTimeout(s);if(i.status=Fe.TransferStatus.CANCELLED,i.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},i=>{if(i.status===Fe.TransferStatus.EXPIRED){t.onComplete?.(!1,"Transfer expired"),this.activeTransfers.delete(e);return}if(i.deliveredChunks)for(let s of i.deliveredChunks)t.deliveredChunks.add(s);if(t.direction===Fe.TransferDirection.DOWNLOAD&&i.missingChunks){t.status=Fe.TransferStatus.ACTIVE;for(let s of i.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 i of t.ackTimeouts.values())clearTimeout(i);t.status=Fe.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 i=0;i<Math.min(Fe.WINDOW_SIZE,t.totalChunks);i++)t.deliveredChunks.has(i)||this.sendChunk(t,i)}sendChunk(e,t){if(!this.socket||!e.chunks)return;let i=e.chunks[t];if(!i)return;let s=e.pendingChunks.get(t),n={seq:t,data:i,retries:s?s.retries:0,sentAt:Date.now()};e.pendingChunks.set(t,n);let a={transferId:e.id,seq:t,data:i.buffer.slice(i.byteOffset,i.byteOffset+i.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)},Fe.ACK_TIMEOUT_MS);e.ackTimeouts.set(t,c)}handleChunkAck(e){let t=this.activeTransfers.get(e.transferId);if(!t||t.status===Fe.TransferStatus.COMPLETED)return;let i=t.ackTimeouts.get(e.seq);i&&(clearTimeout(i),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+Fe.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 i=this.activeTransfers.get(e);if(!i)return;let s=i.pendingChunks.get(t);s&&(s.retries<Fe.MAX_RETRIES?(s.retries++,this.sendChunk(i,t)):this.cancelTransfer(e,"Max retries exceeded"))}finishSending(e){if(!this.socket)return;e.status=Fe.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 i={transferId:e.transferId,seq:e.seq};this.socket.emit("file:chunk:ack",i)}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=Fe.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=ty.dirname(e.filePath);Gn.existsSync(s)||Gn.mkdirSync(s,{recursive:!0}),Gn.writeFileSync(e.filePath,t),e.status=Fe.TransferStatus.COMPLETED,e.onComplete?.(!0),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!0})}catch(s){let n=s instanceof Error?s.message:String(s);e.status=Fe.TransferStatus.FAILED,e.onComplete?.(!1,`Failed to save file: ${n}`),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!1,error:`Failed to save file: ${n}`})}this.activeTransfers.delete(e.id)}handleComplete(e){let t=this.activeTransfers.get(e.transferId);if(t){e.success?(t.status=Fe.TransferStatus.COMPLETED,t.onComplete?.(!0)):(t.status=Fe.TransferStatus.FAILED,t.onComplete?.(!1,e.error));for(let i of t.ackTimeouts.values())clearTimeout(i);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(n=>t({accepted:!1,error:n.message}))}calculateChecksum(e,t="sha256"){return t==="fnv1a"?this.fnv1aHash(e):lh.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=rc});var uc=F((FE,Jn)=>{function gh(r){return Array.isArray(r)?r:[r]}var ry=void 0,nc="",dh=" ",sc="\\",iy=/^\s+$/,sy=/(?:[^\\]|^)\\$/,ny=/^\\!/,oy=/^\\#/,ay=/\r?\n/g,cy=/^\.{0,2}\/|^\.{1,2}$/,fy=/\/$/,Ui="/",mh="node-ignore";typeof Symbol<"u"&&(mh=Symbol.for("node-ignore"));var _h=mh,qi=(r,e,t)=>(Object.defineProperty(r,e,{value:t}),t),uy=/([0-z])-([0-z])/g,yh=()=>!1,ly=r=>r.replace(uy,(e,t,i)=>t.charCodeAt(0)<=i.charCodeAt(0)?e:nc),hy=r=>{let{length:e}=r;return r.slice(0,e-e%2)},dy=[[/^\uFEFF/,()=>nc],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?dh:nc)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+dh}],[/[\\$.|*+(){^]/g,r=>`\\${r}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(r,e,t)=>e+6<t.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(r,e,t)=>{let i=t.replace(/\\\*/g,"[^\\/]*");return e+i}],[/\\\\\\(?=[$.|*+(){^])/g,()=>sc],[/\\\\/g,()=>sc],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,i,s)=>e===sc?`\\[${t}${hy(i)}${s}`:s==="]"&&i.length%2===0?`[${ly(t)}${i}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`]],py=/(^|\\\/)?\\\*$/,vs="regex",Yn="checkRegex",ph="_",gy={[vs](r,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[Yn](r,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},my=r=>dy.reduce((e,[t,i])=>e.replace(t,i.bind(r)),r),Xn=r=>typeof r=="string",_y=r=>r&&Xn(r)&&!iy.test(r)&&!sy.test(r)&&r.indexOf("#")!==0,yy=r=>r.split(ay).filter(Boolean),oc=class{constructor(e,t,i,s,n,a){this.pattern=e,this.mark=t,this.negative=n,qi(this,"body",i),qi(this,"ignoreCase",s),qi(this,"regexPrefix",a)}get regex(){let e=ph+vs;return this[e]?this[e]:this._make(vs,e)}get checkRegex(){let e=ph+Yn;return this[e]?this[e]:this._make(Yn,e)}_make(e,t){let i=this.regexPrefix.replace(py,gy[e]),s=this.ignoreCase?new RegExp(i,"i"):new RegExp(i);return qi(this,t,s)}},vy=({pattern:r,mark:e},t)=>{let i=!1,s=r;s.indexOf("!")===0&&(i=!0,s=s.substr(1)),s=s.replace(ny,"!").replace(oy,"#");let n=my(s);return new oc(r,e,s,t,i,n)},ac=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[_h]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(Xn(e)&&(e={pattern:e}),_y(e.pattern)){let t=vy(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,gh(Xn(e)?yy(e):e).forEach(this._add,this),this._added}test(e,t,i){let s=!1,n=!1,a;this._rules.forEach(u=>{let{negative:d}=u;n===d&&s!==n||d&&!s&&!n&&!t||!u[i].test(e)||(s=!d,n=d,a=d?ry:u)});let c={ignored:s,unignored:n};return a&&(c.rule=a),c}},wy=(r,e)=>{throw new e(r)},vr=(r,e,t)=>Xn(r)?r?vr.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),vh=r=>cy.test(r);vr.isNotRelative=vh;vr.convert=r=>r;var cc=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:i=!1}={}){qi(this,_h,!0),this._rules=new ac(t),this._strictPathCheck=!i,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,i,s){let n=e&&vr.convert(e);return vr(n,e,this._strictPathCheck?wy:yh),this._t(n,t,i,s)}checkIgnore(e){if(!fy.test(e))return this.test(e);let t=e.split(Ui).filter(Boolean);if(t.pop(),t.length){let i=this._t(t.join(Ui)+Ui,this._testCache,!0,t);if(i.ignored)return i}return this._rules.test(e,!1,Yn)}_t(e,t,i,s){if(e in t)return t[e];if(s||(s=e.split(Ui).filter(Boolean)),s.pop(),!s.length)return t[e]=this._rules.test(e,i,vs);let n=this._t(s.join(Ui)+Ui,t,i,s);return t[e]=n.ignored?n:this._rules.test(e,i,vs)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return gh(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},fc=r=>new cc(r),Ey=r=>vr(r&&vr.convert(r),r,yh),wh=()=>{let r=t=>/^\\\\\?\\/.test(t)||/["<>|\u0000-\u001F]+/u.test(t)?t:t.replace(/\\/g,"/");vr.convert=r;let e=/^[a-z]:\//i;vr.isNotRelative=t=>e.test(t)||vh(t)};typeof process<"u"&&process.platform==="win32"&&wh();Jn.exports=fc;fc.default=fc;Jn.exports.isPathValid=Ey;qi(Jn.exports,Symbol.for("setupWindows"),wh)});var bh=F(Dt=>{"use strict";var by=Dt&&Dt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=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,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),xy=Dt&&Dt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Eh=Dt&&Dt.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(i[i.length]=s);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),s=0;s<i.length;s++)i[s]!=="default"&&by(t,e,i[s]);return xy(t,e),t}})(),Sy=Dt&&Dt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Dt,"__esModule",{value:!0});Dt.FileListService=void 0;var ws=Eh(require("path")),lc=Eh(require("fs/promises")),Ty=Sy(uc()),hc=hr(),Cy=["node_modules",".pnpm","vendor",".git","dist","build","out",".next",".nuxt",".output",".cache",".turbo",".idea",".vscode",".DS_Store","Thumbs.db"],dc=class{ignoreFilter;workspaceRoot;onResponseCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,Ty.default)(),this.ignoreFilter.add(Cy),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 lc.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),i=await this.listDirectory(t,e.path);this.sendResponse({requestId:e.requestId,path:e.path,entries:i})}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 i=await lc.readdir(e,{withFileTypes:!0}),s=[];for(let n of i){let a=t==="."||t===""?n.name:ws.join(t,n.name);if(this.shouldHide(a,n.isDirectory()))continue;let c=ws.join(e,n.name),u={name:n.name,path:a,type:n.isDirectory()?hc.FileEntryType.DIRECTORY:hc.FileEntryType.FILE};if(!n.isDirectory())try{let d=await lc.stat(c);u.size=d.size,u.modified=d.mtime.toISOString()}catch{}s.push(u)}return s.sort((n,a)=>n.type!==a.type?n.type===hc.FileEntryType.DIRECTORY?-1:1:n.name.localeCompare(a.name))}shouldHide(e,t){let i=e.split(ws.sep).join("/"),s=t?`${i}/`:i;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=dc});var Sh=F(ir=>{"use strict";var Oy=ir&&ir.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=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,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),ky=ir&&ir.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),xh=ir&&ir.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(i[i.length]=s);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),s=0;s<i.length;s++)i[s]!=="default"&&Oy(t,e,i[s]);return ky(t,e),t}})();Object.defineProperty(ir,"__esModule",{value:!0});ir.FileTrackerService=void 0;var pc=xh(require("path")),fi=xh(require("fs/promises")),Ry=require("child_process"),Py=require("util"),Wt=hr(),gc=(0,Py.promisify)(Ry.exec),mc={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},_c=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 i=this.outputBuffers.get(e)||"";i+=t,i.length>10240&&(i=i.slice(-10240)),this.outputBuffers.set(e,i);try{await this.parseToolCalls(e,i)}catch(s){this.logger.error("Error parsing tool calls",s)}}async parseToolCalls(e,t){let i=this.stripAnsi(t),s=i.match(mc.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 n=i.match(mc.toolSuccess);if(n){let a=n[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(mc.toolError.test(i))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,i,s){if(!this.isFileModifyingTool(i))return;let n=this.extractFilePath(i,s);if(!n)return;let a=this.resolveFilePath(n),c={toolId:t,toolName:i,filePath:n,timestamp:new Date().toISOString()};this.pendingToolCalls.set(t,c);let u;try{u=await fi.readFile(a,"utf-8")}catch{u=void 0}let d={path:n,changeType:u===void 0?Wt.FileChangeType.CREATE:Wt.FileChangeType.MODIFY,toolName:i,toolId:t,timestamp:c.timestamp,previousContent:u},p=this.trackedFiles.get(e)||[];p.push(d),this.trackedFiles.set(e,p)}async handleToolEnd(e,t,i,s){if(!this.isFileModifyingTool(i)||!this.pendingToolCalls.get(t))return;if(this.pendingToolCalls.delete(t),s==="error"){let p=this.trackedFiles.get(e)||[],m=p.findIndex(y=>y.toolId===t);m!==-1&&p.splice(m,1);return}let c=(this.trackedFiles.get(e)||[]).find(p=>p.toolId===t);if(!c)return;let u=this.resolveFilePath(c.path);try{let p=await fi.stat(u);c.size=p.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 i=this.resolveFilePath(t.path),s=this.getViewableMimeType(t.path);if(s&&this.onFileViewTransferCallback){try{let a=await fi.readFile(i),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 n;try{t.type===Wt.FileViewType.CONTENT?n=await this.getFileContent(t,i):n=await this.getFileDiff(e,t,i)}catch(a){n={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:n.type===Wt.FileViewType.CONTENT?"content":"diff",language:n.language,truncated:n.truncated,error:n.error},c=Buffer.from(n.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 i=e.maxSize||1048576,s=await fi.stat(t),n=await fi.readFile(t,"utf-8"),a=!1,c=n;return n.length>i&&(c=n.slice(0,i),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,i){let s=t.diffBase||Wt.DiffBase.GIT,n;return s===Wt.DiffBase.GIT?n=await this.getGitDiff(i):n=await this.getPreviousDiff(e,t.path,i),{requestId:t.requestId,path:t.path,type:Wt.FileViewType.DIFF,content:n,language:"diff"}}async getGitDiff(e){if(!this.workspaceRoot)throw new Error("No workspace root");try{let{stdout:t}=await gc(`git diff --cached -- "${e}"`,{cwd:this.workspaceRoot});if(t.trim())return t;let{stdout:i}=await gc(`git diff -- "${e}"`,{cwd:this.workspaceRoot});if(i.trim())return i;let{stdout:s}=await gc(`git status --porcelain -- "${e}"`,{cwd:this.workspaceRoot});if(s.startsWith("??")||s.startsWith("A ")){let a=(await fi.readFile(e,"utf-8")).split(`
27
27
  `),c=pc.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
28
  `)}return"(no changes)"}catch{throw new Error("Git not available")}}async getPreviousDiff(e,t,i){let a=(this.trackedFiles.get(e)||[]).find(d=>d.path===t&&d.previousContent!==void 0)?.previousContent||"",c;try{c=await fi.readFile(i,"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 i of e.hunks){t.push(`@@ -${i.oldStart},${i.oldLines} +${i.newStart},${i.newLines} @@`);for(let s of i.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(i=>({path:i.path,changeType:i.changeType,timestamp:i.timestamp,source:"tool-call",toolName:i.toolName,toolId:i.toolId,size:i.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 pc.isAbsolute(e)?e:this.workspaceRoot?pc.join(this.workspaceRoot,e):e}dispose(){this.trackedFiles.clear(),this.pendingToolCalls.clear(),this.onFileChangedCallback=null,this.onFileViewTransferCallback=null}};ir.FileTrackerService=_c});var Th=F(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.InputStreamReceiver=st.FileTrackerService=st.FileListService=st.FileTransferService=st.WebSocketService=st.StatusDetector=st.AuthService=st.CryptoService=void 0;var Ay=Xf();Object.defineProperty(st,"CryptoService",{enumerable:!0,get:function(){return Ay.CryptoService}});var Iy=Jf();Object.defineProperty(st,"AuthService",{enumerable:!0,get:function(){return Iy.AuthService}});var Ly=Zf();Object.defineProperty(st,"StatusDetector",{enumerable:!0,get:function(){return Ly.StatusDetector}});var Ny=uh();Object.defineProperty(st,"WebSocketService",{enumerable:!0,get:function(){return Ny.WebSocketService}});var Dy=hh();Object.defineProperty(st,"FileTransferService",{enumerable:!0,get:function(){return Dy.FileTransferService}});var My=bh();Object.defineProperty(st,"FileListService",{enumerable:!0,get:function(){return My.FileListService}});var Fy=Sh();Object.defineProperty(st,"FileTrackerService",{enumerable:!0,get:function(){return Fy.FileTrackerService}});var By=ec();Object.defineProperty(st,"InputStreamReceiver",{enumerable:!0,get:function(){return By.InputStreamReceiver}})});var ws=F(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.InputStreamReceiver=ye.FileTrackerService=ye.FileListService=ye.FileTransferService=ye.WebSocketService=ye.StatusDetector=ye.AuthService=ye.CryptoService=ye.getCurrentCorrelationId=ye.runWithCorrelation=ye.generateCorrelationId=ye.getWsUrl=ye.getApiUrl=ye.CircularBuffer=ye.formatLogLine=ye.shouldLog=ye.LOG_LEVELS=void 0;var yc=gf();Object.defineProperty(ye,"LOG_LEVELS",{enumerable:!0,get:function(){return yc.LOG_LEVELS}});Object.defineProperty(ye,"shouldLog",{enumerable:!0,get:function(){return yc.shouldLog}});Object.defineProperty(ye,"formatLogLine",{enumerable:!0,get:function(){return yc.formatLogLine}});var Wi=yf();Object.defineProperty(ye,"CircularBuffer",{enumerable:!0,get:function(){return Wi.CircularBuffer}});Object.defineProperty(ye,"getApiUrl",{enumerable:!0,get:function(){return Wi.getApiUrl}});Object.defineProperty(ye,"getWsUrl",{enumerable:!0,get:function(){return Wi.getWsUrl}});Object.defineProperty(ye,"generateCorrelationId",{enumerable:!0,get:function(){return Wi.generateCorrelationId}});Object.defineProperty(ye,"runWithCorrelation",{enumerable:!0,get:function(){return Wi.runWithCorrelation}});Object.defineProperty(ye,"getCurrentCorrelationId",{enumerable:!0,get:function(){return Wi.getCurrentCorrelationId}});var Br=Th();Object.defineProperty(ye,"CryptoService",{enumerable:!0,get:function(){return Br.CryptoService}});Object.defineProperty(ye,"AuthService",{enumerable:!0,get:function(){return Br.AuthService}});Object.defineProperty(ye,"StatusDetector",{enumerable:!0,get:function(){return Br.StatusDetector}});Object.defineProperty(ye,"WebSocketService",{enumerable:!0,get:function(){return Br.WebSocketService}});Object.defineProperty(ye,"FileTransferService",{enumerable:!0,get:function(){return Br.FileTransferService}});Object.defineProperty(ye,"FileListService",{enumerable:!0,get:function(){return Br.FileListService}});Object.defineProperty(ye,"FileTrackerService",{enumerable:!0,get:function(){return Br.FileTrackerService}});Object.defineProperty(ye,"InputStreamReceiver",{enumerable:!0,get:function(){return Br.InputStreamReceiver}})});var bc=F((xs,wc)=>{(function(r,e){typeof xs=="object"&&typeof wc=="object"?wc.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 i(n){if(s[n])return s[n].exports;var a=s[n]={exports:{},id:n,loaded:!1};return t[n].call(a.exports,a,a.exports,i),a.loaded=!0,a.exports}var s={};return i.m=t,i.c=s,i.p="",i(0)})([function(t,i,s){t.exports=s(34)},function(t,i,s){var n=s(29)("wks"),a=s(33),c=s(2).Symbol,u=typeof c=="function",d=t.exports=function(g){return n[g]||(n[g]=u&&c[g]||(u?c:a)("Symbol."+g))};d.store=n},function(t,i){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,i,s){var n=s(9);t.exports=function(a){if(!n(a))throw TypeError(a+" is not an object!");return a}},function(t,i,s){t.exports=!s(24)(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7})},function(t,i,s){var n=s(12),a=s(17);t.exports=s(4)?function(c,u,d){return n.f(c,u,a(1,d))}:function(c,u,d){return c[u]=d,c}},function(t,i){var s=t.exports={version:"2.4.0"};typeof __e=="number"&&(__e=s)},function(t,i,s){var n=s(14);t.exports=function(a,c,u){if(n(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,i){var s={}.hasOwnProperty;t.exports=function(n,a){return s.call(n,a)}},function(t,i){t.exports=function(s){return typeof s=="object"?s!==null:typeof s=="function"}},function(t,i){t.exports={}},function(t,i){var s={}.toString;t.exports=function(n){return s.call(n).slice(8,-1)}},function(t,i,s){var n=s(3),a=s(26),c=s(32),u=Object.defineProperty;i.f=s(4)?Object.defineProperty:function(d,g,m){if(n(d),g=c(g,!0),n(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,i,s){var n=s(42),a=s(15);t.exports=function(c){return n(a(c))}},function(t,i){t.exports=function(s){if(typeof s!="function")throw TypeError(s+" is not a function!");return s}},function(t,i){t.exports=function(s){if(s==null)throw TypeError("Can't call method on "+s);return s}},function(t,i,s){var n=s(9),a=s(2).document,c=n(a)&&n(a.createElement);t.exports=function(u){return c?a.createElement(u):{}}},function(t,i){t.exports=function(s,n){return{enumerable:!(1&s),configurable:!(2&s),writable:!(4&s),value:n}}},function(t,i,s){var n=s(12).f,a=s(8),c=s(1)("toStringTag");t.exports=function(u,d,g){u&&!a(u=g?u:u.prototype,c)&&n(u,c,{configurable:!0,value:d})}},function(t,i,s){var n=s(29)("keys"),a=s(33);t.exports=function(c){return n[c]||(n[c]=a(c))}},function(t,i){var s=Math.ceil,n=Math.floor;t.exports=function(a){return isNaN(a=+a)?0:(a>0?n:s)(a)}},function(t,i,s){var n=s(11),a=s(1)("toStringTag"),c=n((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?n(g):(y=n(g))=="Object"&&typeof g.callee=="function"?"Arguments":y}},function(t,i){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,i,s){var n=s(2),a=s(6),c=s(7),u=s(5),d="prototype",g=function(m,y,b){var T,C,H,ge=m&g.F,Y=m&g.G,A=m&g.S,j=m&g.P,Q=m&g.B,I=m&g.W,oe=Y?a:a[y]||(a[y]={}),fe=oe[d],ee=Y?n:A?n[y]:(n[y]||{})[d];Y&&(b=y);for(T in b)C=!ge&&ee&&ee[T]!==void 0,C&&T in oe||(H=C?ee[T]:b[T],oe[T]=Y&&typeof ee[T]!="function"?b[T]:Q&&C?c(H,n):I&&ee[T]==H?(function(ke){var be=function(xe,Se,Ge){if(this instanceof ke){switch(arguments.length){case 0:return new ke;case 1:return new ke(xe);case 2:return new ke(xe,Se)}return new ke(xe,Se,Ge)}return ke.apply(this,arguments)};return be[d]=ke[d],be})(H):j&&typeof H=="function"?c(Function.call,H):H,j&&((oe.virtual||(oe.virtual={}))[T]=H,m&g.R&&fe&&!fe[T]&&u(fe,T,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,i){t.exports=function(s){try{return!!s()}catch{return!0}}},function(t,i,s){t.exports=s(2).document&&document.documentElement},function(t,i,s){t.exports=!s(4)&&!s(24)(function(){return Object.defineProperty(s(16)("div"),"a",{get:function(){return 7}}).a!=7})},function(t,i,s){"use strict";var n=s(28),a=s(23),c=s(57),u=s(5),d=s(8),g=s(10),m=s(45),y=s(18),b=s(52),T=s(1)("iterator"),C=!([].keys&&"next"in[].keys()),H="@@iterator",ge="keys",Y="values",A=function(){return this};t.exports=function(j,Q,I,oe,fe,ee,ke){m(I,Q,oe);var be,xe,Se,Ge=function(L){if(!C&&L in Pe)return Pe[L];switch(L){case ge:return function(){return new I(this,L)};case Y:return function(){return new I(this,L)}}return function(){return new I(this,L)}},Ie=Q+" Iterator",Ye=fe==Y,Ue=!1,Pe=j.prototype,et=Pe[T]||Pe[H]||fe&&Pe[fe],Xe=et||Ge(fe),ut=fe?Ye?Ge("entries"):Xe:void 0,w=Q=="Array"&&Pe.entries||et;if(w&&(Se=b(w.call(new j)),Se!==Object.prototype&&(y(Se,Ie,!0),n||d(Se,T)||u(Se,T,A))),Ye&&et&&et.name!==Y&&(Ue=!0,Xe=function(){return et.call(this)}),n&&!ke||!C&&!Ue&&Pe[T]||u(Pe,T,Xe),g[Q]=Xe,g[Ie]=A,fe)if(be={values:Ye?Xe:Ge(Y),keys:ee?Xe:Ge(ge),entries:ut},ke)for(xe in be)xe in Pe||c(Pe,xe,be[xe]);else a(a.P+a.F*(C||Ue),Q,be);return be}},function(t,i){t.exports=!0},function(t,i,s){var n=s(2),a="__core-js_shared__",c=n[a]||(n[a]={});t.exports=function(u){return c[u]||(c[u]={})}},function(t,i,s){var n,a,c,u=s(7),d=s(41),g=s(25),m=s(16),y=s(2),b=y.process,T=y.setImmediate,C=y.clearImmediate,H=y.MessageChannel,ge=0,Y={},A="onreadystatechange",j=function(){var I=+this;if(Y.hasOwnProperty(I)){var oe=Y[I];delete Y[I],oe()}},Q=function(I){j.call(I.data)};T&&C||(T=function(I){for(var oe=[],fe=1;arguments.length>fe;)oe.push(arguments[fe++]);return Y[++ge]=function(){d(typeof I=="function"?I:Function(I),oe)},n(ge),ge},C=function(I){delete Y[I]},s(11)(b)=="process"?n=function(I){b.nextTick(u(j,I,1))}:H?(a=new H,c=a.port2,a.port1.onmessage=Q,n=u(c.postMessage,c,1)):y.addEventListener&&typeof postMessage=="function"&&!y.importScripts?(n=function(I){y.postMessage(I+"","*")},y.addEventListener("message",Q,!1)):n=A in m("script")?function(I){g.appendChild(m("script"))[A]=function(){g.removeChild(this),j.call(I)}}:function(I){setTimeout(u(j,I,1),0)}),t.exports={set:T,clear:C}},function(t,i,s){var n=s(20),a=Math.min;t.exports=function(c){return c>0?a(n(c),9007199254740991):0}},function(t,i,s){var n=s(9);t.exports=function(a,c){if(!n(a))return a;var u,d;if(c&&typeof(u=a.toString)=="function"&&!n(d=u.call(a))||typeof(u=a.valueOf)=="function"&&!n(d=u.call(a))||!c&&typeof(u=a.toString)=="function"&&!n(d=u.call(a)))return d;throw TypeError("Can't convert object to primitive value")}},function(t,i){var s=0,n=Math.random();t.exports=function(a){return"Symbol(".concat(a===void 0?"":a,")_",(++s+n).toString(36))}},function(t,i,s){"use strict";function n(A){return A&&A.__esModule?A:{default:A}}function a(){return process.platform!=="win32"?"":process.arch==="ia32"&&process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432")?"mixed":"native"}function c(A){return(0,T.createHash)("sha256").update(A).digest("hex")}function u(A){switch(H){case"darwin":return A.split("IOPlatformUUID")[1].split(`
30
- `)[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return A.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return A.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"freebsd":return A.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error("Unsupported platform: "+process.platform)}}function d(A){var j=u((0,b.execSync)(Y[H]).toString());return A?j:c(j)}function g(A){return new y.default(function(j,Q){return(0,b.exec)(Y[H],{},function(I,oe,fe){if(I)return Q(new Error("Error while obtaining machine id: "+I.stack));var ee=u(oe.toString());return j(A?ee:c(ee))})})}Object.defineProperty(i,"__esModule",{value:!0});var m=s(35),y=n(m);i.machineIdSync=d,i.machineId=g;var b=s(70),T=s(71),C=process,H=C.platform,ge={native:"%windir%\\System32",mixed:"%windir%\\sysnative\\cmd.exe /c %windir%\\System32"},Y={darwin:"ioreg -rd1 -c IOPlatformExpertDevice",win32:ge[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,i,s){t.exports={default:s(36),__esModule:!0}},function(t,i,s){s(66),s(68),s(69),s(67),t.exports=s(6).Promise},function(t,i){t.exports=function(){}},function(t,i){t.exports=function(s,n,a,c){if(!(s instanceof n)||c!==void 0&&c in s)throw TypeError(a+": incorrect invocation!");return s}},function(t,i,s){var n=s(13),a=s(31),c=s(62);t.exports=function(u){return function(d,g,m){var y,b=n(d),T=a(b.length),C=c(m,T);if(u&&g!=g){for(;T>C;)if(y=b[C++],y!=y)return!0}else for(;T>C;C++)if((u||C in b)&&b[C]===g)return u||C||0;return!u&&-1}}},function(t,b,s){var n=s(7),a=s(44),c=s(43),u=s(3),d=s(31),g=s(64),m={},y={},b=t.exports=function(T,C,H,ge,Y){var A,j,Q,I,oe=Y?function(){return T}:g(T),fe=n(H,ge,C?2:1),ee=0;if(typeof oe!="function")throw TypeError(T+" is not iterable!");if(c(oe)){for(A=d(T.length);A>ee;ee++)if(I=C?fe(u(j=T[ee])[0],j[1]):fe(T[ee]),I===m||I===y)return I}else for(Q=oe.call(T);!(j=Q.next()).done;)if(I=a(Q,fe,j.value,C),I===m||I===y)return I};b.BREAK=m,b.RETURN=y},function(t,i){t.exports=function(s,n,a){var c=a===void 0;switch(n.length){case 0:return c?s():s.call(a);case 1:return c?s(n[0]):s.call(a,n[0]);case 2:return c?s(n[0],n[1]):s.call(a,n[0],n[1]);case 3:return c?s(n[0],n[1],n[2]):s.call(a,n[0],n[1],n[2]);case 4:return c?s(n[0],n[1],n[2],n[3]):s.call(a,n[0],n[1],n[2],n[3])}return s.apply(a,n)}},function(t,i,s){var n=s(11);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(a){return n(a)=="String"?a.split(""):Object(a)}},function(t,i,s){var n=s(10),a=s(1)("iterator"),c=Array.prototype;t.exports=function(u){return u!==void 0&&(n.Array===u||c[a]===u)}},function(t,i,s){var n=s(3);t.exports=function(a,c,u,d){try{return d?c(n(u)[0],u[1]):c(u)}catch(m){var g=a.return;throw g!==void 0&&n(g.call(a)),m}}},function(t,i,s){"use strict";var n=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=n(u,{next:a(1,m)}),c(d,g+" Iterator")}},function(t,i,s){var n=s(1)("iterator"),a=!1;try{var c=[7][n]();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[n]();y.next=function(){return{done:g=!0}},m[n]=function(){return y},u(m)}catch{}return g}},function(t,i){t.exports=function(s,n){return{value:n,done:!!s}}},function(t,i,s){var n=s(2),a=s(30).set,c=n.MutationObserver||n.WebKitMutationObserver,u=n.process,d=n.Promise,g=s(11)(u)=="process";t.exports=function(){var m,y,b,T=function(){var Y,A;for(g&&(Y=u.domain)&&Y.exit();m;){A=m.fn,m=m.next;try{A()}catch(j){throw m?b():y=void 0,j}}y=void 0,Y&&Y.enter()};if(g)b=function(){u.nextTick(T)};else if(c){var C=!0,H=document.createTextNode("");new c(T).observe(H,{characterData:!0}),b=function(){H.data=C=!C}}else if(d&&d.resolve){var ge=d.resolve();b=function(){ge.then(T)}}else b=function(){a.call(n,T)};return function(Y){var A={fn:Y,next:void 0};y&&(y.next=A),m||(m=A,b()),y=A}}},function(t,i,s){var n=s(3),a=s(50),c=s(22),u=s(19)("IE_PROTO"),d=function(){},g="prototype",m=function(){var y,b=s(16)("iframe"),T=c.length,C=">";for(b.style.display="none",s(25).appendChild(b),b.src="javascript:",y=b.contentWindow.document,y.open(),y.write("<script>document.F=Object</script"+C),y.close(),m=y.F;T--;)delete m[g][c[T]];return m()};t.exports=Object.create||function(y,b){var T;return y!==null?(d[g]=n(y),T=new d,d[g]=null,T[u]=y):T=m(),b===void 0?T:a(T,b)}},function(t,i,s){var n=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,b=0;y>b;)n.f(u,g=m[b++],d[g]);return u}},function(t,i,s){var n=s(55),a=s(17),c=s(13),u=s(32),d=s(8),g=s(26),m=Object.getOwnPropertyDescriptor;i.f=s(4)?m:function(y,b){if(y=c(y),b=u(b,!0),g)try{return m(y,b)}catch{}if(d(y,b))return a(!n.f.call(y,b),y[b])}},function(t,i,s){var n=s(8),a=s(63),c=s(19)("IE_PROTO"),u=Object.prototype;t.exports=Object.getPrototypeOf||function(d){return d=a(d),n(d,c)?d[c]:typeof d.constructor=="function"&&d instanceof d.constructor?d.constructor.prototype:d instanceof Object?u:null}},function(t,i,s){var n=s(8),a=s(13),c=s(39)(!1),u=s(19)("IE_PROTO");t.exports=function(d,g){var m,y=a(d),b=0,T=[];for(m in y)m!=u&&n(y,m)&&T.push(m);for(;g.length>b;)n(y,m=g[b++])&&(~c(T,m)||T.push(m));return T}},function(t,i,s){var n=s(53),a=s(22);t.exports=Object.keys||function(c){return n(c,a)}},function(t,i){i.f={}.propertyIsEnumerable},function(t,i,s){var n=s(5);t.exports=function(a,c,u){for(var d in c)u&&a[d]?a[d]=c[d]:n(a,d,c[d]);return a}},function(t,i,s){t.exports=s(5)},function(t,i,s){var n=s(9),a=s(3),c=function(u,d){if(a(u),!n(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,i,s){"use strict";var n=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]:n[g];u&&m&&!m[d]&&c.f(m,d,{configurable:!0,get:function(){return this}})}},function(t,i,s){var n=s(3),a=s(14),c=s(1)("species");t.exports=function(u,d){var g,m=n(u).constructor;return m===void 0||(g=n(m)[c])==null?d:a(g)}},function(t,i,s){var n=s(20),a=s(15);t.exports=function(c){return function(u,d){var g,m,y=String(a(u)),b=n(d),T=y.length;return b<0||b>=T?c?"":void 0:(g=y.charCodeAt(b),g<55296||g>56319||b+1===T||(m=y.charCodeAt(b+1))<56320||m>57343?c?y.charAt(b):g:c?y.slice(b,b+2):(g-55296<<10)+(m-56320)+65536)}}},function(t,i,s){var n=s(20),a=Math.max,c=Math.min;t.exports=function(u,d){return u=n(u),u<0?a(u+d,0):c(u,d)}},function(t,i,s){var n=s(15);t.exports=function(a){return Object(n(a))}},function(t,i,s){var n=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[n(u)]}},function(t,i,s){"use strict";var n=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,n("keys"),n("values"),n("entries")},function(t,i){},function(t,i,s){"use strict";var n,a,c,u=s(28),d=s(2),g=s(7),m=s(21),y=s(23),b=s(9),T=(s(3),s(14)),C=s(38),H=s(40),ge=(s(58).set,s(60)),Y=s(30).set,A=s(48)(),j="Promise",Q=d.TypeError,oe=d.process,I=d[j],oe=d.process,fe=m(oe)=="process",ee=function(){},ke=!!(function(){try{var w=I.resolve(1),L=(w.constructor={})[s(1)("species")]=function(O){O(ee,ee)};return(fe||typeof PromiseRejectionEvent=="function")&&w.then(ee)instanceof L}catch{}})(),be=function(w,L){return w===L||w===I&&L===c},xe=function(w){var L;return!(!b(w)||typeof(L=w.then)!="function")&&L},Se=function(w){return be(I,w)?new Ge(w):new a(w)},Ge=a=function(w){var L,O;this.promise=new w(function(J,Ae){if(L!==void 0||O!==void 0)throw Q("Bad Promise constructor");L=J,O=Ae}),this.resolve=T(L),this.reject=T(O)},Ie=function(w){try{w()}catch(L){return{error:L}}},Ye=function(w,L){if(!w._n){w._n=!0;var O=w._c;A(function(){for(var J=w._v,Ae=w._s==1,lt=0,vt=function(Et){var wt,nr,Sr=Ae?Et.ok:Et.fail,Vr=Et.resolve,Tr=Et.reject,pi=Et.domain;try{Sr?(Ae||(w._h==2&&et(w),w._h=1),Sr===!0?wt=J:(pi&&pi.enter(),wt=Sr(J),pi&&pi.exit()),wt===Et.promise?Tr(Q("Promise-chain cycle")):(nr=xe(wt))?nr.call(wt,Vr,Tr):Vr(wt)):Tr(J)}catch(Is){Tr(Is)}};O.length>lt;)vt(O[lt++]);w._c=[],w._n=!1,L&&!w._h&&Ue(w)})}},Ue=function(w){Y.call(d,function(){var L,O,J,Ae=w._v;if(Pe(w)&&(L=Ie(function(){fe?oe.emit("unhandledRejection",Ae,w):(O=d.onunhandledrejection)?O({promise:w,reason:Ae}):(J=d.console)&&J.error&&J.error("Unhandled promise rejection",Ae)}),w._h=fe||Pe(w)?2:1),w._a=void 0,L)throw L.error})},Pe=function(w){if(w._h==1)return!1;for(var L,O=w._a||w._c,J=0;O.length>J;)if(L=O[J++],L.fail||!Pe(L.promise))return!1;return!0},et=function(w){Y.call(d,function(){var L;fe?oe.emit("rejectionHandled",w):(L=d.onrejectionhandled)&&L({promise:w,reason:w._v})})},Xe=function(w){var L=this;L._d||(L._d=!0,L=L._w||L,L._v=w,L._s=2,L._a||(L._a=L._c.slice()),Ye(L,!0))},ut=function(w){var L,O=this;if(!O._d){O._d=!0,O=O._w||O;try{if(O===w)throw Q("Promise can't be resolved itself");(L=xe(w))?A(function(){var J={_w:O,_d:!1};try{L.call(w,g(ut,J,1),g(Xe,J,1))}catch(Ae){Xe.call(J,Ae)}}):(O._v=w,O._s=1,Ye(O,!1))}catch(J){Xe.call({_w:O,_d:!1},J)}}};ke||(I=function(w){C(this,I,j,"_h"),T(w),n.call(this);try{w(g(ut,this,1),g(Xe,this,1))}catch(L){Xe.call(this,L)}},n=function(w){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},n.prototype=s(56)(I.prototype,{then:function(w,L){var O=Se(ge(this,I));return O.ok=typeof w!="function"||w,O.fail=typeof L=="function"&&L,O.domain=fe?oe.domain:void 0,this._c.push(O),this._a&&this._a.push(O),this._s&&Ye(this,!1),O.promise},catch:function(w){return this.then(void 0,w)}}),Ge=function(){var w=new n;this.promise=w,this.resolve=g(ut,w,1),this.reject=g(Xe,w,1)}),y(y.G+y.W+y.F*!ke,{Promise:I}),s(18)(I,j),s(59)(j),c=s(6)[j],y(y.S+y.F*!ke,j,{reject:function(w){var L=Se(this),O=L.reject;return O(w),L.promise}}),y(y.S+y.F*(u||!ke),j,{resolve:function(w){if(w instanceof I&&be(w.constructor,this))return w;var L=Se(this),O=L.resolve;return O(w),L.promise}}),y(y.S+y.F*!(ke&&s(46)(function(w){I.all(w).catch(ee)})),j,{all:function(w){var L=this,O=Se(L),J=O.resolve,Ae=O.reject,lt=Ie(function(){var vt=[],Et=0,wt=1;H(w,!1,function(nr){var Sr=Et++,Vr=!1;vt.push(void 0),wt++,L.resolve(nr).then(function(Tr){Vr||(Vr=!0,vt[Sr]=Tr,--wt||J(vt))},Ae)}),--wt||J(vt)});return lt&&Ae(lt.error),O.promise},race:function(w){var L=this,O=Se(L),J=O.reject,Ae=Ie(function(){H(w,!1,function(lt){L.resolve(lt).then(O.resolve,J)})});return Ae&&J(Ae.error),O.promise}})},function(t,i,s){"use strict";var n=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=n(c,u),this._i+=a.length,{value:a,done:!1})})},function(t,i,s){s(65);for(var n=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=n[m],b=y&&y.prototype;b&&!b[u]&&a(b,u,m),c[m]=c.Array}},function(t,i){t.exports=require("child_process")},function(t,i){t.exports=require("crypto")}])})});function Hy(){try{return Sc.default.statSync("/.dockerenv"),!0}catch{return!1}}function Vy(){try{return Sc.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Tc(){return xc===void 0&&(xc=Hy()||Vy()),xc}var Sc,xc,Ph=Ft(()=>{Sc=ae(require("node:fs"),1)});function Hi(){return Cc===void 0&&(Cc=Ky()||Tc()),Cc}var Ah,Cc,Ky,Oc=Ft(()=>{Ah=ae(require("node:fs"),1);Ph();Ky=()=>{try{return Ah.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var kc,Lh,Nh,Ih,Ur,Rc=Ft(()=>{kc=ae(require("node:process"),1),Lh=ae(require("node:os"),1),Nh=ae(require("node:fs"),1);Oc();Ih=()=>{if(kc.default.platform!=="linux")return!1;if(Lh.default.release().toLowerCase().includes("microsoft"))return!Hi();try{return Nh.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!Hi():!1}catch{return!1}},Ur=kc.default.env.__IS_WSL_TEST__?Ih:Ih()});var Pc,Cs,zy,$y,Ac,Dh=Ft(()=>{Pc=ae(require("node:process"),1),Cs=ae(require("node:fs/promises"),1);Rc();Rc();zy=(()=>{let r="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",i=!1;try{await Cs.default.access(t,Cs.constants.F_OK),i=!0}catch{}if(!i)return r;let s=await Cs.default.readFile(t,{encoding:"utf8"}),n=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(s);return n?(e=n.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):r}})(),$y=async()=>`${await zy()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Ac=async()=>Ur?$y():`${Pc.default.env.SYSTEMROOT||Pc.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function qr(r,e,t){let i=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 i(s),s},set(s){i(s)}}),r}var Mh=Ft(()=>{});async function Ic(){if(Bh.default.platform!=="darwin")throw new Error("macOS only");let{stdout:r}=await Gy("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 Fh,Bh,jh,Gy,Uh=Ft(()=>{Fh=require("node:util"),Bh=ae(require("node:process"),1),jh=require("node:child_process"),Gy=(0,Fh.promisify)(jh.execFile)});async function Hh(r,{humanReadableOutput:e=!0,signal:t}={}){if(qh.default.platform!=="darwin")throw new Error("macOS only");let i=e?[]:["-ss"],s={};t&&(s.signal=t);let{stdout:n}=await Yy("osascript",["-e",r,i],s);return n.trim()}var qh,Wh,Lc,Yy,Vh=Ft(()=>{qh=ae(require("node:process"),1),Wh=require("node:util"),Lc=require("node:child_process"),Yy=(0,Wh.promisify)(Lc.execFile)});async function Nc(r){return Hh(`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 Kh=Ft(()=>{Vh()});async function Mc(r=Xy){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 Dc(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:i}=t.groups,s=i.lastIndexOf("."),n=i.lastIndexOf("-"),a=s===-1?void 0:i.slice(0,s),c=n===-1?void 0:i.slice(0,n);return Qn[i]??Qn[a]??Qn[c]??{name:i,id:i}}var zh,$h,Xy,Qn,sb,Dc,Gh=Ft(()=>{zh=require("node:util"),$h=require("node:child_process"),Xy=(0,zh.promisify)($h.execFile),Qn={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"}},sb=new Map(Object.entries(Qn)),Dc=class extends Error{}});async function Fc(){if(eo.default.platform==="darwin"){let r=await Ic();return{name:await Nc(r),id:r}}if(eo.default.platform==="linux"){let{stdout:r}=await Jy("xdg-mime",["query","default","x-scheme-handler/http"]),e=r.trim();return{name:Zy(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(eo.default.platform==="win32")return Mc();throw new Error("Only macOS, Linux, and Windows are supported")}var Yh,eo,Xh,Jy,Zy,Jh=Ft(()=>{Yh=require("node:util"),eo=ae(require("node:process"),1),Xh=require("node:child_process");Uh();Kh();Gh();Jy=(0,Yh.promisify)(Xh.execFile),Zy=r=>r.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var sd={};ep(sd,{apps:()=>Wr,default:()=>iv,openApp:()=>rv});async function ev(){let r=await Ac(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=Uc.Buffer.from(e,"utf16le").toString("base64"),{stdout:i}=await Qy(r,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),s=i.trim(),n={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return n[s]?{id:n[s]}:{}}function td(r){if(typeof r=="string"||Array.isArray(r))return r;let{[Qh]:e}=r;if(!e)throw new Error(`${Qh} is not supported`);return e}function ro({[Vi]:r},{wsl:e}){if(e&&Ur)return td(e);if(!r)throw new Error(`${Vi} is not supported`);return td(r)}var jc,Uc,qc,rd,id,Wc,to,sv,Qy,Bc,Zh,Vi,Qh,ed,Os,tv,rv,Wr,iv,nd=Ft(()=>{jc=ae(require("node:process"),1),Uc=require("node:buffer"),qc=ae(require("node:path"),1),rd=require("node:url"),id=require("node:util"),Wc=ae(require("node:child_process"),1),to=ae(require("node:fs/promises"),1);Dh();Mh();Jh();Oc();sv={},Qy=(0,id.promisify)(Wc.default.execFile),Bc=qc.default.dirname((0,rd.fileURLToPath)(sv.url)),Zh=qc.default.join(Bc,"xdg-open"),{platform:Vi,arch:Qh}=jc.default;ed=async(r,e)=>{let t;for(let i of r)try{return await e(i)}catch(s){t=s}throw t},Os=async r=>{if(r={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...r},Array.isArray(r.app))return ed(r.app,c=>Os({...r,app:c}));let{name:e,arguments:t=[]}=r.app??{};if(t=[...t],Array.isArray(e))return ed(e,c=>Os({...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=Ur?await ev():await Fc();if(d.id in c){let g=c[d.id];return e==="browserPrivate"&&t.push(u[g]),Os({...r,app:{name:Wr[g],arguments:t}})}throw new Error(`${d.name} is not supported as a default browser`)}let i,s=[],n={};if(Vi==="darwin")i="open",r.wait&&s.push("--wait-apps"),r.background&&s.push("--background"),r.newInstance&&s.push("--new"),e&&s.push("-a",e);else if(Vi==="win32"||Ur&&!Hi()&&!e){i=await Ac(),s.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),Ur||(n.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=Uc.Buffer.from(c.join(" "),"utf16le").toString("base64")}else{if(e)i=e;else{let c=!Bc||Bc==="/",u=!1;try{await to.default.access(Zh,to.constants.X_OK),u=!0}catch{}i=jc.default.versions.electron??(Vi==="android"||c||!u)?"xdg-open":Zh}t.length>0&&s.push(...t),r.wait||(n.stdio="ignore",n.detached=!0)}Vi==="darwin"&&t.length>0&&s.push("--args",...t),r.target&&s.push(r.target);let a=Wc.default.spawn(i,s,n);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)},tv=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a `target`");return Os({...e,target:r})},rv=(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 Os({...e,app:{name:r,arguments:t}})};Wr={};qr(Wr,"chrome",()=>ro({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"]}}));qr(Wr,"brave",()=>ro({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"]}}));qr(Wr,"firefox",()=>ro({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));qr(Wr,"edge",()=>ro({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));qr(Wr,"browser",()=>"browser");qr(Wr,"browserPrivate",()=>"browserPrivate");iv=tv});var ar=ae(require("fs")),Us=ae(require("path"));var uf=ae(require("os")),lf=ae(require("path")),Bs=ae(require("fs"));function js(){let r=lf.join(uf.homedir(),".termiq");return Bs.existsSync(r)||Bs.mkdirSync(r,{recursive:!0,mode:448}),r}var Zi=class{filePath;data={};constructor(){this.filePath=Us.join(js(),"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=Us.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=ae(require("fs")),qs=ae(require("path"));var rp={serverUrl:"https://termiq.io",agentName:"",multiViewer:!1},Qi=class{config;filePath;constructor(e){this.filePath=qs.join(js(),"config.json"),this.config={...rp,...this.loadFromFile(),...e}}getServerUrl(){return this.config.serverUrl}getAgentName(){return this.config.agentName}isAutoConnect(){return!0}getMultiViewer(){return this.config.multiViewer}async setMultiViewer(e){this.config.multiViewer=e,this.saveToFile()}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=qs.dirname(this.filePath);cr.existsSync(e)||cr.mkdirSync(e,{recursive:!0,mode:448}),cr.writeFileSync(this.filePath,JSON.stringify(this.config,null,2))}};var pt=ae(require("fs")),Ec=ae(require("path")),Oh=ae(require("os")),Zn=ae(ws()),jy="cli",vc=Ec.join(Oh.homedir(),".termiq","logs"),jr=Ec.join(vc,"cli.log"),Uy=5*1024*1024,Ch=3;function qy(){try{if(!pt.existsSync(jr)||pt.statSync(jr).size<Uy)return;for(let e=Ch-1;e>=1;e--){let t=`${jr}.${e}`,i=`${jr}.${e+1}`;pt.existsSync(t)&&(e+1>Ch?pt.unlinkSync(t):pt.renameSync(t,i))}pt.renameSync(jr,`${jr}.1`)}catch{}}function Wy(r){try{pt.existsSync(vc)||pt.mkdirSync(vc,{recursive:!0}),qy(),pt.appendFileSync(jr,r+`
29
+ `)}clearTerminal(e){this.trackedFiles.delete(e),this.outputBuffers.delete(e)}getChangedFiles(e){return(this.trackedFiles.get(e)||[]).map(i=>({path:i.path,changeType:i.changeType,timestamp:i.timestamp,source:"tool-call",toolName:i.toolName,toolId:i.toolId,size:i.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 pc.isAbsolute(e)?e:this.workspaceRoot?pc.join(this.workspaceRoot,e):e}dispose(){this.trackedFiles.clear(),this.pendingToolCalls.clear(),this.onFileChangedCallback=null,this.onFileViewTransferCallback=null}};ir.FileTrackerService=_c});var Th=F(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.InputStreamReceiver=st.FileTrackerService=st.FileListService=st.FileTransferService=st.WebSocketService=st.StatusDetector=st.AuthService=st.CryptoService=void 0;var Ay=Xf();Object.defineProperty(st,"CryptoService",{enumerable:!0,get:function(){return Ay.CryptoService}});var Iy=Jf();Object.defineProperty(st,"AuthService",{enumerable:!0,get:function(){return Iy.AuthService}});var Ly=Zf();Object.defineProperty(st,"StatusDetector",{enumerable:!0,get:function(){return Ly.StatusDetector}});var Ny=uh();Object.defineProperty(st,"WebSocketService",{enumerable:!0,get:function(){return Ny.WebSocketService}});var Dy=hh();Object.defineProperty(st,"FileTransferService",{enumerable:!0,get:function(){return Dy.FileTransferService}});var My=bh();Object.defineProperty(st,"FileListService",{enumerable:!0,get:function(){return My.FileListService}});var Fy=Sh();Object.defineProperty(st,"FileTrackerService",{enumerable:!0,get:function(){return Fy.FileTrackerService}});var By=ec();Object.defineProperty(st,"InputStreamReceiver",{enumerable:!0,get:function(){return By.InputStreamReceiver}})});var Es=F(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.InputStreamReceiver=we.FileTrackerService=we.FileListService=we.FileTransferService=we.WebSocketService=we.StatusDetector=we.AuthService=we.CryptoService=we.getCurrentCorrelationId=we.runWithCorrelation=we.generateCorrelationId=we.getWsUrl=we.getApiUrl=we.CircularBuffer=we.formatLogLine=we.shouldLog=we.LOG_LEVELS=void 0;var yc=gf();Object.defineProperty(we,"LOG_LEVELS",{enumerable:!0,get:function(){return yc.LOG_LEVELS}});Object.defineProperty(we,"shouldLog",{enumerable:!0,get:function(){return yc.shouldLog}});Object.defineProperty(we,"formatLogLine",{enumerable:!0,get:function(){return yc.formatLogLine}});var Wi=yf();Object.defineProperty(we,"CircularBuffer",{enumerable:!0,get:function(){return Wi.CircularBuffer}});Object.defineProperty(we,"getApiUrl",{enumerable:!0,get:function(){return Wi.getApiUrl}});Object.defineProperty(we,"getWsUrl",{enumerable:!0,get:function(){return Wi.getWsUrl}});Object.defineProperty(we,"generateCorrelationId",{enumerable:!0,get:function(){return Wi.generateCorrelationId}});Object.defineProperty(we,"runWithCorrelation",{enumerable:!0,get:function(){return Wi.runWithCorrelation}});Object.defineProperty(we,"getCurrentCorrelationId",{enumerable:!0,get:function(){return Wi.getCurrentCorrelationId}});var Br=Th();Object.defineProperty(we,"CryptoService",{enumerable:!0,get:function(){return Br.CryptoService}});Object.defineProperty(we,"AuthService",{enumerable:!0,get:function(){return Br.AuthService}});Object.defineProperty(we,"StatusDetector",{enumerable:!0,get:function(){return Br.StatusDetector}});Object.defineProperty(we,"WebSocketService",{enumerable:!0,get:function(){return Br.WebSocketService}});Object.defineProperty(we,"FileTransferService",{enumerable:!0,get:function(){return Br.FileTransferService}});Object.defineProperty(we,"FileListService",{enumerable:!0,get:function(){return Br.FileListService}});Object.defineProperty(we,"FileTrackerService",{enumerable:!0,get:function(){return Br.FileTrackerService}});Object.defineProperty(we,"InputStreamReceiver",{enumerable:!0,get:function(){return Br.InputStreamReceiver}})});var bc=F((xs,Ec)=>{(function(r,e){typeof xs=="object"&&typeof Ec=="object"?Ec.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 i(n){if(s[n])return s[n].exports;var a=s[n]={exports:{},id:n,loaded:!1};return t[n].call(a.exports,a,a.exports,i),a.loaded=!0,a.exports}var s={};return i.m=t,i.c=s,i.p="",i(0)})([function(t,i,s){t.exports=s(34)},function(t,i,s){var n=s(29)("wks"),a=s(33),c=s(2).Symbol,u=typeof c=="function",d=t.exports=function(p){return n[p]||(n[p]=u&&c[p]||(u?c:a)("Symbol."+p))};d.store=n},function(t,i){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,i,s){var n=s(9);t.exports=function(a){if(!n(a))throw TypeError(a+" is not an object!");return a}},function(t,i,s){t.exports=!s(24)(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7})},function(t,i,s){var n=s(12),a=s(17);t.exports=s(4)?function(c,u,d){return n.f(c,u,a(1,d))}:function(c,u,d){return c[u]=d,c}},function(t,i){var s=t.exports={version:"2.4.0"};typeof __e=="number"&&(__e=s)},function(t,i,s){var n=s(14);t.exports=function(a,c,u){if(n(a),c===void 0)return a;switch(u){case 1:return function(d){return a.call(c,d)};case 2:return function(d,p){return a.call(c,d,p)};case 3:return function(d,p,m){return a.call(c,d,p,m)}}return function(){return a.apply(c,arguments)}}},function(t,i){var s={}.hasOwnProperty;t.exports=function(n,a){return s.call(n,a)}},function(t,i){t.exports=function(s){return typeof s=="object"?s!==null:typeof s=="function"}},function(t,i){t.exports={}},function(t,i){var s={}.toString;t.exports=function(n){return s.call(n).slice(8,-1)}},function(t,i,s){var n=s(3),a=s(26),c=s(32),u=Object.defineProperty;i.f=s(4)?Object.defineProperty:function(d,p,m){if(n(d),p=c(p,!0),n(m),a)try{return u(d,p,m)}catch{}if("get"in m||"set"in m)throw TypeError("Accessors not supported!");return"value"in m&&(d[p]=m.value),d}},function(t,i,s){var n=s(42),a=s(15);t.exports=function(c){return n(a(c))}},function(t,i){t.exports=function(s){if(typeof s!="function")throw TypeError(s+" is not a function!");return s}},function(t,i){t.exports=function(s){if(s==null)throw TypeError("Can't call method on "+s);return s}},function(t,i,s){var n=s(9),a=s(2).document,c=n(a)&&n(a.createElement);t.exports=function(u){return c?a.createElement(u):{}}},function(t,i){t.exports=function(s,n){return{enumerable:!(1&s),configurable:!(2&s),writable:!(4&s),value:n}}},function(t,i,s){var n=s(12).f,a=s(8),c=s(1)("toStringTag");t.exports=function(u,d,p){u&&!a(u=p?u:u.prototype,c)&&n(u,c,{configurable:!0,value:d})}},function(t,i,s){var n=s(29)("keys"),a=s(33);t.exports=function(c){return n[c]||(n[c]=a(c))}},function(t,i){var s=Math.ceil,n=Math.floor;t.exports=function(a){return isNaN(a=+a)?0:(a>0?n:s)(a)}},function(t,i,s){var n=s(11),a=s(1)("toStringTag"),c=n((function(){return arguments})())=="Arguments",u=function(d,p){try{return d[p]}catch{}};t.exports=function(d){var p,m,y;return d===void 0?"Undefined":d===null?"Null":typeof(m=u(p=Object(d),a))=="string"?m:c?n(p):(y=n(p))=="Object"&&typeof p.callee=="function"?"Arguments":y}},function(t,i){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,i,s){var n=s(2),a=s(6),c=s(7),u=s(5),d="prototype",p=function(m,y,E){var T,O,H,me=m&p.F,X=m&p.G,A=m&p.S,j=m&p.P,te=m&p.B,I=m&p.W,ae=X?a:a[y]||(a[y]={}),ue=ae[d],Q=X?n:A?n[y]:(n[y]||{})[d];X&&(E=y);for(T in E)O=!me&&Q&&Q[T]!==void 0,O&&T in ae||(H=O?Q[T]:E[T],ae[T]=X&&typeof Q[T]!="function"?E[T]:te&&O?c(H,n):I&&Q[T]==H?(function(Re){var Ee=function(Je,ee,Ye){if(this instanceof Re){switch(arguments.length){case 0:return new Re;case 1:return new Re(Je);case 2:return new Re(Je,ee)}return new Re(Je,ee,Ye)}return Re.apply(this,arguments)};return Ee[d]=Re[d],Ee})(H):j&&typeof H=="function"?c(Function.call,H):H,j&&((ae.virtual||(ae.virtual={}))[T]=H,m&p.R&&ue&&!ue[T]&&u(ue,T,H)))};p.F=1,p.G=2,p.S=4,p.P=8,p.B=16,p.W=32,p.U=64,p.R=128,t.exports=p},function(t,i){t.exports=function(s){try{return!!s()}catch{return!0}}},function(t,i,s){t.exports=s(2).document&&document.documentElement},function(t,i,s){t.exports=!s(4)&&!s(24)(function(){return Object.defineProperty(s(16)("div"),"a",{get:function(){return 7}}).a!=7})},function(t,i,s){"use strict";var n=s(28),a=s(23),c=s(57),u=s(5),d=s(8),p=s(10),m=s(45),y=s(18),E=s(52),T=s(1)("iterator"),O=!([].keys&&"next"in[].keys()),H="@@iterator",me="keys",X="values",A=function(){return this};t.exports=function(j,te,I,ae,ue,Q,Re){m(I,te,ae);var Ee,Je,ee,Ye=function(S){if(!O&&S in Te)return Te[S];switch(S){case me:return function(){return new I(this,S)};case X:return function(){return new I(this,S)}}return function(){return new I(this,S)}},Be=te+" Iterator",je=ue==X,Ue=!1,Te=j.prototype,nt=Te[T]||Te[H]||ue&&Te[ue],Ve=nt||Ye(ue),yt=ue?je?Ye("entries"):Ve:void 0,N=te=="Array"&&Te.entries||nt;if(N&&(ee=E(N.call(new j)),ee!==Object.prototype&&(y(ee,Be,!0),n||d(ee,T)||u(ee,T,A))),je&&nt&&nt.name!==X&&(Ue=!0,Ve=function(){return nt.call(this)}),n&&!Re||!O&&!Ue&&Te[T]||u(Te,T,Ve),p[te]=Ve,p[Be]=A,ue)if(Ee={values:je?Ve:Ye(X),keys:Q?Ve:Ye(me),entries:yt},Re)for(Je in Ee)Je in Te||c(Te,Je,Ee[Je]);else a(a.P+a.F*(O||Ue),te,Ee);return Ee}},function(t,i){t.exports=!0},function(t,i,s){var n=s(2),a="__core-js_shared__",c=n[a]||(n[a]={});t.exports=function(u){return c[u]||(c[u]={})}},function(t,i,s){var n,a,c,u=s(7),d=s(41),p=s(25),m=s(16),y=s(2),E=y.process,T=y.setImmediate,O=y.clearImmediate,H=y.MessageChannel,me=0,X={},A="onreadystatechange",j=function(){var I=+this;if(X.hasOwnProperty(I)){var ae=X[I];delete X[I],ae()}},te=function(I){j.call(I.data)};T&&O||(T=function(I){for(var ae=[],ue=1;arguments.length>ue;)ae.push(arguments[ue++]);return X[++me]=function(){d(typeof I=="function"?I:Function(I),ae)},n(me),me},O=function(I){delete X[I]},s(11)(E)=="process"?n=function(I){E.nextTick(u(j,I,1))}:H?(a=new H,c=a.port2,a.port1.onmessage=te,n=u(c.postMessage,c,1)):y.addEventListener&&typeof postMessage=="function"&&!y.importScripts?(n=function(I){y.postMessage(I+"","*")},y.addEventListener("message",te,!1)):n=A in m("script")?function(I){p.appendChild(m("script"))[A]=function(){p.removeChild(this),j.call(I)}}:function(I){setTimeout(u(j,I,1),0)}),t.exports={set:T,clear:O}},function(t,i,s){var n=s(20),a=Math.min;t.exports=function(c){return c>0?a(n(c),9007199254740991):0}},function(t,i,s){var n=s(9);t.exports=function(a,c){if(!n(a))return a;var u,d;if(c&&typeof(u=a.toString)=="function"&&!n(d=u.call(a))||typeof(u=a.valueOf)=="function"&&!n(d=u.call(a))||!c&&typeof(u=a.toString)=="function"&&!n(d=u.call(a)))return d;throw TypeError("Can't convert object to primitive value")}},function(t,i){var s=0,n=Math.random();t.exports=function(a){return"Symbol(".concat(a===void 0?"":a,")_",(++s+n).toString(36))}},function(t,i,s){"use strict";function n(A){return A&&A.__esModule?A:{default:A}}function a(){return process.platform!=="win32"?"":process.arch==="ia32"&&process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432")?"mixed":"native"}function c(A){return(0,T.createHash)("sha256").update(A).digest("hex")}function u(A){switch(H){case"darwin":return A.split("IOPlatformUUID")[1].split(`
30
+ `)[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return A.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return A.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"freebsd":return A.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error("Unsupported platform: "+process.platform)}}function d(A){var j=u((0,E.execSync)(X[H]).toString());return A?j:c(j)}function p(A){return new y.default(function(j,te){return(0,E.exec)(X[H],{},function(I,ae,ue){if(I)return te(new Error("Error while obtaining machine id: "+I.stack));var Q=u(ae.toString());return j(A?Q:c(Q))})})}Object.defineProperty(i,"__esModule",{value:!0});var m=s(35),y=n(m);i.machineIdSync=d,i.machineId=p;var E=s(70),T=s(71),O=process,H=O.platform,me={native:"%windir%\\System32",mixed:"%windir%\\sysnative\\cmd.exe /c %windir%\\System32"},X={darwin:"ioreg -rd1 -c IOPlatformExpertDevice",win32:me[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,i,s){t.exports={default:s(36),__esModule:!0}},function(t,i,s){s(66),s(68),s(69),s(67),t.exports=s(6).Promise},function(t,i){t.exports=function(){}},function(t,i){t.exports=function(s,n,a,c){if(!(s instanceof n)||c!==void 0&&c in s)throw TypeError(a+": incorrect invocation!");return s}},function(t,i,s){var n=s(13),a=s(31),c=s(62);t.exports=function(u){return function(d,p,m){var y,E=n(d),T=a(E.length),O=c(m,T);if(u&&p!=p){for(;T>O;)if(y=E[O++],y!=y)return!0}else for(;T>O;O++)if((u||O in E)&&E[O]===p)return u||O||0;return!u&&-1}}},function(t,E,s){var n=s(7),a=s(44),c=s(43),u=s(3),d=s(31),p=s(64),m={},y={},E=t.exports=function(T,O,H,me,X){var A,j,te,I,ae=X?function(){return T}:p(T),ue=n(H,me,O?2:1),Q=0;if(typeof ae!="function")throw TypeError(T+" is not iterable!");if(c(ae)){for(A=d(T.length);A>Q;Q++)if(I=O?ue(u(j=T[Q])[0],j[1]):ue(T[Q]),I===m||I===y)return I}else for(te=ae.call(T);!(j=te.next()).done;)if(I=a(te,ue,j.value,O),I===m||I===y)return I};E.BREAK=m,E.RETURN=y},function(t,i){t.exports=function(s,n,a){var c=a===void 0;switch(n.length){case 0:return c?s():s.call(a);case 1:return c?s(n[0]):s.call(a,n[0]);case 2:return c?s(n[0],n[1]):s.call(a,n[0],n[1]);case 3:return c?s(n[0],n[1],n[2]):s.call(a,n[0],n[1],n[2]);case 4:return c?s(n[0],n[1],n[2],n[3]):s.call(a,n[0],n[1],n[2],n[3])}return s.apply(a,n)}},function(t,i,s){var n=s(11);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(a){return n(a)=="String"?a.split(""):Object(a)}},function(t,i,s){var n=s(10),a=s(1)("iterator"),c=Array.prototype;t.exports=function(u){return u!==void 0&&(n.Array===u||c[a]===u)}},function(t,i,s){var n=s(3);t.exports=function(a,c,u,d){try{return d?c(n(u)[0],u[1]):c(u)}catch(m){var p=a.return;throw p!==void 0&&n(p.call(a)),m}}},function(t,i,s){"use strict";var n=s(49),a=s(17),c=s(18),u={};s(5)(u,s(1)("iterator"),function(){return this}),t.exports=function(d,p,m){d.prototype=n(u,{next:a(1,m)}),c(d,p+" Iterator")}},function(t,i,s){var n=s(1)("iterator"),a=!1;try{var c=[7][n]();c.return=function(){a=!0},Array.from(c,function(){throw 2})}catch{}t.exports=function(u,d){if(!d&&!a)return!1;var p=!1;try{var m=[7],y=m[n]();y.next=function(){return{done:p=!0}},m[n]=function(){return y},u(m)}catch{}return p}},function(t,i){t.exports=function(s,n){return{value:n,done:!!s}}},function(t,i,s){var n=s(2),a=s(30).set,c=n.MutationObserver||n.WebKitMutationObserver,u=n.process,d=n.Promise,p=s(11)(u)=="process";t.exports=function(){var m,y,E,T=function(){var X,A;for(p&&(X=u.domain)&&X.exit();m;){A=m.fn,m=m.next;try{A()}catch(j){throw m?E():y=void 0,j}}y=void 0,X&&X.enter()};if(p)E=function(){u.nextTick(T)};else if(c){var O=!0,H=document.createTextNode("");new c(T).observe(H,{characterData:!0}),E=function(){H.data=O=!O}}else if(d&&d.resolve){var me=d.resolve();E=function(){me.then(T)}}else E=function(){a.call(n,T)};return function(X){var A={fn:X,next:void 0};y&&(y.next=A),m||(m=A,E()),y=A}}},function(t,i,s){var n=s(3),a=s(50),c=s(22),u=s(19)("IE_PROTO"),d=function(){},p="prototype",m=function(){var y,E=s(16)("iframe"),T=c.length,O=">";for(E.style.display="none",s(25).appendChild(E),E.src="javascript:",y=E.contentWindow.document,y.open(),y.write("<script>document.F=Object</script"+O),y.close(),m=y.F;T--;)delete m[p][c[T]];return m()};t.exports=Object.create||function(y,E){var T;return y!==null?(d[p]=n(y),T=new d,d[p]=null,T[u]=y):T=m(),E===void 0?T:a(T,E)}},function(t,i,s){var n=s(12),a=s(3),c=s(54);t.exports=s(4)?Object.defineProperties:function(u,d){a(u);for(var p,m=c(d),y=m.length,E=0;y>E;)n.f(u,p=m[E++],d[p]);return u}},function(t,i,s){var n=s(55),a=s(17),c=s(13),u=s(32),d=s(8),p=s(26),m=Object.getOwnPropertyDescriptor;i.f=s(4)?m:function(y,E){if(y=c(y),E=u(E,!0),p)try{return m(y,E)}catch{}if(d(y,E))return a(!n.f.call(y,E),y[E])}},function(t,i,s){var n=s(8),a=s(63),c=s(19)("IE_PROTO"),u=Object.prototype;t.exports=Object.getPrototypeOf||function(d){return d=a(d),n(d,c)?d[c]:typeof d.constructor=="function"&&d instanceof d.constructor?d.constructor.prototype:d instanceof Object?u:null}},function(t,i,s){var n=s(8),a=s(13),c=s(39)(!1),u=s(19)("IE_PROTO");t.exports=function(d,p){var m,y=a(d),E=0,T=[];for(m in y)m!=u&&n(y,m)&&T.push(m);for(;p.length>E;)n(y,m=p[E++])&&(~c(T,m)||T.push(m));return T}},function(t,i,s){var n=s(53),a=s(22);t.exports=Object.keys||function(c){return n(c,a)}},function(t,i){i.f={}.propertyIsEnumerable},function(t,i,s){var n=s(5);t.exports=function(a,c,u){for(var d in c)u&&a[d]?a[d]=c[d]:n(a,d,c[d]);return a}},function(t,i,s){t.exports=s(5)},function(t,i,s){var n=s(9),a=s(3),c=function(u,d){if(a(u),!n(d)&&d!==null)throw TypeError(d+": can't set as prototype!")};t.exports={set:Object.setPrototypeOf||("__proto__"in{}?(function(u,d,p){try{p=s(7)(Function.call,s(51).f(Object.prototype,"__proto__").set,2),p(u,[]),d=!(u instanceof Array)}catch{d=!0}return function(m,y){return c(m,y),d?m.__proto__=y:p(m,y),m}})({},!1):void 0),check:c}},function(t,i,s){"use strict";var n=s(2),a=s(6),c=s(12),u=s(4),d=s(1)("species");t.exports=function(p){var m=typeof a[p]=="function"?a[p]:n[p];u&&m&&!m[d]&&c.f(m,d,{configurable:!0,get:function(){return this}})}},function(t,i,s){var n=s(3),a=s(14),c=s(1)("species");t.exports=function(u,d){var p,m=n(u).constructor;return m===void 0||(p=n(m)[c])==null?d:a(p)}},function(t,i,s){var n=s(20),a=s(15);t.exports=function(c){return function(u,d){var p,m,y=String(a(u)),E=n(d),T=y.length;return E<0||E>=T?c?"":void 0:(p=y.charCodeAt(E),p<55296||p>56319||E+1===T||(m=y.charCodeAt(E+1))<56320||m>57343?c?y.charAt(E):p:c?y.slice(E,E+2):(p-55296<<10)+(m-56320)+65536)}}},function(t,i,s){var n=s(20),a=Math.max,c=Math.min;t.exports=function(u,d){return u=n(u),u<0?a(u+d,0):c(u,d)}},function(t,i,s){var n=s(15);t.exports=function(a){return Object(n(a))}},function(t,i,s){var n=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[n(u)]}},function(t,i,s){"use strict";var n=s(37),a=s(47),c=s(10),u=s(13);t.exports=s(27)(Array,"Array",function(d,p){this._t=u(d),this._i=0,this._k=p},function(){var d=this._t,p=this._k,m=this._i++;return!d||m>=d.length?(this._t=void 0,a(1)):p=="keys"?a(0,m):p=="values"?a(0,d[m]):a(0,[m,d[m]])},"values"),c.Arguments=c.Array,n("keys"),n("values"),n("entries")},function(t,i){},function(t,i,s){"use strict";var n,a,c,u=s(28),d=s(2),p=s(7),m=s(21),y=s(23),E=s(9),T=(s(3),s(14)),O=s(38),H=s(40),me=(s(58).set,s(60)),X=s(30).set,A=s(48)(),j="Promise",te=d.TypeError,ae=d.process,I=d[j],ae=d.process,ue=m(ae)=="process",Q=function(){},Re=!!(function(){try{var N=I.resolve(1),S=(N.constructor={})[s(1)("species")]=function(C){C(Q,Q)};return(ue||typeof PromiseRejectionEvent=="function")&&N.then(Q)instanceof S}catch{}})(),Ee=function(N,S){return N===S||N===I&&S===c},Je=function(N){var S;return!(!E(N)||typeof(S=N.then)!="function")&&S},ee=function(N){return Ee(I,N)?new Ye(N):new a(N)},Ye=a=function(N){var S,C;this.promise=new N(function(Y,ve){if(S!==void 0||C!==void 0)throw te("Bad Promise constructor");S=Y,C=ve}),this.resolve=T(S),this.reject=T(C)},Be=function(N){try{N()}catch(S){return{error:S}}},je=function(N,S){if(!N._n){N._n=!0;var C=N._c;A(function(){for(var Y=N._v,ve=N._s==1,et=0,vt=function(wt){var Et,nr,Sr=ve?wt.ok:wt.fail,Vr=wt.resolve,Tr=wt.reject,pi=wt.domain;try{Sr?(ve||(N._h==2&&nt(N),N._h=1),Sr===!0?Et=Y:(pi&&pi.enter(),Et=Sr(Y),pi&&pi.exit()),Et===wt.promise?Tr(te("Promise-chain cycle")):(nr=Je(Et))?nr.call(Et,Vr,Tr):Vr(Et)):Tr(Y)}catch(Is){Tr(Is)}};C.length>et;)vt(C[et++]);N._c=[],N._n=!1,S&&!N._h&&Ue(N)})}},Ue=function(N){X.call(d,function(){var S,C,Y,ve=N._v;if(Te(N)&&(S=Be(function(){ue?ae.emit("unhandledRejection",ve,N):(C=d.onunhandledrejection)?C({promise:N,reason:ve}):(Y=d.console)&&Y.error&&Y.error("Unhandled promise rejection",ve)}),N._h=ue||Te(N)?2:1),N._a=void 0,S)throw S.error})},Te=function(N){if(N._h==1)return!1;for(var S,C=N._a||N._c,Y=0;C.length>Y;)if(S=C[Y++],S.fail||!Te(S.promise))return!1;return!0},nt=function(N){X.call(d,function(){var S;ue?ae.emit("rejectionHandled",N):(S=d.onrejectionhandled)&&S({promise:N,reason:N._v})})},Ve=function(N){var S=this;S._d||(S._d=!0,S=S._w||S,S._v=N,S._s=2,S._a||(S._a=S._c.slice()),je(S,!0))},yt=function(N){var S,C=this;if(!C._d){C._d=!0,C=C._w||C;try{if(C===N)throw te("Promise can't be resolved itself");(S=Je(N))?A(function(){var Y={_w:C,_d:!1};try{S.call(N,p(yt,Y,1),p(Ve,Y,1))}catch(ve){Ve.call(Y,ve)}}):(C._v=N,C._s=1,je(C,!1))}catch(Y){Ve.call({_w:C,_d:!1},Y)}}};Re||(I=function(N){O(this,I,j,"_h"),T(N),n.call(this);try{N(p(yt,this,1),p(Ve,this,1))}catch(S){Ve.call(this,S)}},n=function(N){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},n.prototype=s(56)(I.prototype,{then:function(N,S){var C=ee(me(this,I));return C.ok=typeof N!="function"||N,C.fail=typeof S=="function"&&S,C.domain=ue?ae.domain:void 0,this._c.push(C),this._a&&this._a.push(C),this._s&&je(this,!1),C.promise},catch:function(N){return this.then(void 0,N)}}),Ye=function(){var N=new n;this.promise=N,this.resolve=p(yt,N,1),this.reject=p(Ve,N,1)}),y(y.G+y.W+y.F*!Re,{Promise:I}),s(18)(I,j),s(59)(j),c=s(6)[j],y(y.S+y.F*!Re,j,{reject:function(N){var S=ee(this),C=S.reject;return C(N),S.promise}}),y(y.S+y.F*(u||!Re),j,{resolve:function(N){if(N instanceof I&&Ee(N.constructor,this))return N;var S=ee(this),C=S.resolve;return C(N),S.promise}}),y(y.S+y.F*!(Re&&s(46)(function(N){I.all(N).catch(Q)})),j,{all:function(N){var S=this,C=ee(S),Y=C.resolve,ve=C.reject,et=Be(function(){var vt=[],wt=0,Et=1;H(N,!1,function(nr){var Sr=wt++,Vr=!1;vt.push(void 0),Et++,S.resolve(nr).then(function(Tr){Vr||(Vr=!0,vt[Sr]=Tr,--Et||Y(vt))},ve)}),--Et||Y(vt)});return et&&ve(et.error),C.promise},race:function(N){var S=this,C=ee(S),Y=C.reject,ve=Be(function(){H(N,!1,function(et){S.resolve(et).then(C.resolve,Y)})});return ve&&Y(ve.error),C.promise}})},function(t,i,s){"use strict";var n=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=n(c,u),this._i+=a.length,{value:a,done:!1})})},function(t,i,s){s(65);for(var n=s(2),a=s(5),c=s(10),u=s(1)("toStringTag"),d=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],p=0;p<5;p++){var m=d[p],y=n[m],E=y&&y.prototype;E&&!E[u]&&a(E,u,m),c[m]=c.Array}},function(t,i){t.exports=require("child_process")},function(t,i){t.exports=require("crypto")}])})});function Hy(){try{return Sc.default.statSync("/.dockerenv"),!0}catch{return!1}}function Vy(){try{return Sc.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Tc(){return xc===void 0&&(xc=Hy()||Vy()),xc}var Sc,xc,Ph=Ft(()=>{Sc=ce(require("node:fs"),1)});function Hi(){return Cc===void 0&&(Cc=zy()||Tc()),Cc}var Ah,Cc,zy,Oc=Ft(()=>{Ah=ce(require("node:fs"),1);Ph();zy=()=>{try{return Ah.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var kc,Lh,Nh,Ih,Ur,Rc=Ft(()=>{kc=ce(require("node:process"),1),Lh=ce(require("node:os"),1),Nh=ce(require("node:fs"),1);Oc();Ih=()=>{if(kc.default.platform!=="linux")return!1;if(Lh.default.release().toLowerCase().includes("microsoft"))return!Hi();try{return Nh.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!Hi():!1}catch{return!1}},Ur=kc.default.env.__IS_WSL_TEST__?Ih:Ih()});var Pc,Cs,Ky,$y,Ac,Dh=Ft(()=>{Pc=ce(require("node:process"),1),Cs=ce(require("node:fs/promises"),1);Rc();Rc();Ky=(()=>{let r="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",i=!1;try{await Cs.default.access(t,Cs.constants.F_OK),i=!0}catch{}if(!i)return r;let s=await Cs.default.readFile(t,{encoding:"utf8"}),n=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(s);return n?(e=n.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):r}})(),$y=async()=>`${await Ky()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Ac=async()=>Ur?$y():`${Pc.default.env.SYSTEMROOT||Pc.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function qr(r,e,t){let i=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 i(s),s},set(s){i(s)}}),r}var Mh=Ft(()=>{});async function Ic(){if(Bh.default.platform!=="darwin")throw new Error("macOS only");let{stdout:r}=await Gy("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 Fh,Bh,jh,Gy,Uh=Ft(()=>{Fh=require("node:util"),Bh=ce(require("node:process"),1),jh=require("node:child_process"),Gy=(0,Fh.promisify)(jh.execFile)});async function Hh(r,{humanReadableOutput:e=!0,signal:t}={}){if(qh.default.platform!=="darwin")throw new Error("macOS only");let i=e?[]:["-ss"],s={};t&&(s.signal=t);let{stdout:n}=await Yy("osascript",["-e",r,i],s);return n.trim()}var qh,Wh,Lc,Yy,Vh=Ft(()=>{qh=ce(require("node:process"),1),Wh=require("node:util"),Lc=require("node:child_process"),Yy=(0,Wh.promisify)(Lc.execFile)});async function Nc(r){return Hh(`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 zh=Ft(()=>{Vh()});async function Mc(r=Xy){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 Dc(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:i}=t.groups,s=i.lastIndexOf("."),n=i.lastIndexOf("-"),a=s===-1?void 0:i.slice(0,s),c=n===-1?void 0:i.slice(0,n);return Qn[i]??Qn[a]??Qn[c]??{name:i,id:i}}var Kh,$h,Xy,Qn,sb,Dc,Gh=Ft(()=>{Kh=require("node:util"),$h=require("node:child_process"),Xy=(0,Kh.promisify)($h.execFile),Qn={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"}},sb=new Map(Object.entries(Qn)),Dc=class extends Error{}});async function Fc(){if(eo.default.platform==="darwin"){let r=await Ic();return{name:await Nc(r),id:r}}if(eo.default.platform==="linux"){let{stdout:r}=await Jy("xdg-mime",["query","default","x-scheme-handler/http"]),e=r.trim();return{name:Zy(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(eo.default.platform==="win32")return Mc();throw new Error("Only macOS, Linux, and Windows are supported")}var Yh,eo,Xh,Jy,Zy,Jh=Ft(()=>{Yh=require("node:util"),eo=ce(require("node:process"),1),Xh=require("node:child_process");Uh();zh();Gh();Jy=(0,Yh.promisify)(Xh.execFile),Zy=r=>r.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var sd={};ep(sd,{apps:()=>Wr,default:()=>iv,openApp:()=>rv});async function ev(){let r=await Ac(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=Uc.Buffer.from(e,"utf16le").toString("base64"),{stdout:i}=await Qy(r,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),s=i.trim(),n={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return n[s]?{id:n[s]}:{}}function td(r){if(typeof r=="string"||Array.isArray(r))return r;let{[Qh]:e}=r;if(!e)throw new Error(`${Qh} is not supported`);return e}function ro({[Vi]:r},{wsl:e}){if(e&&Ur)return td(e);if(!r)throw new Error(`${Vi} is not supported`);return td(r)}var jc,Uc,qc,rd,id,Wc,to,sv,Qy,Bc,Zh,Vi,Qh,ed,Os,tv,rv,Wr,iv,nd=Ft(()=>{jc=ce(require("node:process"),1),Uc=require("node:buffer"),qc=ce(require("node:path"),1),rd=require("node:url"),id=require("node:util"),Wc=ce(require("node:child_process"),1),to=ce(require("node:fs/promises"),1);Dh();Mh();Jh();Oc();sv={},Qy=(0,id.promisify)(Wc.default.execFile),Bc=qc.default.dirname((0,rd.fileURLToPath)(sv.url)),Zh=qc.default.join(Bc,"xdg-open"),{platform:Vi,arch:Qh}=jc.default;ed=async(r,e)=>{let t;for(let i of r)try{return await e(i)}catch(s){t=s}throw t},Os=async r=>{if(r={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...r},Array.isArray(r.app))return ed(r.app,c=>Os({...r,app:c}));let{name:e,arguments:t=[]}=r.app??{};if(t=[...t],Array.isArray(e))return ed(e,c=>Os({...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=Ur?await ev():await Fc();if(d.id in c){let p=c[d.id];return e==="browserPrivate"&&t.push(u[p]),Os({...r,app:{name:Wr[p],arguments:t}})}throw new Error(`${d.name} is not supported as a default browser`)}let i,s=[],n={};if(Vi==="darwin")i="open",r.wait&&s.push("--wait-apps"),r.background&&s.push("--background"),r.newInstance&&s.push("--new"),e&&s.push("-a",e);else if(Vi==="win32"||Ur&&!Hi()&&!e){i=await Ac(),s.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),Ur||(n.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=Uc.Buffer.from(c.join(" "),"utf16le").toString("base64")}else{if(e)i=e;else{let c=!Bc||Bc==="/",u=!1;try{await to.default.access(Zh,to.constants.X_OK),u=!0}catch{}i=jc.default.versions.electron??(Vi==="android"||c||!u)?"xdg-open":Zh}t.length>0&&s.push(...t),r.wait||(n.stdio="ignore",n.detached=!0)}Vi==="darwin"&&t.length>0&&s.push("--args",...t),r.target&&s.push(r.target);let a=Wc.default.spawn(i,s,n);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)},tv=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a `target`");return Os({...e,target:r})},rv=(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 Os({...e,app:{name:r,arguments:t}})};Wr={};qr(Wr,"chrome",()=>ro({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"]}}));qr(Wr,"brave",()=>ro({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"]}}));qr(Wr,"firefox",()=>ro({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));qr(Wr,"edge",()=>ro({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));qr(Wr,"browser",()=>"browser");qr(Wr,"browserPrivate",()=>"browserPrivate");iv=tv});var ar=ce(require("fs")),Us=ce(require("path"));var uf=ce(require("os")),lf=ce(require("path")),Bs=ce(require("fs"));function js(){let r=lf.join(uf.homedir(),".termiq");return Bs.existsSync(r)||Bs.mkdirSync(r,{recursive:!0,mode:448}),r}var Zi=class{filePath;data={};constructor(){this.filePath=Us.join(js(),"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=Us.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=ce(require("fs")),qs=ce(require("path"));var rp={serverUrl:"https://termiq.io",agentName:"",multiViewer:!1},Qi=class{config;filePath;constructor(e){this.filePath=qs.join(js(),"config.json"),this.config={...rp,...this.loadFromFile(),...e}}getServerUrl(){return this.config.serverUrl}getAgentName(){return this.config.agentName}isAutoConnect(){return!0}getMultiViewer(){return this.config.multiViewer}async setMultiViewer(e){this.config.multiViewer=e,this.saveToFile()}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=qs.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=ce(require("fs")),wc=ce(require("path")),Oh=ce(require("os")),Zn=ce(Es()),jy="cli",vc=wc.join(Oh.homedir(),".termiq","logs"),jr=wc.join(vc,"cli.log"),Uy=5*1024*1024,Ch=3;function qy(){try{if(!dt.existsSync(jr)||dt.statSync(jr).size<Uy)return;for(let e=Ch-1;e>=1;e--){let t=`${jr}.${e}`,i=`${jr}.${e+1}`;dt.existsSync(t)&&(e+1>Ch?dt.unlinkSync(t):dt.renameSync(t,i))}dt.renameSync(jr,`${jr}.1`)}catch{}}function Wy(r){try{dt.existsSync(vc)||dt.mkdirSync(vc,{recursive:!0}),qy(),dt.appendFileSync(jr,r+`
32
32
  `,{encoding:"utf8"})}catch{}}var bs=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 jr}write(e,t,i){if(!(0,Zn.shouldLog)(e,this.level))return;let s=(0,Zn.formatLogLine)(e,jy,t,i);this.toFile?Wy(s):process.stderr.write(s+`
33
- `)}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 kh=ae(require("os")),Rh=ae(bc()),Ss=class{cachedId=null;name;constructor(e){this.name=e||kh.hostname()||"CLI"}async getMachineId(){if(this.cachedId)return this.cachedId;try{this.cachedId=(0,Rh.machineIdSync)()}catch{this.cachedId=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}return this.cachedId}getMachineName(){return this.name}};var Ts=class{constructor(e){this.logger=e}info(e){this.logger.info("Notification",{message:e})}warn(e){this.logger.warn("Notification",{message:e})}error(e){this.logger.error("Notification",{message:e})}};var ks=class{async openUrl(e){let{default:t}=await Promise.resolve().then(()=>(nd(),sd));await t(e)}};var od=ae(require("fs")),Hc=ae(require("path"));function io(r){let e=r?[r]:[Hc.join(__dirname,"..","package.json"),Hc.join(__dirname,"..","..","package.json")];for(let t of e)try{let i=JSON.parse(od.readFileSync(t,"utf8"));if(typeof i.version=="string"&&i.version.length>0)return i.version}catch{}return"unknown"}function ad(r,e){for(let t=0;t<r.length;t++){let i=r[t];if(i.startsWith("-")){e.has(i)&&t++;continue}return i}}var Vc=new Set(["--cid","--token","--server","--log-level"]),cd=new Set(["--help","-h","--version","-V","--verbose","-v","--watch","-w","--log-to-file","--statusline","--multi-viewer"]);function fd(r,e,t){for(let i=0;i<r.length;i++){let s=r[i];if(!s.startsWith("-"))continue;let n=s.includes("=")?s.slice(0,s.indexOf("=")):s;if(e.has(n)||t.has(n)){e.has(n)&&!s.includes("=")&&i++;continue}return s}}var Fd=ae(require("path")),yt=ae(ws()),Bd=ae(hr());var ud=ae(require("os")),ld=require("crypto"),hd=ae(require("node-pty")),dd=ae(ws()),so=class r{ptyProcess=null;outputBuffer=new dd.CircularBuffer(100);streamId=null;logger;onOutput=null;onExit=null;preWriteHook=null;onResize=null;sigwinchEnabled=!0;sigwinchListener=null;desiredCols=null;desiredRows=null;rebroadcastTimers=[];static REBROADCAST_DELAYS_MS=[50,200,500];static PASTE_CHAR_DELAY_MS=10;writeQueue=[];draining=!1;drainTimer=null;reservedBottomRows=0;multiViewerMode=!1;static MIN_WIDE_COLS=200;static MIN_WIDE_ROWS=50;constructor(e){this.logger=e}setMultiViewerMode(e){if(this.multiViewerMode!==e&&(this.multiViewerMode=e,this.logger.info("Multi-viewer mode",{enabled:e}),e&&this.ptyProcess)){let t=Math.max(this.ptyProcess.cols,r.MIN_WIDE_COLS),i=Math.max(this.ptyProcess.rows,r.MIN_WIDE_ROWS);(t!==this.ptyProcess.cols||i!==this.ptyProcess.rows)&&(this.ptyProcess.resize(t,i),this.desiredCols=t,this.desiredRows=i)}}spawn(e,t=0){let i=process.env.SHELL||(ud.platform()==="win32"?"powershell.exe":"/bin/bash"),s=process.stdout.columns||80,n=process.stdout.rows||24,a=Math.max(1,n-t);this.multiViewerMode&&(s=Math.max(s,r.MIN_WIDE_COLS),a=Math.max(a,r.MIN_WIDE_ROWS)),this.reservedBottomRows=t,this.ptyProcess=hd.spawn(i,[],{name:"xterm-256color",cols:s,rows:a,cwd:e,env:process.env}),this.onResize?.(s,a),this.streamId=(0,ld.randomUUID)();let c=`cli_${this.ptyProcess.pid}`;return this.ptyProcess.onData(u=>{this.preWriteHook?.(u),process.stdout.write(u),this.outputBuffer.append(u),this.onOutput?.(u)}),this.ptyProcess.onExit(({exitCode:u})=>{this.logger.info("Shell exited",String(u)),this.onExit?.(u)}),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u=>{this.ptyProcess?.write(u.toString())}),this.sigwinchListener=()=>{let u=process.stdout.columns||80,d=Math.max(1,(process.stdout.rows||24)-this.reservedBottomRows);if(this.desiredCols!==null&&this.desiredRows!==null){this.logger.info("Local resize ignored (PWA desired-size set)",{host:{cols:u,rows:d},desired:{cols:this.desiredCols,rows:this.desiredRows}});return}if(!this.sigwinchEnabled){this.logger.info("Local resize ignored (PWA viewers attached)",{cols:u,rows:d});return}this.logger.info("Local resize applied",{cols:u,rows:d}),this.ptyProcess?.resize(u,d),this.onResize?.(u,d)},process.platform==="win32"?process.stdout.on("resize",this.sigwinchListener):process.on("SIGWINCH",this.sigwinchListener),this.logger.info("Shell spawned",i,c),c}write(e,t=!1){if(this.ptyProcess){if(!t&&!this.draining){this.ptyProcess.write(e);return}for(let i of e)this.writeQueue.push(i);this.drainWriteQueue()}}drainWriteQueue(){if(this.draining)return;this.draining=!0;let e=()=>{let t=this.writeQueue.shift();if(t===void 0||!this.ptyProcess){this.draining=!1;return}this.ptyProcess.write(t),this.drainTimer=setTimeout(e,r.PASTE_CHAR_DELAY_MS)};e()}getStreamId(){return this.streamId}resize(e,t){this.multiViewerMode&&(e=Math.max(e,r.MIN_WIDE_COLS),t=Math.max(t,r.MIN_WIDE_ROWS)),this.desiredCols=e,this.desiredRows=t,this.ptyProcess?.resize(e,t),this.onResize?.(e,t),this.cancelRebroadcast();for(let i of r.REBROADCAST_DELAYS_MS)this.rebroadcastTimers.push(setTimeout(()=>{this.ptyProcess&&(this.desiredCols!==e||this.desiredRows!==t||this.ptyProcess.resize(e,t))},i))}cancelRebroadcast(){for(let e of this.rebroadcastTimers)clearTimeout(e);this.rebroadcastTimers=[]}redrawNoResize(){if(this.ptyProcess){if(this.desiredCols===null||this.desiredRows===null){this.logger.info("Redraw skipped (no desired-size set yet)");return}this.ptyProcess.resize(this.desiredCols,this.desiredRows)}}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}setPreWriteHook(e){this.preWriteHook=e}setOnResize(e){this.onResize=e}setOnExit(e){this.onExit=e}isAlive(){return this.ptyProcess!==null}kill(){this.ptyProcess?.kill(),this.ptyProcess=null}dispose(){this.kill(),this.cancelRebroadcast(),this.drainTimer&&(clearTimeout(this.drainTimer),this.drainTimer=null),this.writeQueue=[],this.draining=!1,this.sigwinchListener&&(process.platform==="win32"?process.stdout.removeListener("resize",this.sigwinchListener):process.removeListener("SIGWINCH",this.sigwinchListener),this.sigwinchListener=null),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause()}};var Hr=ae(require("path")),zi=ae(require("fs"));var Rd=require("node:events"),Pd=require("node:fs"),ho=require("node:fs/promises"),_e=ae(require("node:path"),1);var Er=require("node:fs/promises"),wr=require("node:path"),_d=require("node:stream"),Ct={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},Kc={root:".",fileFilter:r=>!0,directoryFilter:r=>!0,type:Ct.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(Kc);var yd="READDIRP_RECURSIVE_ERROR",nv=new Set(["ENOENT","EPERM","EACCES","ELOOP",yd]),pd=[Ct.DIR_TYPE,Ct.EVERYTHING_TYPE,Ct.FILE_DIR_TYPE,Ct.FILE_TYPE],ov=new Set([Ct.DIR_TYPE,Ct.EVERYTHING_TYPE,Ct.FILE_DIR_TYPE]),av=new Set([Ct.EVERYTHING_TYPE,Ct.FILE_DIR_TYPE,Ct.FILE_TYPE]),cv=r=>nv.has(r.code),fv=process.platform==="win32",gd=r=>!0,md=r=>{if(r===void 0)return gd;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(i=>t.basename===i)}return gd},zc=class extends _d.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={...Kc,...e},{root:i,type:s}=t;this._fileFilter=md(t.fileFilter),this._directoryFilter=md(t.directoryFilter);let n=t.lstat?Er.lstat:Er.stat;fv?this._stat=a=>n(a,{bigint:!0}):this._stat=n,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:Kc.depth,this._wantsDir=s?ov.has(s):!1,this._wantsFile=s?av.has(s):!1,this._wantsEverything=s===Ct.EVERYTHING_TYPE,this._root=(0,wr.resolve)(i),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(i,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,i=t&&t.files;if(i&&i.length>0){let{path:s,depth:n}=t,a=i.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)?(n<=this._maxDepth&&this.parents.push(this._exploreDir(u.fullPath,n+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 i;try{i=await(0,Er.readdir)(e,this._rdOptions)}catch(s){this._onError(s)}return{files:i,depth:t,path:e}}async _formatEntry(e,t){let i,s=this._isDirent?e.name:e;try{let n=(0,wr.resolve)((0,wr.join)(t,s));i={path:(0,wr.relative)(this._root,n),fullPath:n,basename:s},i[this._statsProp]=this._isDirent?e:await this._stat(n)}catch(n){this._onError(n);return}return i}_onError(e){cv(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 i=e.fullPath;try{let s=await(0,Er.realpath)(i),n=await(0,Er.lstat)(s);if(n.isFile())return"file";if(n.isDirectory()){let a=s.length;if(i.startsWith(s)&&i.substr(a,1)===wr.sep){let c=new Error(`Circular symlink detected: "${i}" points to "${s}"`);return c.code=yd,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 vd(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&&!pd.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${pd.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=r,new zc(e)}var li=require("node:fs"),Vt=require("node:fs/promises"),wd=require("node:os"),He=ae(require("node:path"),1),uv="data",Yc="end",bd="close",fo=()=>{};var uo=process.platform,Xc=uo==="win32",lv=uo==="darwin",hv=uo==="linux",dv=uo==="freebsd",xd=(0,wd.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,pv="watch",gv={lstat:Vt.lstat,stat:Vt.stat},ui="listeners",no="errHandlers",Ki="rawEmitters",mv=[ui,no,Ki],_v=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"]),yv=r=>_v.has(He.extname(r).slice(1).toLowerCase()),Gc=(r,e)=>{r instanceof Set?r.forEach(e):e(r)},Rs=(r,e,t)=>{let i=r[e];i instanceof Set||(r[e]=i=new Set([i])),i.add(t)},vv=r=>e=>{let t=r[e];t instanceof Set?t.clear():delete r[e]},Ps=(r,e,t)=>{let i=r[e];i instanceof Set?i.delete(t):i===t&&delete r[e]},Sd=r=>r instanceof Set?r.size===0:!r,oo=new Map;function Ed(r,e,t,i,s){let n=(a,c)=>{t(r),s(a,c,{watchedPath:r}),c&&r!==c&&ao(He.resolve(r,c),ui,He.join(r,c))};try{return(0,li.watch)(r,{persistent:e.persistent},n)}catch(a){i(a);return}}var ao=(r,e,t,i,s)=>{let n=oo.get(r);n&&Gc(n[e],a=>{a(t,i,s)})},Ev=(r,e,t,i)=>{let{listener:s,errHandler:n,rawEmitter:a}=i,c=oo.get(e),u;if(!t.persistent)return u=Ed(r,t,s,n,a),u?u.close.bind(u):void 0;if(c)Rs(c,ui,s),Rs(c,no,n),Rs(c,Ki,a);else{if(u=Ed(r,t,ao.bind(null,e,ui),n,ao.bind(null,e,Ki)),!u)return;u.on(Ht.ERROR,async d=>{let g=ao.bind(null,e,no);if(c&&(c.watcherUnusable=!0),Xc&&d.code==="EPERM")try{await(await(0,Vt.open)(r,"r")).close(),g(d)}catch{}else g(d)}),c={listeners:s,errHandlers:n,rawEmitters:a,watcher:u},oo.set(e,c)}return()=>{Ps(c,ui,s),Ps(c,no,n),Ps(c,Ki,a),Sd(c.listeners)&&(c.watcher.close(),oo.delete(e),mv.forEach(vv(c)),c.watcher=void 0,Object.freeze(c))}},$c=new Map,wv=(r,e,t,i)=>{let{listener:s,rawEmitter:n}=i,a=$c.get(e),c=a&&a.options;return c&&(c.persistent<t.persistent||c.interval>t.interval)&&((0,li.unwatchFile)(e),a=void 0),a?(Rs(a,ui,s),Rs(a,Ki,n)):(a={listeners:s,rawEmitters:n,options:t,watcher:(0,li.watchFile)(e,t,(u,d)=>{Gc(a.rawEmitters,m=>{m(Ht.CHANGE,e,{curr:u,prev:d})});let g=u.mtimeMs;(u.size!==d.size||g>d.mtimeMs||g===0)&&Gc(a.listeners,m=>m(r,u))})},$c.set(e,a)),()=>{Ps(a,ui,s),Ps(a,Ki,n),Sd(a.listeners)&&($c.delete(e),(0,li.unwatchFile)(e),a.options=a.watcher=void 0,Object.freeze(a))}},co=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let i=this.fsw.options,s=He.dirname(e),n=He.basename(e);this.fsw._getWatchedDir(s).add(n);let c=He.resolve(e),u={persistent:i.persistent};t||(t=fo);let d;if(i.usePolling){let g=i.interval!==i.binaryInterval;u.interval=g&&yv(n)?i.binaryInterval:i.interval,d=wv(e,c,u,{listener:t,rawEmitter:this.fsw._emitRaw})}else d=Ev(e,c,u,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return d}_handleFile(e,t,i){if(this.fsw.closed)return;let s=He.dirname(e),n=He.basename(e),a=this.fsw._getWatchedDir(s),c=t;if(a.has(n))return;let u=async(g,m)=>{if(this.fsw._throttle(pv,e,5)){if(!m||m.mtimeMs===0)try{let y=await(0,Vt.stat)(e);if(this.fsw.closed)return;let b=y.atimeMs,T=y.mtimeMs;if((!b||b<=T||T!==c.mtimeMs)&&this.fsw._emit(Ht.CHANGE,e,y),(lv||hv||dv)&&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,n)}else if(a.has(n)){let y=m.atimeMs,b=m.mtimeMs;(!y||y<=b||b!==c.mtimeMs)&&this.fsw._emit(Ht.CHANGE,e,m),c=m}}},d=this._watchWithNodeFs(e,u);if(!(i&&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,i,s){if(this.fsw.closed)return;let n=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let c;try{c=await(0,Vt.realpath)(i)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(s)?this.fsw._symlinkPaths.get(n)!==c&&(this.fsw._symlinkPaths.set(n,c),this.fsw._emit(Ht.CHANGE,i,e.stats)):(a.add(s),this.fsw._symlinkPaths.set(n,c),this.fsw._emit(Ht.ADD,i,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(n))return!0;this.fsw._symlinkPaths.set(n,!0)}_handleRead(e,t,i,s,n,a,c){e=He.join(e,"");let u=s?`${e}:${s}`:e;if(c=this.fsw._throttle("readdir",u,1e3),!c)return;let d=this.fsw._getWatchedDir(i.path),g=new Set,m=this.fsw._readdirp(e,{fileFilter:y=>i.filterPath(y),directoryFilter:y=>i.filterDir(y)});if(m)return m.on(uv,async y=>{if(this.fsw.closed){m=void 0;return}let b=y.path,T=He.join(e,b);if(g.add(b),!(y.stats.isSymbolicLink()&&await this._handleSymlink(y,e,T,b))){if(this.fsw.closed){m=void 0;return}(b===s||!s&&!d.has(b))&&(this.fsw._incrReadyCount(),T=He.join(n,He.relative(n,T)),this._addToNodeFs(T,t,i,a+1))}}).on(Ht.ERROR,this._boundHandleError),new Promise((y,b)=>{if(!m)return b();m.once(Yc,()=>{if(this.fsw.closed){m=void 0;return}let T=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,T&&this._handleRead(e,!1,i,s,n,a,c)})})}async _handleDir(e,t,i,s,n,a,c){let u=this.fsw._getWatchedDir(He.dirname(e)),d=u.has(He.basename(e));!(i&&this.fsw.options.ignoreInitial)&&!n&&!d&&this.fsw._emit(Ht.ADD_DIR,e,t),u.add(He.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(!n&&(await this._handleRead(e,i,a,n,e,s,g),this.fsw.closed))return;m=this._watchWithNodeFs(e,(b,T)=>{T&&T.mtimeMs===0||this._handleRead(b,!1,a,n,e,s,g)})}return m}async _addToNodeFs(e,t,i,s,n){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let c=this.fsw._getWatchHelpers(e);i&&(c.filterPath=u=>i.filterPath(u),c.filterDir=u=>i.filterDir(u));try{let u=await gv[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=He.resolve(e),y=d?await(0,Vt.realpath)(e):e;if(this.fsw.closed||(g=await this._handleDir(c.watchPath,u,t,s,n,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=He.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(He.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 Jc="/",bv="//",Ad=".",xv="..",Sv="string",Tv=/\\/g,Id=/\/\//g,Cv=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Ov=/^\.[/\\]/;function lo(r){return Array.isArray(r)?r:[r]}var Zc=r=>typeof r=="object"&&r!==null&&!(r instanceof RegExp);function kv(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=_e.relative(r.path,e);return t?!t.startsWith("..")&&!_e.isAbsolute(t):!1}return!1}:()=>!1}function Rv(r){if(typeof r!="string")throw new Error("string expected");r=_e.normalize(r),r=r.replace(/\\/g,"/");let e=!1;return r.startsWith("//")&&(e=!0),r=r.replace(Id,"/"),e&&(r="/"+r),r}function Td(r,e,t){let i=Rv(e);for(let s=0;s<r.length;s++){let n=r[s];if(n(i,t))return!0}return!1}function Pv(r,e){if(r==null)throw new TypeError("anymatch: specify first argument");let i=lo(r).map(s=>kv(s));return e==null?(s,n)=>Td(i,s,n):Td(i,e)}var Cd=r=>{let e=lo(r).flat();if(!e.every(t=>typeof t===Sv))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Ld)},Od=r=>{let e=r.replace(Tv,Jc),t=!1;return e.startsWith(bv)&&(t=!0),e=e.replace(Id,Jc),t&&(e=Jc+e),e},Ld=r=>Od(_e.normalize(Od(r))),kd=(r="")=>e=>typeof e=="string"?Ld(_e.isAbsolute(e)?e:_e.join(r,e)):e,Av=(r,e)=>_e.isAbsolute(r)?r:_e.join(e,r),Iv=Object.freeze(new Set),Qc=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!==Ad&&e!==xv&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let i=this.path;try{await(0,ho.readdir)(i)}catch{this._removeWatcher&&this._removeWatcher(_e.dirname(i),_e.basename(i))}}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=fo,this.items=Iv,Object.freeze(this)}},Lv="stat",Nv="lstat",ef=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,t,i){this.fsw=i;let s=e;this.path=e=e.replace(Ov,""),this.watchPath=s,this.fullWatchPath=_e.resolve(s),this.dirParts=[],this.dirParts.forEach(n=>{n.length>1&&n.pop()}),this.followSymlinks=t,this.statMethod=t?Lv:Nv}entryPath(e){return _e.join(this.watchPath,_e.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let i=this.entryPath(e);return this.fsw._isntIgnored(i,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},tf=class extends Rd.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,i={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?lo(e.ignored):lo([]),awaitWriteFinish:t===!0?i:typeof t=="object"?{...i,...t}:!1};xd&&(s.usePolling=!0),s.atomic===void 0&&(s.atomic=!s.usePolling);let n=process.env.CHOKIDAR_USEPOLLING;if(n!==void 0){let u=n.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=fo,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 co(this),Object.freeze(s)}_addIgnoredPath(e){if(Zc(e)){for(let t of this._ignoredPaths)if(Zc(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)Zc(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,i){let{cwd:s}=this.options;this.closed=!1,this._closePromise=void 0;let n=Cd(e);return s&&(n=n.map(a=>Av(a,s))),n.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=n.length,Promise.all(n.map(async a=>{let c=await this._nodeFsHandler._addToNodeFs(a,!i,void 0,0,t);return c&&this._emitReady(),c})).then(a=>{this.closed||a.forEach(c=>{c&&this.add(_e.dirname(c),_e.basename(t||c))})}),this}unwatch(e){if(this.closed)return this;let t=Cd(e),{cwd:i}=this.options;return t.forEach(s=>{!_e.isAbsolute(s)&&!this._closers.has(s)&&(i&&(s=_e.join(i,s)),s=_e.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(i=>{let s=i();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,i)=>{let n=(this.options.cwd?_e.relative(this.options.cwd,i):i)||Ad;e[n]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==Ve.ERROR&&this.emit(Ve.ALL,e,...t)}async _emit(e,t,i){if(this.closed)return;let s=this.options;Xc&&(t=_e.normalize(t)),s.cwd&&(t=_e.relative(s.cwd,t));let n=[t];i!=null&&n.push(i);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,...n]),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,n[0]=d,this.emitWithAll(e,n)):g&&(n.length>1?n[1]=g:n.push(g),this.emitWithAll(e,n))};return this._awaitWriteFinish(t,a.stabilityThreshold,e,u),this}if(e===Ve.CHANGE&&!this._throttle(Ve.CHANGE,t,50))return this;if(s.alwaysStat&&i===void 0&&(e===Ve.ADD||e===Ve.ADD_DIR||e===Ve.CHANGE)){let u=s.cwd?_e.join(s.cwd,t):t,d;try{d=await(0,ho.stat)(u)}catch{}if(!d||this.closed)return;n.push(d)}return this.emitWithAll(e,n),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,i){this._throttled.has(e)||this._throttled.set(e,new Map);let s=this._throttled.get(e);if(!s)throw new Error("invalid throttle");let n=s.get(t);if(n)return n.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,i);let u={timeoutObject:a,clear:c,count:0};return s.set(t,u),u}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,i,s){let n=this.options.awaitWriteFinish;if(typeof n!="object")return;let a=n.pollInterval,c,u=e;this.options.cwd&&!_e.isAbsolute(e)&&(u=_e.join(this.options.cwd,e));let d=new Date,g=this._pendingWrites;function m(y){(0,Pd.stat)(u,(b,T)=>{if(b||!g.has(e)){b&&b.code!=="ENOENT"&&s(b);return}let C=Number(new Date);y&&T.size!==y.size&&(g.get(e).lastChange=C);let H=g.get(e);C-H.lastChange>=t?(g.delete(e),s(void 0,T)):c=setTimeout(m,a,T)})}g.has(e)||(g.set(e,{lastChange:d,cancelWait:()=>(g.delete(e),clearTimeout(c),i)}),c=setTimeout(m,a))}_isIgnored(e,t){if(this.options.atomic&&Cv.test(e))return!0;if(!this._userIgnored){let{cwd:i}=this.options,n=(this.options.ignored||[]).map(kd(i)),c=[...[...this._ignoredPaths].map(kd(i)),...n];this._userIgnored=Pv(c,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new ef(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=_e.resolve(e);return this._watched.has(t)||this._watched.set(t,new Qc(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,i){let s=_e.join(e,t),n=_e.resolve(s);if(i=i??(this._watched.has(s)||this._watched.has(n)),!this._throttle("remove",s,100))return;!i&&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(n)&&this._symlinkPaths.delete(n);let g=s;if(this.options.cwd&&(g=_e.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(n);let m=i?Ve.UNLINK_DIR:Ve.UNLINK;d&&!this._isIgnored(s)&&this._emit(m,s),this._closePath(s)}_closePath(e){this._closeFile(e);let t=_e.dirname(e);this._getWatchedDir(t).remove(_e.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(i=>i()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let i=this._closers.get(e);i||(i=[],this._closers.set(e,i)),i.push(t)}_readdirp(e,t){if(this.closed)return;let i={type:Ve.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},s=vd(e,i);return this._streams.add(s),s.once(bd,()=>{s=void 0}),s.once(Yc,()=>{s&&(this._streams.delete(s),s=void 0)}),s}};function Nd(r,e={}){let t=new tf(e);return t.add(r),t}var Dd=ae(uc()),sr=ae(hr()),Dv=["**/node_modules/**","**/.git/**","**/dist/**","**/.next/**","**/.turbo/**","**/.cache/**","**/coverage/**","**/*.log"],Mv=300,po=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,Dd.default)(),this.initializeIgnoreFilter()}initializeIgnoreFilter(){this.ignoreFilter.add(Dv);let e=Hr.join(this.workspaceRoot,".gitignore");try{if(zi.existsSync(e)){let t=zi.readFileSync(e,"utf-8");this.ignoreFilter.add(t)}}catch{}}onFileChanged(e){this.onFileChangedCallback=e}start(){this.watcher||(this.watcher=Nd(this.workspaceRoot,{ignored:e=>{let t=Hr.relative(this.workspaceRoot,e);if(!t||t===".")return!1;let i=t.split(Hr.sep).join("/");return this.ignoreFilter.ignores(i)},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 i=Hr.relative(this.workspaceRoot,e);if(!i)return;let s=this.pendingEvents.get(i);s&&clearTimeout(s);let n=this.pendingTypes.get(i);this.pendingTypes.set(i,this.mergeTypes(n,t));let a=setTimeout(()=>{this.emit(i,this.pendingTypes.get(i)||t),this.pendingEvents.delete(i),this.pendingTypes.delete(i)},Mv);this.pendingEvents.set(i,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 i={path:e,changeType:t,timestamp:new Date().toISOString(),source:"watcher"};if(t!==sr.FileChangeType.DELETE)try{let s=Hr.join(this.workspaceRoot,e),n=zi.statSync(s);i.size=n.size}catch{}this.onFileChangedCallback?.(i)}dispose(){this.stop(),this.onFileChangedCallback=null}};var Fv={online:!1,viewerCount:0},go=class r{enabled=!1;state={...Fv};altScreenActive=!1;logger;refreshTimer=null;static REFRESH_INTERVAL_MS=1e3;constructor(e){this.logger=e}reservedRows(){return this.enabled&&process.stdout.isTTY?1:0}enable(){if(!process.stdout.isTTY){this.logger.warn("StatusLine: stdout is not a TTY, cannot enable");return}this.enabled=!0,this.installScrollRegion(),this.startRefreshTimer(),this.logger.info("StatusLine enabled")}startRefreshTimer(){this.stopRefreshTimer(),this.refreshTimer=setInterval(()=>{!this.enabled||this.altScreenActive||this.render()},r.REFRESH_INTERVAL_MS)}stopRefreshTimer(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null)}installScrollRegion(){let e=process.stdout.rows;!e||e<2||(process.stdout.write(`\x1B[1;${e-1}r`),process.stdout.write("\x1B[1;1H"))}resetScrollRegion(){process.stdout.write("\x1B[r")}update(e){this.state={...this.state,...e},this.render()}render(){if(!this.enabled||this.altScreenActive)return;let e=process.stdout.rows;if(!e||e<2)return;let t=this.formatLine(),i=`\x1B[1;${e-1}r\x1B7\x1B[${e};1H\x1B[2K${t}\x1B8`;process.stdout.write(i)}clear(){if(!this.enabled)return;let e=process.stdout.rows;!e||e<2||process.stdout.write(`\x1B7\x1B[${e};1H\x1B[2K\x1B8`)}disable(){this.enabled&&(this.stopRefreshTimer(),this.clear(),this.resetScrollRegion(),this.enabled=!1)}inspectPtyOutput(e){if(this.enabled){if(e.includes("\x1B[?1049h")||e.includes("\x1B[?47h")){this.altScreenActive=!0;return}(e.includes("\x1B[?1049l")||e.includes("\x1B[?47l"))&&(this.altScreenActive=!1,this.render())}}getState(){return this.state}isEnabled(){return this.enabled}isAltScreenActive(){return this.altScreenActive}formatLine(){let e=[];if(e.push(this.state.online?"\u25CF online":"\u25CB offline"),this.state.viewerCount>0){let t=this.state.viewerCount===1?"1 viewer":`${this.state.viewerCount} viewers`;e.push(t)}else e.push("no viewers");return this.state.agentName&&e.push(this.state.agentName),this.state.ptyCols&&this.state.ptyRows&&e.push(`${this.state.ptyCols}\xD7${this.state.ptyRows}`)," "+e.join(" \xB7 ")+" "}};async function mo(r,e,t,i){if(i)return process.stderr.write(`Logging in with API key...
33
+ `)}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 kh=ce(require("os")),Rh=ce(bc()),Ss=class{cachedId=null;name;constructor(e){this.name=e||kh.hostname()||"CLI"}async getMachineId(){if(this.cachedId)return this.cachedId;try{this.cachedId=(0,Rh.machineIdSync)()}catch{this.cachedId=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}return this.cachedId}getMachineName(){return this.name}};var Ts=class{constructor(e){this.logger=e}info(e){this.logger.info("Notification",{message:e})}warn(e){this.logger.warn("Notification",{message:e})}error(e){this.logger.error("Notification",{message:e})}};var ks=class{async openUrl(e){let{default:t}=await Promise.resolve().then(()=>(nd(),sd));await t(e)}};var od=ce(require("fs")),Hc=ce(require("path"));function io(r){let e=r?[r]:[Hc.join(__dirname,"..","package.json"),Hc.join(__dirname,"..","..","package.json")];for(let t of e)try{let i=JSON.parse(od.readFileSync(t,"utf8"));if(typeof i.version=="string"&&i.version.length>0)return i.version}catch{}return"unknown"}function ad(r,e){for(let t=0;t<r.length;t++){let i=r[t];if(i.startsWith("-")){e.has(i)&&t++;continue}return i}}var Vc=new Set(["--cid","--token","--server","--log-level"]),cd=new Set(["--help","-h","--version","-V","--verbose","-v","--watch","-w","--log-to-file","--statusline","--multi-viewer"]);function fd(r,e,t){for(let i=0;i<r.length;i++){let s=r[i];if(!s.startsWith("-"))continue;let n=s.includes("=")?s.slice(0,s.indexOf("=")):s;if(e.has(n)||t.has(n)){e.has(n)&&!s.includes("=")&&i++;continue}return s}}var Fd=ce(require("path")),_t=ce(Es()),Bd=ce(hr());var ud=ce(require("os")),ld=require("crypto"),hd=ce(require("node-pty")),dd=ce(Es()),so=class r{ptyProcess=null;outputBuffer=new dd.CircularBuffer(100);streamId=null;logger;onOutput=null;onExit=null;preWriteHook=null;onResize=null;sigwinchEnabled=!0;sigwinchListener=null;desiredCols=null;desiredRows=null;rebroadcastTimers=[];static REBROADCAST_DELAYS_MS=[50,200,500];static PASTE_CHAR_DELAY_MS=10;writeQueue=[];draining=!1;drainTimer=null;reservedBottomRows=0;multiViewerMode=!1;static MIN_WIDE_COLS=200;static MIN_WIDE_ROWS=50;inAltScreen=!1;lastRawCols=null;lastRawRows=null;constructor(e){this.logger=e}setMultiViewerMode(e){if(this.multiViewerMode!==e&&(this.multiViewerMode=e,this.logger.info("Multi-viewer mode",{enabled:e}),e&&this.ptyProcess)){let t=Math.max(this.ptyProcess.cols,r.MIN_WIDE_COLS),i=Math.max(this.ptyProcess.rows,r.MIN_WIDE_ROWS);(t!==this.ptyProcess.cols||i!==this.ptyProcess.rows)&&(this.ptyProcess.resize(t,i),this.desiredCols=t,this.desiredRows=i)}}spawn(e,t=0){let i=process.env.SHELL||(ud.platform()==="win32"?"powershell.exe":"/bin/bash"),s=process.stdout.columns||80,n=process.stdout.rows||24,a=Math.max(1,n-t);this.multiViewerMode&&(s=Math.max(s,r.MIN_WIDE_COLS),a=Math.max(a,r.MIN_WIDE_ROWS)),this.reservedBottomRows=t,this.ptyProcess=hd.spawn(i,[],{name:"xterm-256color",cols:s,rows:a,cwd:e,env:process.env}),this.onResize?.(s,a),this.streamId=(0,ld.randomUUID)();let c=`cli_${this.ptyProcess.pid}`;return this.ptyProcess.onData(u=>{this.multiViewerMode&&this.detectAltScreen(u),this.preWriteHook?.(u),process.stdout.write(u),this.outputBuffer.append(u),this.onOutput?.(u)}),this.ptyProcess.onExit(({exitCode:u})=>{this.logger.info("Shell exited",String(u)),this.onExit?.(u)}),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u=>{this.ptyProcess?.write(u.toString())}),this.sigwinchListener=()=>{let u=process.stdout.columns||80,d=Math.max(1,(process.stdout.rows||24)-this.reservedBottomRows);if(this.desiredCols!==null&&this.desiredRows!==null){this.logger.info("Local resize ignored (PWA desired-size set)",{host:{cols:u,rows:d},desired:{cols:this.desiredCols,rows:this.desiredRows}});return}if(!this.sigwinchEnabled){this.logger.info("Local resize ignored (PWA viewers attached)",{cols:u,rows:d});return}this.logger.info("Local resize applied",{cols:u,rows:d}),this.ptyProcess?.resize(u,d),this.onResize?.(u,d)},process.platform==="win32"?process.stdout.on("resize",this.sigwinchListener):process.on("SIGWINCH",this.sigwinchListener),this.logger.info("Shell spawned",i,c),c}write(e,t=!1){if(this.ptyProcess){if(!t&&!this.draining){this.ptyProcess.write(e);return}for(let i of e)this.writeQueue.push(i);this.drainWriteQueue()}}drainWriteQueue(){if(this.draining)return;this.draining=!0;let e=()=>{let t=this.writeQueue.shift();if(t===void 0||!this.ptyProcess){this.draining=!1;return}this.ptyProcess.write(t),this.drainTimer=setTimeout(e,r.PASTE_CHAR_DELAY_MS)};e()}getStreamId(){return this.streamId}getPtyCols(){return this.ptyProcess?.cols??0}getPtyRows(){return this.ptyProcess?.rows??0}resize(e,t){this.lastRawCols=e,this.lastRawRows=t,this.multiViewerMode&&!this.inAltScreen&&(e=Math.max(e,r.MIN_WIDE_COLS),t=Math.max(t,r.MIN_WIDE_ROWS)),this.desiredCols=e,this.desiredRows=t,this.ptyProcess?.resize(e,t),this.onResize?.(e,t),this.cancelRebroadcast();for(let i of r.REBROADCAST_DELAYS_MS)this.rebroadcastTimers.push(setTimeout(()=>{this.ptyProcess&&(this.desiredCols!==e||this.desiredRows!==t||this.ptyProcess.resize(e,t))},i))}cancelRebroadcast(){for(let e of this.rebroadcastTimers)clearTimeout(e);this.rebroadcastTimers=[]}detectAltScreen(e){if(!this.ptyProcess)return;let t="\x1B",i=new RegExp(t+"\\[\\?(?:1049|47)h","g"),s=new RegExp(t+"\\[\\?(?:1049|47)l","g"),n=[...e.matchAll(i)],a=[...e.matchAll(s)];if(n.length===0&&a.length===0)return;let c=n.at(-1),u=a.at(-1),d=u&&c?(u.index??0)<(c.index??0):!!c;if(d===this.inAltScreen)return;this.inAltScreen=d,this.logger.info("Alt-screen",{active:d});let p=this.lastRawCols??this.ptyProcess.cols,m=this.lastRawRows??this.ptyProcess.rows,y,E;d?(y=p,E=m):(y=Math.max(p,r.MIN_WIDE_COLS),E=Math.max(m,r.MIN_WIDE_ROWS)),(y!==this.ptyProcess.cols||E!==this.ptyProcess.rows)&&(this.desiredCols=y,this.desiredRows=E,this.ptyProcess.resize(y,E),this.onResize?.(y,E))}redrawNoResize(){if(this.ptyProcess){if(this.desiredCols===null||this.desiredRows===null){this.logger.info("Redraw skipped (no desired-size set yet)");return}this.ptyProcess.resize(this.desiredCols,this.desiredRows)}}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}setPreWriteHook(e){this.preWriteHook=e}setOnResize(e){this.onResize=e}setOnExit(e){this.onExit=e}isAlive(){return this.ptyProcess!==null}kill(){this.ptyProcess?.kill(),this.ptyProcess=null}dispose(){this.kill(),this.cancelRebroadcast(),this.drainTimer&&(clearTimeout(this.drainTimer),this.drainTimer=null),this.writeQueue=[],this.draining=!1,this.sigwinchListener&&(process.platform==="win32"?process.stdout.removeListener("resize",this.sigwinchListener):process.removeListener("SIGWINCH",this.sigwinchListener),this.sigwinchListener=null),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause()}};var Hr=ce(require("path")),Ki=ce(require("fs"));var Rd=require("node:events"),Pd=require("node:fs"),ho=require("node:fs/promises"),ye=ce(require("node:path"),1);var wr=require("node:fs/promises"),Er=require("node:path"),_d=require("node:stream"),Ct={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},zc={root:".",fileFilter:r=>!0,directoryFilter:r=>!0,type:Ct.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(zc);var yd="READDIRP_RECURSIVE_ERROR",nv=new Set(["ENOENT","EPERM","EACCES","ELOOP",yd]),pd=[Ct.DIR_TYPE,Ct.EVERYTHING_TYPE,Ct.FILE_DIR_TYPE,Ct.FILE_TYPE],ov=new Set([Ct.DIR_TYPE,Ct.EVERYTHING_TYPE,Ct.FILE_DIR_TYPE]),av=new Set([Ct.EVERYTHING_TYPE,Ct.FILE_DIR_TYPE,Ct.FILE_TYPE]),cv=r=>nv.has(r.code),fv=process.platform==="win32",gd=r=>!0,md=r=>{if(r===void 0)return gd;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(i=>t.basename===i)}return gd},Kc=class extends _d.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={...zc,...e},{root:i,type:s}=t;this._fileFilter=md(t.fileFilter),this._directoryFilter=md(t.directoryFilter);let n=t.lstat?wr.lstat:wr.stat;fv?this._stat=a=>n(a,{bigint:!0}):this._stat=n,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:zc.depth,this._wantsDir=s?ov.has(s):!1,this._wantsFile=s?av.has(s):!1,this._wantsEverything=s===Ct.EVERYTHING_TYPE,this._root=(0,Er.resolve)(i),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(i,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,i=t&&t.files;if(i&&i.length>0){let{path:s,depth:n}=t,a=i.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)?(n<=this._maxDepth&&this.parents.push(this._exploreDir(u.fullPath,n+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 i;try{i=await(0,wr.readdir)(e,this._rdOptions)}catch(s){this._onError(s)}return{files:i,depth:t,path:e}}async _formatEntry(e,t){let i,s=this._isDirent?e.name:e;try{let n=(0,Er.resolve)((0,Er.join)(t,s));i={path:(0,Er.relative)(this._root,n),fullPath:n,basename:s},i[this._statsProp]=this._isDirent?e:await this._stat(n)}catch(n){this._onError(n);return}return i}_onError(e){cv(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 i=e.fullPath;try{let s=await(0,wr.realpath)(i),n=await(0,wr.lstat)(s);if(n.isFile())return"file";if(n.isDirectory()){let a=s.length;if(i.startsWith(s)&&i.substr(a,1)===Er.sep){let c=new Error(`Circular symlink detected: "${i}" points to "${s}"`);return c.code=yd,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 vd(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&&!pd.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${pd.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=r,new Kc(e)}var li=require("node:fs"),Vt=require("node:fs/promises"),Ed=require("node:os"),He=ce(require("node:path"),1),uv="data",Yc="end",bd="close",fo=()=>{};var uo=process.platform,Xc=uo==="win32",lv=uo==="darwin",hv=uo==="linux",dv=uo==="freebsd",xd=(0,Ed.type)()==="OS400",ze={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},Ht=ze,pv="watch",gv={lstat:Vt.lstat,stat:Vt.stat},ui="listeners",no="errHandlers",zi="rawEmitters",mv=[ui,no,zi],_v=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"]),yv=r=>_v.has(He.extname(r).slice(1).toLowerCase()),Gc=(r,e)=>{r instanceof Set?r.forEach(e):e(r)},Rs=(r,e,t)=>{let i=r[e];i instanceof Set||(r[e]=i=new Set([i])),i.add(t)},vv=r=>e=>{let t=r[e];t instanceof Set?t.clear():delete r[e]},Ps=(r,e,t)=>{let i=r[e];i instanceof Set?i.delete(t):i===t&&delete r[e]},Sd=r=>r instanceof Set?r.size===0:!r,oo=new Map;function wd(r,e,t,i,s){let n=(a,c)=>{t(r),s(a,c,{watchedPath:r}),c&&r!==c&&ao(He.resolve(r,c),ui,He.join(r,c))};try{return(0,li.watch)(r,{persistent:e.persistent},n)}catch(a){i(a);return}}var ao=(r,e,t,i,s)=>{let n=oo.get(r);n&&Gc(n[e],a=>{a(t,i,s)})},wv=(r,e,t,i)=>{let{listener:s,errHandler:n,rawEmitter:a}=i,c=oo.get(e),u;if(!t.persistent)return u=wd(r,t,s,n,a),u?u.close.bind(u):void 0;if(c)Rs(c,ui,s),Rs(c,no,n),Rs(c,zi,a);else{if(u=wd(r,t,ao.bind(null,e,ui),n,ao.bind(null,e,zi)),!u)return;u.on(Ht.ERROR,async d=>{let p=ao.bind(null,e,no);if(c&&(c.watcherUnusable=!0),Xc&&d.code==="EPERM")try{await(await(0,Vt.open)(r,"r")).close(),p(d)}catch{}else p(d)}),c={listeners:s,errHandlers:n,rawEmitters:a,watcher:u},oo.set(e,c)}return()=>{Ps(c,ui,s),Ps(c,no,n),Ps(c,zi,a),Sd(c.listeners)&&(c.watcher.close(),oo.delete(e),mv.forEach(vv(c)),c.watcher=void 0,Object.freeze(c))}},$c=new Map,Ev=(r,e,t,i)=>{let{listener:s,rawEmitter:n}=i,a=$c.get(e),c=a&&a.options;return c&&(c.persistent<t.persistent||c.interval>t.interval)&&((0,li.unwatchFile)(e),a=void 0),a?(Rs(a,ui,s),Rs(a,zi,n)):(a={listeners:s,rawEmitters:n,options:t,watcher:(0,li.watchFile)(e,t,(u,d)=>{Gc(a.rawEmitters,m=>{m(Ht.CHANGE,e,{curr:u,prev:d})});let p=u.mtimeMs;(u.size!==d.size||p>d.mtimeMs||p===0)&&Gc(a.listeners,m=>m(r,u))})},$c.set(e,a)),()=>{Ps(a,ui,s),Ps(a,zi,n),Sd(a.listeners)&&($c.delete(e),(0,li.unwatchFile)(e),a.options=a.watcher=void 0,Object.freeze(a))}},co=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let i=this.fsw.options,s=He.dirname(e),n=He.basename(e);this.fsw._getWatchedDir(s).add(n);let c=He.resolve(e),u={persistent:i.persistent};t||(t=fo);let d;if(i.usePolling){let p=i.interval!==i.binaryInterval;u.interval=p&&yv(n)?i.binaryInterval:i.interval,d=Ev(e,c,u,{listener:t,rawEmitter:this.fsw._emitRaw})}else d=wv(e,c,u,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return d}_handleFile(e,t,i){if(this.fsw.closed)return;let s=He.dirname(e),n=He.basename(e),a=this.fsw._getWatchedDir(s),c=t;if(a.has(n))return;let u=async(p,m)=>{if(this.fsw._throttle(pv,e,5)){if(!m||m.mtimeMs===0)try{let y=await(0,Vt.stat)(e);if(this.fsw.closed)return;let E=y.atimeMs,T=y.mtimeMs;if((!E||E<=T||T!==c.mtimeMs)&&this.fsw._emit(Ht.CHANGE,e,y),(lv||hv||dv)&&c.ino!==y.ino){this.fsw._closeFile(p),c=y;let O=this._watchWithNodeFs(e,u);O&&this.fsw._addPathCloser(p,O)}else c=y}catch{this.fsw._remove(s,n)}else if(a.has(n)){let y=m.atimeMs,E=m.mtimeMs;(!y||y<=E||E!==c.mtimeMs)&&this.fsw._emit(Ht.CHANGE,e,m),c=m}}},d=this._watchWithNodeFs(e,u);if(!(i&&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,i,s){if(this.fsw.closed)return;let n=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let c;try{c=await(0,Vt.realpath)(i)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(s)?this.fsw._symlinkPaths.get(n)!==c&&(this.fsw._symlinkPaths.set(n,c),this.fsw._emit(Ht.CHANGE,i,e.stats)):(a.add(s),this.fsw._symlinkPaths.set(n,c),this.fsw._emit(Ht.ADD,i,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(n))return!0;this.fsw._symlinkPaths.set(n,!0)}_handleRead(e,t,i,s,n,a,c){e=He.join(e,"");let u=s?`${e}:${s}`:e;if(c=this.fsw._throttle("readdir",u,1e3),!c)return;let d=this.fsw._getWatchedDir(i.path),p=new Set,m=this.fsw._readdirp(e,{fileFilter:y=>i.filterPath(y),directoryFilter:y=>i.filterDir(y)});if(m)return m.on(uv,async y=>{if(this.fsw.closed){m=void 0;return}let E=y.path,T=He.join(e,E);if(p.add(E),!(y.stats.isSymbolicLink()&&await this._handleSymlink(y,e,T,E))){if(this.fsw.closed){m=void 0;return}(E===s||!s&&!d.has(E))&&(this.fsw._incrReadyCount(),T=He.join(n,He.relative(n,T)),this._addToNodeFs(T,t,i,a+1))}}).on(Ht.ERROR,this._boundHandleError),new Promise((y,E)=>{if(!m)return E();m.once(Yc,()=>{if(this.fsw.closed){m=void 0;return}let T=c?c.clear():!1;y(void 0),d.getChildren().filter(O=>O!==e&&!p.has(O)).forEach(O=>{this.fsw._remove(e,O)}),m=void 0,T&&this._handleRead(e,!1,i,s,n,a,c)})})}async _handleDir(e,t,i,s,n,a,c){let u=this.fsw._getWatchedDir(He.dirname(e)),d=u.has(He.basename(e));!(i&&this.fsw.options.ignoreInitial)&&!n&&!d&&this.fsw._emit(Ht.ADD_DIR,e,t),u.add(He.basename(e)),this.fsw._getWatchedDir(e);let p,m,y=this.fsw.options.depth;if((y==null||s<=y)&&!this.fsw._symlinkPaths.has(c)){if(!n&&(await this._handleRead(e,i,a,n,e,s,p),this.fsw.closed))return;m=this._watchWithNodeFs(e,(E,T)=>{T&&T.mtimeMs===0||this._handleRead(E,!1,a,n,e,s,p)})}return m}async _addToNodeFs(e,t,i,s,n){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let c=this.fsw._getWatchHelpers(e);i&&(c.filterPath=u=>i.filterPath(u),c.filterDir=u=>i.filterDir(u));try{let u=await gv[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,p;if(u.isDirectory()){let m=He.resolve(e),y=d?await(0,Vt.realpath)(e):e;if(this.fsw.closed||(p=await this._handleDir(c.watchPath,u,t,s,n,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=He.dirname(c.watchPath);if(this.fsw._getWatchedDir(y).add(c.watchPath),this.fsw._emit(Ht.ADD,c.watchPath,u),p=await this._handleDir(y,u,t,s,e,c,m),this.fsw.closed)return;m!==void 0&&this.fsw._symlinkPaths.set(He.resolve(e),m)}else p=this._handleFile(c.watchPath,u,t);return a(),p&&this.fsw._addPathCloser(e,p),!1}catch(u){if(this.fsw._handleError(u))return a(),e}}};var Jc="/",bv="//",Ad=".",xv="..",Sv="string",Tv=/\\/g,Id=/\/\//g,Cv=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Ov=/^\.[/\\]/;function lo(r){return Array.isArray(r)?r:[r]}var Zc=r=>typeof r=="object"&&r!==null&&!(r instanceof RegExp);function kv(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 Rv(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(Id,"/"),e&&(r="/"+r),r}function Td(r,e,t){let i=Rv(e);for(let s=0;s<r.length;s++){let n=r[s];if(n(i,t))return!0}return!1}function Pv(r,e){if(r==null)throw new TypeError("anymatch: specify first argument");let i=lo(r).map(s=>kv(s));return e==null?(s,n)=>Td(i,s,n):Td(i,e)}var Cd=r=>{let e=lo(r).flat();if(!e.every(t=>typeof t===Sv))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Ld)},Od=r=>{let e=r.replace(Tv,Jc),t=!1;return e.startsWith(bv)&&(t=!0),e=e.replace(Id,Jc),t&&(e=Jc+e),e},Ld=r=>Od(ye.normalize(Od(r))),kd=(r="")=>e=>typeof e=="string"?Ld(ye.isAbsolute(e)?e:ye.join(r,e)):e,Av=(r,e)=>ye.isAbsolute(r)?r:ye.join(e,r),Iv=Object.freeze(new Set),Qc=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!==Ad&&e!==xv&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let i=this.path;try{await(0,ho.readdir)(i)}catch{this._removeWatcher&&this._removeWatcher(ye.dirname(i),ye.basename(i))}}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=fo,this.items=Iv,Object.freeze(this)}},Lv="stat",Nv="lstat",ef=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,t,i){this.fsw=i;let s=e;this.path=e=e.replace(Ov,""),this.watchPath=s,this.fullWatchPath=ye.resolve(s),this.dirParts=[],this.dirParts.forEach(n=>{n.length>1&&n.pop()}),this.followSymlinks=t,this.statMethod=t?Lv:Nv}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 i=this.entryPath(e);return this.fsw._isntIgnored(i,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},tf=class extends Rd.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,i={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?lo(e.ignored):lo([]),awaitWriteFinish:t===!0?i:typeof t=="object"?{...i,...t}:!1};xd&&(s.usePolling=!0),s.atomic===void 0&&(s.atomic=!s.usePolling);let n=process.env.CHOKIDAR_USEPOLLING;if(n!==void 0){let u=n.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=fo,this._readyEmitted=!0,process.nextTick(()=>this.emit(ze.READY)))},this._emitRaw=(...u)=>this.emit(ze.RAW,...u),this._boundRemove=this._remove.bind(this),this.options=s,this._nodeFsHandler=new co(this),Object.freeze(s)}_addIgnoredPath(e){if(Zc(e)){for(let t of this._ignoredPaths)if(Zc(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)Zc(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,i){let{cwd:s}=this.options;this.closed=!1,this._closePromise=void 0;let n=Cd(e);return s&&(n=n.map(a=>Av(a,s))),n.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=n.length,Promise.all(n.map(async a=>{let c=await this._nodeFsHandler._addToNodeFs(a,!i,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=Cd(e),{cwd:i}=this.options;return t.forEach(s=>{!ye.isAbsolute(s)&&!this._closers.has(s)&&(i&&(s=ye.join(i,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(i=>{let s=i();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,i)=>{let n=(this.options.cwd?ye.relative(this.options.cwd,i):i)||Ad;e[n]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==ze.ERROR&&this.emit(ze.ALL,e,...t)}async _emit(e,t,i){if(this.closed)return;let s=this.options;Xc&&(t=ye.normalize(t)),s.cwd&&(t=ye.relative(s.cwd,t));let n=[t];i!=null&&n.push(i);let a=s.awaitWriteFinish,c;if(a&&(c=this._pendingWrites.get(t)))return c.lastChange=new Date,this;if(s.atomic){if(e===ze.UNLINK)return this._pendingUnlinks.set(t,[e,...n]),setTimeout(()=>{this._pendingUnlinks.forEach((u,d)=>{this.emit(...u),this.emit(ze.ALL,...u),this._pendingUnlinks.delete(d)})},typeof s.atomic=="number"?s.atomic:100),this;e===ze.ADD&&this._pendingUnlinks.has(t)&&(e=ze.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===ze.ADD||e===ze.CHANGE)&&this._readyEmitted){let u=(d,p)=>{d?(e=ze.ERROR,n[0]=d,this.emitWithAll(e,n)):p&&(n.length>1?n[1]=p:n.push(p),this.emitWithAll(e,n))};return this._awaitWriteFinish(t,a.stabilityThreshold,e,u),this}if(e===ze.CHANGE&&!this._throttle(ze.CHANGE,t,50))return this;if(s.alwaysStat&&i===void 0&&(e===ze.ADD||e===ze.ADD_DIR||e===ze.CHANGE)){let u=s.cwd?ye.join(s.cwd,t):t,d;try{d=await(0,ho.stat)(u)}catch{}if(!d||this.closed)return;n.push(d)}return this.emitWithAll(e,n),this}_handleError(e){let t=e&&e.code;return e&&t!=="ENOENT"&&t!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||t!=="EPERM"&&t!=="EACCES")&&this.emit(ze.ERROR,e),e||this.closed}_throttle(e,t,i){this._throttled.has(e)||this._throttled.set(e,new Map);let s=this._throttled.get(e);if(!s)throw new Error("invalid throttle");let n=s.get(t);if(n)return n.count++,!1;let a,c=()=>{let d=s.get(t),p=d?d.count:0;return s.delete(t),clearTimeout(a),d&&clearTimeout(d.timeoutObject),p};a=setTimeout(c,i);let u={timeoutObject:a,clear:c,count:0};return s.set(t,u),u}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,i,s){let n=this.options.awaitWriteFinish;if(typeof n!="object")return;let a=n.pollInterval,c,u=e;this.options.cwd&&!ye.isAbsolute(e)&&(u=ye.join(this.options.cwd,e));let d=new Date,p=this._pendingWrites;function m(y){(0,Pd.stat)(u,(E,T)=>{if(E||!p.has(e)){E&&E.code!=="ENOENT"&&s(E);return}let O=Number(new Date);y&&T.size!==y.size&&(p.get(e).lastChange=O);let H=p.get(e);O-H.lastChange>=t?(p.delete(e),s(void 0,T)):c=setTimeout(m,a,T)})}p.has(e)||(p.set(e,{lastChange:d,cancelWait:()=>(p.delete(e),clearTimeout(c),i)}),c=setTimeout(m,a))}_isIgnored(e,t){if(this.options.atomic&&Cv.test(e))return!0;if(!this._userIgnored){let{cwd:i}=this.options,n=(this.options.ignored||[]).map(kd(i)),c=[...[...this._ignoredPaths].map(kd(i)),...n];this._userIgnored=Pv(c,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new ef(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=ye.resolve(e);return this._watched.has(t)||this._watched.set(t,new Qc(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,i){let s=ye.join(e,t),n=ye.resolve(s);if(i=i??(this._watched.has(s)||this._watched.has(n)),!this._throttle("remove",s,100))return;!i&&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(n)&&this._symlinkPaths.delete(n);let p=s;if(this.options.cwd&&(p=ye.relative(this.options.cwd,s)),this.options.awaitWriteFinish&&this._pendingWrites.has(p)&&this._pendingWrites.get(p).cancelWait()===ze.ADD)return;this._watched.delete(s),this._watched.delete(n);let m=i?ze.UNLINK_DIR:ze.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(i=>i()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let i=this._closers.get(e);i||(i=[],this._closers.set(e,i)),i.push(t)}_readdirp(e,t){if(this.closed)return;let i={type:ze.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},s=vd(e,i);return this._streams.add(s),s.once(bd,()=>{s=void 0}),s.once(Yc,()=>{s&&(this._streams.delete(s),s=void 0)}),s}};function Nd(r,e={}){let t=new tf(e);return t.add(r),t}var Dd=ce(uc()),sr=ce(hr()),Dv=["**/node_modules/**","**/.git/**","**/dist/**","**/.next/**","**/.turbo/**","**/.cache/**","**/coverage/**","**/*.log"],Mv=300,po=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,Dd.default)(),this.initializeIgnoreFilter()}initializeIgnoreFilter(){this.ignoreFilter.add(Dv);let e=Hr.join(this.workspaceRoot,".gitignore");try{if(Ki.existsSync(e)){let t=Ki.readFileSync(e,"utf-8");this.ignoreFilter.add(t)}}catch{}}onFileChanged(e){this.onFileChangedCallback=e}start(){this.watcher||(this.watcher=Nd(this.workspaceRoot,{ignored:e=>{let t=Hr.relative(this.workspaceRoot,e);if(!t||t===".")return!1;let i=t.split(Hr.sep).join("/");return this.ignoreFilter.ignores(i)},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 i=Hr.relative(this.workspaceRoot,e);if(!i)return;let s=this.pendingEvents.get(i);s&&clearTimeout(s);let n=this.pendingTypes.get(i);this.pendingTypes.set(i,this.mergeTypes(n,t));let a=setTimeout(()=>{this.emit(i,this.pendingTypes.get(i)||t),this.pendingEvents.delete(i),this.pendingTypes.delete(i)},Mv);this.pendingEvents.set(i,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 i={path:e,changeType:t,timestamp:new Date().toISOString(),source:"watcher"};if(t!==sr.FileChangeType.DELETE)try{let s=Hr.join(this.workspaceRoot,e),n=Ki.statSync(s);i.size=n.size}catch{}this.onFileChangedCallback?.(i)}dispose(){this.stop(),this.onFileChangedCallback=null}};var Fv={online:!1,viewerCount:0},go=class r{enabled=!1;state={...Fv};altScreenActive=!1;logger;refreshTimer=null;static REFRESH_INTERVAL_MS=1e3;constructor(e){this.logger=e}reservedRows(){return this.enabled&&process.stdout.isTTY?1:0}enable(){if(!process.stdout.isTTY){this.logger.warn("StatusLine: stdout is not a TTY, cannot enable");return}this.enabled=!0,this.installScrollRegion(),this.startRefreshTimer(),this.logger.info("StatusLine enabled")}startRefreshTimer(){this.stopRefreshTimer(),this.refreshTimer=setInterval(()=>{!this.enabled||this.altScreenActive||this.render()},r.REFRESH_INTERVAL_MS)}stopRefreshTimer(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null)}installScrollRegion(){let e=process.stdout.rows;!e||e<2||(process.stdout.write(`\x1B[1;${e-1}r`),process.stdout.write("\x1B[1;1H"))}resetScrollRegion(){process.stdout.write("\x1B[r")}update(e){this.state={...this.state,...e},this.render()}render(){if(!this.enabled||this.altScreenActive)return;let e=process.stdout.rows;if(!e||e<2)return;let t=this.formatLine(),i=`\x1B[1;${e-1}r\x1B7\x1B[${e};1H\x1B[2K${t}\x1B8`;process.stdout.write(i)}clear(){if(!this.enabled)return;let e=process.stdout.rows;!e||e<2||process.stdout.write(`\x1B7\x1B[${e};1H\x1B[2K\x1B8`)}disable(){this.enabled&&(this.stopRefreshTimer(),this.clear(),this.resetScrollRegion(),this.enabled=!1)}inspectPtyOutput(e){if(this.enabled){if(e.includes("\x1B[?1049h")||e.includes("\x1B[?47h")){this.altScreenActive=!0;return}(e.includes("\x1B[?1049l")||e.includes("\x1B[?47l"))&&(this.altScreenActive=!1,this.render())}}getState(){return this.state}isEnabled(){return this.enabled}isAltScreenActive(){return this.altScreenActive}formatLine(){let e=[];if(e.push(this.state.online?"\u25CF online":"\u25CB offline"),this.state.viewerCount>0){let t=this.state.viewerCount===1?"1 viewer":`${this.state.viewerCount} viewers`;e.push(t)}else e.push("no viewers");return this.state.agentName&&e.push(this.state.agentName),this.state.ptyCols&&this.state.ptyRows&&e.push(`${this.state.ptyCols}\xD7${this.state.ptyRows}`)," "+e.join(" \xB7 ")+" "}};async function mo(r,e,t,i){if(i)return process.stderr.write(`Logging in with API key...
34
34
  `),await r.loginWithApiKey(i)?(process.stderr.write(`Login successful.
35
35
  `),!0):(process.stderr.write(`Login failed. Check your API key.
36
36
  `),!1);try{let s=await r.startDeviceCodeFlow();process.stderr.write(`
@@ -43,19 +43,19 @@ tell application "System Events" to get value of property list item "CFBundleNam
43
43
  `),!0):(process.stderr.write(` Login failed or expired.
44
44
 
45
45
  `),!1)}catch(s){return t.error("Login error",s),process.stderr.write(`Login error: ${s instanceof Error?s.message:String(s)}
46
- `),!1}}var $i=ae(hr());function Bv(r){switch(r){case"numbered-choice":return"select";case"free-input":return"input";default:return"confirmation"}}function Md(r,e,t){let i=new Date().toISOString();switch(r){case"working":return e==="idle"?{type:$i.TerminalEventType.SESSION_START,timestamp:i}:null;case"waiting":return{type:$i.TerminalEventType.WAITING_INPUT,timestamp:i,promptType:Bv(t?.type),question:t?.question||"Confirm action?",options:t?.choices?.map(s=>s.label)};case"completed":return{type:$i.TerminalEventType.SESSION_END,timestamp:i,status:"success"};case"error":return e==="working"?{type:$i.TerminalEventType.SESSION_END,timestamp:i,status:"error"}:{type:$i.TerminalEventType.ERROR,timestamp:i,severity:"error",message:"Command failed"};default:return null}}async function jd(r){let{storage:e,config:t,logger:i,machineId:s,notification:n,browser:a,cwd:c,watch:u,statusLine:d,multiViewer:g}=r,m=new go(i);d&&m.enable();let y=t.getServerUrl(),b=new URL(y).host,T=await s.getMachineId(),C=new yt.CryptoService(e,i,b,T);await C.initialize();let H=new yt.AuthService(e,C,s,t,i,n,a,b,T),ge=await H.hasValidToken();ge||await H.refreshAccessToken()||(process.stderr.write(`Not logged in. Starting login flow...
47
- `),await mo(H,a,i)||process.exit(1),ge=!0);let Y;try{let{machineIdSync:w}=await Promise.resolve().then(()=>ae(bc()));Y=w()}catch{Y=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}let A,j=new yt.StatusDetector((w,L,O)=>{if(!I.getStatus().connected)return;let J=A;A=L,I.updateStatus({instanceId:ee,terminalId:w,status:L,prompt:O||void 0,encryptedPrompt:O&&C.encryptPromptInfo(O)||void 0}).catch(()=>{});let Ae=Md(L,J,O);Ae&&I.sendTerminalEvent(ee,w,Ae)}),Q=g?[Bd.Capability.MULTI_VIEWER_RENDER]:[],I=new yt.WebSocketService(H,C,t,i,n,Y,"cli",Q);g&&i.info("Multi-viewer rendering capability advertised");let oe=!1;I.onStatusChange(w=>{if(w==="connected"){if(oe)i.info("Reconnected to termiq.io");else{let L=g?" (multi-viewer mode)":"";process.stderr.write(`Connected to termiq.io${L}
48
- `),oe=!0}m.update({online:!0})}else w==="disconnected"&&(i.info("Disconnected from termiq.io (will retry)"),m.update({online:!1}))}),I.onAuthFailure(()=>{process.stderr.write(`Session expired. Please run "termiq login" again.
49
- `),ut(),process.exit(1)});try{await I.connect()}catch(w){process.stderr.write(`Connection failed: ${w instanceof Error?w.message:String(w)}
50
- `),process.exit(1)}let fe=Fd.basename(c),ee=`cli_${Date.now()}`,ke=C.encryptWorkspaceInfo({name:fe,path:c});await I.registerWorkspace({instanceId:ee,name:ke?void 0:fe,path:ke?void 0:c,encryptedInfo:ke||void 0});let be=new so(i);g&&be.setMultiViewerMode(!0),be.setPreWriteHook(w=>m.inspectPtyOutput(w)),be.setOnResize((w,L)=>{m.update({ptyCols:w,ptyRows:L})});let xe=be.spawn(c,m.reservedRows()),Se=`CLI: ${fe}`,Ge=process.env.SHELL||"/bin/bash",Ie=C.encryptTerminalInfo({name:Se,command:Ge,cwd:c});await I.terminalCreated({instanceId:ee,terminalId:xe,name:Ie?void 0:Se,command:Ie?void 0:Ge,cwd:Ie?void 0:c,encryptedInfo:Ie||void 0,streamId:be.getStreamId()??void 0});let Ye=new yt.FileTransferService(i),Ue=new yt.FileTrackerService(i,c),Pe=new yt.FileListService(i,c),et=u?new po(i,c):null,Xe=I.getSocket();Xe&&Ye.attach(Xe,ee),Ue.onFileChanged((w,L)=>{I.sendFileChangedEvent(ee,w,L)}),Ue.onFileViewTransfer(async(w,L,O)=>{try{await Ye.sendBuffer(w,L,O.path.split("/").pop()||"view",O.mimeType||"text/plain",{purpose:"view",viewMetadata:O})}catch(J){i.error("File view transfer failed",J)}}),I.onFileViewRequest((w,L)=>{Ue.handleViewRequest(w,L)}),I.onFileListRequest((w,L)=>{Pe.handleListRequest(L)}),Pe.onResponse(w=>{I.sendFileListResponse(ee,w)}),I.onFileDownloadRequest(async(w,L,O)=>{try{await Ye.sendFile(w,L,void 0,void 0,O)}catch(J){i.error("File download failed",J)}}),et&&(et.onFileChanged(w=>{I.sendFileChangedEvent(ee,xe,w)}),et.start()),j.startTracking(xe),be.setOnOutput(w=>{I.sendOutput(ee,xe,w),j.processOutput(xe,w),Ue.processOutput(xe,w)}),I.onInput((w,L,O,J)=>{w===xe&&be.write(L,J)}),I.setTerminalActiveCheck(w=>w===xe&&be.isAlive()),I.onResizeRequest((w,L,O)=>{w===xe&&(i.info("Remote resize received",{terminalId:w,cols:L,rows:O}),be.resize(L,O))}),I.onClientAttached(({clientCount:w})=>{be.setSigwinchEnabled(!1),m.update({viewerCount:w}),I.sendInputResume(xe)}),I.onClientDetached(({clientCount:w})=>{w===0&&be.setSigwinchEnabled(!0),m.update({viewerCount:w})}),I.onGetBufferRequest(w=>w===xe?be.getBuffer():null),I.onRedrawRequest(w=>{w===xe&&be.redrawNoResize()}),I.onReconnect(async()=>{try{await I.registerWorkspace({instanceId:ee,name:ke?void 0:fe,path:ke?void 0:c,encryptedInfo:ke||void 0}),await I.terminalCreated({instanceId:ee,terminalId:xe,name:Ie?void 0:Se,command:Ie?void 0:Ge,cwd:Ie?void 0:c,encryptedInfo:Ie||void 0});let w=I.getSocket();w&&Ye.attach(w,ee)}catch(w){i.error("Failed to re-register on reconnect",w)}});function ut(){et?.dispose(),Ye.detach(),Ue.dispose(),Pe.dispose(),j.stopTracking(xe),j.dispose(),I.disposeInputStream(xe),I.terminalClosed({instanceId:ee,terminalId:xe}).catch(()=>{}),I.unregisterWorkspace(ee).catch(()=>{}),I.disconnect(),be.dispose()}be.setOnExit(()=>{m.disable(),process.stderr.write(`Session ended.
51
- `),ut(),process.exit(0)}),process.on("SIGINT",()=>{m.disable(),process.stderr.write(`Session ended.
52
- `),ut(),process.exit(0)}),process.on("SIGTERM",()=>{m.disable(),process.stderr.write(`Session ended.
53
- `),ut(),process.exit(0)})}async function Ud(r){await r.logout(),process.stderr.write(`Logged out.
46
+ `),!1}}var $i=ce(hr());function Bv(r){switch(r){case"numbered-choice":return"select";case"free-input":return"input";default:return"confirmation"}}function Md(r,e,t){let i=new Date().toISOString();switch(r){case"working":return e==="idle"?{type:$i.TerminalEventType.SESSION_START,timestamp:i}:null;case"waiting":return{type:$i.TerminalEventType.WAITING_INPUT,timestamp:i,promptType:Bv(t?.type),question:t?.question||"Confirm action?",options:t?.choices?.map(s=>s.label)};case"completed":return{type:$i.TerminalEventType.SESSION_END,timestamp:i,status:"success"};case"error":return e==="working"?{type:$i.TerminalEventType.SESSION_END,timestamp:i,status:"error"}:{type:$i.TerminalEventType.ERROR,timestamp:i,severity:"error",message:"Command failed"};default:return null}}async function jd(r){let{storage:e,config:t,logger:i,machineId:s,notification:n,browser:a,cwd:c,watch:u,statusLine:d,multiViewer:p}=r,m=new go(i);d&&m.enable();let y=t.getServerUrl(),E=new URL(y).host,T=await s.getMachineId(),O=new _t.CryptoService(e,i,E,T);await O.initialize();let H=new _t.AuthService(e,O,s,t,i,n,a,E,T),me=await H.hasValidToken();me||await H.refreshAccessToken()||(process.stderr.write(`Not logged in. Starting login flow...
47
+ `),await mo(H,a,i)||process.exit(1),me=!0);let X;try{let{machineIdSync:S}=await Promise.resolve().then(()=>ce(bc()));X=S()}catch{X=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}let A,j=new _t.StatusDetector((S,C,Y)=>{if(!I.getStatus().connected)return;let ve=A;A=C,I.updateStatus({instanceId:Q,terminalId:S,status:C,prompt:Y||void 0,encryptedPrompt:Y&&O.encryptPromptInfo(Y)||void 0}).catch(()=>{});let et=Md(C,ve,Y);et&&I.sendTerminalEvent(Q,S,et)}),te=p?[Bd.Capability.MULTI_VIEWER_RENDER]:[],I=new _t.WebSocketService(H,O,t,i,n,X,"cli",te);p&&i.info("Multi-viewer rendering capability advertised");let ae=!1;I.onStatusChange(S=>{if(S==="connected"){if(ae)i.info("Reconnected to termiq.io");else{let C=p?" (multi-viewer mode)":"";process.stderr.write(`Connected to termiq.io${C}
48
+ `),ae=!0}m.update({online:!0})}else S==="disconnected"&&(i.info("Disconnected from termiq.io (will retry)"),m.update({online:!1}))}),I.onAuthFailure(()=>{process.stderr.write(`Session expired. Please run "termiq login" again.
49
+ `),N(),process.exit(1)});try{await I.connect()}catch(S){process.stderr.write(`Connection failed: ${S instanceof Error?S.message:String(S)}
50
+ `),process.exit(1)}let ue=Fd.basename(c),Q=`cli_${Date.now()}`,Re=O.encryptWorkspaceInfo({name:ue,path:c});await I.registerWorkspace({instanceId:Q,name:Re?void 0:ue,path:Re?void 0:c,encryptedInfo:Re||void 0});let Ee=new so(i);p&&Ee.setMultiViewerMode(!0),Ee.setPreWriteHook(S=>m.inspectPtyOutput(S));let Je=null;Ee.setOnResize((S,C)=>{m.update({ptyCols:S,ptyRows:C}),p&&Je&&I.sendPtyResized(Q,Je,S,C)});let ee=Ee.spawn(c,m.reservedRows());Je=ee,p&&I.sendPtyResized(Q,ee,Ee.getPtyCols(),Ee.getPtyRows());let Ye=`CLI: ${ue}`,Be=process.env.SHELL||"/bin/bash",je=O.encryptTerminalInfo({name:Ye,command:Be,cwd:c});await I.terminalCreated({instanceId:Q,terminalId:ee,name:je?void 0:Ye,command:je?void 0:Be,cwd:je?void 0:c,encryptedInfo:je||void 0,streamId:Ee.getStreamId()??void 0});let Ue=new _t.FileTransferService(i),Te=new _t.FileTrackerService(i,c),nt=new _t.FileListService(i,c),Ve=u?new po(i,c):null,yt=I.getSocket();yt&&Ue.attach(yt,Q),Te.onFileChanged((S,C)=>{I.sendFileChangedEvent(Q,S,C)}),Te.onFileViewTransfer(async(S,C,Y)=>{try{await Ue.sendBuffer(S,C,Y.path.split("/").pop()||"view",Y.mimeType||"text/plain",{purpose:"view",viewMetadata:Y})}catch(ve){i.error("File view transfer failed",ve)}}),I.onFileViewRequest((S,C)=>{Te.handleViewRequest(S,C)}),I.onFileListRequest((S,C)=>{nt.handleListRequest(C)}),nt.onResponse(S=>{I.sendFileListResponse(Q,S)}),I.onFileDownloadRequest(async(S,C,Y)=>{try{await Ue.sendFile(S,C,void 0,void 0,Y)}catch(ve){i.error("File download failed",ve)}}),Ve&&(Ve.onFileChanged(S=>{I.sendFileChangedEvent(Q,ee,S)}),Ve.start()),j.startTracking(ee),Ee.setOnOutput(S=>{I.sendOutput(Q,ee,S),j.processOutput(ee,S),Te.processOutput(ee,S)}),I.onInput((S,C,Y,ve)=>{S===ee&&Ee.write(C,ve)}),I.setTerminalActiveCheck(S=>S===ee&&Ee.isAlive()),I.onResizeRequest((S,C,Y)=>{S===ee&&(i.info("Remote resize received",{terminalId:S,cols:C,rows:Y}),Ee.resize(C,Y))}),I.onClientAttached(({clientCount:S})=>{Ee.setSigwinchEnabled(!1),m.update({viewerCount:S}),I.sendInputResume(ee)}),I.onClientDetached(({clientCount:S})=>{S===0&&Ee.setSigwinchEnabled(!0),m.update({viewerCount:S})}),I.onGetBufferRequest(S=>S===ee?Ee.getBuffer():null),I.onRedrawRequest(S=>{S===ee&&Ee.redrawNoResize()}),I.onReconnect(async()=>{try{await I.registerWorkspace({instanceId:Q,name:Re?void 0:ue,path:Re?void 0:c,encryptedInfo:Re||void 0}),await I.terminalCreated({instanceId:Q,terminalId:ee,name:je?void 0:Ye,command:je?void 0:Be,cwd:je?void 0:c,encryptedInfo:je||void 0});let S=I.getSocket();S&&Ue.attach(S,Q)}catch(S){i.error("Failed to re-register on reconnect",S)}});function N(){Ve?.dispose(),Ue.detach(),Te.dispose(),nt.dispose(),j.stopTracking(ee),j.dispose(),I.disposeInputStream(ee),I.terminalClosed({instanceId:Q,terminalId:ee}).catch(()=>{}),I.unregisterWorkspace(Q).catch(()=>{}),I.disconnect(),Ee.dispose()}Ee.setOnExit(()=>{m.disable(),process.stderr.write(`Session ended.
51
+ `),N(),process.exit(0)}),process.on("SIGINT",()=>{m.disable(),process.stderr.write(`Session ended.
52
+ `),N(),process.exit(0)}),process.on("SIGTERM",()=>{m.disable(),process.stderr.write(`Session ended.
53
+ `),N(),process.exit(0)})}async function Ud(r){await r.logout(),process.stderr.write(`Logged out.
54
54
  `)}async function qd(r){let e=await r.hasValidToken(),t=await r.getAgentId();e?(process.stderr.write(`Status: logged in
55
55
  `),t&&process.stderr.write(`Agent ID: ${t}
56
56
  `)):(process.stderr.write(`Status: not logged in
57
57
  `),process.stderr.write(`Run 'termiq login' to authenticate.
58
- `))}var Mt=ae(ws()),Ne=process.argv.slice(2);(Ne.includes("--help")||Ne.includes("-h"))&&(process.stderr.write(`
58
+ `))}var Mt=ce(Es()),Ie=process.argv.slice(2);(Ie.includes("--help")||Ie.includes("-h"))&&(process.stderr.write(`
59
59
  termiq v${io()} \u2014 Access terminals from anywhere
60
60
 
61
61
  Usage:
@@ -83,10 +83,10 @@ tell application "System Events" to get value of property list item "CFBundleNam
83
83
  Environment:
84
84
  TERMIQ_TOKEN API key (equivalent to --token)
85
85
 
86
- `),process.exit(0));(Ne.includes("--version")||Ne.includes("-V"))&&(process.stdout.write(`${io()}
87
- `),process.exit(0));var Wd=fd(Ne,Vc,cd);Wd&&(process.stderr.write(`Unknown flag: ${Wd}
86
+ `),process.exit(0));(Ie.includes("--version")||Ie.includes("-V"))&&(process.stdout.write(`${io()}
87
+ `),process.exit(0));var Wd=fd(Ie,Vc,cd);Wd&&(process.stderr.write(`Unknown flag: ${Wd}
88
88
  Run 'termiq --help' for usage.
89
- `),process.exit(1));var Hd=ad(Ne,Vc)??"start",jv=Ne.includes("--verbose")||Ne.includes("-v"),Uv=Ne.includes("--watch")||Ne.includes("-w"),qv=Ne.includes("--log-to-file"),Wv=Ne.includes("--statusline"),Hv=Ne.includes("--multi-viewer"),Vv=Ne.find(r=>r.startsWith("--token="))?.split("=")[1]||(Ne.includes("--token")?Ne[Ne.indexOf("--token")+1]:void 0),Vd=Ne.find(r=>r.startsWith("--server="))?.split("=")[1]||(Ne.includes("--server")?Ne[Ne.indexOf("--server")+1]:void 0),rf=Ne.find(r=>r.startsWith("--log-level="))?.split("=")[1]||(Ne.includes("--log-level")?Ne[Ne.indexOf("--log-level")+1]:void 0),Kv=["silent","error","warn","info","debug"],zv=rf&&Kv.includes(rf)?rf:jv?"info":"silent",$v=Ne.find(r=>r.startsWith("--cid="))?.split("=")[1]||(Ne.includes("--cid")?Ne[Ne.indexOf("--cid")+1]:void 0),Gv=$v||(0,Mt.generateCorrelationId)(),Yv=process.env.TERMIQ_TOKEN,xr=new bs(zv,qv),hi=new Zi,br=new Qi(Vd?{serverUrl:Vd}:void 0),di=new Ss,_o=new Ts(xr),As=new ks;async function Xv(){switch(Hd){case"start":case void 0:{Hv&&await br.setMultiViewer(!0);let r=br.getMultiViewer();await jd({storage:hi,config:br,logger:xr,machineId:di,notification:_o,browser:As,cwd:process.cwd(),watch:Uv,statusLine:Wv,multiViewer:r});break}case"login":{let r=new URL(br.getServerUrl()).host,e=await di.getMachineId(),t=new Mt.CryptoService(hi,xr,r,e);await t.initialize();let i=new Mt.AuthService(hi,t,di,br,xr,_o,As,r,e),s=await mo(i,As,xr,Vv||Yv);process.exit(s?0:1);break}case"logout":{let r=new URL(br.getServerUrl()).host,e=await di.getMachineId(),t=new Mt.CryptoService(hi,xr,r,e);await t.initialize();let i=new Mt.AuthService(hi,t,di,br,xr,_o,As,r,e);await Ud(i),process.exit(0);break}case"status":{let r=new URL(br.getServerUrl()).host,e=await di.getMachineId(),t=new Mt.CryptoService(hi,xr,r,e);await t.initialize();let i=new Mt.AuthService(hi,t,di,br,xr,_o,As,r,e);await qd(i),process.exit(0);break}case"version":{process.stdout.write(`${io()}
89
+ `),process.exit(1));var Hd=ad(Ie,Vc)??"start",jv=Ie.includes("--verbose")||Ie.includes("-v"),Uv=Ie.includes("--watch")||Ie.includes("-w"),qv=Ie.includes("--log-to-file"),Wv=Ie.includes("--statusline"),Hv=Ie.includes("--multi-viewer"),Vv=Ie.find(r=>r.startsWith("--token="))?.split("=")[1]||(Ie.includes("--token")?Ie[Ie.indexOf("--token")+1]:void 0),Vd=Ie.find(r=>r.startsWith("--server="))?.split("=")[1]||(Ie.includes("--server")?Ie[Ie.indexOf("--server")+1]:void 0),rf=Ie.find(r=>r.startsWith("--log-level="))?.split("=")[1]||(Ie.includes("--log-level")?Ie[Ie.indexOf("--log-level")+1]:void 0),zv=["silent","error","warn","info","debug"],Kv=rf&&zv.includes(rf)?rf:jv?"info":"silent",$v=Ie.find(r=>r.startsWith("--cid="))?.split("=")[1]||(Ie.includes("--cid")?Ie[Ie.indexOf("--cid")+1]:void 0),Gv=$v||(0,Mt.generateCorrelationId)(),Yv=process.env.TERMIQ_TOKEN,xr=new bs(Kv,qv),hi=new Zi,br=new Qi(Vd?{serverUrl:Vd}:void 0),di=new Ss,_o=new Ts(xr),As=new ks;async function Xv(){switch(Hd){case"start":case void 0:{Hv&&await br.setMultiViewer(!0);let r=br.getMultiViewer();await jd({storage:hi,config:br,logger:xr,machineId:di,notification:_o,browser:As,cwd:process.cwd(),watch:Uv,statusLine:Wv,multiViewer:r});break}case"login":{let r=new URL(br.getServerUrl()).host,e=await di.getMachineId(),t=new Mt.CryptoService(hi,xr,r,e);await t.initialize();let i=new Mt.AuthService(hi,t,di,br,xr,_o,As,r,e),s=await mo(i,As,xr,Vv||Yv);process.exit(s?0:1);break}case"logout":{let r=new URL(br.getServerUrl()).host,e=await di.getMachineId(),t=new Mt.CryptoService(hi,xr,r,e);await t.initialize();let i=new Mt.AuthService(hi,t,di,br,xr,_o,As,r,e);await Ud(i),process.exit(0);break}case"status":{let r=new URL(br.getServerUrl()).host,e=await di.getMachineId(),t=new Mt.CryptoService(hi,xr,r,e);await t.initialize();let i=new Mt.AuthService(hi,t,di,br,xr,_o,As,r,e);await qd(i),process.exit(0);break}case"version":{process.stdout.write(`${io()}
90
90
  `),process.exit(0);break}case"help":{process.stderr.write(`Run 'termiq --help' for full usage.
91
91
  `),process.exit(0);break}default:process.stderr.write(`Unknown command: ${Hd}
92
92
  Run 'termiq --help' for usage.