@termiq/cli 3.17.10 → 3.17.12

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,38 +1,38 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var mp=Object.create;var zo=Object.defineProperty;var yp=Object.getOwnPropertyDescriptor;var _p=Object.getOwnPropertyNames;var vp=Object.getPrototypeOf,bp=Object.prototype.hasOwnProperty;var Kt=(r,e)=>()=>(r&&(e=r(r=0)),e);var M=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ep=(r,e)=>{for(var t in e)zo(r,t,{get:e[t],enumerable:!0})},wp=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of _p(e))!bp.call(r,n)&&n!==t&&zo(r,n,{get:()=>e[n],enumerable:!(i=yp(e,n))||i.enumerable});return r};var fe=(r,e,t)=>(t=r!=null?mp(vp(r)):{},wp(e||!r||!r.__esModule?zo(t,"default",{value:r,enumerable:!0}):t,r));var os=M(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.generateCorrelationId=Tp;mn.runWithCorrelation=Cp;mn.getCurrentCorrelationId=kp;var Sp=require("async_hooks");function Tp(){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 Af=new Sp.AsyncLocalStorage;function Cp(r,e){return Af.run(r,e)}function kp(){return Af.getStore()}});var If=M(Ai=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:!0});Ai.LOG_LEVELS=void 0;Ai.shouldLog=Pp;Ai.formatLogLine=Ap;var Op=os();Ai.LOG_LEVELS=["silent","error","warn","info","debug"];var Rf={silent:0,error:1,warn:2,info:3,debug:4};function Pp(r,e){return Rf[r]<=Rf[e]}function Ap(r,e,t,i){let n={ts:new Date().toISOString(),level:r,src:e,msg:t},s=(0,Op.getCurrentCorrelationId)();s&&(n.cid=s);let a=i;a.length>0&&typeof a[0]=="object"&&a[0]!==null&&!(a[0]instanceof Error)&&!Array.isArray(a[0])&&(n.ctx=a[0],a=a.slice(1));let c=[...a].reverse().find(u=>u instanceof Error);c&&(n.err={message:c.message,stack:c.stack,name:c.name},a=a.filter(u=>u!==c)),a.length>0&&(n.args=a);try{return JSON.stringify(n)}catch{return JSON.stringify({ts:n.ts,level:r,src:e,msg:t,_unserializable:!0})}}});var Lf=M(Dr=>{"use strict";Object.defineProperty(Dr,"__esModule",{value:!0});Dr.formatLogLine=Dr.shouldLog=Dr.LOG_LEVELS=void 0;var $o=If();Object.defineProperty(Dr,"LOG_LEVELS",{enumerable:!0,get:function(){return $o.LOG_LEVELS}});Object.defineProperty(Dr,"shouldLog",{enumerable:!0,get:function(){return $o.shouldLog}});Object.defineProperty(Dr,"formatLogLine",{enumerable:!0,get:function(){return $o.formatLogLine}})});var Nf=M(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.CircularBuffer=void 0;var Go=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}};as.CircularBuffer=Go});var fs=M(cs=>{"use strict";Object.defineProperty(cs,"__esModule",{value:!0});cs.getApiUrl=Rp;cs.getWsUrl=Ip;function Rp(r){return`${r.getServerUrl()}/api`}function Ip(r){let e=r.getServerUrl();return e.startsWith("https://")?e.replace(/^https:\/\//,"wss://"):e.replace(/^http:\/\//,"ws://")}});var Ff=M(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.getCurrentCorrelationId=vt.runWithCorrelation=vt.generateCorrelationId=vt.getWsUrl=vt.getApiUrl=vt.CircularBuffer=void 0;var Lp=Nf();Object.defineProperty(vt,"CircularBuffer",{enumerable:!0,get:function(){return Lp.CircularBuffer}});var Mf=fs();Object.defineProperty(vt,"getApiUrl",{enumerable:!0,get:function(){return Mf.getApiUrl}});Object.defineProperty(vt,"getWsUrl",{enumerable:!0,get:function(){return Mf.getWsUrl}});var Yo=os();Object.defineProperty(vt,"generateCorrelationId",{enumerable:!0,get:function(){return Yo.generateCorrelationId}});Object.defineProperty(vt,"runWithCorrelation",{enumerable:!0,get:function(){return Yo.runWithCorrelation}});Object.defineProperty(vt,"getCurrentCorrelationId",{enumerable:!0,get:function(){return Yo.getCurrentCorrelationId}})});var Bf=M(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0})});var Uf=M(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0})});var qf=M(us=>{"use strict";Object.defineProperty(us,"__esModule",{value:!0});us.PLAN_LIMITS=void 0;us.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 Wf=M(Kf=>{"use strict";Object.defineProperty(Kf,"__esModule",{value:!0})});var Hf=M(Jt=>{"use strict";var Np=Jt&&Jt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),ls=Jt&&Jt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Np(e,r,t)};Object.defineProperty(Jt,"__esModule",{value:!0});ls(Bf(),Jt);ls(Uf(),Jt);ls(qf(),Jt);ls(Wf(),Jt)});var Vf=M(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.API_VERSION=It.WS_NAMESPACES=It.TIMEOUTS=It.STATUS_PATTERNS=It.TERMINAL_STATUSES=void 0;It.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"}};It.STATUS_PATTERNS={idle:[/[❯$]\s*$/,/>\s*$/],waiting:[/\[Y\/n\]/i,/\(y\/N\)/i,/Continue\?/i,/proceed\?/i],completed:[/✓/,/Done/,/Completed/,/Success/],error:[/Error/,/Failed/,/✕/,/Exception/]};It.TIMEOUTS={HEARTBEAT_INTERVAL:3e4,OFFLINE_THRESHOLD:6e4,DEVICE_CODE_EXPIRY:9e5,DEVICE_CODE_POLL_INTERVAL:5e3};It.WS_NAMESPACES={AGENT:"/agent",CLIENT:"/client"};It.API_VERSION="v1"});var zf=M(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.isMultiRecipientPayload=Mp;hs.isEncryptedPayload=Fp;function Mp(r){return typeof r=="object"&&r!==null&&"v"in r&&r.v===2&&"recipients"in r&&Array.isArray(r.recipients)}function Fp(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 Xo=M(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.KX_SIG_VERSION=Zt.KX_FINGERPRINT_LABEL=Zt.KX_ACK_LABEL=Zt.KX_SIGN_LABEL=void 0;Zt.KX_SIGN_LABEL="termiq-kx-v1";Zt.KX_ACK_LABEL="termiq-kxack-v1";Zt.KX_FINGERPRINT_LABEL="termiq-fp-v1";Zt.KX_SIG_VERSION=1});var yn=M((nE,ds)=>{(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),n=new Uint8Array(32);n[0]=9;var s=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]),_=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 S(f,h,l,o,g){var v,b=0;for(v=0;v<g;v++)b|=f[h+v]^l[o+v];return(1&b-1>>>8)-1}function T(f,h,l,o){return S(f,h,l,o,16)}function z(f,h,l,o){return S(f,h,l,o,32)}function ge(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,b=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,k=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,D=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,J=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,W=h[0]&255|(h[1]&255)<<8|(h[2]&255)<<16|(h[3]&255)<<24,Pe=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,ne=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,se=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,he=l[16]&255|(l[17]&255)<<8|(l[18]&255)<<16|(l[19]&255)<<24,le=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,oe=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,ce=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,ae=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,$=g,Q=v,H=b,G=k,Y=D,K=J,w=W,x=Pe,I=V,C=ne,O=se,F=he,ie=le,de=oe,me=ce,pe=ae,y,ve=0;ve<20;ve+=2)y=$+ie|0,Y^=y<<7|y>>>25,y=Y+$|0,I^=y<<9|y>>>23,y=I+Y|0,ie^=y<<13|y>>>19,y=ie+I|0,$^=y<<18|y>>>14,y=K+Q|0,C^=y<<7|y>>>25,y=C+K|0,de^=y<<9|y>>>23,y=de+C|0,Q^=y<<13|y>>>19,y=Q+de|0,K^=y<<18|y>>>14,y=O+w|0,me^=y<<7|y>>>25,y=me+O|0,H^=y<<9|y>>>23,y=H+me|0,w^=y<<13|y>>>19,y=w+H|0,O^=y<<18|y>>>14,y=pe+F|0,G^=y<<7|y>>>25,y=G+pe|0,x^=y<<9|y>>>23,y=x+G|0,F^=y<<13|y>>>19,y=F+x|0,pe^=y<<18|y>>>14,y=$+G|0,Q^=y<<7|y>>>25,y=Q+$|0,H^=y<<9|y>>>23,y=H+Q|0,G^=y<<13|y>>>19,y=G+H|0,$^=y<<18|y>>>14,y=K+Y|0,w^=y<<7|y>>>25,y=w+K|0,x^=y<<9|y>>>23,y=x+w|0,Y^=y<<13|y>>>19,y=Y+x|0,K^=y<<18|y>>>14,y=O+C|0,F^=y<<7|y>>>25,y=F+O|0,I^=y<<9|y>>>23,y=I+F|0,C^=y<<13|y>>>19,y=C+I|0,O^=y<<18|y>>>14,y=pe+me|0,ie^=y<<7|y>>>25,y=ie+pe|0,de^=y<<9|y>>>23,y=de+ie|0,me^=y<<13|y>>>19,y=me+de|0,pe^=y<<18|y>>>14;$=$+g|0,Q=Q+v|0,H=H+b|0,G=G+k|0,Y=Y+D|0,K=K+J|0,w=w+W|0,x=x+Pe|0,I=I+V|0,C=C+ne|0,O=O+se|0,F=F+he|0,ie=ie+le|0,de=de+oe|0,me=me+ce|0,pe=pe+ae|0,f[0]=$>>>0&255,f[1]=$>>>8&255,f[2]=$>>>16&255,f[3]=$>>>24&255,f[4]=Q>>>0&255,f[5]=Q>>>8&255,f[6]=Q>>>16&255,f[7]=Q>>>24&255,f[8]=H>>>0&255,f[9]=H>>>8&255,f[10]=H>>>16&255,f[11]=H>>>24&255,f[12]=G>>>0&255,f[13]=G>>>8&255,f[14]=G>>>16&255,f[15]=G>>>24&255,f[16]=Y>>>0&255,f[17]=Y>>>8&255,f[18]=Y>>>16&255,f[19]=Y>>>24&255,f[20]=K>>>0&255,f[21]=K>>>8&255,f[22]=K>>>16&255,f[23]=K>>>24&255,f[24]=w>>>0&255,f[25]=w>>>8&255,f[26]=w>>>16&255,f[27]=w>>>24&255,f[28]=x>>>0&255,f[29]=x>>>8&255,f[30]=x>>>16&255,f[31]=x>>>24&255,f[32]=I>>>0&255,f[33]=I>>>8&255,f[34]=I>>>16&255,f[35]=I>>>24&255,f[36]=C>>>0&255,f[37]=C>>>8&255,f[38]=C>>>16&255,f[39]=C>>>24&255,f[40]=O>>>0&255,f[41]=O>>>8&255,f[42]=O>>>16&255,f[43]=O>>>24&255,f[44]=F>>>0&255,f[45]=F>>>8&255,f[46]=F>>>16&255,f[47]=F>>>24&255,f[48]=ie>>>0&255,f[49]=ie>>>8&255,f[50]=ie>>>16&255,f[51]=ie>>>24&255,f[52]=de>>>0&255,f[53]=de>>>8&255,f[54]=de>>>16&255,f[55]=de>>>24&255,f[56]=me>>>0&255,f[57]=me>>>8&255,f[58]=me>>>16&255,f[59]=me>>>24&255,f[60]=pe>>>0&255,f[61]=pe>>>8&255,f[62]=pe>>>16&255,f[63]=pe>>>24&255}function ee(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,b=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,k=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,D=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,J=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,W=h[0]&255|(h[1]&255)<<8|(h[2]&255)<<16|(h[3]&255)<<24,Pe=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,ne=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,se=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,he=l[16]&255|(l[17]&255)<<8|(l[18]&255)<<16|(l[19]&255)<<24,le=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,oe=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,ce=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,ae=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,$=g,Q=v,H=b,G=k,Y=D,K=J,w=W,x=Pe,I=V,C=ne,O=se,F=he,ie=le,de=oe,me=ce,pe=ae,y,ve=0;ve<20;ve+=2)y=$+ie|0,Y^=y<<7|y>>>25,y=Y+$|0,I^=y<<9|y>>>23,y=I+Y|0,ie^=y<<13|y>>>19,y=ie+I|0,$^=y<<18|y>>>14,y=K+Q|0,C^=y<<7|y>>>25,y=C+K|0,de^=y<<9|y>>>23,y=de+C|0,Q^=y<<13|y>>>19,y=Q+de|0,K^=y<<18|y>>>14,y=O+w|0,me^=y<<7|y>>>25,y=me+O|0,H^=y<<9|y>>>23,y=H+me|0,w^=y<<13|y>>>19,y=w+H|0,O^=y<<18|y>>>14,y=pe+F|0,G^=y<<7|y>>>25,y=G+pe|0,x^=y<<9|y>>>23,y=x+G|0,F^=y<<13|y>>>19,y=F+x|0,pe^=y<<18|y>>>14,y=$+G|0,Q^=y<<7|y>>>25,y=Q+$|0,H^=y<<9|y>>>23,y=H+Q|0,G^=y<<13|y>>>19,y=G+H|0,$^=y<<18|y>>>14,y=K+Y|0,w^=y<<7|y>>>25,y=w+K|0,x^=y<<9|y>>>23,y=x+w|0,Y^=y<<13|y>>>19,y=Y+x|0,K^=y<<18|y>>>14,y=O+C|0,F^=y<<7|y>>>25,y=F+O|0,I^=y<<9|y>>>23,y=I+F|0,C^=y<<13|y>>>19,y=C+I|0,O^=y<<18|y>>>14,y=pe+me|0,ie^=y<<7|y>>>25,y=ie+pe|0,de^=y<<9|y>>>23,y=de+ie|0,me^=y<<13|y>>>19,y=me+de|0,pe^=y<<18|y>>>14;f[0]=$>>>0&255,f[1]=$>>>8&255,f[2]=$>>>16&255,f[3]=$>>>24&255,f[4]=K>>>0&255,f[5]=K>>>8&255,f[6]=K>>>16&255,f[7]=K>>>24&255,f[8]=O>>>0&255,f[9]=O>>>8&255,f[10]=O>>>16&255,f[11]=O>>>24&255,f[12]=pe>>>0&255,f[13]=pe>>>8&255,f[14]=pe>>>16&255,f[15]=pe>>>24&255,f[16]=w>>>0&255,f[17]=w>>>8&255,f[18]=w>>>16&255,f[19]=w>>>24&255,f[20]=x>>>0&255,f[21]=x>>>8&255,f[22]=x>>>16&255,f[23]=x>>>24&255,f[24]=I>>>0&255,f[25]=I>>>8&255,f[26]=I>>>16&255,f[27]=I>>>24&255,f[28]=C>>>0&255,f[29]=C>>>8&255,f[30]=C>>>16&255,f[31]=C>>>24&255}function A(f,h,l,o){ge(f,h,l,o)}function B(f,h,l,o){ee(f,h,l,o)}var re=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function q(f,h,l,o,g,v,b){var k=new Uint8Array(16),D=new Uint8Array(64),J,W;for(W=0;W<16;W++)k[W]=0;for(W=0;W<8;W++)k[W]=v[W];for(;g>=64;){for(A(D,k,b,re),W=0;W<64;W++)f[h+W]=l[o+W]^D[W];for(J=1,W=8;W<16;W++)J=J+(k[W]&255)|0,k[W]=J&255,J>>>=8;g-=64,h+=64,o+=64}if(g>0)for(A(D,k,b,re),W=0;W<g;W++)f[h+W]=l[o+W]^D[W];return 0}function U(f,h,l,o,g){var v=new Uint8Array(16),b=new Uint8Array(64),k,D;for(D=0;D<16;D++)v[D]=0;for(D=0;D<8;D++)v[D]=o[D];for(;l>=64;){for(A(b,v,g,re),D=0;D<64;D++)f[h+D]=b[D];for(k=1,D=8;D<16;D++)k=k+(v[D]&255)|0,v[D]=k&255,k>>>=8;l-=64,h+=64}if(l>0)for(A(b,v,g,re),D=0;D<l;D++)f[h+D]=b[D];return 0}function ye(f,h,l,o,g){var v=new Uint8Array(32);B(v,o,g,re);for(var b=new Uint8Array(8),k=0;k<8;k++)b[k]=o[k+16];return U(f,h,l,b,v)}function xe(f,h,l,o,g,v,b){var k=new Uint8Array(32);B(k,v,b,re);for(var D=new Uint8Array(8),J=0;J<8;J++)D[J]=v[J+16];return q(f,h,l,o,g,D,k)}var ue=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,b,k,D;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,b=f[10]&255|(f[11]&255)<<8,this.r[6]=(v>>>14|b<<2)&8191,k=f[12]&255|(f[13]&255)<<8,this.r[7]=(b>>>11|k<<5)&8065,D=f[14]&255|(f[15]&255)<<8,this.r[8]=(k>>>8|D<<8)&8191,this.r[9]=D>>>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};ue.prototype.blocks=function(f,h,l){for(var o=this.fin?0:2048,g,v,b,k,D,J,W,Pe,V,ne,se,he,le,oe,ce,ae,$,Q,H,G=this.h[0],Y=this.h[1],K=this.h[2],w=this.h[3],x=this.h[4],I=this.h[5],C=this.h[6],O=this.h[7],F=this.h[8],ie=this.h[9],de=this.r[0],me=this.r[1],pe=this.r[2],y=this.r[3],ve=this.r[4],Ae=this.r[5],Re=this.r[6],_e=this.r[7],Ce=this.r[8],ke=this.r[9];l>=16;)g=f[h+0]&255|(f[h+1]&255)<<8,G+=g&8191,v=f[h+2]&255|(f[h+3]&255)<<8,Y+=(g>>>13|v<<3)&8191,b=f[h+4]&255|(f[h+5]&255)<<8,K+=(v>>>10|b<<6)&8191,k=f[h+6]&255|(f[h+7]&255)<<8,w+=(b>>>7|k<<9)&8191,D=f[h+8]&255|(f[h+9]&255)<<8,x+=(k>>>4|D<<12)&8191,I+=D>>>1&8191,J=f[h+10]&255|(f[h+11]&255)<<8,C+=(D>>>14|J<<2)&8191,W=f[h+12]&255|(f[h+13]&255)<<8,O+=(J>>>11|W<<5)&8191,Pe=f[h+14]&255|(f[h+15]&255)<<8,F+=(W>>>8|Pe<<8)&8191,ie+=Pe>>>5|o,V=0,ne=V,ne+=G*de,ne+=Y*(5*ke),ne+=K*(5*Ce),ne+=w*(5*_e),ne+=x*(5*Re),V=ne>>>13,ne&=8191,ne+=I*(5*Ae),ne+=C*(5*ve),ne+=O*(5*y),ne+=F*(5*pe),ne+=ie*(5*me),V+=ne>>>13,ne&=8191,se=V,se+=G*me,se+=Y*de,se+=K*(5*ke),se+=w*(5*Ce),se+=x*(5*_e),V=se>>>13,se&=8191,se+=I*(5*Re),se+=C*(5*Ae),se+=O*(5*ve),se+=F*(5*y),se+=ie*(5*pe),V+=se>>>13,se&=8191,he=V,he+=G*pe,he+=Y*me,he+=K*de,he+=w*(5*ke),he+=x*(5*Ce),V=he>>>13,he&=8191,he+=I*(5*_e),he+=C*(5*Re),he+=O*(5*Ae),he+=F*(5*ve),he+=ie*(5*y),V+=he>>>13,he&=8191,le=V,le+=G*y,le+=Y*pe,le+=K*me,le+=w*de,le+=x*(5*ke),V=le>>>13,le&=8191,le+=I*(5*Ce),le+=C*(5*_e),le+=O*(5*Re),le+=F*(5*Ae),le+=ie*(5*ve),V+=le>>>13,le&=8191,oe=V,oe+=G*ve,oe+=Y*y,oe+=K*pe,oe+=w*me,oe+=x*de,V=oe>>>13,oe&=8191,oe+=I*(5*ke),oe+=C*(5*Ce),oe+=O*(5*_e),oe+=F*(5*Re),oe+=ie*(5*Ae),V+=oe>>>13,oe&=8191,ce=V,ce+=G*Ae,ce+=Y*ve,ce+=K*y,ce+=w*pe,ce+=x*me,V=ce>>>13,ce&=8191,ce+=I*de,ce+=C*(5*ke),ce+=O*(5*Ce),ce+=F*(5*_e),ce+=ie*(5*Re),V+=ce>>>13,ce&=8191,ae=V,ae+=G*Re,ae+=Y*Ae,ae+=K*ve,ae+=w*y,ae+=x*pe,V=ae>>>13,ae&=8191,ae+=I*me,ae+=C*de,ae+=O*(5*ke),ae+=F*(5*Ce),ae+=ie*(5*_e),V+=ae>>>13,ae&=8191,$=V,$+=G*_e,$+=Y*Re,$+=K*Ae,$+=w*ve,$+=x*y,V=$>>>13,$&=8191,$+=I*pe,$+=C*me,$+=O*de,$+=F*(5*ke),$+=ie*(5*Ce),V+=$>>>13,$&=8191,Q=V,Q+=G*Ce,Q+=Y*_e,Q+=K*Re,Q+=w*Ae,Q+=x*ve,V=Q>>>13,Q&=8191,Q+=I*y,Q+=C*pe,Q+=O*me,Q+=F*de,Q+=ie*(5*ke),V+=Q>>>13,Q&=8191,H=V,H+=G*ke,H+=Y*Ce,H+=K*_e,H+=w*Re,H+=x*Ae,V=H>>>13,H&=8191,H+=I*ve,H+=C*y,H+=O*pe,H+=F*me,H+=ie*de,V+=H>>>13,H&=8191,V=(V<<2)+V|0,V=V+ne|0,ne=V&8191,V=V>>>13,se+=V,G=ne,Y=se,K=he,w=le,x=oe,I=ce,C=ae,O=$,F=Q,ie=H,h+=16,l-=16;this.h[0]=G,this.h[1]=Y,this.h[2]=K,this.h[3]=w,this.h[4]=x,this.h[5]=I,this.h[6]=C,this.h[7]=O,this.h[8]=F,this.h[9]=ie},ue.prototype.finish=function(f,h){var l=new Uint16Array(10),o,g,v,b;if(this.leftover){for(b=this.leftover,this.buffer[b++]=1;b<16;b++)this.buffer[b]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(o=this.h[1]>>>13,this.h[1]&=8191,b=2;b<10;b++)this.h[b]+=o,o=this.h[b]>>>13,this.h[b]&=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,b=1;b<10;b++)l[b]=this.h[b]+o,o=l[b]>>>13,l[b]&=8191;for(l[9]-=8192,g=(o^1)-1,b=0;b<10;b++)l[b]&=g;for(g=~g,b=0;b<10;b++)this.h[b]=this.h[b]&g|l[b];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,b=1;b<8;b++)v=(this.h[b]+this.pad[b]|0)+(v>>>16)|0,this.h[b]=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},ue.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 rt(f,h,l,o,g,v){var b=new ue(v);return b.update(l,o,g),b.finish(f,h),0}function Ee(f,h,l,o,g,v){var b=new Uint8Array(16);return rt(b,0,l,o,g,v),T(f,h,b,0)}function Se(f,h,l,o,g){var v;if(l<32)return-1;for(xe(f,0,h,0,l,o,g),rt(f,16,f,32,l-32,f),v=0;v<16;v++)f[v]=0;return 0}function be(f,h,l,o,g){var v,b=new Uint8Array(32);if(l<32||(ye(b,0,32,o,g),Ee(h,16,h,32,l-32,b)!==0))return-1;for(xe(f,0,h,0,l,o,g),v=0;v<32;v++)f[v]=0;return 0}function We(f,h){var l;for(l=0;l<16;l++)f[l]=h[l]|0}function st(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 Ze(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(),b=e();for(l=0;l<16;l++)b[l]=h[l];for(st(b),st(b),st(b),o=0;o<2;o++){for(v[0]=b[0]-65517,l=1;l<15;l++)v[l]=b[l]-65535-(v[l-1]>>16&1),v[l-1]&=65535;v[15]=b[15]-32767-(v[14]>>16&1),g=v[15]>>16&1,v[14]&=65535,Ze(b,v,1-g)}for(l=0;l<16;l++)f[2*l]=b[l]&255,f[2*l+1]=b[l]>>8}function it(f,h){var l=new Uint8Array(32),o=new Uint8Array(32);return Te(l,f),Te(o,h),z(l,0,o,0)}function ze(f){var h=new Uint8Array(32);return Te(h,f),h[0]&1}function gt(f,h){var l;for(l=0;l<16;l++)f[l]=h[2*l]+(h[2*l+1]<<8);f[15]&=32767}function L(f,h,l){for(var o=0;o<16;o++)f[o]=h[o]+l[o]}function j(f,h,l){for(var o=0;o<16;o++)f[o]=h[o]-l[o]}function R(f,h,l){var o,g,v=0,b=0,k=0,D=0,J=0,W=0,Pe=0,V=0,ne=0,se=0,he=0,le=0,oe=0,ce=0,ae=0,$=0,Q=0,H=0,G=0,Y=0,K=0,w=0,x=0,I=0,C=0,O=0,F=0,ie=0,de=0,me=0,pe=0,y=l[0],ve=l[1],Ae=l[2],Re=l[3],_e=l[4],Ce=l[5],ke=l[6],Je=l[7],Me=l[8],$e=l[9],Ge=l[10],Ye=l[11],nt=l[12],ht=l[13],dt=l[14],pt=l[15];o=h[0],v+=o*y,b+=o*ve,k+=o*Ae,D+=o*Re,J+=o*_e,W+=o*Ce,Pe+=o*ke,V+=o*Je,ne+=o*Me,se+=o*$e,he+=o*Ge,le+=o*Ye,oe+=o*nt,ce+=o*ht,ae+=o*dt,$+=o*pt,o=h[1],b+=o*y,k+=o*ve,D+=o*Ae,J+=o*Re,W+=o*_e,Pe+=o*Ce,V+=o*ke,ne+=o*Je,se+=o*Me,he+=o*$e,le+=o*Ge,oe+=o*Ye,ce+=o*nt,ae+=o*ht,$+=o*dt,Q+=o*pt,o=h[2],k+=o*y,D+=o*ve,J+=o*Ae,W+=o*Re,Pe+=o*_e,V+=o*Ce,ne+=o*ke,se+=o*Je,he+=o*Me,le+=o*$e,oe+=o*Ge,ce+=o*Ye,ae+=o*nt,$+=o*ht,Q+=o*dt,H+=o*pt,o=h[3],D+=o*y,J+=o*ve,W+=o*Ae,Pe+=o*Re,V+=o*_e,ne+=o*Ce,se+=o*ke,he+=o*Je,le+=o*Me,oe+=o*$e,ce+=o*Ge,ae+=o*Ye,$+=o*nt,Q+=o*ht,H+=o*dt,G+=o*pt,o=h[4],J+=o*y,W+=o*ve,Pe+=o*Ae,V+=o*Re,ne+=o*_e,se+=o*Ce,he+=o*ke,le+=o*Je,oe+=o*Me,ce+=o*$e,ae+=o*Ge,$+=o*Ye,Q+=o*nt,H+=o*ht,G+=o*dt,Y+=o*pt,o=h[5],W+=o*y,Pe+=o*ve,V+=o*Ae,ne+=o*Re,se+=o*_e,he+=o*Ce,le+=o*ke,oe+=o*Je,ce+=o*Me,ae+=o*$e,$+=o*Ge,Q+=o*Ye,H+=o*nt,G+=o*ht,Y+=o*dt,K+=o*pt,o=h[6],Pe+=o*y,V+=o*ve,ne+=o*Ae,se+=o*Re,he+=o*_e,le+=o*Ce,oe+=o*ke,ce+=o*Je,ae+=o*Me,$+=o*$e,Q+=o*Ge,H+=o*Ye,G+=o*nt,Y+=o*ht,K+=o*dt,w+=o*pt,o=h[7],V+=o*y,ne+=o*ve,se+=o*Ae,he+=o*Re,le+=o*_e,oe+=o*Ce,ce+=o*ke,ae+=o*Je,$+=o*Me,Q+=o*$e,H+=o*Ge,G+=o*Ye,Y+=o*nt,K+=o*ht,w+=o*dt,x+=o*pt,o=h[8],ne+=o*y,se+=o*ve,he+=o*Ae,le+=o*Re,oe+=o*_e,ce+=o*Ce,ae+=o*ke,$+=o*Je,Q+=o*Me,H+=o*$e,G+=o*Ge,Y+=o*Ye,K+=o*nt,w+=o*ht,x+=o*dt,I+=o*pt,o=h[9],se+=o*y,he+=o*ve,le+=o*Ae,oe+=o*Re,ce+=o*_e,ae+=o*Ce,$+=o*ke,Q+=o*Je,H+=o*Me,G+=o*$e,Y+=o*Ge,K+=o*Ye,w+=o*nt,x+=o*ht,I+=o*dt,C+=o*pt,o=h[10],he+=o*y,le+=o*ve,oe+=o*Ae,ce+=o*Re,ae+=o*_e,$+=o*Ce,Q+=o*ke,H+=o*Je,G+=o*Me,Y+=o*$e,K+=o*Ge,w+=o*Ye,x+=o*nt,I+=o*ht,C+=o*dt,O+=o*pt,o=h[11],le+=o*y,oe+=o*ve,ce+=o*Ae,ae+=o*Re,$+=o*_e,Q+=o*Ce,H+=o*ke,G+=o*Je,Y+=o*Me,K+=o*$e,w+=o*Ge,x+=o*Ye,I+=o*nt,C+=o*ht,O+=o*dt,F+=o*pt,o=h[12],oe+=o*y,ce+=o*ve,ae+=o*Ae,$+=o*Re,Q+=o*_e,H+=o*Ce,G+=o*ke,Y+=o*Je,K+=o*Me,w+=o*$e,x+=o*Ge,I+=o*Ye,C+=o*nt,O+=o*ht,F+=o*dt,ie+=o*pt,o=h[13],ce+=o*y,ae+=o*ve,$+=o*Ae,Q+=o*Re,H+=o*_e,G+=o*Ce,Y+=o*ke,K+=o*Je,w+=o*Me,x+=o*$e,I+=o*Ge,C+=o*Ye,O+=o*nt,F+=o*ht,ie+=o*dt,de+=o*pt,o=h[14],ae+=o*y,$+=o*ve,Q+=o*Ae,H+=o*Re,G+=o*_e,Y+=o*Ce,K+=o*ke,w+=o*Je,x+=o*Me,I+=o*$e,C+=o*Ge,O+=o*Ye,F+=o*nt,ie+=o*ht,de+=o*dt,me+=o*pt,o=h[15],$+=o*y,Q+=o*ve,H+=o*Ae,G+=o*Re,Y+=o*_e,K+=o*Ce,w+=o*ke,x+=o*Je,I+=o*Me,C+=o*$e,O+=o*Ge,F+=o*Ye,ie+=o*nt,de+=o*ht,me+=o*dt,pe+=o*pt,v+=38*Q,b+=38*H,k+=38*G,D+=38*Y,J+=38*K,W+=38*w,Pe+=38*x,V+=38*I,ne+=38*C,se+=38*O,he+=38*F,le+=38*ie,oe+=38*de,ce+=38*me,ae+=38*pe,g=1,o=v+g+65535,g=Math.floor(o/65536),v=o-g*65536,o=b+g+65535,g=Math.floor(o/65536),b=o-g*65536,o=k+g+65535,g=Math.floor(o/65536),k=o-g*65536,o=D+g+65535,g=Math.floor(o/65536),D=o-g*65536,o=J+g+65535,g=Math.floor(o/65536),J=o-g*65536,o=W+g+65535,g=Math.floor(o/65536),W=o-g*65536,o=Pe+g+65535,g=Math.floor(o/65536),Pe=o-g*65536,o=V+g+65535,g=Math.floor(o/65536),V=o-g*65536,o=ne+g+65535,g=Math.floor(o/65536),ne=o-g*65536,o=se+g+65535,g=Math.floor(o/65536),se=o-g*65536,o=he+g+65535,g=Math.floor(o/65536),he=o-g*65536,o=le+g+65535,g=Math.floor(o/65536),le=o-g*65536,o=oe+g+65535,g=Math.floor(o/65536),oe=o-g*65536,o=ce+g+65535,g=Math.floor(o/65536),ce=o-g*65536,o=ae+g+65535,g=Math.floor(o/65536),ae=o-g*65536,o=$+g+65535,g=Math.floor(o/65536),$=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=b+g+65535,g=Math.floor(o/65536),b=o-g*65536,o=k+g+65535,g=Math.floor(o/65536),k=o-g*65536,o=D+g+65535,g=Math.floor(o/65536),D=o-g*65536,o=J+g+65535,g=Math.floor(o/65536),J=o-g*65536,o=W+g+65535,g=Math.floor(o/65536),W=o-g*65536,o=Pe+g+65535,g=Math.floor(o/65536),Pe=o-g*65536,o=V+g+65535,g=Math.floor(o/65536),V=o-g*65536,o=ne+g+65535,g=Math.floor(o/65536),ne=o-g*65536,o=se+g+65535,g=Math.floor(o/65536),se=o-g*65536,o=he+g+65535,g=Math.floor(o/65536),he=o-g*65536,o=le+g+65535,g=Math.floor(o/65536),le=o-g*65536,o=oe+g+65535,g=Math.floor(o/65536),oe=o-g*65536,o=ce+g+65535,g=Math.floor(o/65536),ce=o-g*65536,o=ae+g+65535,g=Math.floor(o/65536),ae=o-g*65536,o=$+g+65535,g=Math.floor(o/65536),$=o-g*65536,v+=g-1+37*(g-1),f[0]=v,f[1]=b,f[2]=k,f[3]=D,f[4]=J,f[5]=W,f[6]=Pe,f[7]=V,f[8]=ne,f[9]=se,f[10]=he,f[11]=le,f[12]=oe,f[13]=ce,f[14]=ae,f[15]=$}function P(f,h){R(f,h,h)}function Z(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=253;o>=0;o--)P(l,l),o!==2&&o!==4&&R(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function Ne(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=250;o>=0;o--)P(l,l),o!==1&&R(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function Xe(f,h,l){var o=new Uint8Array(32),g=new Float64Array(80),v,b,k=e(),D=e(),J=e(),W=e(),Pe=e(),V=e();for(b=0;b<31;b++)o[b]=h[b];for(o[31]=h[31]&127|64,o[0]&=248,gt(g,l),b=0;b<16;b++)D[b]=g[b],W[b]=k[b]=J[b]=0;for(k[0]=W[0]=1,b=254;b>=0;--b)v=o[b>>>3]>>>(b&7)&1,Ze(k,D,v),Ze(J,W,v),L(Pe,k,J),j(k,k,J),L(J,D,W),j(D,D,W),P(W,Pe),P(V,k),R(k,J,k),R(J,D,Pe),L(Pe,k,J),j(k,k,J),P(D,k),j(J,W,V),R(k,J,c),L(k,k,W),R(J,J,k),R(k,W,V),R(W,D,g),P(D,Pe),Ze(k,D,v),Ze(J,W,v);for(b=0;b<16;b++)g[b+16]=k[b],g[b+32]=J[b],g[b+48]=D[b],g[b+64]=W[b];var ne=g.subarray(32),se=g.subarray(16);return Z(ne,ne),R(se,se,ne),Te(f,se),0}function lt(f,h){return Xe(f,h,n)}function wt(f,h){return t(h,32),lt(f,h)}function mr(f,h,l){var o=new Uint8Array(32);return Xe(o,l,h),B(f,i,o,re)}var Mr=Se,ii=be;function Fr(f,h,l,o,g,v){var b=new Uint8Array(32);return mr(b,g,v),Mr(f,h,l,o,b)}function ki(f,h,l,o,g,v){var b=new Uint8Array(32);return mr(b,g,v),ii(f,h,l,o,b)}var Xn=[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 wf(f,h,l,o){for(var g=new Int32Array(16),v=new Int32Array(16),b,k,D,J,W,Pe,V,ne,se,he,le,oe,ce,ae,$,Q,H,G,Y,K,w,x,I,C,O,F,ie=f[0],de=f[1],me=f[2],pe=f[3],y=f[4],ve=f[5],Ae=f[6],Re=f[7],_e=h[0],Ce=h[1],ke=h[2],Je=h[3],Me=h[4],$e=h[5],Ge=h[6],Ye=h[7],nt=0;o>=128;){for(Y=0;Y<16;Y++)K=8*Y+nt,g[Y]=l[K+0]<<24|l[K+1]<<16|l[K+2]<<8|l[K+3],v[Y]=l[K+4]<<24|l[K+5]<<16|l[K+6]<<8|l[K+7];for(Y=0;Y<80;Y++)if(b=ie,k=de,D=me,J=pe,W=y,Pe=ve,V=Ae,ne=Re,se=_e,he=Ce,le=ke,oe=Je,ce=Me,ae=$e,$=Ge,Q=Ye,w=Re,x=Ye,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=(y>>>14|Me<<18)^(y>>>18|Me<<14)^(Me>>>9|y<<23),x=(Me>>>14|y<<18)^(Me>>>18|y<<14)^(y>>>9|Me<<23),I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,w=y&ve^~y&Ae,x=Me&$e^~Me&Ge,I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,w=Xn[Y*2],x=Xn[Y*2+1],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,w=g[Y%16],x=v[Y%16],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,H=O&65535|F<<16,G=I&65535|C<<16,w=H,x=G,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=(ie>>>28|_e<<4)^(_e>>>2|ie<<30)^(_e>>>7|ie<<25),x=(_e>>>28|ie<<4)^(ie>>>2|_e<<30)^(ie>>>7|_e<<25),I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,w=ie&de^ie&me^de&me,x=_e&Ce^_e&ke^Ce&ke,I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,ne=O&65535|F<<16,Q=I&65535|C<<16,w=J,x=oe,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=H,x=G,I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,J=O&65535|F<<16,oe=I&65535|C<<16,de=b,me=k,pe=D,y=J,ve=W,Ae=Pe,Re=V,ie=ne,Ce=se,ke=he,Je=le,Me=oe,$e=ce,Ge=ae,Ye=$,_e=Q,Y%16===15)for(K=0;K<16;K++)w=g[K],x=v[K],I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=g[(K+9)%16],x=v[(K+9)%16],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,H=g[(K+1)%16],G=v[(K+1)%16],w=(H>>>1|G<<31)^(H>>>8|G<<24)^H>>>7,x=(G>>>1|H<<31)^(G>>>8|H<<24)^(G>>>7|H<<25),I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,H=g[(K+14)%16],G=v[(K+14)%16],w=(H>>>19|G<<13)^(G>>>29|H<<3)^H>>>6,x=(G>>>19|H<<13)^(H>>>29|G<<3)^(G>>>6|H<<26),I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,g[K]=O&65535|F<<16,v[K]=I&65535|C<<16;w=ie,x=_e,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[0],x=h[0],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[0]=ie=O&65535|F<<16,h[0]=_e=I&65535|C<<16,w=de,x=Ce,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[1],x=h[1],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[1]=de=O&65535|F<<16,h[1]=Ce=I&65535|C<<16,w=me,x=ke,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[2],x=h[2],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[2]=me=O&65535|F<<16,h[2]=ke=I&65535|C<<16,w=pe,x=Je,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[3],x=h[3],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[3]=pe=O&65535|F<<16,h[3]=Je=I&65535|C<<16,w=y,x=Me,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[4],x=h[4],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[4]=y=O&65535|F<<16,h[4]=Me=I&65535|C<<16,w=ve,x=$e,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[5],x=h[5],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[5]=ve=O&65535|F<<16,h[5]=$e=I&65535|C<<16,w=Ae,x=Ge,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[6],x=h[6],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[6]=Ae=O&65535|F<<16,h[6]=Ge=I&65535|C<<16,w=Re,x=Ye,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[7],x=h[7],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[7]=Re=O&65535|F<<16,h[7]=Ye=I&65535|C<<16,nt+=128,o-=128}return o}function ni(f,h,l){var o=new Int32Array(8),g=new Int32Array(8),v=new Uint8Array(256),b,k=l;for(o[0]=1779033703,o[1]=3144134277,o[2]=1013904242,o[3]=2773480762,o[4]=1359893119,o[5]=2600822924,o[6]=528734635,o[7]=1541459225,g[0]=4089235720,g[1]=2227873595,g[2]=4271175723,g[3]=1595750129,g[4]=2917565137,g[5]=725511199,g[6]=4215389547,g[7]=327033209,wf(o,g,h,l),l%=128,b=0;b<l;b++)v[b]=h[k-l+b];for(v[l]=128,l=256-128*(l<112?1:0),v[l-9]=0,E(v,l-8,k/536870912|0,k<<3),wf(o,g,v,l),b=0;b<8;b++)E(f,8*b,o[b],g[b]);return 0}function Jn(f,h){var l=e(),o=e(),g=e(),v=e(),b=e(),k=e(),D=e(),J=e(),W=e();j(l,f[1],f[0]),j(W,h[1],h[0]),R(l,l,W),L(o,f[0],f[1]),L(W,h[0],h[1]),R(o,o,W),R(g,f[3],h[3]),R(g,g,d),R(v,f[2],h[2]),L(v,v,v),j(b,o,l),j(k,v,g),L(D,v,g),L(J,o,l),R(f[0],b,k),R(f[1],J,D),R(f[2],D,k),R(f[3],b,J)}function xf(f,h,l){var o;for(o=0;o<4;o++)Ze(f[o],h[o],l)}function Fo(f,h){var l=e(),o=e(),g=e();Z(g,h[2]),R(l,h[0],g),R(o,h[1],g),Te(f,o),f[31]^=ze(l)<<7}function Do(f,h,l){var o,g;for(We(f[0],s),We(f[1],a),We(f[2],a),We(f[3],s),g=255;g>=0;--g)o=l[g/8|0]>>(g&7)&1,xf(f,h,o),Jn(h,f),Jn(f,f),xf(f,h,o)}function Zn(f,h){var l=[e(),e(),e(),e()];We(l[0],p),We(l[1],m),We(l[2],a),R(l[3],p,m),Do(f,l,h)}function Bo(f,h,l){var o=new Uint8Array(64),g=[e(),e(),e(),e()],v;for(l||t(h,32),ni(o,h,32),o[0]&=248,o[31]&=127,o[31]|=64,Zn(g,o),Fo(f,g),v=0;v<32;v++)h[v+32]=f[v];return 0}var Qn=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 jo(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]*Qn[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)*Qn[g],l=h[g]>>8,h[g]&=255;for(g=0;g<32;g++)h[g]-=l*Qn[g];for(o=0;o<32;o++)h[o+1]+=h[o]>>8,f[o]=h[o]&255}function Uo(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;jo(f,h)}function Sf(f,h,l,o){var g=new Uint8Array(64),v=new Uint8Array(64),b=new Uint8Array(64),k,D,J=new Float64Array(64),W=[e(),e(),e(),e()];ni(g,o,32),g[0]&=248,g[31]&=127,g[31]|=64;var Pe=l+64;for(k=0;k<l;k++)f[64+k]=h[k];for(k=0;k<32;k++)f[32+k]=g[32+k];for(ni(b,f.subarray(32),l+32),Uo(b),Zn(W,b),Fo(f,W),k=32;k<64;k++)f[k]=o[k];for(ni(v,f,l+64),Uo(v),k=0;k<64;k++)J[k]=0;for(k=0;k<32;k++)J[k]=b[k];for(k=0;k<32;k++)for(D=0;D<32;D++)J[k+D]+=v[k]*g[D];return jo(f.subarray(32),J),Pe}function hp(f,h){var l=e(),o=e(),g=e(),v=e(),b=e(),k=e(),D=e();return We(f[2],a),gt(f[1],h),P(g,f[1]),R(v,g,u),j(g,g,f[2]),L(v,f[2],v),P(b,v),P(k,b),R(D,k,b),R(l,D,g),R(l,l,v),Ne(l,l),R(l,l,g),R(l,l,v),R(l,l,v),R(f[0],l,v),P(o,f[0]),R(o,o,v),it(o,g)&&R(f[0],f[0],_),P(o,f[0]),R(o,o,v),it(o,g)?-1:(ze(f[0])===h[31]>>7&&j(f[0],s,f[0]),R(f[3],f[0],f[1]),0)}function qo(f,h,l,o){var g,v=new Uint8Array(32),b=new Uint8Array(64),k=[e(),e(),e(),e()],D=[e(),e(),e(),e()];if(l<64||hp(D,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(ni(b,f,l),Uo(b),Do(k,D,b),Zn(D,h.subarray(32)),Jn(k,D),Fo(v,k),l-=64,z(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 Ko=32,es=24,un=32,Oi=16,ln=32,ts=32,hn=32,dn=32,Wo=32,Tf=es,dp=un,pp=Oi,yr=64,si=32,Pi=64,Ho=32,Vo=64;r.lowlevel={crypto_core_hsalsa20:B,crypto_stream_xor:xe,crypto_stream:ye,crypto_stream_salsa20_xor:q,crypto_stream_salsa20:U,crypto_onetimeauth:rt,crypto_onetimeauth_verify:Ee,crypto_verify_16:T,crypto_verify_32:z,crypto_secretbox:Se,crypto_secretbox_open:be,crypto_scalarmult:Xe,crypto_scalarmult_base:lt,crypto_box_beforenm:mr,crypto_box_afternm:Mr,crypto_box:Fr,crypto_box_open:ki,crypto_box_keypair:wt,crypto_hash:ni,crypto_sign:Sf,crypto_sign_keypair:Bo,crypto_sign_open:qo,crypto_secretbox_KEYBYTES:Ko,crypto_secretbox_NONCEBYTES:es,crypto_secretbox_ZEROBYTES:un,crypto_secretbox_BOXZEROBYTES:Oi,crypto_scalarmult_BYTES:ln,crypto_scalarmult_SCALARBYTES:ts,crypto_box_PUBLICKEYBYTES:hn,crypto_box_SECRETKEYBYTES:dn,crypto_box_BEFORENMBYTES:Wo,crypto_box_NONCEBYTES:Tf,crypto_box_ZEROBYTES:dp,crypto_box_BOXZEROBYTES:pp,crypto_sign_BYTES:yr,crypto_sign_PUBLICKEYBYTES:si,crypto_sign_SECRETKEYBYTES:Pi,crypto_sign_SEEDBYTES:Ho,crypto_hash_BYTES:Vo,gf:e,D:u,L:Qn,pack25519:Te,unpack25519:gt,M:R,A:L,S:P,Z:j,pow2523:Ne,add:Jn,set25519:We,modL:jo,scalarmult:Do,scalarbase:Zn};function Cf(f,h){if(f.length!==Ko)throw new Error("bad key size");if(h.length!==es)throw new Error("bad nonce size")}function gp(f,h){if(f.length!==hn)throw new Error("bad public key size");if(h.length!==dn)throw new Error("bad secret key size")}function xt(){for(var f=0;f<arguments.length;f++)if(!(arguments[f]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function kf(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){xt(f,h,l),Cf(l,h);for(var o=new Uint8Array(un+f.length),g=new Uint8Array(o.length),v=0;v<f.length;v++)o[v+un]=f[v];return Se(g,o,o.length,h,l),g.subarray(Oi)},r.secretbox.open=function(f,h,l){xt(f,h,l),Cf(l,h);for(var o=new Uint8Array(Oi+f.length),g=new Uint8Array(o.length),v=0;v<f.length;v++)o[v+Oi]=f[v];return o.length<32||be(g,o,o.length,h,l)!==0?null:g.subarray(un)},r.secretbox.keyLength=Ko,r.secretbox.nonceLength=es,r.secretbox.overheadLength=Oi,r.scalarMult=function(f,h){if(xt(f,h),f.length!==ts)throw new Error("bad n size");if(h.length!==ln)throw new Error("bad p size");var l=new Uint8Array(ln);return Xe(l,f,h),l},r.scalarMult.base=function(f){if(xt(f),f.length!==ts)throw new Error("bad n size");var h=new Uint8Array(ln);return lt(h,f),h},r.scalarMult.scalarLength=ts,r.scalarMult.groupElementLength=ln,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){xt(f,h),gp(f,h);var l=new Uint8Array(Wo);return mr(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(hn),h=new Uint8Array(dn);return wt(f,h),{publicKey:f,secretKey:h}},r.box.keyPair.fromSecretKey=function(f){if(xt(f),f.length!==dn)throw new Error("bad secret key size");var h=new Uint8Array(hn);return lt(h,f),{publicKey:h,secretKey:new Uint8Array(f)}},r.box.publicKeyLength=hn,r.box.secretKeyLength=dn,r.box.sharedKeyLength=Wo,r.box.nonceLength=Tf,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(f,h){if(xt(f,h),h.length!==Pi)throw new Error("bad secret key size");var l=new Uint8Array(yr+f.length);return Sf(l,f,f.length,h),l},r.sign.open=function(f,h){if(xt(f,h),h.length!==si)throw new Error("bad public key size");var l=new Uint8Array(f.length),o=qo(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(yr),g=0;g<o.length;g++)o[g]=l[g];return o},r.sign.detached.verify=function(f,h,l){if(xt(f,h,l),h.length!==yr)throw new Error("bad signature size");if(l.length!==si)throw new Error("bad public key size");var o=new Uint8Array(yr+f.length),g=new Uint8Array(yr+f.length),v;for(v=0;v<yr;v++)o[v]=h[v];for(v=0;v<f.length;v++)o[v+yr]=f[v];return qo(g,o,o.length,l)>=0},r.sign.keyPair=function(){var f=new Uint8Array(si),h=new Uint8Array(Pi);return Bo(f,h),{publicKey:f,secretKey:h}},r.sign.keyPair.fromSecretKey=function(f){if(xt(f),f.length!==Pi)throw new Error("bad secret key size");for(var h=new Uint8Array(si),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(xt(f),f.length!==Ho)throw new Error("bad seed size");for(var h=new Uint8Array(si),l=new Uint8Array(Pi),o=0;o<32;o++)l[o]=f[o];return Bo(h,l,!0),{publicKey:h,secretKey:l}},r.sign.publicKeyLength=si,r.sign.secretKeyLength=Pi,r.sign.seedLength=Ho,r.sign.signatureLength=yr,r.hash=function(f){xt(f);var h=new Uint8Array(Vo);return ni(h,f,f.length),h},r.hash.hashLength=Vo,r.verify=function(f,h){return xt(f,h),f.length===0||h.length===0||f.length!==h.length?!1:S(f,0,h,0,f.length)===0},r.setPRNG=function(f){t=f},(function(){var f=typeof self<"u"?self.crypto||self.msCrypto:null;if(f&&f.getRandomValues){var h=65536;r.setPRNG(function(l,o){var 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];kf(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];kf(v)}))})()})(typeof ds<"u"&&ds.exports?ds.exports:self.nacl=self.nacl||{})});var _n=M(($f,ps)=>{(function(r,e){"use strict";typeof ps<"u"&&ps.exports?ps.exports=e():(r.nacl||(r.nacl={}),r.nacl.util=e())})($f,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,n=unescape(encodeURIComponent(t)),s=new Uint8Array(n.length);for(i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s},r.encodeUTF8=function(t){var i,n=[];for(i=0;i<t.length;i++)n.push(String.fromCharCode(t[i]));return decodeURIComponent(escape(n.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,n=[],s=t.length;for(i=0;i<s;i++)n.push(String.fromCharCode(t[i]));return btoa(n.join(""))},r.decodeBase64=function(t){e(t);var i,n=atob(t),s=new Uint8Array(n.length);for(i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s}),r})});var Gf=M(Tt=>{"use strict";var Dp=Tt&&Tt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Tt,"__esModule",{value:!0});Tt.concatBytes=vn;Tt.generateIdentityKeyPair=Bp;Tt.identityPublicFromSecret=jp;Tt.signSessionKey=Up;Tt.verifySessionKey=qp;Tt.buildKxCanonical=Kp;Tt.buildKxAckCanonical=Wp;Tt.fingerprintIdentityKey=Hp;Tt.fingerprintShortHex=Vp;var Qt=Dp(yn()),St=_n(),gs=Xo();function vn(...r){let e=0;for(let n of r)e+=n.length;let t=new Uint8Array(e),i=0;for(let n of r)t.set(n,i),i+=n.length;return t}function Bp(){let r=Qt.default.sign.keyPair();return{identityPublicKey:(0,St.encodeBase64)(r.publicKey),identitySecretKey:(0,St.encodeBase64)(r.secretKey)}}function jp(r){let e=(0,St.decodeBase64)(r);if(e.length!==Qt.default.sign.secretKeyLength)throw new Error("bad identity secret key length");let t=Qt.default.sign.keyPair.fromSecretKey(e);return(0,St.encodeBase64)(t.publicKey)}function Up(r,e){let t=(0,St.decodeBase64)(e);if(t.length!==Qt.default.sign.secretKeyLength)throw new Error("bad identity secret key length");return(0,St.encodeBase64)(Qt.default.sign.detached(r,t))}function qp(r,e,t){try{let i=(0,St.decodeBase64)(e),n=(0,St.decodeBase64)(t);return n.length!==Qt.default.sign.publicKeyLength||i.length!==Qt.default.sign.signatureLength?!1:Qt.default.sign.detached.verify(r,i,n)}catch{return!1}}var oi=new Uint8Array([0]);function Kp(r){let e=new TextEncoder,t=e.encode(gs.KX_SIGN_LABEL),i=e.encode(r.agentId),n=e.encode(String(r.keyVersion)),s=(0,St.decodeBase64)(r.boxPublicKey);return vn(t,oi,i,oi,n,oi,s)}function Wp(r){let e=new TextEncoder;return vn(e.encode(gs.KX_ACK_LABEL),oi,e.encode(r.agentId),oi,e.encode(String(r.keyVersion)),oi,(0,St.decodeBase64)(r.boxPublicKey),oi,(0,St.decodeBase64)(r.boundClientKey))}function Hp(r){let e=(0,St.decodeBase64)(r),t=vn(new TextEncoder().encode(gs.KX_FINGERPRINT_LABEL),e),i=Qt.default.hash(t),n=[];for(let s=0;s<12;s++){let a=s*5,u=(((i[a]<<24>>>0)+(i[a+1]<<16)+(i[a+2]<<8)+i[a+3]^i[a+4])>>>0)%1e5;n.push(String(u).padStart(5,"0"))}return n.join(" ")}function Vp(r){let e=(0,St.decodeBase64)(r),t=vn(new TextEncoder().encode(gs.KX_FINGERPRINT_LABEL),e),i=Qt.default.hash(t).slice(0,8);return Array.from(i).map(n=>n.toString(16).padStart(2,"0")).join(":").toUpperCase()}});var Yf=M(jr=>{"use strict";var zp=jr&&jr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(jr,"__esModule",{value:!0});jr.encrypt=$p;jr.decrypt=Gp;jr.encryptBinary=Yp;jr.decryptBinary=Xp;var br=zp(yn()),Br=_n();function $p(r,e,t){let i=br.default.randomBytes(br.default.secretbox.nonceLength),n=new TextEncoder().encode(r),s=br.default.secretbox(n,i,e);return{v:1,sid:t,n:(0,Br.encodeBase64)(i),c:(0,Br.encodeBase64)(s)}}function Gp(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Br.decodeBase64)(r.n),i=(0,Br.decodeBase64)(r.c);if(t.length!==br.default.secretbox.nonceLength)throw new Error(`Invalid nonce length: ${t.length}`);let n=br.default.secretbox.open(i,t,e);if(!n)throw new Error("Decryption failed: invalid ciphertext or wrong key");return new TextDecoder().decode(n)}function Yp(r,e,t){let i=br.default.randomBytes(br.default.secretbox.nonceLength),n=br.default.secretbox(r,i,e);return{v:1,sid:t,n:(0,Br.encodeBase64)(i),c:(0,Br.encodeBase64)(n)}}function Xp(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Br.decodeBase64)(r.n),i=(0,Br.decodeBase64)(r.c),n=br.default.secretbox.open(i,t,e);if(!n)throw new Error("Decryption failed: invalid ciphertext or wrong key");return n}});var Xf=M(Wt=>{"use strict";var Jp=Wt&&Wt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Wt,"__esModule",{value:!0});Wt.generateKeyPair=Zp;Wt.deriveSharedSecret=Qp;Wt.deriveMetaSid=eg;Wt.isValidPublicKey=tg;Wt.clearKey=rg;Wt.keyToBase64=ig;Wt.base64ToKey=ng;var Ri=Jp(yn()),er=_n();function Zp(){let r=Ri.default.box.keyPair();return{publicKey:(0,er.encodeBase64)(r.publicKey),secretKey:(0,er.encodeBase64)(r.secretKey)}}function Qp(r,e){let t=(0,er.decodeBase64)(r),i=(0,er.decodeBase64)(e);if(t.length!==Ri.default.box.publicKeyLength)throw new Error(`Invalid public key length: ${t.length}`);if(i.length!==Ri.default.box.secretKeyLength)throw new Error(`Invalid secret key length: ${i.length}`);return Ri.default.box.before(t,i)}function eg(r,e){let t=new TextEncoder().encode("termiq-meta-v1"),i=(0,er.decodeBase64)(r),n=(0,er.decodeBase64)(e),s=new Uint8Array(t.length+i.length+n.length);return s.set(t,0),s.set(i,t.length),s.set(n,t.length+i.length),(0,er.encodeBase64)(Ri.default.hash(s).slice(0,32))}function tg(r){try{return(0,er.decodeBase64)(r).length===Ri.default.box.publicKeyLength}catch{return!1}}function rg(r){r.fill(0)}function ig(r){return(0,er.encodeBase64)(r)}function ng(r){return(0,er.decodeBase64)(r)}});var Zf=M(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.base64ToKey=te.keyToBase64=te.clearKey=te.isValidPublicKey=te.deriveMetaSid=te.deriveSharedSecret=te.generateKeyPair=te.decryptBinary=te.encryptBinary=te.decrypt=te.encrypt=te.concatBytes=te.fingerprintShortHex=te.fingerprintIdentityKey=te.buildKxAckCanonical=te.buildKxCanonical=te.verifySessionKey=te.signSessionKey=te.identityPublicFromSecret=te.generateIdentityKeyPair=te.KX_SIG_VERSION=te.KX_FINGERPRINT_LABEL=te.KX_ACK_LABEL=te.KX_SIGN_LABEL=te.isMultiRecipientPayload=te.isEncryptedPayload=void 0;var Jf=zf();Object.defineProperty(te,"isEncryptedPayload",{enumerable:!0,get:function(){return Jf.isEncryptedPayload}});Object.defineProperty(te,"isMultiRecipientPayload",{enumerable:!0,get:function(){return Jf.isMultiRecipientPayload}});var ms=Xo();Object.defineProperty(te,"KX_SIGN_LABEL",{enumerable:!0,get:function(){return ms.KX_SIGN_LABEL}});Object.defineProperty(te,"KX_ACK_LABEL",{enumerable:!0,get:function(){return ms.KX_ACK_LABEL}});Object.defineProperty(te,"KX_FINGERPRINT_LABEL",{enumerable:!0,get:function(){return ms.KX_FINGERPRINT_LABEL}});Object.defineProperty(te,"KX_SIG_VERSION",{enumerable:!0,get:function(){return ms.KX_SIG_VERSION}});var Er=Gf();Object.defineProperty(te,"generateIdentityKeyPair",{enumerable:!0,get:function(){return Er.generateIdentityKeyPair}});Object.defineProperty(te,"identityPublicFromSecret",{enumerable:!0,get:function(){return Er.identityPublicFromSecret}});Object.defineProperty(te,"signSessionKey",{enumerable:!0,get:function(){return Er.signSessionKey}});Object.defineProperty(te,"verifySessionKey",{enumerable:!0,get:function(){return Er.verifySessionKey}});Object.defineProperty(te,"buildKxCanonical",{enumerable:!0,get:function(){return Er.buildKxCanonical}});Object.defineProperty(te,"buildKxAckCanonical",{enumerable:!0,get:function(){return Er.buildKxAckCanonical}});Object.defineProperty(te,"fingerprintIdentityKey",{enumerable:!0,get:function(){return Er.fingerprintIdentityKey}});Object.defineProperty(te,"fingerprintShortHex",{enumerable:!0,get:function(){return Er.fingerprintShortHex}});Object.defineProperty(te,"concatBytes",{enumerable:!0,get:function(){return Er.concatBytes}});var ys=Yf();Object.defineProperty(te,"encrypt",{enumerable:!0,get:function(){return ys.encrypt}});Object.defineProperty(te,"decrypt",{enumerable:!0,get:function(){return ys.decrypt}});Object.defineProperty(te,"encryptBinary",{enumerable:!0,get:function(){return ys.encryptBinary}});Object.defineProperty(te,"decryptBinary",{enumerable:!0,get:function(){return ys.decryptBinary}});var ai=Xf();Object.defineProperty(te,"generateKeyPair",{enumerable:!0,get:function(){return ai.generateKeyPair}});Object.defineProperty(te,"deriveSharedSecret",{enumerable:!0,get:function(){return ai.deriveSharedSecret}});Object.defineProperty(te,"deriveMetaSid",{enumerable:!0,get:function(){return ai.deriveMetaSid}});Object.defineProperty(te,"isValidPublicKey",{enumerable:!0,get:function(){return ai.isValidPublicKey}});Object.defineProperty(te,"clearKey",{enumerable:!0,get:function(){return ai.clearKey}});Object.defineProperty(te,"keyToBase64",{enumerable:!0,get:function(){return ai.keyToBase64}});Object.defineProperty(te,"base64ToKey",{enumerable:!0,get:function(){return ai.base64ToKey}})});var Qf=M(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.MIN_CLIENT_VERSION=Ct.PROTOCOL_VERSION_MINOR=Ct.PROTOCOL_VERSION_MAJOR=Ct.PROTOCOL_VERSION=void 0;Ct.isCompatibleVersion=sg;Ct.compareVersions=og;Ct.PROTOCOL_VERSION="2.1";Ct.PROTOCOL_VERSION_MAJOR=2;Ct.PROTOCOL_VERSION_MINOR=1;Ct.MIN_CLIENT_VERSION="2.0";function sg(r){let[e]=r.split(".").map(Number);return e===Ct.PROTOCOL_VERSION_MAJOR}function og(r,e){let[t,i]=r.split(".").map(Number),[n,s]=e.split(".").map(Number);return t!==n?t<n?-1:1:i!==s?i<s?-1:1:0}});var eu=M(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.SERVER_CAPABILITIES=tr.DEFAULT_CLIENT_CAPABILITIES=tr.Capability=void 0;tr.hasCapability=ag;tr.negotiateCapabilities=cg;var Ii;(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"})(Ii||(tr.Capability=Ii={}));tr.DEFAULT_CLIENT_CAPABILITIES=[Ii.E2E_ENCRYPTION,Ii.TERMINAL_EVENTS,Ii.RELIABLE_INPUT];tr.SERVER_CAPABILITIES=Object.values(Ii);function ag(r,e){return r.includes(e)}function cg(r,e){return r.filter(t=>e.includes(t))}});var tu=M(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.DEFAULT_PRIORITY=wr.PRIORITY_NAMES=wr.Priority=void 0;wr.comparePriority=fg;var ci;(function(r){r[r.CRITICAL=0]="CRITICAL",r[r.HIGH=1]="HIGH",r[r.NORMAL=2]="NORMAL",r[r.LOW=3]="LOW"})(ci||(wr.Priority=ci={}));wr.PRIORITY_NAMES={[ci.CRITICAL]:"CRITICAL",[ci.HIGH]:"HIGH",[ci.NORMAL]:"NORMAL",[ci.LOW]:"LOW"};wr.DEFAULT_PRIORITY=ci.NORMAL;function fg(r,e){return r-e}});var ru=M(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.DEFAULT_RELIABILITY=rr.RELIABILITY_NAMES=rr.Reliability=void 0;rr.requiresAck=ug;rr.requiresBuffer=lg;var Ur;(function(r){r[r.FIRE_FORGET=0]="FIRE_FORGET",r[r.BUFFERED=1]="BUFFERED",r[r.GUARANTEED=2]="GUARANTEED"})(Ur||(rr.Reliability=Ur={}));rr.RELIABILITY_NAMES={[Ur.FIRE_FORGET]:"FIRE_FORGET",[Ur.BUFFERED]:"BUFFERED",[Ur.GUARANTEED]:"GUARANTEED"};rr.DEFAULT_RELIABILITY=Ur.FIRE_FORGET;function ug(r){return r===Ur.GUARANTEED}function lg(r){return r>=Ur.BUFFERED}});var iu=M(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.createMessage=hg;function hg(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 nu=M(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.TerminalEventType=void 0;fi.deriveStatusFromEvent=dg;fi.shouldTriggerPushNotification=pg;fi.getPushNotificationMessage=gg;var mt;(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"})(mt||(fi.TerminalEventType=mt={}));function dg(r){switch(r.type){case mt.SESSION_START:case mt.TOOL_START:case mt.MESSAGE:return"working";case mt.WAITING_INPUT:return"waiting";case mt.SESSION_END:return r.status==="success"?"completed":"error";case mt.ERROR:return r.severity==="fatal"?"error":"working";case mt.TOOL_END:return r.status==="error"?"error":"working";default:return"idle"}}function pg(r){switch(r.type){case mt.WAITING_INPUT:return!0;case mt.SESSION_END:return!0;case mt.ERROR:return r.severity!=="warning";default:return!1}}function gg(r,e){switch(r.type){case mt.WAITING_INPUT:return{title:`${e}: Input Required`,body:r.question.slice(0,100)};case mt.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 mt.ERROR:{let t=r;return t.severity==="warning"?null:{title:`${e}: Error`,body:t.message.slice(0,100)}}default:return null}}});var au=M(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.TransferDirection=Ue.TransferStatus=Ue.CHUNK_TTL_SECONDS=Ue.TRANSFER_TTL_SECONDS=Ue.MAX_RETRIES=Ue.ACK_TIMEOUT_MS=Ue.WINDOW_SIZE=Ue.DEFAULT_MAX_FILE_SIZE=Ue.CHUNK_SIZE=void 0;Ue.calculateTotalChunks=mg;Ue.getMissingChunks=yg;Ue.isTransferComplete=_g;Ue.CHUNK_SIZE=64*1024;Ue.DEFAULT_MAX_FILE_SIZE=100*1024*1024;Ue.WINDOW_SIZE=10;Ue.ACK_TIMEOUT_MS=3e4;Ue.MAX_RETRIES=3;Ue.TRANSFER_TTL_SECONDS=1440*60;Ue.CHUNK_TTL_SECONDS=1440*60;var su;(function(r){r.PENDING="pending",r.ACTIVE="active",r.PAUSED="paused",r.COMPLETED="completed",r.FAILED="failed",r.CANCELLED="cancelled",r.EXPIRED="expired"})(su||(Ue.TransferStatus=su={}));var ou;(function(r){r.DOWNLOAD="download",r.UPLOAD="upload"})(ou||(Ue.TransferDirection=ou={}));function mg(r,e=Ue.CHUNK_SIZE){return Math.ceil(r/e)}function yg(r,e){let t=new Set(e),i=[];for(let n=0;n<r;n++)t.has(n)||i.push(n);return i}function _g(r,e){return e.length===r}});var cu=M(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.ERROR_MESSAGES=xr.ErrorCode=void 0;xr.createError=vg;xr.isRetryableError=bg;var Ie;(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"})(Ie||(xr.ErrorCode=Ie={}));xr.ERROR_MESSAGES={[Ie.AUTH_FAILED]:"Authentication failed",[Ie.TOKEN_EXPIRED]:"Token expired",[Ie.TOKEN_INVALID]:"Invalid token",[Ie.NOT_FOUND]:"Resource not found",[Ie.ALREADY_EXISTS]:"Resource already exists",[Ie.ACCESS_DENIED]:"Access denied",[Ie.FORBIDDEN]:"Operation forbidden",[Ie.RATE_LIMITED]:"Rate limit exceeded",[Ie.TOO_MANY_CONNECTIONS]:"Too many connections",[Ie.QUOTA_EXCEEDED]:"Plan quota exceeded",[Ie.FILE_TOO_LARGE]:"File size exceeds limit",[Ie.QUEUE_FULL]:"Message queue is full",[Ie.TRANSFERS_LIMIT]:"Daily transfers limit reached",[Ie.TRANSFER_FAILED]:"File transfer failed",[Ie.TRANSFER_EXPIRED]:"Transfer expired",[Ie.TRANSFER_CANCELLED]:"Transfer cancelled",[Ie.CHECKSUM_MISMATCH]:"File checksum mismatch",[Ie.CHUNK_MISSING]:"Chunk missing or corrupted",[Ie.INVALID_MESSAGE]:"Invalid message format",[Ie.UNSUPPORTED_VERSION]:"Unsupported protocol version",[Ie.CAPABILITY_REQUIRED]:"Required capability not supported",[Ie.INVALID_STATE]:"Invalid state for this operation",[Ie.TIMEOUT]:"Operation timed out",[Ie.CONNECTION_LOST]:"Connection lost",[Ie.INTERNAL_ERROR]:"Internal server error",[Ie.SERVICE_UNAVAILABLE]:"Service temporarily unavailable"};function vg(r,e={}){return{code:r,message:e.message||xr.ERROR_MESSAGES[r],details:e.details,retryable:e.retryable??!1,retryAfter:e.retryAfter}}function bg(r){return[Ie.RATE_LIMITED,Ie.TIMEOUT,Ie.CONNECTION_LOST,Ie.SERVICE_UNAVAILABLE].includes(r)}});var hu=M(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.FileEntryType=kt.DiffBase=kt.FileViewType=kt.FileChangeType=void 0;kt.getLanguageFromPath=Eg;kt.parseUnifiedDiff=wg;kt.createSimpleDiff=xg;var qr;(function(r){r.CREATE="create",r.MODIFY="modify",r.DELETE="delete"})(qr||(kt.FileChangeType=qr={}));var fu;(function(r){r.CONTENT="content",r.DIFF="diff"})(fu||(kt.FileViewType=fu={}));var uu;(function(r){r.GIT="git",r.PREVIOUS="previous"})(uu||(kt.DiffBase=uu={}));function Eg(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 wg(r,e){let t=r.split(`
3
- `),i=[],n=0,s=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 _=parseInt(m[1],10),E=parseInt(m[2]||"1",10),S=parseInt(m[3],10),T=parseInt(m[4]||"1",10);a={oldStart:_,oldLines:E,newStart:S,newLines:T,lines:[]},c=_,u=S;continue}a&&(p.startsWith("+")?(a.lines.push({type:"add",content:p.slice(1),oldLineNumber:null,newLineNumber:u++}),n++):p.startsWith("-")?(a.lines.push({type:"remove",content:p.slice(1),oldLineNumber:c++,newLineNumber:null}),s++):(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 s===0&&n>0&&i.length===1&&i[0].oldLines===0?d=qr.CREATE:n===0&&s>0&&i.length===1&&i[0].newLines===0?d=qr.DELETE:d=qr.MODIFY,{path:e,changeType:d,hunks:i,additions:n,deletions:s,isBinary:!1}}function xg(r,e,t){let i=r.split(`
2
+ "use strict";var mp=Object.create;var zo=Object.defineProperty;var yp=Object.getOwnPropertyDescriptor;var _p=Object.getOwnPropertyNames;var bp=Object.getPrototypeOf,vp=Object.prototype.hasOwnProperty;var qt=(r,e)=>()=>(r&&(e=r(r=0)),e);var M=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ep=(r,e)=>{for(var t in e)zo(r,t,{get:e[t],enumerable:!0})},wp=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of _p(e))!vp.call(r,n)&&n!==t&&zo(r,n,{get:()=>e[n],enumerable:!(i=yp(e,n))||i.enumerable});return r};var fe=(r,e,t)=>(t=r!=null?mp(bp(r)):{},wp(e||!r||!r.__esModule?zo(t,"default",{value:r,enumerable:!0}):t,r));var os=M(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.generateCorrelationId=Tp;mn.runWithCorrelation=Cp;mn.getCurrentCorrelationId=kp;var Sp=require("async_hooks");function Tp(){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 Rf=new Sp.AsyncLocalStorage;function Cp(r,e){return Rf.run(r,e)}function kp(){return Rf.getStore()}});var If=M(Ai=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:!0});Ai.LOG_LEVELS=void 0;Ai.shouldLog=Pp;Ai.formatLogLine=Rp;var Op=os();Ai.LOG_LEVELS=["silent","error","warn","info","debug"];var Af={silent:0,error:1,warn:2,info:3,debug:4};function Pp(r,e){return Af[r]<=Af[e]}function Rp(r,e,t,i){let n={ts:new Date().toISOString(),level:r,src:e,msg:t},s=(0,Op.getCurrentCorrelationId)();s&&(n.cid=s);let a=i;a.length>0&&typeof a[0]=="object"&&a[0]!==null&&!(a[0]instanceof Error)&&!Array.isArray(a[0])&&(n.ctx=a[0],a=a.slice(1));let c=[...a].reverse().find(u=>u instanceof Error);c&&(n.err={message:c.message,stack:c.stack,name:c.name},a=a.filter(u=>u!==c)),a.length>0&&(n.args=a);try{return JSON.stringify(n)}catch{return JSON.stringify({ts:n.ts,level:r,src:e,msg:t,_unserializable:!0})}}});var Lf=M(Dr=>{"use strict";Object.defineProperty(Dr,"__esModule",{value:!0});Dr.formatLogLine=Dr.shouldLog=Dr.LOG_LEVELS=void 0;var $o=If();Object.defineProperty(Dr,"LOG_LEVELS",{enumerable:!0,get:function(){return $o.LOG_LEVELS}});Object.defineProperty(Dr,"shouldLog",{enumerable:!0,get:function(){return $o.shouldLog}});Object.defineProperty(Dr,"formatLogLine",{enumerable:!0,get:function(){return $o.formatLogLine}})});var Nf=M(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.CircularBuffer=void 0;var Go=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}};as.CircularBuffer=Go});var fs=M(cs=>{"use strict";Object.defineProperty(cs,"__esModule",{value:!0});cs.getApiUrl=Ap;cs.getWsUrl=Ip;function Ap(r){return`${r.getServerUrl()}/api`}function Ip(r){let e=r.getServerUrl();return e.startsWith("https://")?e.replace(/^https:\/\//,"wss://"):e.replace(/^http:\/\//,"ws://")}});var Ff=M(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.getCurrentCorrelationId=bt.runWithCorrelation=bt.generateCorrelationId=bt.getWsUrl=bt.getApiUrl=bt.CircularBuffer=void 0;var Lp=Nf();Object.defineProperty(bt,"CircularBuffer",{enumerable:!0,get:function(){return Lp.CircularBuffer}});var Mf=fs();Object.defineProperty(bt,"getApiUrl",{enumerable:!0,get:function(){return Mf.getApiUrl}});Object.defineProperty(bt,"getWsUrl",{enumerable:!0,get:function(){return Mf.getWsUrl}});var Yo=os();Object.defineProperty(bt,"generateCorrelationId",{enumerable:!0,get:function(){return Yo.generateCorrelationId}});Object.defineProperty(bt,"runWithCorrelation",{enumerable:!0,get:function(){return Yo.runWithCorrelation}});Object.defineProperty(bt,"getCurrentCorrelationId",{enumerable:!0,get:function(){return Yo.getCurrentCorrelationId}})});var Bf=M(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0})});var Uf=M(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0})});var Kf=M(us=>{"use strict";Object.defineProperty(us,"__esModule",{value:!0});us.PLAN_LIMITS=void 0;us.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 Wf=M(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0})});var Hf=M(Jt=>{"use strict";var Np=Jt&&Jt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),ls=Jt&&Jt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Np(e,r,t)};Object.defineProperty(Jt,"__esModule",{value:!0});ls(Bf(),Jt);ls(Uf(),Jt);ls(Kf(),Jt);ls(Wf(),Jt)});var Vf=M(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.API_VERSION=It.WS_NAMESPACES=It.TIMEOUTS=It.STATUS_PATTERNS=It.TERMINAL_STATUSES=void 0;It.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"}};It.STATUS_PATTERNS={idle:[/[❯$]\s*$/,/>\s*$/],waiting:[/\[Y\/n\]/i,/\(y\/N\)/i,/Continue\?/i,/proceed\?/i],completed:[/✓/,/Done/,/Completed/,/Success/],error:[/Error/,/Failed/,/✕/,/Exception/]};It.TIMEOUTS={HEARTBEAT_INTERVAL:3e4,OFFLINE_THRESHOLD:6e4,DEVICE_CODE_EXPIRY:9e5,DEVICE_CODE_POLL_INTERVAL:5e3};It.WS_NAMESPACES={AGENT:"/agent",CLIENT:"/client"};It.API_VERSION="v1"});var zf=M(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.isMultiRecipientPayload=Mp;hs.isEncryptedPayload=Fp;function Mp(r){return typeof r=="object"&&r!==null&&"v"in r&&r.v===2&&"recipients"in r&&Array.isArray(r.recipients)}function Fp(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 Xo=M(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.KX_SIG_VERSION=Zt.KX_FINGERPRINT_LABEL=Zt.KX_ACK_LABEL=Zt.KX_SIGN_LABEL=void 0;Zt.KX_SIGN_LABEL="termiq-kx-v1";Zt.KX_ACK_LABEL="termiq-kxack-v1";Zt.KX_FINGERPRINT_LABEL="termiq-fp-v1";Zt.KX_SIG_VERSION=1});var yn=M((nE,ds)=>{(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),n=new Uint8Array(32);n[0]=9;var s=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]),_=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 S(f,h,l,o,g){var b,v=0;for(b=0;b<g;b++)v|=f[h+b]^l[o+b];return(1&v-1>>>8)-1}function T(f,h,l,o){return S(f,h,l,o,16)}function z(f,h,l,o){return S(f,h,l,o,32)}function ge(f,h,l,o){for(var g=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,b=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,v=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,k=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,D=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,J=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,W=h[0]&255|(h[1]&255)<<8|(h[2]&255)<<16|(h[3]&255)<<24,Pe=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,ne=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,se=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,he=l[16]&255|(l[17]&255)<<8|(l[18]&255)<<16|(l[19]&255)<<24,le=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,oe=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,ce=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,ae=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,$=g,Q=b,H=v,G=k,Y=D,q=J,w=W,x=Pe,I=V,C=ne,O=se,F=he,ie=le,de=oe,me=ce,pe=ae,y,be=0;be<20;be+=2)y=$+ie|0,Y^=y<<7|y>>>25,y=Y+$|0,I^=y<<9|y>>>23,y=I+Y|0,ie^=y<<13|y>>>19,y=ie+I|0,$^=y<<18|y>>>14,y=q+Q|0,C^=y<<7|y>>>25,y=C+q|0,de^=y<<9|y>>>23,y=de+C|0,Q^=y<<13|y>>>19,y=Q+de|0,q^=y<<18|y>>>14,y=O+w|0,me^=y<<7|y>>>25,y=me+O|0,H^=y<<9|y>>>23,y=H+me|0,w^=y<<13|y>>>19,y=w+H|0,O^=y<<18|y>>>14,y=pe+F|0,G^=y<<7|y>>>25,y=G+pe|0,x^=y<<9|y>>>23,y=x+G|0,F^=y<<13|y>>>19,y=F+x|0,pe^=y<<18|y>>>14,y=$+G|0,Q^=y<<7|y>>>25,y=Q+$|0,H^=y<<9|y>>>23,y=H+Q|0,G^=y<<13|y>>>19,y=G+H|0,$^=y<<18|y>>>14,y=q+Y|0,w^=y<<7|y>>>25,y=w+q|0,x^=y<<9|y>>>23,y=x+w|0,Y^=y<<13|y>>>19,y=Y+x|0,q^=y<<18|y>>>14,y=O+C|0,F^=y<<7|y>>>25,y=F+O|0,I^=y<<9|y>>>23,y=I+F|0,C^=y<<13|y>>>19,y=C+I|0,O^=y<<18|y>>>14,y=pe+me|0,ie^=y<<7|y>>>25,y=ie+pe|0,de^=y<<9|y>>>23,y=de+ie|0,me^=y<<13|y>>>19,y=me+de|0,pe^=y<<18|y>>>14;$=$+g|0,Q=Q+b|0,H=H+v|0,G=G+k|0,Y=Y+D|0,q=q+J|0,w=w+W|0,x=x+Pe|0,I=I+V|0,C=C+ne|0,O=O+se|0,F=F+he|0,ie=ie+le|0,de=de+oe|0,me=me+ce|0,pe=pe+ae|0,f[0]=$>>>0&255,f[1]=$>>>8&255,f[2]=$>>>16&255,f[3]=$>>>24&255,f[4]=Q>>>0&255,f[5]=Q>>>8&255,f[6]=Q>>>16&255,f[7]=Q>>>24&255,f[8]=H>>>0&255,f[9]=H>>>8&255,f[10]=H>>>16&255,f[11]=H>>>24&255,f[12]=G>>>0&255,f[13]=G>>>8&255,f[14]=G>>>16&255,f[15]=G>>>24&255,f[16]=Y>>>0&255,f[17]=Y>>>8&255,f[18]=Y>>>16&255,f[19]=Y>>>24&255,f[20]=q>>>0&255,f[21]=q>>>8&255,f[22]=q>>>16&255,f[23]=q>>>24&255,f[24]=w>>>0&255,f[25]=w>>>8&255,f[26]=w>>>16&255,f[27]=w>>>24&255,f[28]=x>>>0&255,f[29]=x>>>8&255,f[30]=x>>>16&255,f[31]=x>>>24&255,f[32]=I>>>0&255,f[33]=I>>>8&255,f[34]=I>>>16&255,f[35]=I>>>24&255,f[36]=C>>>0&255,f[37]=C>>>8&255,f[38]=C>>>16&255,f[39]=C>>>24&255,f[40]=O>>>0&255,f[41]=O>>>8&255,f[42]=O>>>16&255,f[43]=O>>>24&255,f[44]=F>>>0&255,f[45]=F>>>8&255,f[46]=F>>>16&255,f[47]=F>>>24&255,f[48]=ie>>>0&255,f[49]=ie>>>8&255,f[50]=ie>>>16&255,f[51]=ie>>>24&255,f[52]=de>>>0&255,f[53]=de>>>8&255,f[54]=de>>>16&255,f[55]=de>>>24&255,f[56]=me>>>0&255,f[57]=me>>>8&255,f[58]=me>>>16&255,f[59]=me>>>24&255,f[60]=pe>>>0&255,f[61]=pe>>>8&255,f[62]=pe>>>16&255,f[63]=pe>>>24&255}function ee(f,h,l,o){for(var g=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,b=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,v=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,k=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,D=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,J=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,W=h[0]&255|(h[1]&255)<<8|(h[2]&255)<<16|(h[3]&255)<<24,Pe=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,ne=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,se=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,he=l[16]&255|(l[17]&255)<<8|(l[18]&255)<<16|(l[19]&255)<<24,le=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,oe=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,ce=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,ae=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,$=g,Q=b,H=v,G=k,Y=D,q=J,w=W,x=Pe,I=V,C=ne,O=se,F=he,ie=le,de=oe,me=ce,pe=ae,y,be=0;be<20;be+=2)y=$+ie|0,Y^=y<<7|y>>>25,y=Y+$|0,I^=y<<9|y>>>23,y=I+Y|0,ie^=y<<13|y>>>19,y=ie+I|0,$^=y<<18|y>>>14,y=q+Q|0,C^=y<<7|y>>>25,y=C+q|0,de^=y<<9|y>>>23,y=de+C|0,Q^=y<<13|y>>>19,y=Q+de|0,q^=y<<18|y>>>14,y=O+w|0,me^=y<<7|y>>>25,y=me+O|0,H^=y<<9|y>>>23,y=H+me|0,w^=y<<13|y>>>19,y=w+H|0,O^=y<<18|y>>>14,y=pe+F|0,G^=y<<7|y>>>25,y=G+pe|0,x^=y<<9|y>>>23,y=x+G|0,F^=y<<13|y>>>19,y=F+x|0,pe^=y<<18|y>>>14,y=$+G|0,Q^=y<<7|y>>>25,y=Q+$|0,H^=y<<9|y>>>23,y=H+Q|0,G^=y<<13|y>>>19,y=G+H|0,$^=y<<18|y>>>14,y=q+Y|0,w^=y<<7|y>>>25,y=w+q|0,x^=y<<9|y>>>23,y=x+w|0,Y^=y<<13|y>>>19,y=Y+x|0,q^=y<<18|y>>>14,y=O+C|0,F^=y<<7|y>>>25,y=F+O|0,I^=y<<9|y>>>23,y=I+F|0,C^=y<<13|y>>>19,y=C+I|0,O^=y<<18|y>>>14,y=pe+me|0,ie^=y<<7|y>>>25,y=ie+pe|0,de^=y<<9|y>>>23,y=de+ie|0,me^=y<<13|y>>>19,y=me+de|0,pe^=y<<18|y>>>14;f[0]=$>>>0&255,f[1]=$>>>8&255,f[2]=$>>>16&255,f[3]=$>>>24&255,f[4]=q>>>0&255,f[5]=q>>>8&255,f[6]=q>>>16&255,f[7]=q>>>24&255,f[8]=O>>>0&255,f[9]=O>>>8&255,f[10]=O>>>16&255,f[11]=O>>>24&255,f[12]=pe>>>0&255,f[13]=pe>>>8&255,f[14]=pe>>>16&255,f[15]=pe>>>24&255,f[16]=w>>>0&255,f[17]=w>>>8&255,f[18]=w>>>16&255,f[19]=w>>>24&255,f[20]=x>>>0&255,f[21]=x>>>8&255,f[22]=x>>>16&255,f[23]=x>>>24&255,f[24]=I>>>0&255,f[25]=I>>>8&255,f[26]=I>>>16&255,f[27]=I>>>24&255,f[28]=C>>>0&255,f[29]=C>>>8&255,f[30]=C>>>16&255,f[31]=C>>>24&255}function R(f,h,l,o){ge(f,h,l,o)}function B(f,h,l,o){ee(f,h,l,o)}var re=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function K(f,h,l,o,g,b,v){var k=new Uint8Array(16),D=new Uint8Array(64),J,W;for(W=0;W<16;W++)k[W]=0;for(W=0;W<8;W++)k[W]=b[W];for(;g>=64;){for(R(D,k,v,re),W=0;W<64;W++)f[h+W]=l[o+W]^D[W];for(J=1,W=8;W<16;W++)J=J+(k[W]&255)|0,k[W]=J&255,J>>>=8;g-=64,h+=64,o+=64}if(g>0)for(R(D,k,v,re),W=0;W<g;W++)f[h+W]=l[o+W]^D[W];return 0}function U(f,h,l,o,g){var b=new Uint8Array(16),v=new Uint8Array(64),k,D;for(D=0;D<16;D++)b[D]=0;for(D=0;D<8;D++)b[D]=o[D];for(;l>=64;){for(R(v,b,g,re),D=0;D<64;D++)f[h+D]=v[D];for(k=1,D=8;D<16;D++)k=k+(b[D]&255)|0,b[D]=k&255,k>>>=8;l-=64,h+=64}if(l>0)for(R(v,b,g,re),D=0;D<l;D++)f[h+D]=v[D];return 0}function ye(f,h,l,o,g){var b=new Uint8Array(32);B(b,o,g,re);for(var v=new Uint8Array(8),k=0;k<8;k++)v[k]=o[k+16];return U(f,h,l,v,b)}function xe(f,h,l,o,g,b,v){var k=new Uint8Array(32);B(k,b,v,re);for(var D=new Uint8Array(8),J=0;J<8;J++)D[J]=b[J+16];return K(f,h,l,o,g,D,k)}var ue=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,b,v,k,D;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,b=f[8]&255|(f[9]&255)<<8,this.r[4]=(g>>>4|b<<12)&255,this.r[5]=b>>>1&8190,v=f[10]&255|(f[11]&255)<<8,this.r[6]=(b>>>14|v<<2)&8191,k=f[12]&255|(f[13]&255)<<8,this.r[7]=(v>>>11|k<<5)&8065,D=f[14]&255|(f[15]&255)<<8,this.r[8]=(k>>>8|D<<8)&8191,this.r[9]=D>>>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};ue.prototype.blocks=function(f,h,l){for(var o=this.fin?0:2048,g,b,v,k,D,J,W,Pe,V,ne,se,he,le,oe,ce,ae,$,Q,H,G=this.h[0],Y=this.h[1],q=this.h[2],w=this.h[3],x=this.h[4],I=this.h[5],C=this.h[6],O=this.h[7],F=this.h[8],ie=this.h[9],de=this.r[0],me=this.r[1],pe=this.r[2],y=this.r[3],be=this.r[4],Re=this.r[5],Ae=this.r[6],_e=this.r[7],Ce=this.r[8],ke=this.r[9];l>=16;)g=f[h+0]&255|(f[h+1]&255)<<8,G+=g&8191,b=f[h+2]&255|(f[h+3]&255)<<8,Y+=(g>>>13|b<<3)&8191,v=f[h+4]&255|(f[h+5]&255)<<8,q+=(b>>>10|v<<6)&8191,k=f[h+6]&255|(f[h+7]&255)<<8,w+=(v>>>7|k<<9)&8191,D=f[h+8]&255|(f[h+9]&255)<<8,x+=(k>>>4|D<<12)&8191,I+=D>>>1&8191,J=f[h+10]&255|(f[h+11]&255)<<8,C+=(D>>>14|J<<2)&8191,W=f[h+12]&255|(f[h+13]&255)<<8,O+=(J>>>11|W<<5)&8191,Pe=f[h+14]&255|(f[h+15]&255)<<8,F+=(W>>>8|Pe<<8)&8191,ie+=Pe>>>5|o,V=0,ne=V,ne+=G*de,ne+=Y*(5*ke),ne+=q*(5*Ce),ne+=w*(5*_e),ne+=x*(5*Ae),V=ne>>>13,ne&=8191,ne+=I*(5*Re),ne+=C*(5*be),ne+=O*(5*y),ne+=F*(5*pe),ne+=ie*(5*me),V+=ne>>>13,ne&=8191,se=V,se+=G*me,se+=Y*de,se+=q*(5*ke),se+=w*(5*Ce),se+=x*(5*_e),V=se>>>13,se&=8191,se+=I*(5*Ae),se+=C*(5*Re),se+=O*(5*be),se+=F*(5*y),se+=ie*(5*pe),V+=se>>>13,se&=8191,he=V,he+=G*pe,he+=Y*me,he+=q*de,he+=w*(5*ke),he+=x*(5*Ce),V=he>>>13,he&=8191,he+=I*(5*_e),he+=C*(5*Ae),he+=O*(5*Re),he+=F*(5*be),he+=ie*(5*y),V+=he>>>13,he&=8191,le=V,le+=G*y,le+=Y*pe,le+=q*me,le+=w*de,le+=x*(5*ke),V=le>>>13,le&=8191,le+=I*(5*Ce),le+=C*(5*_e),le+=O*(5*Ae),le+=F*(5*Re),le+=ie*(5*be),V+=le>>>13,le&=8191,oe=V,oe+=G*be,oe+=Y*y,oe+=q*pe,oe+=w*me,oe+=x*de,V=oe>>>13,oe&=8191,oe+=I*(5*ke),oe+=C*(5*Ce),oe+=O*(5*_e),oe+=F*(5*Ae),oe+=ie*(5*Re),V+=oe>>>13,oe&=8191,ce=V,ce+=G*Re,ce+=Y*be,ce+=q*y,ce+=w*pe,ce+=x*me,V=ce>>>13,ce&=8191,ce+=I*de,ce+=C*(5*ke),ce+=O*(5*Ce),ce+=F*(5*_e),ce+=ie*(5*Ae),V+=ce>>>13,ce&=8191,ae=V,ae+=G*Ae,ae+=Y*Re,ae+=q*be,ae+=w*y,ae+=x*pe,V=ae>>>13,ae&=8191,ae+=I*me,ae+=C*de,ae+=O*(5*ke),ae+=F*(5*Ce),ae+=ie*(5*_e),V+=ae>>>13,ae&=8191,$=V,$+=G*_e,$+=Y*Ae,$+=q*Re,$+=w*be,$+=x*y,V=$>>>13,$&=8191,$+=I*pe,$+=C*me,$+=O*de,$+=F*(5*ke),$+=ie*(5*Ce),V+=$>>>13,$&=8191,Q=V,Q+=G*Ce,Q+=Y*_e,Q+=q*Ae,Q+=w*Re,Q+=x*be,V=Q>>>13,Q&=8191,Q+=I*y,Q+=C*pe,Q+=O*me,Q+=F*de,Q+=ie*(5*ke),V+=Q>>>13,Q&=8191,H=V,H+=G*ke,H+=Y*Ce,H+=q*_e,H+=w*Ae,H+=x*Re,V=H>>>13,H&=8191,H+=I*be,H+=C*y,H+=O*pe,H+=F*me,H+=ie*de,V+=H>>>13,H&=8191,V=(V<<2)+V|0,V=V+ne|0,ne=V&8191,V=V>>>13,se+=V,G=ne,Y=se,q=he,w=le,x=oe,I=ce,C=ae,O=$,F=Q,ie=H,h+=16,l-=16;this.h[0]=G,this.h[1]=Y,this.h[2]=q,this.h[3]=w,this.h[4]=x,this.h[5]=I,this.h[6]=C,this.h[7]=O,this.h[8]=F,this.h[9]=ie},ue.prototype.finish=function(f,h){var l=new Uint16Array(10),o,g,b,v;if(this.leftover){for(v=this.leftover,this.buffer[v++]=1;v<16;v++)this.buffer[v]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(o=this.h[1]>>>13,this.h[1]&=8191,v=2;v<10;v++)this.h[v]+=o,o=this.h[v]>>>13,this.h[v]&=8191;for(this.h[0]+=o*5,o=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=o,o=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=o,l[0]=this.h[0]+5,o=l[0]>>>13,l[0]&=8191,v=1;v<10;v++)l[v]=this.h[v]+o,o=l[v]>>>13,l[v]&=8191;for(l[9]-=8192,g=(o^1)-1,v=0;v<10;v++)l[v]&=g;for(g=~g,v=0;v<10;v++)this.h[v]=this.h[v]&g|l[v];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,b=this.h[0]+this.pad[0],this.h[0]=b&65535,v=1;v<8;v++)b=(this.h[v]+this.pad[v]|0)+(b>>>16)|0,this.h[v]=b&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},ue.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 rt(f,h,l,o,g,b){var v=new ue(b);return v.update(l,o,g),v.finish(f,h),0}function Ee(f,h,l,o,g,b){var v=new Uint8Array(16);return rt(v,0,l,o,g,b),T(f,h,v,0)}function Se(f,h,l,o,g){var b;if(l<32)return-1;for(xe(f,0,h,0,l,o,g),rt(f,16,f,32,l-32,f),b=0;b<16;b++)f[b]=0;return 0}function ve(f,h,l,o,g){var b,v=new Uint8Array(32);if(l<32||(ye(v,0,32,o,g),Ee(h,16,h,32,l-32,v)!==0))return-1;for(xe(f,0,h,0,l,o,g),b=0;b<32;b++)f[b]=0;return 0}function We(f,h){var l;for(l=0;l<16;l++)f[l]=h[l]|0}function st(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 Ze(f,h,l){for(var o,g=~(l-1),b=0;b<16;b++)o=g&(f[b]^h[b]),f[b]^=o,h[b]^=o}function Te(f,h){var l,o,g,b=e(),v=e();for(l=0;l<16;l++)v[l]=h[l];for(st(v),st(v),st(v),o=0;o<2;o++){for(b[0]=v[0]-65517,l=1;l<15;l++)b[l]=v[l]-65535-(b[l-1]>>16&1),b[l-1]&=65535;b[15]=v[15]-32767-(b[14]>>16&1),g=b[15]>>16&1,b[14]&=65535,Ze(v,b,1-g)}for(l=0;l<16;l++)f[2*l]=v[l]&255,f[2*l+1]=v[l]>>8}function it(f,h){var l=new Uint8Array(32),o=new Uint8Array(32);return Te(l,f),Te(o,h),z(l,0,o,0)}function ze(f){var h=new Uint8Array(32);return Te(h,f),h[0]&1}function gt(f,h){var l;for(l=0;l<16;l++)f[l]=h[2*l]+(h[2*l+1]<<8);f[15]&=32767}function L(f,h,l){for(var o=0;o<16;o++)f[o]=h[o]+l[o]}function j(f,h,l){for(var o=0;o<16;o++)f[o]=h[o]-l[o]}function A(f,h,l){var o,g,b=0,v=0,k=0,D=0,J=0,W=0,Pe=0,V=0,ne=0,se=0,he=0,le=0,oe=0,ce=0,ae=0,$=0,Q=0,H=0,G=0,Y=0,q=0,w=0,x=0,I=0,C=0,O=0,F=0,ie=0,de=0,me=0,pe=0,y=l[0],be=l[1],Re=l[2],Ae=l[3],_e=l[4],Ce=l[5],ke=l[6],Je=l[7],Me=l[8],$e=l[9],Ge=l[10],Ye=l[11],nt=l[12],ht=l[13],dt=l[14],pt=l[15];o=h[0],b+=o*y,v+=o*be,k+=o*Re,D+=o*Ae,J+=o*_e,W+=o*Ce,Pe+=o*ke,V+=o*Je,ne+=o*Me,se+=o*$e,he+=o*Ge,le+=o*Ye,oe+=o*nt,ce+=o*ht,ae+=o*dt,$+=o*pt,o=h[1],v+=o*y,k+=o*be,D+=o*Re,J+=o*Ae,W+=o*_e,Pe+=o*Ce,V+=o*ke,ne+=o*Je,se+=o*Me,he+=o*$e,le+=o*Ge,oe+=o*Ye,ce+=o*nt,ae+=o*ht,$+=o*dt,Q+=o*pt,o=h[2],k+=o*y,D+=o*be,J+=o*Re,W+=o*Ae,Pe+=o*_e,V+=o*Ce,ne+=o*ke,se+=o*Je,he+=o*Me,le+=o*$e,oe+=o*Ge,ce+=o*Ye,ae+=o*nt,$+=o*ht,Q+=o*dt,H+=o*pt,o=h[3],D+=o*y,J+=o*be,W+=o*Re,Pe+=o*Ae,V+=o*_e,ne+=o*Ce,se+=o*ke,he+=o*Je,le+=o*Me,oe+=o*$e,ce+=o*Ge,ae+=o*Ye,$+=o*nt,Q+=o*ht,H+=o*dt,G+=o*pt,o=h[4],J+=o*y,W+=o*be,Pe+=o*Re,V+=o*Ae,ne+=o*_e,se+=o*Ce,he+=o*ke,le+=o*Je,oe+=o*Me,ce+=o*$e,ae+=o*Ge,$+=o*Ye,Q+=o*nt,H+=o*ht,G+=o*dt,Y+=o*pt,o=h[5],W+=o*y,Pe+=o*be,V+=o*Re,ne+=o*Ae,se+=o*_e,he+=o*Ce,le+=o*ke,oe+=o*Je,ce+=o*Me,ae+=o*$e,$+=o*Ge,Q+=o*Ye,H+=o*nt,G+=o*ht,Y+=o*dt,q+=o*pt,o=h[6],Pe+=o*y,V+=o*be,ne+=o*Re,se+=o*Ae,he+=o*_e,le+=o*Ce,oe+=o*ke,ce+=o*Je,ae+=o*Me,$+=o*$e,Q+=o*Ge,H+=o*Ye,G+=o*nt,Y+=o*ht,q+=o*dt,w+=o*pt,o=h[7],V+=o*y,ne+=o*be,se+=o*Re,he+=o*Ae,le+=o*_e,oe+=o*Ce,ce+=o*ke,ae+=o*Je,$+=o*Me,Q+=o*$e,H+=o*Ge,G+=o*Ye,Y+=o*nt,q+=o*ht,w+=o*dt,x+=o*pt,o=h[8],ne+=o*y,se+=o*be,he+=o*Re,le+=o*Ae,oe+=o*_e,ce+=o*Ce,ae+=o*ke,$+=o*Je,Q+=o*Me,H+=o*$e,G+=o*Ge,Y+=o*Ye,q+=o*nt,w+=o*ht,x+=o*dt,I+=o*pt,o=h[9],se+=o*y,he+=o*be,le+=o*Re,oe+=o*Ae,ce+=o*_e,ae+=o*Ce,$+=o*ke,Q+=o*Je,H+=o*Me,G+=o*$e,Y+=o*Ge,q+=o*Ye,w+=o*nt,x+=o*ht,I+=o*dt,C+=o*pt,o=h[10],he+=o*y,le+=o*be,oe+=o*Re,ce+=o*Ae,ae+=o*_e,$+=o*Ce,Q+=o*ke,H+=o*Je,G+=o*Me,Y+=o*$e,q+=o*Ge,w+=o*Ye,x+=o*nt,I+=o*ht,C+=o*dt,O+=o*pt,o=h[11],le+=o*y,oe+=o*be,ce+=o*Re,ae+=o*Ae,$+=o*_e,Q+=o*Ce,H+=o*ke,G+=o*Je,Y+=o*Me,q+=o*$e,w+=o*Ge,x+=o*Ye,I+=o*nt,C+=o*ht,O+=o*dt,F+=o*pt,o=h[12],oe+=o*y,ce+=o*be,ae+=o*Re,$+=o*Ae,Q+=o*_e,H+=o*Ce,G+=o*ke,Y+=o*Je,q+=o*Me,w+=o*$e,x+=o*Ge,I+=o*Ye,C+=o*nt,O+=o*ht,F+=o*dt,ie+=o*pt,o=h[13],ce+=o*y,ae+=o*be,$+=o*Re,Q+=o*Ae,H+=o*_e,G+=o*Ce,Y+=o*ke,q+=o*Je,w+=o*Me,x+=o*$e,I+=o*Ge,C+=o*Ye,O+=o*nt,F+=o*ht,ie+=o*dt,de+=o*pt,o=h[14],ae+=o*y,$+=o*be,Q+=o*Re,H+=o*Ae,G+=o*_e,Y+=o*Ce,q+=o*ke,w+=o*Je,x+=o*Me,I+=o*$e,C+=o*Ge,O+=o*Ye,F+=o*nt,ie+=o*ht,de+=o*dt,me+=o*pt,o=h[15],$+=o*y,Q+=o*be,H+=o*Re,G+=o*Ae,Y+=o*_e,q+=o*Ce,w+=o*ke,x+=o*Je,I+=o*Me,C+=o*$e,O+=o*Ge,F+=o*Ye,ie+=o*nt,de+=o*ht,me+=o*dt,pe+=o*pt,b+=38*Q,v+=38*H,k+=38*G,D+=38*Y,J+=38*q,W+=38*w,Pe+=38*x,V+=38*I,ne+=38*C,se+=38*O,he+=38*F,le+=38*ie,oe+=38*de,ce+=38*me,ae+=38*pe,g=1,o=b+g+65535,g=Math.floor(o/65536),b=o-g*65536,o=v+g+65535,g=Math.floor(o/65536),v=o-g*65536,o=k+g+65535,g=Math.floor(o/65536),k=o-g*65536,o=D+g+65535,g=Math.floor(o/65536),D=o-g*65536,o=J+g+65535,g=Math.floor(o/65536),J=o-g*65536,o=W+g+65535,g=Math.floor(o/65536),W=o-g*65536,o=Pe+g+65535,g=Math.floor(o/65536),Pe=o-g*65536,o=V+g+65535,g=Math.floor(o/65536),V=o-g*65536,o=ne+g+65535,g=Math.floor(o/65536),ne=o-g*65536,o=se+g+65535,g=Math.floor(o/65536),se=o-g*65536,o=he+g+65535,g=Math.floor(o/65536),he=o-g*65536,o=le+g+65535,g=Math.floor(o/65536),le=o-g*65536,o=oe+g+65535,g=Math.floor(o/65536),oe=o-g*65536,o=ce+g+65535,g=Math.floor(o/65536),ce=o-g*65536,o=ae+g+65535,g=Math.floor(o/65536),ae=o-g*65536,o=$+g+65535,g=Math.floor(o/65536),$=o-g*65536,b+=g-1+37*(g-1),g=1,o=b+g+65535,g=Math.floor(o/65536),b=o-g*65536,o=v+g+65535,g=Math.floor(o/65536),v=o-g*65536,o=k+g+65535,g=Math.floor(o/65536),k=o-g*65536,o=D+g+65535,g=Math.floor(o/65536),D=o-g*65536,o=J+g+65535,g=Math.floor(o/65536),J=o-g*65536,o=W+g+65535,g=Math.floor(o/65536),W=o-g*65536,o=Pe+g+65535,g=Math.floor(o/65536),Pe=o-g*65536,o=V+g+65535,g=Math.floor(o/65536),V=o-g*65536,o=ne+g+65535,g=Math.floor(o/65536),ne=o-g*65536,o=se+g+65535,g=Math.floor(o/65536),se=o-g*65536,o=he+g+65535,g=Math.floor(o/65536),he=o-g*65536,o=le+g+65535,g=Math.floor(o/65536),le=o-g*65536,o=oe+g+65535,g=Math.floor(o/65536),oe=o-g*65536,o=ce+g+65535,g=Math.floor(o/65536),ce=o-g*65536,o=ae+g+65535,g=Math.floor(o/65536),ae=o-g*65536,o=$+g+65535,g=Math.floor(o/65536),$=o-g*65536,b+=g-1+37*(g-1),f[0]=b,f[1]=v,f[2]=k,f[3]=D,f[4]=J,f[5]=W,f[6]=Pe,f[7]=V,f[8]=ne,f[9]=se,f[10]=he,f[11]=le,f[12]=oe,f[13]=ce,f[14]=ae,f[15]=$}function P(f,h){A(f,h,h)}function Z(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=253;o>=0;o--)P(l,l),o!==2&&o!==4&&A(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function Ne(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=250;o>=0;o--)P(l,l),o!==1&&A(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function Xe(f,h,l){var o=new Uint8Array(32),g=new Float64Array(80),b,v,k=e(),D=e(),J=e(),W=e(),Pe=e(),V=e();for(v=0;v<31;v++)o[v]=h[v];for(o[31]=h[31]&127|64,o[0]&=248,gt(g,l),v=0;v<16;v++)D[v]=g[v],W[v]=k[v]=J[v]=0;for(k[0]=W[0]=1,v=254;v>=0;--v)b=o[v>>>3]>>>(v&7)&1,Ze(k,D,b),Ze(J,W,b),L(Pe,k,J),j(k,k,J),L(J,D,W),j(D,D,W),P(W,Pe),P(V,k),A(k,J,k),A(J,D,Pe),L(Pe,k,J),j(k,k,J),P(D,k),j(J,W,V),A(k,J,c),L(k,k,W),A(J,J,k),A(k,W,V),A(W,D,g),P(D,Pe),Ze(k,D,b),Ze(J,W,b);for(v=0;v<16;v++)g[v+16]=k[v],g[v+32]=J[v],g[v+48]=D[v],g[v+64]=W[v];var ne=g.subarray(32),se=g.subarray(16);return Z(ne,ne),A(se,se,ne),Te(f,se),0}function lt(f,h){return Xe(f,h,n)}function wt(f,h){return t(h,32),lt(f,h)}function mr(f,h,l){var o=new Uint8Array(32);return Xe(o,l,h),B(f,i,o,re)}var Mr=Se,ii=ve;function Fr(f,h,l,o,g,b){var v=new Uint8Array(32);return mr(v,g,b),Mr(f,h,l,o,v)}function Oi(f,h,l,o,g,b){var v=new Uint8Array(32);return mr(v,g,b),ii(f,h,l,o,v)}var Xn=[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 wf(f,h,l,o){for(var g=new Int32Array(16),b=new Int32Array(16),v,k,D,J,W,Pe,V,ne,se,he,le,oe,ce,ae,$,Q,H,G,Y,q,w,x,I,C,O,F,ie=f[0],de=f[1],me=f[2],pe=f[3],y=f[4],be=f[5],Re=f[6],Ae=f[7],_e=h[0],Ce=h[1],ke=h[2],Je=h[3],Me=h[4],$e=h[5],Ge=h[6],Ye=h[7],nt=0;o>=128;){for(Y=0;Y<16;Y++)q=8*Y+nt,g[Y]=l[q+0]<<24|l[q+1]<<16|l[q+2]<<8|l[q+3],b[Y]=l[q+4]<<24|l[q+5]<<16|l[q+6]<<8|l[q+7];for(Y=0;Y<80;Y++)if(v=ie,k=de,D=me,J=pe,W=y,Pe=be,V=Re,ne=Ae,se=_e,he=Ce,le=ke,oe=Je,ce=Me,ae=$e,$=Ge,Q=Ye,w=Ae,x=Ye,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=(y>>>14|Me<<18)^(y>>>18|Me<<14)^(Me>>>9|y<<23),x=(Me>>>14|y<<18)^(Me>>>18|y<<14)^(y>>>9|Me<<23),I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,w=y&be^~y&Re,x=Me&$e^~Me&Ge,I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,w=Xn[Y*2],x=Xn[Y*2+1],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,w=g[Y%16],x=b[Y%16],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,H=O&65535|F<<16,G=I&65535|C<<16,w=H,x=G,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=(ie>>>28|_e<<4)^(_e>>>2|ie<<30)^(_e>>>7|ie<<25),x=(_e>>>28|ie<<4)^(ie>>>2|_e<<30)^(ie>>>7|_e<<25),I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,w=ie&de^ie&me^de&me,x=_e&Ce^_e&ke^Ce&ke,I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,ne=O&65535|F<<16,Q=I&65535|C<<16,w=J,x=oe,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=H,x=G,I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,J=O&65535|F<<16,oe=I&65535|C<<16,de=v,me=k,pe=D,y=J,be=W,Re=Pe,Ae=V,ie=ne,Ce=se,ke=he,Je=le,Me=oe,$e=ce,Ge=ae,Ye=$,_e=Q,Y%16===15)for(q=0;q<16;q++)w=g[q],x=b[q],I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=g[(q+9)%16],x=b[(q+9)%16],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,H=g[(q+1)%16],G=b[(q+1)%16],w=(H>>>1|G<<31)^(H>>>8|G<<24)^H>>>7,x=(G>>>1|H<<31)^(G>>>8|H<<24)^(G>>>7|H<<25),I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,H=g[(q+14)%16],G=b[(q+14)%16],w=(H>>>19|G<<13)^(G>>>29|H<<3)^H>>>6,x=(G>>>19|H<<13)^(H>>>29|G<<3)^(G>>>6|H<<26),I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,g[q]=O&65535|F<<16,b[q]=I&65535|C<<16;w=ie,x=_e,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[0],x=h[0],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[0]=ie=O&65535|F<<16,h[0]=_e=I&65535|C<<16,w=de,x=Ce,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[1],x=h[1],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[1]=de=O&65535|F<<16,h[1]=Ce=I&65535|C<<16,w=me,x=ke,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[2],x=h[2],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[2]=me=O&65535|F<<16,h[2]=ke=I&65535|C<<16,w=pe,x=Je,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[3],x=h[3],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[3]=pe=O&65535|F<<16,h[3]=Je=I&65535|C<<16,w=y,x=Me,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[4],x=h[4],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[4]=y=O&65535|F<<16,h[4]=Me=I&65535|C<<16,w=be,x=$e,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[5],x=h[5],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[5]=be=O&65535|F<<16,h[5]=$e=I&65535|C<<16,w=Re,x=Ge,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[6],x=h[6],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[6]=Re=O&65535|F<<16,h[6]=Ge=I&65535|C<<16,w=Ae,x=Ye,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[7],x=h[7],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[7]=Ae=O&65535|F<<16,h[7]=Ye=I&65535|C<<16,nt+=128,o-=128}return o}function ni(f,h,l){var o=new Int32Array(8),g=new Int32Array(8),b=new Uint8Array(256),v,k=l;for(o[0]=1779033703,o[1]=3144134277,o[2]=1013904242,o[3]=2773480762,o[4]=1359893119,o[5]=2600822924,o[6]=528734635,o[7]=1541459225,g[0]=4089235720,g[1]=2227873595,g[2]=4271175723,g[3]=1595750129,g[4]=2917565137,g[5]=725511199,g[6]=4215389547,g[7]=327033209,wf(o,g,h,l),l%=128,v=0;v<l;v++)b[v]=h[k-l+v];for(b[l]=128,l=256-128*(l<112?1:0),b[l-9]=0,E(b,l-8,k/536870912|0,k<<3),wf(o,g,b,l),v=0;v<8;v++)E(f,8*v,o[v],g[v]);return 0}function Jn(f,h){var l=e(),o=e(),g=e(),b=e(),v=e(),k=e(),D=e(),J=e(),W=e();j(l,f[1],f[0]),j(W,h[1],h[0]),A(l,l,W),L(o,f[0],f[1]),L(W,h[0],h[1]),A(o,o,W),A(g,f[3],h[3]),A(g,g,d),A(b,f[2],h[2]),L(b,b,b),j(v,o,l),j(k,b,g),L(D,b,g),L(J,o,l),A(f[0],v,k),A(f[1],J,D),A(f[2],D,k),A(f[3],v,J)}function xf(f,h,l){var o;for(o=0;o<4;o++)Ze(f[o],h[o],l)}function Fo(f,h){var l=e(),o=e(),g=e();Z(g,h[2]),A(l,h[0],g),A(o,h[1],g),Te(f,o),f[31]^=ze(l)<<7}function Do(f,h,l){var o,g;for(We(f[0],s),We(f[1],a),We(f[2],a),We(f[3],s),g=255;g>=0;--g)o=l[g/8|0]>>(g&7)&1,xf(f,h,o),Jn(h,f),Jn(f,f),xf(f,h,o)}function Zn(f,h){var l=[e(),e(),e(),e()];We(l[0],p),We(l[1],m),We(l[2],a),A(l[3],p,m),Do(f,l,h)}function Bo(f,h,l){var o=new Uint8Array(64),g=[e(),e(),e(),e()],b;for(l||t(h,32),ni(o,h,32),o[0]&=248,o[31]&=127,o[31]|=64,Zn(g,o),Fo(f,g),b=0;b<32;b++)h[b+32]=f[b];return 0}var Qn=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 jo(f,h){var l,o,g,b;for(o=63;o>=32;--o){for(l=0,g=o-32,b=o-12;g<b;++g)h[g]+=l-16*h[o]*Qn[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)*Qn[g],l=h[g]>>8,h[g]&=255;for(g=0;g<32;g++)h[g]-=l*Qn[g];for(o=0;o<32;o++)h[o+1]+=h[o]>>8,f[o]=h[o]&255}function Uo(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;jo(f,h)}function Sf(f,h,l,o){var g=new Uint8Array(64),b=new Uint8Array(64),v=new Uint8Array(64),k,D,J=new Float64Array(64),W=[e(),e(),e(),e()];ni(g,o,32),g[0]&=248,g[31]&=127,g[31]|=64;var Pe=l+64;for(k=0;k<l;k++)f[64+k]=h[k];for(k=0;k<32;k++)f[32+k]=g[32+k];for(ni(v,f.subarray(32),l+32),Uo(v),Zn(W,v),Fo(f,W),k=32;k<64;k++)f[k]=o[k];for(ni(b,f,l+64),Uo(b),k=0;k<64;k++)J[k]=0;for(k=0;k<32;k++)J[k]=v[k];for(k=0;k<32;k++)for(D=0;D<32;D++)J[k+D]+=b[k]*g[D];return jo(f.subarray(32),J),Pe}function hp(f,h){var l=e(),o=e(),g=e(),b=e(),v=e(),k=e(),D=e();return We(f[2],a),gt(f[1],h),P(g,f[1]),A(b,g,u),j(g,g,f[2]),L(b,f[2],b),P(v,b),P(k,v),A(D,k,v),A(l,D,g),A(l,l,b),Ne(l,l),A(l,l,g),A(l,l,b),A(l,l,b),A(f[0],l,b),P(o,f[0]),A(o,o,b),it(o,g)&&A(f[0],f[0],_),P(o,f[0]),A(o,o,b),it(o,g)?-1:(ze(f[0])===h[31]>>7&&j(f[0],s,f[0]),A(f[3],f[0],f[1]),0)}function Ko(f,h,l,o){var g,b=new Uint8Array(32),v=new Uint8Array(64),k=[e(),e(),e(),e()],D=[e(),e(),e(),e()];if(l<64||hp(D,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(ni(v,f,l),Uo(v),Do(k,D,v),Zn(D,h.subarray(32)),Jn(k,D),Fo(b,k),l-=64,z(h,0,b,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 qo=32,es=24,un=32,Pi=16,ln=32,ts=32,hn=32,dn=32,Wo=32,Tf=es,dp=un,pp=Pi,yr=64,si=32,Ri=64,Ho=32,Vo=64;r.lowlevel={crypto_core_hsalsa20:B,crypto_stream_xor:xe,crypto_stream:ye,crypto_stream_salsa20_xor:K,crypto_stream_salsa20:U,crypto_onetimeauth:rt,crypto_onetimeauth_verify:Ee,crypto_verify_16:T,crypto_verify_32:z,crypto_secretbox:Se,crypto_secretbox_open:ve,crypto_scalarmult:Xe,crypto_scalarmult_base:lt,crypto_box_beforenm:mr,crypto_box_afternm:Mr,crypto_box:Fr,crypto_box_open:Oi,crypto_box_keypair:wt,crypto_hash:ni,crypto_sign:Sf,crypto_sign_keypair:Bo,crypto_sign_open:Ko,crypto_secretbox_KEYBYTES:qo,crypto_secretbox_NONCEBYTES:es,crypto_secretbox_ZEROBYTES:un,crypto_secretbox_BOXZEROBYTES:Pi,crypto_scalarmult_BYTES:ln,crypto_scalarmult_SCALARBYTES:ts,crypto_box_PUBLICKEYBYTES:hn,crypto_box_SECRETKEYBYTES:dn,crypto_box_BEFORENMBYTES:Wo,crypto_box_NONCEBYTES:Tf,crypto_box_ZEROBYTES:dp,crypto_box_BOXZEROBYTES:pp,crypto_sign_BYTES:yr,crypto_sign_PUBLICKEYBYTES:si,crypto_sign_SECRETKEYBYTES:Ri,crypto_sign_SEEDBYTES:Ho,crypto_hash_BYTES:Vo,gf:e,D:u,L:Qn,pack25519:Te,unpack25519:gt,M:A,A:L,S:P,Z:j,pow2523:Ne,add:Jn,set25519:We,modL:jo,scalarmult:Do,scalarbase:Zn};function Cf(f,h){if(f.length!==qo)throw new Error("bad key size");if(h.length!==es)throw new Error("bad nonce size")}function gp(f,h){if(f.length!==hn)throw new Error("bad public key size");if(h.length!==dn)throw new Error("bad secret key size")}function xt(){for(var f=0;f<arguments.length;f++)if(!(arguments[f]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function kf(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){xt(f,h,l),Cf(l,h);for(var o=new Uint8Array(un+f.length),g=new Uint8Array(o.length),b=0;b<f.length;b++)o[b+un]=f[b];return Se(g,o,o.length,h,l),g.subarray(Pi)},r.secretbox.open=function(f,h,l){xt(f,h,l),Cf(l,h);for(var o=new Uint8Array(Pi+f.length),g=new Uint8Array(o.length),b=0;b<f.length;b++)o[b+Pi]=f[b];return o.length<32||ve(g,o,o.length,h,l)!==0?null:g.subarray(un)},r.secretbox.keyLength=qo,r.secretbox.nonceLength=es,r.secretbox.overheadLength=Pi,r.scalarMult=function(f,h){if(xt(f,h),f.length!==ts)throw new Error("bad n size");if(h.length!==ln)throw new Error("bad p size");var l=new Uint8Array(ln);return Xe(l,f,h),l},r.scalarMult.base=function(f){if(xt(f),f.length!==ts)throw new Error("bad n size");var h=new Uint8Array(ln);return lt(h,f),h},r.scalarMult.scalarLength=ts,r.scalarMult.groupElementLength=ln,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){xt(f,h),gp(f,h);var l=new Uint8Array(Wo);return mr(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(hn),h=new Uint8Array(dn);return wt(f,h),{publicKey:f,secretKey:h}},r.box.keyPair.fromSecretKey=function(f){if(xt(f),f.length!==dn)throw new Error("bad secret key size");var h=new Uint8Array(hn);return lt(h,f),{publicKey:h,secretKey:new Uint8Array(f)}},r.box.publicKeyLength=hn,r.box.secretKeyLength=dn,r.box.sharedKeyLength=Wo,r.box.nonceLength=Tf,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(f,h){if(xt(f,h),h.length!==Ri)throw new Error("bad secret key size");var l=new Uint8Array(yr+f.length);return Sf(l,f,f.length,h),l},r.sign.open=function(f,h){if(xt(f,h),h.length!==si)throw new Error("bad public key size");var l=new Uint8Array(f.length),o=Ko(l,f,f.length,h);if(o<0)return null;for(var g=new Uint8Array(o),b=0;b<g.length;b++)g[b]=l[b];return g},r.sign.detached=function(f,h){for(var l=r.sign(f,h),o=new Uint8Array(yr),g=0;g<o.length;g++)o[g]=l[g];return o},r.sign.detached.verify=function(f,h,l){if(xt(f,h,l),h.length!==yr)throw new Error("bad signature size");if(l.length!==si)throw new Error("bad public key size");var o=new Uint8Array(yr+f.length),g=new Uint8Array(yr+f.length),b;for(b=0;b<yr;b++)o[b]=h[b];for(b=0;b<f.length;b++)o[b+yr]=f[b];return Ko(g,o,o.length,l)>=0},r.sign.keyPair=function(){var f=new Uint8Array(si),h=new Uint8Array(Ri);return Bo(f,h),{publicKey:f,secretKey:h}},r.sign.keyPair.fromSecretKey=function(f){if(xt(f),f.length!==Ri)throw new Error("bad secret key size");for(var h=new Uint8Array(si),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(xt(f),f.length!==Ho)throw new Error("bad seed size");for(var h=new Uint8Array(si),l=new Uint8Array(Ri),o=0;o<32;o++)l[o]=f[o];return Bo(h,l,!0),{publicKey:h,secretKey:l}},r.sign.publicKeyLength=si,r.sign.secretKeyLength=Ri,r.sign.seedLength=Ho,r.sign.signatureLength=yr,r.hash=function(f){xt(f);var h=new Uint8Array(Vo);return ni(h,f,f.length),h},r.hash.hashLength=Vo,r.verify=function(f,h){return xt(f,h),f.length===0||h.length===0||f.length!==h.length?!1:S(f,0,h,0,f.length)===0},r.setPRNG=function(f){t=f},(function(){var f=typeof self<"u"?self.crypto||self.msCrypto:null;if(f&&f.getRandomValues){var h=65536;r.setPRNG(function(l,o){var g,b=new Uint8Array(o);for(g=0;g<o;g+=h)f.getRandomValues(b.subarray(g,g+Math.min(o-g,h)));for(g=0;g<o;g++)l[g]=b[g];kf(b)})}else typeof require<"u"&&(f=require("crypto"),f&&f.randomBytes&&r.setPRNG(function(l,o){var g,b=f.randomBytes(o);for(g=0;g<o;g++)l[g]=b[g];kf(b)}))})()})(typeof ds<"u"&&ds.exports?ds.exports:self.nacl=self.nacl||{})});var _n=M(($f,ps)=>{(function(r,e){"use strict";typeof ps<"u"&&ps.exports?ps.exports=e():(r.nacl||(r.nacl={}),r.nacl.util=e())})($f,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,n=unescape(encodeURIComponent(t)),s=new Uint8Array(n.length);for(i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s},r.encodeUTF8=function(t){var i,n=[];for(i=0;i<t.length;i++)n.push(String.fromCharCode(t[i]));return decodeURIComponent(escape(n.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,n=[],s=t.length;for(i=0;i<s;i++)n.push(String.fromCharCode(t[i]));return btoa(n.join(""))},r.decodeBase64=function(t){e(t);var i,n=atob(t),s=new Uint8Array(n.length);for(i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s}),r})});var Gf=M(Tt=>{"use strict";var Dp=Tt&&Tt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Tt,"__esModule",{value:!0});Tt.concatBytes=bn;Tt.generateIdentityKeyPair=Bp;Tt.identityPublicFromSecret=jp;Tt.signSessionKey=Up;Tt.verifySessionKey=Kp;Tt.buildKxCanonical=qp;Tt.buildKxAckCanonical=Wp;Tt.fingerprintIdentityKey=Hp;Tt.fingerprintShortHex=Vp;var Qt=Dp(yn()),St=_n(),gs=Xo();function bn(...r){let e=0;for(let n of r)e+=n.length;let t=new Uint8Array(e),i=0;for(let n of r)t.set(n,i),i+=n.length;return t}function Bp(){let r=Qt.default.sign.keyPair();return{identityPublicKey:(0,St.encodeBase64)(r.publicKey),identitySecretKey:(0,St.encodeBase64)(r.secretKey)}}function jp(r){let e=(0,St.decodeBase64)(r);if(e.length!==Qt.default.sign.secretKeyLength)throw new Error("bad identity secret key length");let t=Qt.default.sign.keyPair.fromSecretKey(e);return(0,St.encodeBase64)(t.publicKey)}function Up(r,e){let t=(0,St.decodeBase64)(e);if(t.length!==Qt.default.sign.secretKeyLength)throw new Error("bad identity secret key length");return(0,St.encodeBase64)(Qt.default.sign.detached(r,t))}function Kp(r,e,t){try{let i=(0,St.decodeBase64)(e),n=(0,St.decodeBase64)(t);return n.length!==Qt.default.sign.publicKeyLength||i.length!==Qt.default.sign.signatureLength?!1:Qt.default.sign.detached.verify(r,i,n)}catch{return!1}}var oi=new Uint8Array([0]);function qp(r){let e=new TextEncoder,t=e.encode(gs.KX_SIGN_LABEL),i=e.encode(r.agentId),n=e.encode(String(r.keyVersion)),s=(0,St.decodeBase64)(r.boxPublicKey);return bn(t,oi,i,oi,n,oi,s)}function Wp(r){let e=new TextEncoder;return bn(e.encode(gs.KX_ACK_LABEL),oi,e.encode(r.agentId),oi,e.encode(String(r.keyVersion)),oi,(0,St.decodeBase64)(r.boxPublicKey),oi,(0,St.decodeBase64)(r.boundClientKey))}function Hp(r){let e=(0,St.decodeBase64)(r),t=bn(new TextEncoder().encode(gs.KX_FINGERPRINT_LABEL),e),i=Qt.default.hash(t),n=[];for(let s=0;s<12;s++){let a=s*5,u=(((i[a]<<24>>>0)+(i[a+1]<<16)+(i[a+2]<<8)+i[a+3]^i[a+4])>>>0)%1e5;n.push(String(u).padStart(5,"0"))}return n.join(" ")}function Vp(r){let e=(0,St.decodeBase64)(r),t=bn(new TextEncoder().encode(gs.KX_FINGERPRINT_LABEL),e),i=Qt.default.hash(t).slice(0,8);return Array.from(i).map(n=>n.toString(16).padStart(2,"0")).join(":").toUpperCase()}});var Yf=M(jr=>{"use strict";var zp=jr&&jr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(jr,"__esModule",{value:!0});jr.encrypt=$p;jr.decrypt=Gp;jr.encryptBinary=Yp;jr.decryptBinary=Xp;var vr=zp(yn()),Br=_n();function $p(r,e,t){let i=vr.default.randomBytes(vr.default.secretbox.nonceLength),n=new TextEncoder().encode(r),s=vr.default.secretbox(n,i,e);return{v:1,sid:t,n:(0,Br.encodeBase64)(i),c:(0,Br.encodeBase64)(s)}}function Gp(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Br.decodeBase64)(r.n),i=(0,Br.decodeBase64)(r.c);if(t.length!==vr.default.secretbox.nonceLength)throw new Error(`Invalid nonce length: ${t.length}`);let n=vr.default.secretbox.open(i,t,e);if(!n)throw new Error("Decryption failed: invalid ciphertext or wrong key");return new TextDecoder().decode(n)}function Yp(r,e,t){let i=vr.default.randomBytes(vr.default.secretbox.nonceLength),n=vr.default.secretbox(r,i,e);return{v:1,sid:t,n:(0,Br.encodeBase64)(i),c:(0,Br.encodeBase64)(n)}}function Xp(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Br.decodeBase64)(r.n),i=(0,Br.decodeBase64)(r.c),n=vr.default.secretbox.open(i,t,e);if(!n)throw new Error("Decryption failed: invalid ciphertext or wrong key");return n}});var Xf=M(Wt=>{"use strict";var Jp=Wt&&Wt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Wt,"__esModule",{value:!0});Wt.generateKeyPair=Zp;Wt.deriveSharedSecret=Qp;Wt.deriveMetaSid=eg;Wt.isValidPublicKey=tg;Wt.clearKey=rg;Wt.keyToBase64=ig;Wt.base64ToKey=ng;var Ii=Jp(yn()),er=_n();function Zp(){let r=Ii.default.box.keyPair();return{publicKey:(0,er.encodeBase64)(r.publicKey),secretKey:(0,er.encodeBase64)(r.secretKey)}}function Qp(r,e){let t=(0,er.decodeBase64)(r),i=(0,er.decodeBase64)(e);if(t.length!==Ii.default.box.publicKeyLength)throw new Error(`Invalid public key length: ${t.length}`);if(i.length!==Ii.default.box.secretKeyLength)throw new Error(`Invalid secret key length: ${i.length}`);return Ii.default.box.before(t,i)}function eg(r,e){let t=new TextEncoder().encode("termiq-meta-v1"),i=(0,er.decodeBase64)(r),n=(0,er.decodeBase64)(e),s=new Uint8Array(t.length+i.length+n.length);return s.set(t,0),s.set(i,t.length),s.set(n,t.length+i.length),(0,er.encodeBase64)(Ii.default.hash(s).slice(0,32))}function tg(r){try{return(0,er.decodeBase64)(r).length===Ii.default.box.publicKeyLength}catch{return!1}}function rg(r){r.fill(0)}function ig(r){return(0,er.encodeBase64)(r)}function ng(r){return(0,er.decodeBase64)(r)}});var Zf=M(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.base64ToKey=te.keyToBase64=te.clearKey=te.isValidPublicKey=te.deriveMetaSid=te.deriveSharedSecret=te.generateKeyPair=te.decryptBinary=te.encryptBinary=te.decrypt=te.encrypt=te.concatBytes=te.fingerprintShortHex=te.fingerprintIdentityKey=te.buildKxAckCanonical=te.buildKxCanonical=te.verifySessionKey=te.signSessionKey=te.identityPublicFromSecret=te.generateIdentityKeyPair=te.KX_SIG_VERSION=te.KX_FINGERPRINT_LABEL=te.KX_ACK_LABEL=te.KX_SIGN_LABEL=te.isMultiRecipientPayload=te.isEncryptedPayload=void 0;var Jf=zf();Object.defineProperty(te,"isEncryptedPayload",{enumerable:!0,get:function(){return Jf.isEncryptedPayload}});Object.defineProperty(te,"isMultiRecipientPayload",{enumerable:!0,get:function(){return Jf.isMultiRecipientPayload}});var ms=Xo();Object.defineProperty(te,"KX_SIGN_LABEL",{enumerable:!0,get:function(){return ms.KX_SIGN_LABEL}});Object.defineProperty(te,"KX_ACK_LABEL",{enumerable:!0,get:function(){return ms.KX_ACK_LABEL}});Object.defineProperty(te,"KX_FINGERPRINT_LABEL",{enumerable:!0,get:function(){return ms.KX_FINGERPRINT_LABEL}});Object.defineProperty(te,"KX_SIG_VERSION",{enumerable:!0,get:function(){return ms.KX_SIG_VERSION}});var Er=Gf();Object.defineProperty(te,"generateIdentityKeyPair",{enumerable:!0,get:function(){return Er.generateIdentityKeyPair}});Object.defineProperty(te,"identityPublicFromSecret",{enumerable:!0,get:function(){return Er.identityPublicFromSecret}});Object.defineProperty(te,"signSessionKey",{enumerable:!0,get:function(){return Er.signSessionKey}});Object.defineProperty(te,"verifySessionKey",{enumerable:!0,get:function(){return Er.verifySessionKey}});Object.defineProperty(te,"buildKxCanonical",{enumerable:!0,get:function(){return Er.buildKxCanonical}});Object.defineProperty(te,"buildKxAckCanonical",{enumerable:!0,get:function(){return Er.buildKxAckCanonical}});Object.defineProperty(te,"fingerprintIdentityKey",{enumerable:!0,get:function(){return Er.fingerprintIdentityKey}});Object.defineProperty(te,"fingerprintShortHex",{enumerable:!0,get:function(){return Er.fingerprintShortHex}});Object.defineProperty(te,"concatBytes",{enumerable:!0,get:function(){return Er.concatBytes}});var ys=Yf();Object.defineProperty(te,"encrypt",{enumerable:!0,get:function(){return ys.encrypt}});Object.defineProperty(te,"decrypt",{enumerable:!0,get:function(){return ys.decrypt}});Object.defineProperty(te,"encryptBinary",{enumerable:!0,get:function(){return ys.encryptBinary}});Object.defineProperty(te,"decryptBinary",{enumerable:!0,get:function(){return ys.decryptBinary}});var ai=Xf();Object.defineProperty(te,"generateKeyPair",{enumerable:!0,get:function(){return ai.generateKeyPair}});Object.defineProperty(te,"deriveSharedSecret",{enumerable:!0,get:function(){return ai.deriveSharedSecret}});Object.defineProperty(te,"deriveMetaSid",{enumerable:!0,get:function(){return ai.deriveMetaSid}});Object.defineProperty(te,"isValidPublicKey",{enumerable:!0,get:function(){return ai.isValidPublicKey}});Object.defineProperty(te,"clearKey",{enumerable:!0,get:function(){return ai.clearKey}});Object.defineProperty(te,"keyToBase64",{enumerable:!0,get:function(){return ai.keyToBase64}});Object.defineProperty(te,"base64ToKey",{enumerable:!0,get:function(){return ai.base64ToKey}})});var Qf=M(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.MIN_CLIENT_VERSION=Ct.PROTOCOL_VERSION_MINOR=Ct.PROTOCOL_VERSION_MAJOR=Ct.PROTOCOL_VERSION=void 0;Ct.isCompatibleVersion=sg;Ct.compareVersions=og;Ct.PROTOCOL_VERSION="2.1";Ct.PROTOCOL_VERSION_MAJOR=2;Ct.PROTOCOL_VERSION_MINOR=1;Ct.MIN_CLIENT_VERSION="2.0";function sg(r){let[e]=r.split(".").map(Number);return e===Ct.PROTOCOL_VERSION_MAJOR}function og(r,e){let[t,i]=r.split(".").map(Number),[n,s]=e.split(".").map(Number);return t!==n?t<n?-1:1:i!==s?i<s?-1:1:0}});var eu=M(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.SERVER_CAPABILITIES=tr.DEFAULT_CLIENT_CAPABILITIES=tr.Capability=void 0;tr.hasCapability=ag;tr.negotiateCapabilities=cg;var Li;(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"})(Li||(tr.Capability=Li={}));tr.DEFAULT_CLIENT_CAPABILITIES=[Li.E2E_ENCRYPTION,Li.TERMINAL_EVENTS,Li.RELIABLE_INPUT];tr.SERVER_CAPABILITIES=Object.values(Li);function ag(r,e){return r.includes(e)}function cg(r,e){return r.filter(t=>e.includes(t))}});var tu=M(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.DEFAULT_PRIORITY=wr.PRIORITY_NAMES=wr.Priority=void 0;wr.comparePriority=fg;var ci;(function(r){r[r.CRITICAL=0]="CRITICAL",r[r.HIGH=1]="HIGH",r[r.NORMAL=2]="NORMAL",r[r.LOW=3]="LOW"})(ci||(wr.Priority=ci={}));wr.PRIORITY_NAMES={[ci.CRITICAL]:"CRITICAL",[ci.HIGH]:"HIGH",[ci.NORMAL]:"NORMAL",[ci.LOW]:"LOW"};wr.DEFAULT_PRIORITY=ci.NORMAL;function fg(r,e){return r-e}});var ru=M(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.DEFAULT_RELIABILITY=rr.RELIABILITY_NAMES=rr.Reliability=void 0;rr.requiresAck=ug;rr.requiresBuffer=lg;var Ur;(function(r){r[r.FIRE_FORGET=0]="FIRE_FORGET",r[r.BUFFERED=1]="BUFFERED",r[r.GUARANTEED=2]="GUARANTEED"})(Ur||(rr.Reliability=Ur={}));rr.RELIABILITY_NAMES={[Ur.FIRE_FORGET]:"FIRE_FORGET",[Ur.BUFFERED]:"BUFFERED",[Ur.GUARANTEED]:"GUARANTEED"};rr.DEFAULT_RELIABILITY=Ur.FIRE_FORGET;function ug(r){return r===Ur.GUARANTEED}function lg(r){return r>=Ur.BUFFERED}});var iu=M(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.createMessage=hg;function hg(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 nu=M(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.TerminalEventType=void 0;fi.deriveStatusFromEvent=dg;fi.shouldTriggerPushNotification=pg;fi.getPushNotificationMessage=gg;var mt;(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"})(mt||(fi.TerminalEventType=mt={}));function dg(r){switch(r.type){case mt.SESSION_START:case mt.TOOL_START:case mt.MESSAGE:return"working";case mt.WAITING_INPUT:return"waiting";case mt.SESSION_END:return r.status==="success"?"completed":"error";case mt.ERROR:return r.severity==="fatal"?"error":"working";case mt.TOOL_END:return r.status==="error"?"error":"working";default:return"idle"}}function pg(r){switch(r.type){case mt.WAITING_INPUT:return!0;case mt.SESSION_END:return!0;case mt.ERROR:return r.severity!=="warning";default:return!1}}function gg(r,e){switch(r.type){case mt.WAITING_INPUT:return{title:`${e}: Input Required`,body:r.question.slice(0,100)};case mt.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 mt.ERROR:{let t=r;return t.severity==="warning"?null:{title:`${e}: Error`,body:t.message.slice(0,100)}}default:return null}}});var au=M(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.TransferDirection=Ue.TransferStatus=Ue.CHUNK_TTL_SECONDS=Ue.TRANSFER_TTL_SECONDS=Ue.MAX_RETRIES=Ue.ACK_TIMEOUT_MS=Ue.WINDOW_SIZE=Ue.DEFAULT_MAX_FILE_SIZE=Ue.CHUNK_SIZE=void 0;Ue.calculateTotalChunks=mg;Ue.getMissingChunks=yg;Ue.isTransferComplete=_g;Ue.CHUNK_SIZE=64*1024;Ue.DEFAULT_MAX_FILE_SIZE=100*1024*1024;Ue.WINDOW_SIZE=10;Ue.ACK_TIMEOUT_MS=3e4;Ue.MAX_RETRIES=3;Ue.TRANSFER_TTL_SECONDS=1440*60;Ue.CHUNK_TTL_SECONDS=1440*60;var su;(function(r){r.PENDING="pending",r.ACTIVE="active",r.PAUSED="paused",r.COMPLETED="completed",r.FAILED="failed",r.CANCELLED="cancelled",r.EXPIRED="expired"})(su||(Ue.TransferStatus=su={}));var ou;(function(r){r.DOWNLOAD="download",r.UPLOAD="upload"})(ou||(Ue.TransferDirection=ou={}));function mg(r,e=Ue.CHUNK_SIZE){return Math.ceil(r/e)}function yg(r,e){let t=new Set(e),i=[];for(let n=0;n<r;n++)t.has(n)||i.push(n);return i}function _g(r,e){return e.length===r}});var cu=M(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.ERROR_MESSAGES=xr.ErrorCode=void 0;xr.createError=bg;xr.isRetryableError=vg;var Ie;(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"})(Ie||(xr.ErrorCode=Ie={}));xr.ERROR_MESSAGES={[Ie.AUTH_FAILED]:"Authentication failed",[Ie.TOKEN_EXPIRED]:"Token expired",[Ie.TOKEN_INVALID]:"Invalid token",[Ie.NOT_FOUND]:"Resource not found",[Ie.ALREADY_EXISTS]:"Resource already exists",[Ie.ACCESS_DENIED]:"Access denied",[Ie.FORBIDDEN]:"Operation forbidden",[Ie.RATE_LIMITED]:"Rate limit exceeded",[Ie.TOO_MANY_CONNECTIONS]:"Too many connections",[Ie.QUOTA_EXCEEDED]:"Plan quota exceeded",[Ie.FILE_TOO_LARGE]:"File size exceeds limit",[Ie.QUEUE_FULL]:"Message queue is full",[Ie.TRANSFERS_LIMIT]:"Daily transfers limit reached",[Ie.TRANSFER_FAILED]:"File transfer failed",[Ie.TRANSFER_EXPIRED]:"Transfer expired",[Ie.TRANSFER_CANCELLED]:"Transfer cancelled",[Ie.CHECKSUM_MISMATCH]:"File checksum mismatch",[Ie.CHUNK_MISSING]:"Chunk missing or corrupted",[Ie.INVALID_MESSAGE]:"Invalid message format",[Ie.UNSUPPORTED_VERSION]:"Unsupported protocol version",[Ie.CAPABILITY_REQUIRED]:"Required capability not supported",[Ie.INVALID_STATE]:"Invalid state for this operation",[Ie.TIMEOUT]:"Operation timed out",[Ie.CONNECTION_LOST]:"Connection lost",[Ie.INTERNAL_ERROR]:"Internal server error",[Ie.SERVICE_UNAVAILABLE]:"Service temporarily unavailable"};function bg(r,e={}){return{code:r,message:e.message||xr.ERROR_MESSAGES[r],details:e.details,retryable:e.retryable??!1,retryAfter:e.retryAfter}}function vg(r){return[Ie.RATE_LIMITED,Ie.TIMEOUT,Ie.CONNECTION_LOST,Ie.SERVICE_UNAVAILABLE].includes(r)}});var hu=M(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.FileEntryType=kt.DiffBase=kt.FileViewType=kt.FileChangeType=void 0;kt.getLanguageFromPath=Eg;kt.parseUnifiedDiff=wg;kt.createSimpleDiff=xg;var Kr;(function(r){r.CREATE="create",r.MODIFY="modify",r.DELETE="delete"})(Kr||(kt.FileChangeType=Kr={}));var fu;(function(r){r.CONTENT="content",r.DIFF="diff"})(fu||(kt.FileViewType=fu={}));var uu;(function(r){r.GIT="git",r.PREVIOUS="previous"})(uu||(kt.DiffBase=uu={}));function Eg(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 wg(r,e){let t=r.split(`
3
+ `),i=[],n=0,s=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 _=parseInt(m[1],10),E=parseInt(m[2]||"1",10),S=parseInt(m[3],10),T=parseInt(m[4]||"1",10);a={oldStart:_,oldLines:E,newStart:S,newLines:T,lines:[]},c=_,u=S;continue}a&&(p.startsWith("+")?(a.lines.push({type:"add",content:p.slice(1),oldLineNumber:null,newLineNumber:u++}),n++):p.startsWith("-")?(a.lines.push({type:"remove",content:p.slice(1),oldLineNumber:c++,newLineNumber:null}),s++):(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 s===0&&n>0&&i.length===1&&i[0].oldLines===0?d=Kr.CREATE:n===0&&s>0&&i.length===1&&i[0].newLines===0?d=Kr.DELETE:d=Kr.MODIFY,{path:e,changeType:d,hunks:i,additions:n,deletions:s,isBinary:!1}}function xg(r,e,t){let i=r.split(`
4
4
  `),n=e.split(`
5
- `),s=[],a=0,c=0,u=Math.max(i.length,n.length);for(let p=0;p<u;p++){let m=i[p],_=n[p];m===_?m!==void 0&&s.push({type:"context",content:m,oldLineNumber:p+1,newLineNumber:p+1}):(m!==void 0&&(s.push({type:"remove",content:m,oldLineNumber:p+1,newLineNumber:null}),c++),_!==void 0&&(s.push({type:"add",content:_,oldLineNumber:null,newLineNumber:p+1}),a++))}let d;return r===""?d=qr.CREATE:e===""?d=qr.DELETE:d=qr.MODIFY,{path:t,changeType:d,hunks:[{oldStart:1,oldLines:i.length,newStart:1,newLines:n.length,lines:s}],additions:a,deletions:c,isBinary:!1}}var lu;(function(r){r.FILE="file",r.DIRECTORY="directory"})(lu||(kt.FileEntryType=lu={}))});var du=M(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.createSimpleDiff=N.parseUnifiedDiff=N.getLanguageFromPath=N.FileEntryType=N.DiffBase=N.FileViewType=N.FileChangeType=N.isRetryableError=N.createError=N.ERROR_MESSAGES=N.ErrorCode=N.isTransferComplete=N.getMissingChunks=N.calculateTotalChunks=N.TransferDirection=N.TransferStatus=N.CHUNK_TTL_SECONDS=N.TRANSFER_TTL_SECONDS=N.MAX_RETRIES=N.ACK_TIMEOUT_MS=N.WINDOW_SIZE=N.DEFAULT_MAX_FILE_SIZE=N.CHUNK_SIZE=N.getPushNotificationMessage=N.shouldTriggerPushNotification=N.deriveStatusFromEvent=N.TerminalEventType=N.createMessage=N.requiresBuffer=N.requiresAck=N.DEFAULT_RELIABILITY=N.RELIABILITY_NAMES=N.Reliability=N.comparePriority=N.DEFAULT_PRIORITY=N.PRIORITY_NAMES=N.Priority=N.negotiateCapabilities=N.hasCapability=N.SERVER_CAPABILITIES=N.DEFAULT_CLIENT_CAPABILITIES=N.Capability=N.compareVersions=N.isCompatibleVersion=N.MIN_CLIENT_VERSION=N.PROTOCOL_VERSION_MINOR=N.PROTOCOL_VERSION_MAJOR=N.PROTOCOL_VERSION=void 0;var Li=Qf();Object.defineProperty(N,"PROTOCOL_VERSION",{enumerable:!0,get:function(){return Li.PROTOCOL_VERSION}});Object.defineProperty(N,"PROTOCOL_VERSION_MAJOR",{enumerable:!0,get:function(){return Li.PROTOCOL_VERSION_MAJOR}});Object.defineProperty(N,"PROTOCOL_VERSION_MINOR",{enumerable:!0,get:function(){return Li.PROTOCOL_VERSION_MINOR}});Object.defineProperty(N,"MIN_CLIENT_VERSION",{enumerable:!0,get:function(){return Li.MIN_CLIENT_VERSION}});Object.defineProperty(N,"isCompatibleVersion",{enumerable:!0,get:function(){return Li.isCompatibleVersion}});Object.defineProperty(N,"compareVersions",{enumerable:!0,get:function(){return Li.compareVersions}});var bn=eu();Object.defineProperty(N,"Capability",{enumerable:!0,get:function(){return bn.Capability}});Object.defineProperty(N,"DEFAULT_CLIENT_CAPABILITIES",{enumerable:!0,get:function(){return bn.DEFAULT_CLIENT_CAPABILITIES}});Object.defineProperty(N,"SERVER_CAPABILITIES",{enumerable:!0,get:function(){return bn.SERVER_CAPABILITIES}});Object.defineProperty(N,"hasCapability",{enumerable:!0,get:function(){return bn.hasCapability}});Object.defineProperty(N,"negotiateCapabilities",{enumerable:!0,get:function(){return bn.negotiateCapabilities}});var _s=tu();Object.defineProperty(N,"Priority",{enumerable:!0,get:function(){return _s.Priority}});Object.defineProperty(N,"PRIORITY_NAMES",{enumerable:!0,get:function(){return _s.PRIORITY_NAMES}});Object.defineProperty(N,"DEFAULT_PRIORITY",{enumerable:!0,get:function(){return _s.DEFAULT_PRIORITY}});Object.defineProperty(N,"comparePriority",{enumerable:!0,get:function(){return _s.comparePriority}});var En=ru();Object.defineProperty(N,"Reliability",{enumerable:!0,get:function(){return En.Reliability}});Object.defineProperty(N,"RELIABILITY_NAMES",{enumerable:!0,get:function(){return En.RELIABILITY_NAMES}});Object.defineProperty(N,"DEFAULT_RELIABILITY",{enumerable:!0,get:function(){return En.DEFAULT_RELIABILITY}});Object.defineProperty(N,"requiresAck",{enumerable:!0,get:function(){return En.requiresAck}});Object.defineProperty(N,"requiresBuffer",{enumerable:!0,get:function(){return En.requiresBuffer}});var Sg=iu();Object.defineProperty(N,"createMessage",{enumerable:!0,get:function(){return Sg.createMessage}});var vs=nu();Object.defineProperty(N,"TerminalEventType",{enumerable:!0,get:function(){return vs.TerminalEventType}});Object.defineProperty(N,"deriveStatusFromEvent",{enumerable:!0,get:function(){return vs.deriveStatusFromEvent}});Object.defineProperty(N,"shouldTriggerPushNotification",{enumerable:!0,get:function(){return vs.shouldTriggerPushNotification}});Object.defineProperty(N,"getPushNotificationMessage",{enumerable:!0,get:function(){return vs.getPushNotificationMessage}});var Lt=au();Object.defineProperty(N,"CHUNK_SIZE",{enumerable:!0,get:function(){return Lt.CHUNK_SIZE}});Object.defineProperty(N,"DEFAULT_MAX_FILE_SIZE",{enumerable:!0,get:function(){return Lt.DEFAULT_MAX_FILE_SIZE}});Object.defineProperty(N,"WINDOW_SIZE",{enumerable:!0,get:function(){return Lt.WINDOW_SIZE}});Object.defineProperty(N,"ACK_TIMEOUT_MS",{enumerable:!0,get:function(){return Lt.ACK_TIMEOUT_MS}});Object.defineProperty(N,"MAX_RETRIES",{enumerable:!0,get:function(){return Lt.MAX_RETRIES}});Object.defineProperty(N,"TRANSFER_TTL_SECONDS",{enumerable:!0,get:function(){return Lt.TRANSFER_TTL_SECONDS}});Object.defineProperty(N,"CHUNK_TTL_SECONDS",{enumerable:!0,get:function(){return Lt.CHUNK_TTL_SECONDS}});Object.defineProperty(N,"TransferStatus",{enumerable:!0,get:function(){return Lt.TransferStatus}});Object.defineProperty(N,"TransferDirection",{enumerable:!0,get:function(){return Lt.TransferDirection}});Object.defineProperty(N,"calculateTotalChunks",{enumerable:!0,get:function(){return Lt.calculateTotalChunks}});Object.defineProperty(N,"getMissingChunks",{enumerable:!0,get:function(){return Lt.getMissingChunks}});Object.defineProperty(N,"isTransferComplete",{enumerable:!0,get:function(){return Lt.isTransferComplete}});var bs=cu();Object.defineProperty(N,"ErrorCode",{enumerable:!0,get:function(){return bs.ErrorCode}});Object.defineProperty(N,"ERROR_MESSAGES",{enumerable:!0,get:function(){return bs.ERROR_MESSAGES}});Object.defineProperty(N,"createError",{enumerable:!0,get:function(){return bs.createError}});Object.defineProperty(N,"isRetryableError",{enumerable:!0,get:function(){return bs.isRetryableError}});var ui=hu();Object.defineProperty(N,"FileChangeType",{enumerable:!0,get:function(){return ui.FileChangeType}});Object.defineProperty(N,"FileViewType",{enumerable:!0,get:function(){return ui.FileViewType}});Object.defineProperty(N,"DiffBase",{enumerable:!0,get:function(){return ui.DiffBase}});Object.defineProperty(N,"FileEntryType",{enumerable:!0,get:function(){return ui.FileEntryType}});Object.defineProperty(N,"getLanguageFromPath",{enumerable:!0,get:function(){return ui.getLanguageFromPath}});Object.defineProperty(N,"parseUnifiedDiff",{enumerable:!0,get:function(){return ui.parseUnifiedDiff}});Object.defineProperty(N,"createSimpleDiff",{enumerable:!0,get:function(){return ui.createSimpleDiff}})});var Sr=M(ir=>{"use strict";var Tg=ir&&ir.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),Es=ir&&ir.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Tg(e,r,t)};Object.defineProperty(ir,"__esModule",{value:!0});Es(Hf(),ir);Es(Vf(),ir);Es(Zf(),ir);Es(du(),ir)});var Zo=M(He=>{"use strict";var Cg=He&&He.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(He,"__esModule",{value:!0});He.FP_LABEL=He.KX_ACK_LABEL=He.KX_SIGN_LABEL=void 0;He.concatBytes=wn;He.generateIdentityKeyPair=kg;He.identityPublicFromSecret=Og;He.signSessionKey=Pg;He.verifySessionKey=Ag;He.buildKxCanonical=Rg;He.buildKxAckCanonical=Ig;He.fingerprintIdentityKey=Lg;He.fingerprintShortHex=Ng;var nr=Cg(yn()),Ot=_n();He.KX_SIGN_LABEL="termiq-kx-v1";He.KX_ACK_LABEL="termiq-kxack-v1";He.FP_LABEL="termiq-fp-v1";function wn(...r){let e=0;for(let n of r)e+=n.length;let t=new Uint8Array(e),i=0;for(let n of r)t.set(n,i),i+=n.length;return t}function kg(){let r=nr.default.sign.keyPair();return{identityPublicKey:(0,Ot.encodeBase64)(r.publicKey),identitySecretKey:(0,Ot.encodeBase64)(r.secretKey)}}function Og(r){let e=(0,Ot.decodeBase64)(r);if(e.length!==nr.default.sign.secretKeyLength)throw new Error("bad identity secret key length");let t=nr.default.sign.keyPair.fromSecretKey(e);return(0,Ot.encodeBase64)(t.publicKey)}function Pg(r,e){let t=(0,Ot.decodeBase64)(e);if(t.length!==nr.default.sign.secretKeyLength)throw new Error("bad identity secret key length");return(0,Ot.encodeBase64)(nr.default.sign.detached(r,t))}function Ag(r,e,t){try{let i=(0,Ot.decodeBase64)(e),n=(0,Ot.decodeBase64)(t);return n.length!==nr.default.sign.publicKeyLength||i.length!==nr.default.sign.signatureLength?!1:nr.default.sign.detached.verify(r,i,n)}catch{return!1}}var li=new Uint8Array([0]);function Rg(r){let e=new TextEncoder,t=e.encode(He.KX_SIGN_LABEL),i=e.encode(r.agentId),n=e.encode(String(r.keyVersion)),s=(0,Ot.decodeBase64)(r.boxPublicKey);return wn(t,li,i,li,n,li,s)}function Ig(r){let e=new TextEncoder;return wn(e.encode(He.KX_ACK_LABEL),li,e.encode(r.agentId),li,e.encode(String(r.keyVersion)),li,(0,Ot.decodeBase64)(r.boxPublicKey),li,(0,Ot.decodeBase64)(r.boundClientKey))}function Lg(r){let e=(0,Ot.decodeBase64)(r),t=wn(new TextEncoder().encode(He.FP_LABEL),e),i=nr.default.hash(t),n=[];for(let s=0;s<12;s++){let a=s*5,u=(((i[a]<<24>>>0)+(i[a+1]<<16)+(i[a+2]<<8)+i[a+3]^i[a+4])>>>0)%1e5;n.push(String(u).padStart(5,"0"))}return n.join(" ")}function Ng(r){let e=(0,Ot.decodeBase64)(r),t=wn(new TextEncoder().encode(He.FP_LABEL),e),i=nr.default.hash(t).slice(0,8);return Array.from(i).map(n=>n.toString(16).padStart(2,"0")).join(":").toUpperCase()}});var gu=M(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});ws.CryptoService=void 0;var Qe=Sr(),Kr=Zo(),Mg=3600*1e3,pu=10,Qo=class{storage;logger;sessions=new Map;agentSessions=new Map;metaSessions=new Map;keyPair=null;identityKeyPair=null;publicKeyKey;secretKeyKey;keyVersionKey;identityPublicKeyKey;identitySecretKeyKey;constructor(e,t,i,n){this.storage=e,this.logger=t;let s=`termiq.${i}.${n}`;this.publicKeyKey=`${s}.crypto.publicKey`,this.secretKeyKey=`${s}.crypto.secretKey`,this.keyVersionKey=`${s}.crypto.keyVersion`,this.identityPublicKeyKey=`${s}.crypto.identityPublicKey`,this.identitySecretKeyKey=`${s}.crypto.identitySecretKey`,this.logger.info("CryptoService namespace",i,n)}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 box key pair")):await this.generateBoxKeyPair(),await this.ensureIdentityKeyPair()}async generateBoxKeyPair(){this.logger.info("Generating new box key pair"),this.keyPair=(0,Qe.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("Box key pair generated and stored"),this.keyPair}async generateIdentityKeyPair(){return this.generateBoxKeyPair()}async ensureIdentityKeyPair(){if(this.identityKeyPair)return this.identityKeyPair;let e=await this.storage.get(this.identitySecretKeyKey),t=await this.storage.get(this.identityPublicKeyKey);return e?(t||(t=(0,Kr.identityPublicFromSecret)(e),await this.storage.set(this.identityPublicKeyKey,t)),this.identityKeyPair={identityPublicKey:t,identitySecretKey:e},this.logger.info("Loaded existing identity (Ed25519) key pair"),this.identityKeyPair):(this.logger.info("Generating new identity (Ed25519) key pair"),this.identityKeyPair=(0,Kr.generateIdentityKeyPair)(),await this.storage.set(this.identityPublicKeyKey,this.identityKeyPair.identityPublicKey),await this.storage.set(this.identitySecretKeyKey,this.identityKeyPair.identitySecretKey),this.logger.info("Identity (Ed25519) key pair generated and stored"),this.identityKeyPair)}async getIdentityPublicKey(){return(await this.ensureIdentityKeyPair()).identityPublicKey}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 getSignedAgentKey(e){if(!this.keyPair&&(await this.initialize(),!this.keyPair))return this.logger.error("No box key pair available for signing"),null;let t=await this.ensureIdentityKeyPair(),i=await this.getKeyVersion(),n=this.keyPair.publicKey,s=(0,Kr.buildKxCanonical)({agentId:e,keyVersion:i,boxPublicKey:n}),a=(0,Kr.signSessionKey)(s,t.identitySecretKey);return{boxPublicKey:n,identityPublicKey:t.identityPublicKey,keyVersion:i,signature:a,sigVersion:1}}async signKeyExchangeAck(e,t){if(!this.keyPair&&(await this.initialize(),!this.keyPair))return this.logger.error("No box key pair available for ACK signing"),null;let i=await this.ensureIdentityKeyPair(),n=await this.getKeyVersion(),s=(0,Kr.buildKxAckCanonical)({agentId:e,keyVersion:n,boxPublicKey:this.keyPair.publicKey,boundClientKey:t});return(0,Kr.signSessionKey)(s,i.identitySecretKey)}async getSafetyNumber(){let e=await this.ensureIdentityKeyPair();return(0,Kr.fingerprintIdentityKey)(e.identityPublicKey)}async getShortFingerprint(){let e=await this.ensureIdentityKeyPair();return(0,Kr.fingerprintShortHex)(e.identityPublicKey)}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 n=this.sessions.get(e);n||(n=new Map,this.sessions.set(e,n));let s=(0,Qe.deriveSharedSecret)(t,this.keyPair.secretKey),a={terminalId:e,clientPublicKey:t,sharedSecret:s,createdAt:Date.now(),sessionId:i};return n.set(i,a),this.logger.info("Key exchange completed",e,i,"total:",n.size),!0}catch(n){return this.logger.error("Key exchange failed",n),!1}}encryptOutput(e,t){let i=this.sessions.get(e);if(!i||i.size===0)return null;try{if(i.size===1){let s=i.values().next().value;return s?(0,Qe.encrypt)(t,s.sharedSecret,s.sessionId):null}let n=[];for(let s of i.values()){let a=(0,Qe.encrypt)(t,s.sharedSecret,s.sessionId);n.push({sid:a.sid,n:a.n,c:a.c})}return{v:2,recipients:n}}catch(n){return this.logger.error("Encryption failed",n),null}}decryptInput(e,t){let i=this.sessions.get(e);if(!i)return this.logger.error("No sessions for terminal",e),null;let n=i.get(t.sid);if(!n)return this.logger.error("No session for sessionId",t.sid),null;try{return(0,Qe.decrypt)(t,n.sharedSecret)}catch(s){return this.logger.error("Decryption failed",s),null}}encryptFileChunk(e,t){let i=this.sessions.get(e);if(!i||i.size===0)return null;let n=null;for(let s of i.values())(!n||s.createdAt>n.createdAt)&&(n=s);if(!n)return null;try{return(0,Qe.encryptBinary)(t,n.sharedSecret,n.sessionId)}catch(s){return this.logger.error("File chunk encryption failed",s),null}}decryptFileChunk(e,t){let i=this.sessions.get(e)?.get(t.sid);if(!i)return this.logger.error("No session for file chunk",e,t.sid),null;try{return(0,Qe.decryptBinary)(t,i.sharedSecret)}catch(n){return this.logger.error("File chunk 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 n=i.get(t);n&&((0,Qe.clearKey)(n.sharedSecret),i.delete(t),this.logger.info("Session removed",e,t)),i.size===0&&this.sessions.delete(e)}else{for(let n of i.values())(0,Qe.clearKey)(n.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,Qe.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(),n=[];for(let[s,a]of t)i-a.createdAt>Mg&&n.push(s);for(let s of n){let a=t.get(s);a&&((0,Qe.clearKey)(a.sharedSecret),t.delete(s),this.logger.info("Session expired (TTL)",e,s,`age:${Math.round((i-a.createdAt)/1e3)}s`))}if(t.size>pu){let a=Array.from(t.entries()).sort((c,u)=>c[1].createdAt-u[1].createdAt).slice(0,t.size-pu);for(let[,c]of a)(0,Qe.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 n of i.values())e.push({terminalId:t,createdAt:n.createdAt,sessionId:n.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,Qe.clearKey)(i.sharedSecret));let n=(0,Qe.deriveSharedSecret)(e,this.keyPair.secretKey),s={sessionId:t,clientPublicKey:e,sharedSecret:n,createdAt:Date.now()};return this.agentSessions.set(t,s),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,Qe.clearKey)(t.sharedSecret),this.agentSessions.delete(e),this.logger.info("Agent session removed",e))}hasAgentSessions(){return this.agentSessions.size>0}async handleMetaKeyExchange(e){if(!this.keyPair&&(await this.initialize(),!this.keyPair))return{ok:!1,isNew:!1};try{let t=!this.metaSessions.has(e),i=(0,Qe.deriveSharedSecret)(e,this.keyPair.secretKey),n=(0,Qe.deriveMetaSid)(this.keyPair.publicKey,e);return this.metaSessions.set(e,{clientIdentityPub:e,sharedSecret:i,sidMeta:n}),this.logger.info("Meta key exchange completed",n,"isNew:",t,"total:",this.metaSessions.size),{ok:!0,isNew:t}}catch(t){return this.logger.error("Meta key exchange failed",t),{ok:!1,isNew:!1}}}hasMetaSession(){return this.metaSessions.size>0}encryptWorkspaceInfo(e){let t=this.encryptForMeta(JSON.stringify(e));return t?{encrypted:t}:null}encryptTerminalInfo(e){let t=this.encryptForMeta(JSON.stringify(e));return t?{encrypted:t}:null}encryptPromptInfo(e){let t=this.encryptForMeta(JSON.stringify(e));return t?{encrypted:t}:null}encryptForMeta(e){if(this.metaSessions.size===0)return null;try{if(this.metaSessions.size===1){let i=this.metaSessions.values().next().value;return i?(0,Qe.encrypt)(e,i.sharedSecret,i.sidMeta):null}let t=[];for(let i of this.metaSessions.values()){let n=(0,Qe.encrypt)(e,i.sharedSecret,i.sidMeta);t.push({sid:n.sid,n:n.n,c:n.c})}return{v:2,recipients:t}}catch(t){return this.logger.error("Meta encryption failed",t),null}}clearAllAgentSessions(){for(let e of this.agentSessions.values())(0,Qe.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),await this.storage.delete(this.identityPublicKeyKey),await this.storage.delete(this.identitySecretKeyKey),this.keyPair=null,this.identityKeyPair=null,this.clearAllSessions(),this.clearAllAgentSessions(),this.logger.info("All crypto keys deleted")}};ws.CryptoService=Qo});var mu=M(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});xs.AuthService=void 0;var xn=fs(),ea=class{storage;cryptoService;machineId;config;logger;notification;browser;pollingAbortController=null;tokenKey;refreshTokenKey;agentIdKey;constructor(e,t,i,n,s,a,c,u,d){this.storage=e,this.cryptoService=t,this.machineId=i,this.config=n,this.logger=s,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,xn.getApiUrl)(this.config),t=await this.machineId.getMachineId(),i=this.machineId.getMachineName(),n=await this.cryptoService.getPublicKey();n||(await this.cryptoService.generateIdentityKeyPair(),n=await this.cryptoService.getPublicKey()),this.logger.info("Starting device code flow",t,i);let s=await fetch(`${e}/auth/device/code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machineId:t,machineName:i,publicKey:n})});if(!s.ok){let a=await s.text();throw new Error(`Failed to get device code: ${a}`)}return s.json()}async pollForToken(e){this.cancelPolling();let t=(0,xn.getApiUrl)(this.config),i=5e3,n=60;this.pollingAbortController=new AbortController;let s=this.pollingAbortController.signal;this.logger.info("Starting token polling");for(let a=0;a<n;a++){if(s.aborted)return this.logger.info("Polling was cancelled"),null;if(await this.sleep(i),s.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:s});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(s.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,xn.getApiUrl)(this.config),i=await this.machineId.getMachineId(),n=this.machineId.getMachineName(),s=await this.cryptoService.getPublicKey();s||(await this.cryptoService.generateIdentityKeyPair(),s=await this.cryptoService.getPublicKey()),this.logger.info("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:n,publicKey:s})});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,xn.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 n=await i.json();return await this.storage.set(this.tokenKey,n.accessToken),await this.storage.set(this.refreshTokenKey,n.refreshToken),this.logger.info("Access token refreshed successfully"),n.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,xn.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 n=i instanceof Error?i.message:String(i);return this.logger.error(`Error fetching limits: ${n}`),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))}};xs.AuthService=ea});var yu=M(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.StatusDetector=void 0;Sn.isAnswerKeystroke=Fg;var Ss={working:[/✶/,/⠋|⠙|⠹|⠸|⠼|⠴|⠦|⠧|⠇|⠏/],idle:[/[❯$#>]\s*$/,/^\s*\d+\s*[❯$#>]\s*$/,/\(base\)\s*[❯$#>]\s*$/,/\)\s*[❯$#>]\s*$/],waiting:[/\[y\/n\]\s*$/i,/\[y\/N\]\s*$/i,/\(y\/n\)\s*$/i,/\(yes\/no\)\s*$/i,/press enter to continue\s*$/i,/press any key\s*$/i,/\[enter\]\s*$/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]},Ni={IDLE_TIMEOUT_MS:5e3,DEBOUNCE_MS:500,BUFFER_SIZE:16e3,WORKING_TIMEOUT_MS:3e4,RESOLVE_GRACE_MS:1500},ta=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,pendingStatus:null,resolveGraceUntil:0,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>Ni.BUFFER_SIZE&&(i.outputBuffer=i.outputBuffer.slice(-Ni.BUFFER_SIZE));let n=Date.now()<i.resolveGraceUntil,s=!1;if(!n){let a=this.detectPrompt(i.outputBuffer);a&&a.type!=="free-input"&&this.isPromptActive(i.outputBuffer)&&(s=!0)}if(s)this.scheduleStatusUpdate(e,"waiting");else if(i.status==="waiting"&&!n){let a=this.analyzeOutput(i.outputBuffer);(a==="completed"||a==="error")&&this.scheduleStatusUpdate(e,a)}else{let a=this.analyzeOutput(i.outputBuffer);a&&this.scheduleStatusUpdate(e,a)}this.resetWorkingTimeout(e,i)}isPromptActive(e){let i=this.normalizeBuffer(this.stripAnsi(e)).split(`
5
+ `),s=[],a=0,c=0,u=Math.max(i.length,n.length);for(let p=0;p<u;p++){let m=i[p],_=n[p];m===_?m!==void 0&&s.push({type:"context",content:m,oldLineNumber:p+1,newLineNumber:p+1}):(m!==void 0&&(s.push({type:"remove",content:m,oldLineNumber:p+1,newLineNumber:null}),c++),_!==void 0&&(s.push({type:"add",content:_,oldLineNumber:null,newLineNumber:p+1}),a++))}let d;return r===""?d=Kr.CREATE:e===""?d=Kr.DELETE:d=Kr.MODIFY,{path:t,changeType:d,hunks:[{oldStart:1,oldLines:i.length,newStart:1,newLines:n.length,lines:s}],additions:a,deletions:c,isBinary:!1}}var lu;(function(r){r.FILE="file",r.DIRECTORY="directory"})(lu||(kt.FileEntryType=lu={}))});var du=M(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.createSimpleDiff=N.parseUnifiedDiff=N.getLanguageFromPath=N.FileEntryType=N.DiffBase=N.FileViewType=N.FileChangeType=N.isRetryableError=N.createError=N.ERROR_MESSAGES=N.ErrorCode=N.isTransferComplete=N.getMissingChunks=N.calculateTotalChunks=N.TransferDirection=N.TransferStatus=N.CHUNK_TTL_SECONDS=N.TRANSFER_TTL_SECONDS=N.MAX_RETRIES=N.ACK_TIMEOUT_MS=N.WINDOW_SIZE=N.DEFAULT_MAX_FILE_SIZE=N.CHUNK_SIZE=N.getPushNotificationMessage=N.shouldTriggerPushNotification=N.deriveStatusFromEvent=N.TerminalEventType=N.createMessage=N.requiresBuffer=N.requiresAck=N.DEFAULT_RELIABILITY=N.RELIABILITY_NAMES=N.Reliability=N.comparePriority=N.DEFAULT_PRIORITY=N.PRIORITY_NAMES=N.Priority=N.negotiateCapabilities=N.hasCapability=N.SERVER_CAPABILITIES=N.DEFAULT_CLIENT_CAPABILITIES=N.Capability=N.compareVersions=N.isCompatibleVersion=N.MIN_CLIENT_VERSION=N.PROTOCOL_VERSION_MINOR=N.PROTOCOL_VERSION_MAJOR=N.PROTOCOL_VERSION=void 0;var Ni=Qf();Object.defineProperty(N,"PROTOCOL_VERSION",{enumerable:!0,get:function(){return Ni.PROTOCOL_VERSION}});Object.defineProperty(N,"PROTOCOL_VERSION_MAJOR",{enumerable:!0,get:function(){return Ni.PROTOCOL_VERSION_MAJOR}});Object.defineProperty(N,"PROTOCOL_VERSION_MINOR",{enumerable:!0,get:function(){return Ni.PROTOCOL_VERSION_MINOR}});Object.defineProperty(N,"MIN_CLIENT_VERSION",{enumerable:!0,get:function(){return Ni.MIN_CLIENT_VERSION}});Object.defineProperty(N,"isCompatibleVersion",{enumerable:!0,get:function(){return Ni.isCompatibleVersion}});Object.defineProperty(N,"compareVersions",{enumerable:!0,get:function(){return Ni.compareVersions}});var vn=eu();Object.defineProperty(N,"Capability",{enumerable:!0,get:function(){return vn.Capability}});Object.defineProperty(N,"DEFAULT_CLIENT_CAPABILITIES",{enumerable:!0,get:function(){return vn.DEFAULT_CLIENT_CAPABILITIES}});Object.defineProperty(N,"SERVER_CAPABILITIES",{enumerable:!0,get:function(){return vn.SERVER_CAPABILITIES}});Object.defineProperty(N,"hasCapability",{enumerable:!0,get:function(){return vn.hasCapability}});Object.defineProperty(N,"negotiateCapabilities",{enumerable:!0,get:function(){return vn.negotiateCapabilities}});var _s=tu();Object.defineProperty(N,"Priority",{enumerable:!0,get:function(){return _s.Priority}});Object.defineProperty(N,"PRIORITY_NAMES",{enumerable:!0,get:function(){return _s.PRIORITY_NAMES}});Object.defineProperty(N,"DEFAULT_PRIORITY",{enumerable:!0,get:function(){return _s.DEFAULT_PRIORITY}});Object.defineProperty(N,"comparePriority",{enumerable:!0,get:function(){return _s.comparePriority}});var En=ru();Object.defineProperty(N,"Reliability",{enumerable:!0,get:function(){return En.Reliability}});Object.defineProperty(N,"RELIABILITY_NAMES",{enumerable:!0,get:function(){return En.RELIABILITY_NAMES}});Object.defineProperty(N,"DEFAULT_RELIABILITY",{enumerable:!0,get:function(){return En.DEFAULT_RELIABILITY}});Object.defineProperty(N,"requiresAck",{enumerable:!0,get:function(){return En.requiresAck}});Object.defineProperty(N,"requiresBuffer",{enumerable:!0,get:function(){return En.requiresBuffer}});var Sg=iu();Object.defineProperty(N,"createMessage",{enumerable:!0,get:function(){return Sg.createMessage}});var bs=nu();Object.defineProperty(N,"TerminalEventType",{enumerable:!0,get:function(){return bs.TerminalEventType}});Object.defineProperty(N,"deriveStatusFromEvent",{enumerable:!0,get:function(){return bs.deriveStatusFromEvent}});Object.defineProperty(N,"shouldTriggerPushNotification",{enumerable:!0,get:function(){return bs.shouldTriggerPushNotification}});Object.defineProperty(N,"getPushNotificationMessage",{enumerable:!0,get:function(){return bs.getPushNotificationMessage}});var Lt=au();Object.defineProperty(N,"CHUNK_SIZE",{enumerable:!0,get:function(){return Lt.CHUNK_SIZE}});Object.defineProperty(N,"DEFAULT_MAX_FILE_SIZE",{enumerable:!0,get:function(){return Lt.DEFAULT_MAX_FILE_SIZE}});Object.defineProperty(N,"WINDOW_SIZE",{enumerable:!0,get:function(){return Lt.WINDOW_SIZE}});Object.defineProperty(N,"ACK_TIMEOUT_MS",{enumerable:!0,get:function(){return Lt.ACK_TIMEOUT_MS}});Object.defineProperty(N,"MAX_RETRIES",{enumerable:!0,get:function(){return Lt.MAX_RETRIES}});Object.defineProperty(N,"TRANSFER_TTL_SECONDS",{enumerable:!0,get:function(){return Lt.TRANSFER_TTL_SECONDS}});Object.defineProperty(N,"CHUNK_TTL_SECONDS",{enumerable:!0,get:function(){return Lt.CHUNK_TTL_SECONDS}});Object.defineProperty(N,"TransferStatus",{enumerable:!0,get:function(){return Lt.TransferStatus}});Object.defineProperty(N,"TransferDirection",{enumerable:!0,get:function(){return Lt.TransferDirection}});Object.defineProperty(N,"calculateTotalChunks",{enumerable:!0,get:function(){return Lt.calculateTotalChunks}});Object.defineProperty(N,"getMissingChunks",{enumerable:!0,get:function(){return Lt.getMissingChunks}});Object.defineProperty(N,"isTransferComplete",{enumerable:!0,get:function(){return Lt.isTransferComplete}});var vs=cu();Object.defineProperty(N,"ErrorCode",{enumerable:!0,get:function(){return vs.ErrorCode}});Object.defineProperty(N,"ERROR_MESSAGES",{enumerable:!0,get:function(){return vs.ERROR_MESSAGES}});Object.defineProperty(N,"createError",{enumerable:!0,get:function(){return vs.createError}});Object.defineProperty(N,"isRetryableError",{enumerable:!0,get:function(){return vs.isRetryableError}});var ui=hu();Object.defineProperty(N,"FileChangeType",{enumerable:!0,get:function(){return ui.FileChangeType}});Object.defineProperty(N,"FileViewType",{enumerable:!0,get:function(){return ui.FileViewType}});Object.defineProperty(N,"DiffBase",{enumerable:!0,get:function(){return ui.DiffBase}});Object.defineProperty(N,"FileEntryType",{enumerable:!0,get:function(){return ui.FileEntryType}});Object.defineProperty(N,"getLanguageFromPath",{enumerable:!0,get:function(){return ui.getLanguageFromPath}});Object.defineProperty(N,"parseUnifiedDiff",{enumerable:!0,get:function(){return ui.parseUnifiedDiff}});Object.defineProperty(N,"createSimpleDiff",{enumerable:!0,get:function(){return ui.createSimpleDiff}})});var Sr=M(ir=>{"use strict";var Tg=ir&&ir.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),Es=ir&&ir.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Tg(e,r,t)};Object.defineProperty(ir,"__esModule",{value:!0});Es(Hf(),ir);Es(Vf(),ir);Es(Zf(),ir);Es(du(),ir)});var Zo=M(He=>{"use strict";var Cg=He&&He.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(He,"__esModule",{value:!0});He.FP_LABEL=He.KX_ACK_LABEL=He.KX_SIGN_LABEL=void 0;He.concatBytes=wn;He.generateIdentityKeyPair=kg;He.identityPublicFromSecret=Og;He.signSessionKey=Pg;He.verifySessionKey=Rg;He.buildKxCanonical=Ag;He.buildKxAckCanonical=Ig;He.fingerprintIdentityKey=Lg;He.fingerprintShortHex=Ng;var nr=Cg(yn()),Ot=_n();He.KX_SIGN_LABEL="termiq-kx-v1";He.KX_ACK_LABEL="termiq-kxack-v1";He.FP_LABEL="termiq-fp-v1";function wn(...r){let e=0;for(let n of r)e+=n.length;let t=new Uint8Array(e),i=0;for(let n of r)t.set(n,i),i+=n.length;return t}function kg(){let r=nr.default.sign.keyPair();return{identityPublicKey:(0,Ot.encodeBase64)(r.publicKey),identitySecretKey:(0,Ot.encodeBase64)(r.secretKey)}}function Og(r){let e=(0,Ot.decodeBase64)(r);if(e.length!==nr.default.sign.secretKeyLength)throw new Error("bad identity secret key length");let t=nr.default.sign.keyPair.fromSecretKey(e);return(0,Ot.encodeBase64)(t.publicKey)}function Pg(r,e){let t=(0,Ot.decodeBase64)(e);if(t.length!==nr.default.sign.secretKeyLength)throw new Error("bad identity secret key length");return(0,Ot.encodeBase64)(nr.default.sign.detached(r,t))}function Rg(r,e,t){try{let i=(0,Ot.decodeBase64)(e),n=(0,Ot.decodeBase64)(t);return n.length!==nr.default.sign.publicKeyLength||i.length!==nr.default.sign.signatureLength?!1:nr.default.sign.detached.verify(r,i,n)}catch{return!1}}var li=new Uint8Array([0]);function Ag(r){let e=new TextEncoder,t=e.encode(He.KX_SIGN_LABEL),i=e.encode(r.agentId),n=e.encode(String(r.keyVersion)),s=(0,Ot.decodeBase64)(r.boxPublicKey);return wn(t,li,i,li,n,li,s)}function Ig(r){let e=new TextEncoder;return wn(e.encode(He.KX_ACK_LABEL),li,e.encode(r.agentId),li,e.encode(String(r.keyVersion)),li,(0,Ot.decodeBase64)(r.boxPublicKey),li,(0,Ot.decodeBase64)(r.boundClientKey))}function Lg(r){let e=(0,Ot.decodeBase64)(r),t=wn(new TextEncoder().encode(He.FP_LABEL),e),i=nr.default.hash(t),n=[];for(let s=0;s<12;s++){let a=s*5,u=(((i[a]<<24>>>0)+(i[a+1]<<16)+(i[a+2]<<8)+i[a+3]^i[a+4])>>>0)%1e5;n.push(String(u).padStart(5,"0"))}return n.join(" ")}function Ng(r){let e=(0,Ot.decodeBase64)(r),t=wn(new TextEncoder().encode(He.FP_LABEL),e),i=nr.default.hash(t).slice(0,8);return Array.from(i).map(n=>n.toString(16).padStart(2,"0")).join(":").toUpperCase()}});var gu=M(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});ws.CryptoService=void 0;var Qe=Sr(),qr=Zo(),Mg=3600*1e3,pu=10,Qo=class{storage;logger;sessions=new Map;agentSessions=new Map;metaSessions=new Map;keyPair=null;identityKeyPair=null;publicKeyKey;secretKeyKey;keyVersionKey;identityPublicKeyKey;identitySecretKeyKey;constructor(e,t,i,n){this.storage=e,this.logger=t;let s=`termiq.${i}.${n}`;this.publicKeyKey=`${s}.crypto.publicKey`,this.secretKeyKey=`${s}.crypto.secretKey`,this.keyVersionKey=`${s}.crypto.keyVersion`,this.identityPublicKeyKey=`${s}.crypto.identityPublicKey`,this.identitySecretKeyKey=`${s}.crypto.identitySecretKey`,this.logger.info("CryptoService namespace",i,n)}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 box key pair")):await this.generateBoxKeyPair(),await this.ensureIdentityKeyPair()}async generateBoxKeyPair(){this.logger.info("Generating new box key pair"),this.keyPair=(0,Qe.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("Box key pair generated and stored"),this.keyPair}async generateIdentityKeyPair(){return this.generateBoxKeyPair()}async ensureIdentityKeyPair(){if(this.identityKeyPair)return this.identityKeyPair;let e=await this.storage.get(this.identitySecretKeyKey),t=await this.storage.get(this.identityPublicKeyKey);return e?(t||(t=(0,qr.identityPublicFromSecret)(e),await this.storage.set(this.identityPublicKeyKey,t)),this.identityKeyPair={identityPublicKey:t,identitySecretKey:e},this.logger.info("Loaded existing identity (Ed25519) key pair"),this.identityKeyPair):(this.logger.info("Generating new identity (Ed25519) key pair"),this.identityKeyPair=(0,qr.generateIdentityKeyPair)(),await this.storage.set(this.identityPublicKeyKey,this.identityKeyPair.identityPublicKey),await this.storage.set(this.identitySecretKeyKey,this.identityKeyPair.identitySecretKey),this.logger.info("Identity (Ed25519) key pair generated and stored"),this.identityKeyPair)}async getIdentityPublicKey(){return(await this.ensureIdentityKeyPair()).identityPublicKey}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 getSignedAgentKey(e){if(!this.keyPair&&(await this.initialize(),!this.keyPair))return this.logger.error("No box key pair available for signing"),null;let t=await this.ensureIdentityKeyPair(),i=await this.getKeyVersion(),n=this.keyPair.publicKey,s=(0,qr.buildKxCanonical)({agentId:e,keyVersion:i,boxPublicKey:n}),a=(0,qr.signSessionKey)(s,t.identitySecretKey);return{boxPublicKey:n,identityPublicKey:t.identityPublicKey,keyVersion:i,signature:a,sigVersion:1}}async signKeyExchangeAck(e,t){if(!this.keyPair&&(await this.initialize(),!this.keyPair))return this.logger.error("No box key pair available for ACK signing"),null;let i=await this.ensureIdentityKeyPair(),n=await this.getKeyVersion(),s=(0,qr.buildKxAckCanonical)({agentId:e,keyVersion:n,boxPublicKey:this.keyPair.publicKey,boundClientKey:t});return(0,qr.signSessionKey)(s,i.identitySecretKey)}async getSafetyNumber(){let e=await this.ensureIdentityKeyPair();return(0,qr.fingerprintIdentityKey)(e.identityPublicKey)}async getShortFingerprint(){let e=await this.ensureIdentityKeyPair();return(0,qr.fingerprintShortHex)(e.identityPublicKey)}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 n=this.sessions.get(e);n||(n=new Map,this.sessions.set(e,n));let s=(0,Qe.deriveSharedSecret)(t,this.keyPair.secretKey),a={terminalId:e,clientPublicKey:t,sharedSecret:s,createdAt:Date.now(),sessionId:i};return n.set(i,a),this.logger.info("Key exchange completed",e,i,"total:",n.size),!0}catch(n){return this.logger.error("Key exchange failed",n),!1}}encryptOutput(e,t){let i=this.sessions.get(e);if(!i||i.size===0)return null;try{if(i.size===1){let s=i.values().next().value;return s?(0,Qe.encrypt)(t,s.sharedSecret,s.sessionId):null}let n=[];for(let s of i.values()){let a=(0,Qe.encrypt)(t,s.sharedSecret,s.sessionId);n.push({sid:a.sid,n:a.n,c:a.c})}return{v:2,recipients:n}}catch(n){return this.logger.error("Encryption failed",n),null}}decryptInput(e,t){let i=this.sessions.get(e);if(!i)return this.logger.error("No sessions for terminal",e),null;let n=i.get(t.sid);if(!n)return this.logger.error("No session for sessionId",t.sid),null;try{return(0,Qe.decrypt)(t,n.sharedSecret)}catch(s){return this.logger.error("Decryption failed",s),null}}encryptFileChunk(e,t){let i=this.sessions.get(e);if(!i||i.size===0)return null;let n=null;for(let s of i.values())(!n||s.createdAt>n.createdAt)&&(n=s);if(!n)return null;try{return(0,Qe.encryptBinary)(t,n.sharedSecret,n.sessionId)}catch(s){return this.logger.error("File chunk encryption failed",s),null}}decryptFileChunk(e,t){let i=this.sessions.get(e)?.get(t.sid);if(!i)return this.logger.error("No session for file chunk",e,t.sid),null;try{return(0,Qe.decryptBinary)(t,i.sharedSecret)}catch(n){return this.logger.error("File chunk 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 n=i.get(t);n&&((0,Qe.clearKey)(n.sharedSecret),i.delete(t),this.logger.info("Session removed",e,t)),i.size===0&&this.sessions.delete(e)}else{for(let n of i.values())(0,Qe.clearKey)(n.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,Qe.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(),n=[];for(let[s,a]of t)i-a.createdAt>Mg&&n.push(s);for(let s of n){let a=t.get(s);a&&((0,Qe.clearKey)(a.sharedSecret),t.delete(s),this.logger.info("Session expired (TTL)",e,s,`age:${Math.round((i-a.createdAt)/1e3)}s`))}if(t.size>pu){let a=Array.from(t.entries()).sort((c,u)=>c[1].createdAt-u[1].createdAt).slice(0,t.size-pu);for(let[,c]of a)(0,Qe.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 n of i.values())e.push({terminalId:t,createdAt:n.createdAt,sessionId:n.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,Qe.clearKey)(i.sharedSecret));let n=(0,Qe.deriveSharedSecret)(e,this.keyPair.secretKey),s={sessionId:t,clientPublicKey:e,sharedSecret:n,createdAt:Date.now()};return this.agentSessions.set(t,s),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,Qe.clearKey)(t.sharedSecret),this.agentSessions.delete(e),this.logger.info("Agent session removed",e))}hasAgentSessions(){return this.agentSessions.size>0}async handleMetaKeyExchange(e){if(!this.keyPair&&(await this.initialize(),!this.keyPair))return{ok:!1,isNew:!1};try{let t=!this.metaSessions.has(e),i=(0,Qe.deriveSharedSecret)(e,this.keyPair.secretKey),n=(0,Qe.deriveMetaSid)(this.keyPair.publicKey,e);return this.metaSessions.set(e,{clientIdentityPub:e,sharedSecret:i,sidMeta:n}),this.logger.info("Meta key exchange completed",n,"isNew:",t,"total:",this.metaSessions.size),{ok:!0,isNew:t}}catch(t){return this.logger.error("Meta key exchange failed",t),{ok:!1,isNew:!1}}}hasMetaSession(){return this.metaSessions.size>0}encryptWorkspaceInfo(e){let t=this.encryptForMeta(JSON.stringify(e));return t?{encrypted:t}:null}encryptTerminalInfo(e){let t=this.encryptForMeta(JSON.stringify(e));return t?{encrypted:t}:null}encryptPromptInfo(e){let t=this.encryptForMeta(JSON.stringify(e));return t?{encrypted:t}:null}encryptForMeta(e){if(this.metaSessions.size===0)return null;try{if(this.metaSessions.size===1){let i=this.metaSessions.values().next().value;return i?(0,Qe.encrypt)(e,i.sharedSecret,i.sidMeta):null}let t=[];for(let i of this.metaSessions.values()){let n=(0,Qe.encrypt)(e,i.sharedSecret,i.sidMeta);t.push({sid:n.sid,n:n.n,c:n.c})}return{v:2,recipients:t}}catch(t){return this.logger.error("Meta encryption failed",t),null}}clearAllAgentSessions(){for(let e of this.agentSessions.values())(0,Qe.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),await this.storage.delete(this.identityPublicKeyKey),await this.storage.delete(this.identitySecretKeyKey),this.keyPair=null,this.identityKeyPair=null,this.clearAllSessions(),this.clearAllAgentSessions(),this.logger.info("All crypto keys deleted")}};ws.CryptoService=Qo});var mu=M(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});xs.AuthService=void 0;var xn=fs(),ea=class{storage;cryptoService;machineId;config;logger;notification;browser;pollingAbortController=null;tokenKey;refreshTokenKey;agentIdKey;constructor(e,t,i,n,s,a,c,u,d){this.storage=e,this.cryptoService=t,this.machineId=i,this.config=n,this.logger=s,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,xn.getApiUrl)(this.config),t=await this.machineId.getMachineId(),i=this.machineId.getMachineName(),n=await this.cryptoService.getPublicKey();n||(await this.cryptoService.generateIdentityKeyPair(),n=await this.cryptoService.getPublicKey()),this.logger.info("Starting device code flow",t,i);let s=await fetch(`${e}/auth/device/code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machineId:t,machineName:i,publicKey:n})});if(!s.ok){let a=await s.text();throw new Error(`Failed to get device code: ${a}`)}return s.json()}async pollForToken(e){this.cancelPolling();let t=(0,xn.getApiUrl)(this.config),i=5e3,n=60;this.pollingAbortController=new AbortController;let s=this.pollingAbortController.signal;this.logger.info("Starting token polling");for(let a=0;a<n;a++){if(s.aborted)return this.logger.info("Polling was cancelled"),null;if(await this.sleep(i),s.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:s});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(s.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,xn.getApiUrl)(this.config),i=await this.machineId.getMachineId(),n=this.machineId.getMachineName(),s=await this.cryptoService.getPublicKey();s||(await this.cryptoService.generateIdentityKeyPair(),s=await this.cryptoService.getPublicKey()),this.logger.info("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:n,publicKey:s})});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,xn.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 n=await i.json();return await this.storage.set(this.tokenKey,n.accessToken),await this.storage.set(this.refreshTokenKey,n.refreshToken),this.logger.info("Access token refreshed successfully"),n.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,xn.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 n=i instanceof Error?i.message:String(i);return this.logger.error(`Error fetching limits: ${n}`),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))}};xs.AuthService=ea});var yu=M(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.StatusDetector=void 0;Sn.isAnswerKeystroke=Fg;var Ss={working:[/✶/,/⠋|⠙|⠹|⠸|⠼|⠴|⠦|⠧|⠇|⠏/],idle:[/[❯$#>]\s*$/,/^\s*\d+\s*[❯$#>]\s*$/,/\(base\)\s*[❯$#>]\s*$/,/\)\s*[❯$#>]\s*$/],waiting:[/\[y\/n\]\s*$/i,/\[y\/N\]\s*$/i,/\(y\/n\)\s*$/i,/\(yes\/no\)\s*$/i,/press enter to continue\s*$/i,/press any key\s*$/i,/\[enter\]\s*$/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]},hi={IDLE_TIMEOUT_MS:5e3,DEBOUNCE_MS:500,BUFFER_SIZE:16e3,WORKING_TIMEOUT_MS:3e4,RESOLVE_GRACE_MS:1500,PROMPT_REFRESH_MS:450},ta=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,pendingStatus:null,pendingPrompt:null,emittedPromptKey:null,lastSeenPromptKey:null,promptRefreshTimer:null,resolveGraceUntil:0,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),t.promptRefreshTimer&&clearTimeout(t.promptRefreshTimer)),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>hi.BUFFER_SIZE&&(i.outputBuffer=i.outputBuffer.slice(-hi.BUFFER_SIZE));let n=Date.now()<i.resolveGraceUntil,s=!1;if(!n){let a=this.detectPrompt(i.outputBuffer);if(a&&a.type!=="free-input"&&this.isPromptActive(i.outputBuffer)&&(s=!0,i.pendingPrompt=a,i.status==="waiting")){let c=this.promptKey(a);c!==i.lastSeenPromptKey&&(i.lastSeenPromptKey=c,this.schedulePromptRefresh(e))}}if(s)this.scheduleStatusUpdate(e,"waiting");else if(i.status==="waiting"&&!n){let a=this.analyzeOutput(i.outputBuffer);(a==="completed"||a==="error")&&this.scheduleStatusUpdate(e,a)}else{let a=this.analyzeOutput(i.outputBuffer);a&&this.scheduleStatusUpdate(e,a)}this.resetWorkingTimeout(e,i)}isPromptActive(e){let i=this.normalizeBuffer(this.stripAnsi(e)).split(`
6
6
  `).map(a=>a.trim()).filter(Boolean);if(i.length===0)return!1;let n=i[i.length-1],s=i.slice(-18).join(`
7
- `);return/[❯›●]/.test(s)||/\[y\/n\]|\(y\/n\)|\[y\/N\]|\(yes\/no\)/i.test(n)||/esc to cancel|enter to confirm|press enter|press any key|\[enter\]|\(esc\)/i.test(s)}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 n;if(t!==void 0&&t!==0)n="error";else{let s=this.analyzeOutput(i.outputBuffer);s==="waiting"?n="waiting":s==="error"?n="error":s==="completed"?n="completed":n="idle"}this.scheduleStatusUpdate(e,n),(n==="completed"||n==="error")&&setTimeout(()=>{let s=this.states.get(e);s&&(s.status==="completed"||s.status==="error")&&this.scheduleStatusUpdate(e,"idle")},Ni.IDLE_TIMEOUT_MS)}analyzeOutput(e){let i=this.normalizeBuffer(this.stripAnsi(e)).split(`
7
+ `);return/[❯›●]/.test(s)||/\[y\/n\]|\(y\/n\)|\[y\/N\]|\(yes\/no\)/i.test(n)||/esc to cancel|enter to confirm|press enter|press any key|\[enter\]|\(esc\)/i.test(s)}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 n;if(t!==void 0&&t!==0)n="error";else{let s=this.analyzeOutput(i.outputBuffer);s==="waiting"?n="waiting":s==="error"?n="error":s==="completed"?n="completed":n="idle"}this.scheduleStatusUpdate(e,n),(n==="completed"||n==="error")&&setTimeout(()=>{let s=this.states.get(e);s&&(s.status==="completed"||s.status==="error")&&this.scheduleStatusUpdate(e,"idle")},hi.IDLE_TIMEOUT_MS)}analyzeOutput(e){let i=this.normalizeBuffer(this.stripAnsi(e)).split(`
8
8
  `).slice(-10),n=i.join(`
9
9
  `),s=(i[i.length-1]||"").trim();for(let a of Ss.waiting)if(a.test(s))return"waiting";for(let a of Ss.working)if(a.test(s))return"working";for(let a of Ss.completed)if(a.test(n))return"completed";for(let a of Ss.idle)if(a.test(s))return"idle";return null}detectPrompt(e){let n=this.normalizeBuffer(this.stripAnsi(e)).split(`
10
10
  `).slice(-20),s=n.join(`
11
11
  `),a=n[n.length-1]||"",c=this.extractNumberedChoices(e);if(c.length>=2)return{type:"numbered-choice",question:this.extractQuestion(s)||"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(s))return{type:"yes-no",question:this.extractQuestion(s)||"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(s))return{type:"enter",question:this.extractQuestion(s)||"Press Enter to continue"};let p=[/Press any key/i,/press a key/i];for(let m of p)if(m.test(s))return{type:"any-key",question:this.extractQuestion(s)||"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=[],n=this.normalizeBuffer(this.stripAnsi(e)).split(`
12
- `),s=/^\s*[❯>*›●]?\s*(?:(\d+)[.)]\s*|\[(\d+)\]\s*)(.+)$/;for(let a of n){let c=a.match(s);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(`
13
- `).filter(i=>i.trim());for(let i=t.length-1;i>=Math.max(0,t.length-5);i--){let n=t[i].trim();if(!n||/^\s*\d+[.)]\s/.test(n)||/^\s*\[/.test(n))continue;let s=this.stripAnsi(n);if(s.endsWith("?")||s.endsWith(":"))return s.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
+ `),s=/^[\s│┃┊┋┆┇╎╏]*(?:[❯▶▸›●>*]\s*)?(?:(\d+)[.)]\s*|\[(\d+)\]\s*)(.+?)[\s│┃]*$/u,a=[],c=-1,u=[],d=m=>m.length*1e3+m.reduce((_,E)=>_+E.label.length,0),p=()=>{u.length>=1&&d(u)>=c&&(a=u.slice(),c=d(u))};for(let m of n){let _=m.match(s);if(!_)continue;let E=_[1]||_[2],S=_[3].replace(/\s+/g," ").trim();if(!E||!S||S.length>=100||S.includes("error"))continue;let T=parseInt(E,10);T===u.length+1?u.push({key:E,label:S}):T===1?(p(),u=[{key:E,label:S}]):(p(),u=[])}return p(),t.push(...a),t}extractQuestion(e){let t=e.split(`
13
+ `).filter(i=>i.trim());for(let i=t.length-1;i>=Math.max(0,t.length-8);i--){let n=t[i].trim();if(!n||/^[\s│┃]*(?:[❯▶▸›●>*]\s*)?\d+[.)]\s/.test(n)||/^[\s│┃]*\[/.test(n))continue;let s=this.stripAnsi(n).replace(/^[\s│┃┊┋┆┇╎╏]+/u,"").replace(/[\s│┃┊┋┆┇╎╏]+$/u,"").replace(/\s+/g," ");if(s.endsWith("?")||s.endsWith(":"))return s.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]*[GC]/g," ").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,`
14
14
  `).replace(/\r/g,`
15
15
  `).replace(/\n{3,}/g,`
16
16
 
17
- `)}scheduleStatusUpdate(e,t){let i=this.states.get(e);i&&i.status!==t&&i.pendingStatus!==t&&(i.pendingUpdate&&clearTimeout(i.pendingUpdate),i.pendingStatus=t,i.pendingUpdate=setTimeout(()=>{i.pendingStatus=null,this.emitStatus(e,t),i.pendingUpdate=null},Ni.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 n;t==="waiting"&&(n=this.detectPrompt(i.outputBuffer)||void 0),this.onStatusChange(e,t,n)}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))},Ni.WORKING_TIMEOUT_MS))}resolvePrompt(e){let t=this.states.get(e);t&&t.status==="waiting"&&(t.resolveGraceUntil=Date.now()+Ni.RESOLVE_GRACE_MS,t.outputBuffer="",this.scheduleStatusUpdate(e,"working"))}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)}};Sn.StatusDetector=ta;function Fg(r){for(let e=0;e<r.length;e++){let t=r.charCodeAt(e);if(t===27){let i=r[e+1];if(i==="["||i==="O"){for(e+=2;e<r.length&&!/[A-Za-z~]/.test(r[e]);)e++;continue}if(i==="]"){for(e+=2;e<r.length&&r.charCodeAt(e)!==7;)e++;continue}return!0}if(t===13||t===10||t===3||t>=32&&t!==127)return!0}return!1}});var bu=M((SE,vu)=>{var Mi=require("fs"),_u=require("url"),Dg=require("child_process").spawn;vu.exports=ra;ra.XMLHttpRequest=ra;function ra(r){"use strict";r=r||{};var e=this,t=require("http"),i=require("https"),n,s,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"],_=!1,E=!1,S=!1,T={};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 z=function(A){return c||A&&p.indexOf(A.toLowerCase())===-1},ge=function(A){return A&&m.indexOf(A)===-1};this.open=function(A,B,re,q,U){if(this.abort(),E=!1,S=!1,!ge(A))throw new Error("SecurityError: Request method not allowed");a={method:A,url:B.toString(),async:typeof re!="boolean"?!0:re,user:q||null,password:U||null},ee(this.OPENED)},this.setDisableHeaderCheck=function(A){c=A},this.setRequestHeader=function(A,B){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");if(!z(A))return console.warn('Refused to set unsafe header "'+A+'"'),!1;if(_)throw new Error("INVALID_STATE_ERR: send flag is true");return d[A]=B,!0},this.getResponseHeader=function(A){return typeof A=="string"&&this.readyState>this.OPENED&&s.headers[A.toLowerCase()]&&!E?s.headers[A.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||E)return"";var A="";for(var B in s.headers)B!=="set-cookie"&&B!=="set-cookie2"&&(A+=B+": "+s.headers[B]+`\r
18
- `);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(_)throw new Error("INVALID_STATE_ERR: send has already been called");var B=!1,re=!1,q=_u.parse(a.url),U;switch(q.protocol){case"https:":B=!0;case"http:":U=q.hostname;break;case"file:":re=!0;break;case void 0:case"":U="localhost";break;default:throw new Error("Protocol not supported.")}if(re){if(a.method!=="GET")throw new Error("XMLHttpRequest: Only GET method is supported");if(a.async)Mi.readFile(unescape(q.pathname),function(R,P){R?e.handleError(R,R.errno||-1):(e.status=200,e.responseText=P.toString("utf8"),e.response=P,ee(e.DONE))});else try{this.response=Mi.readFileSync(unescape(q.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,ee(e.DONE)}catch(R){this.handleError(R,R.errno||-1)}return}var ye=q.port||(B?443:80),xe=q.pathname+(q.search?q.search:"");if(d.Host=U,B&&ye===443||ye===80||(d.Host+=":"+q.port),a.user){typeof a.password>"u"&&(a.password="");var ue=new Buffer(a.user+":"+a.password);d.Authorization="Basic "+ue.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 rt=Object.keys(d);rt.some(function(R){return R.toLowerCase()==="content-type"})||(d["Content-Type"]="text/plain;charset=UTF-8")}else a.method==="POST"&&(d["Content-Length"]=0);var Ee=r.agent||!1,Se={host:U,port:ye,path:xe,method:a.method,headers:d,agent:Ee};if(B&&(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),E=!1,a.async){var be=B?i.request:t.request;_=!0,e.dispatchEvent("readystatechange");var We=function(R){if(s=R,s.statusCode===302||s.statusCode===303||s.statusCode===307){a.url=s.headers.location;var P=_u.parse(a.url);U=P.hostname;var Z={hostname:P.hostname,port:P.port,path:P.path,method:s.statusCode===303?"GET":a.method,headers:d};B&&(Z.pfx=r.pfx,Z.key=r.key,Z.passphrase=r.passphrase,Z.cert=r.cert,Z.ca=r.ca,Z.ciphers=r.ciphers,Z.rejectUnauthorized=r.rejectUnauthorized!==!1),n=be(Z,We).on("error",st),n.end();return}ee(e.HEADERS_RECEIVED),e.status=s.statusCode,s.on("data",function(Ne){if(Ne){var Xe=Buffer.from(Ne);e.response=Buffer.concat([e.response,Xe])}_&&ee(e.LOADING)}),s.on("end",function(){_&&(_=!1,ee(e.DONE),e.responseText=e.response.toString("utf8"))}),s.on("error",function(Ne){e.handleError(Ne)})},st=function(R){if(n.reusedSocket&&R.code==="ECONNRESET")return be(Se,We).on("error",st);e.handleError(R)};n=be(Se,We).on("error",st),r.autoUnref&&n.on("socket",R=>{R.unref()}),A&&n.write(A),n.end(),e.dispatchEvent("loadstart")}else{var Ze=".node-xmlhttprequest-content-"+process.pid,Te=".node-xmlhttprequest-sync-"+process.pid;Mi.writeFileSync(Te,"","utf8");for(var it="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(B?"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('"+Ze+"', 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('"+Ze+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Te+"');});}).on('error', function(error) {fs.writeFileSync('"+Ze+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Te+"');});"+(A?"req.write('"+JSON.stringify(A).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",ze=Dg(process.argv[0],["-e",it]),gt;Mi.existsSync(Te););if(e.responseText=Mi.readFileSync(Ze,"utf8"),ze.stdin.end(),Mi.unlinkSync(Ze),e.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var L=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,""));e.handleError(L,503)}else{e.status=e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/,"$1");var j=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"));s={statusCode:e.status,headers:j.data.headers},e.responseText=j.data.text,e.response=Buffer.from(j.data.data,"base64"),ee(e.DONE,!0)}}},this.handleError=function(A,B){this.status=B||0,this.statusText=A,this.responseText=A.stack,E=!0,ee(this.DONE)},this.abort=function(){n&&(n.abort(),n=null),d=Object.assign({},u),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),E=S=!0,this.readyState!==this.UNSENT&&(this.readyState!==this.OPENED||_)&&this.readyState!==this.DONE&&(_=!1,ee(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(A,B){A in T||(T[A]=[]),T[A].push(B)},this.removeEventListener=function(A,B){A in T&&(T[A]=T[A].filter(function(re){return re!==B}))},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 T)for(let B=0,re=T[A].length;B<re;B++)this.readyState===this.DONE?setTimeout(function(){T[A][B].call(e)},0):T[A][B].call(e)};var ee=function(A){if(!(e.readyState===A||e.readyState===e.UNSENT&&S)&&(e.readyState=A,(a.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let B;S?B="abort":E?B="error":B="load",e.dispatchEvent(B),e.dispatchEvent("loadend")}}}});var Ts=M(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.ERROR_PACKET=Wr.PACKET_TYPES_REVERSE=Wr.PACKET_TYPES=void 0;var sr=Object.create(null);Wr.PACKET_TYPES=sr;sr.open="0";sr.close="1";sr.ping="2";sr.pong="3";sr.message="4";sr.upgrade="5";sr.noop="6";var Eu=Object.create(null);Wr.PACKET_TYPES_REVERSE=Eu;Object.keys(sr).forEach(r=>{Eu[sr[r]]=r});var Bg={type:"error",data:"parser error"};Wr.ERROR_PACKET=Bg});var xu=M(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});Fi.encodePacket=void 0;Fi.encodePacketToBinary=qg;var jg=Ts(),Ug=({type:r,data:e},t,i)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?i(t?e:"b"+wu(e,!0).toString("base64")):i(jg.PACKET_TYPES[r]+(e||""));Fi.encodePacket=Ug;var wu=(r,e)=>Buffer.isBuffer(r)||r instanceof Uint8Array&&!e?r:r instanceof ArrayBuffer?Buffer.from(r):Buffer.from(r.buffer,r.byteOffset,r.byteLength),ia;function qg(r,e){if(r.data instanceof ArrayBuffer||ArrayBuffer.isView(r.data))return e(wu(r.data,!1));(0,Fi.encodePacket)(r,!0,t=>{ia||(ia=new TextEncoder),e(ia.encode(t))})}});var Tu=M(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.decodePacket=void 0;var Cs=Ts(),Kg=(r,e)=>{if(typeof r!="string")return{type:"message",data:Su(r,e)};let t=r.charAt(0);if(t==="b"){let i=Buffer.from(r.substring(1),"base64");return{type:"message",data:Su(i,e)}}return Cs.PACKET_TYPES_REVERSE[t]?r.length>1?{type:Cs.PACKET_TYPES_REVERSE[t],data:r.substring(1)}:{type:Cs.PACKET_TYPES_REVERSE[t]}:Cs.ERROR_PACKET};ks.decodePacket=Kg;var Su=(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 Di=M(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.decodePayload=bt.decodePacket=bt.encodePayload=bt.encodePacket=bt.protocol=void 0;bt.createPacketEncoderStream=Vg;bt.createPacketDecoderStream=zg;var sa=xu();Object.defineProperty(bt,"encodePacket",{enumerable:!0,get:function(){return sa.encodePacket}});var oa=Tu();Object.defineProperty(bt,"decodePacket",{enumerable:!0,get:function(){return oa.decodePacket}});var Cu=Ts(),ku="",Wg=(r,e)=>{let t=r.length,i=new Array(t),n=0;r.forEach((s,a)=>{(0,sa.encodePacket)(s,!1,c=>{i[a]=c,++n===t&&e(i.join(ku))})})};bt.encodePayload=Wg;var Hg=(r,e)=>{let t=r.split(ku),i=[];for(let n=0;n<t.length;n++){let s=(0,oa.decodePacket)(t[n],e);if(i.push(s),s.type==="error")break}return i};bt.decodePayload=Hg;function Vg(){return new TransformStream({transform(r,e){(0,sa.encodePacketToBinary)(r,t=>{let i=t.length,n;if(i<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,i);else if(i<65536){n=new Uint8Array(3);let s=new DataView(n.buffer);s.setUint8(0,126),s.setUint16(1,i)}else{n=new Uint8Array(9);let s=new DataView(n.buffer);s.setUint8(0,127),s.setBigUint64(1,BigInt(i))}r.data&&typeof r.data!="string"&&(n[0]|=128),e.enqueue(n),e.enqueue(t)})}})}var na;function Os(r){return r.reduce((e,t)=>e+t.length,0)}function Ps(r,e){if(r[0].length===e)return r.shift();let t=new Uint8Array(e),i=0;for(let n=0;n<e;n++)t[n]=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 zg(r,e){na||(na=new TextDecoder);let t=[],i=0,n=-1,s=!1;return new TransformStream({transform(a,c){for(t.push(a);;){if(i===0){if(Os(t)<1)break;let u=Ps(t,1);s=(u[0]&128)===128,n=u[0]&127,n<126?i=3:n===126?i=1:i=2}else if(i===1){if(Os(t)<2)break;let u=Ps(t,2);n=new DataView(u.buffer,u.byteOffset,u.length).getUint16(0),i=3}else if(i===2){if(Os(t)<8)break;let u=Ps(t,8),d=new DataView(u.buffer,u.byteOffset,u.length),p=d.getUint32(0);if(p>Math.pow(2,21)-1){c.enqueue(Cu.ERROR_PACKET);break}n=p*Math.pow(2,32)+d.getUint32(4),i=3}else{if(Os(t)<n)break;let u=Ps(t,n);c.enqueue((0,oa.decodePacket)(s?u:na.decode(u),e)),i=0}if(n===0||n>r){c.enqueue(Cu.ERROR_PACKET);break}}}})}bt.protocol=4});var hi=M(Ou=>{Ou.Emitter=yt;function yt(r){if(r)return $g(r)}function $g(r){for(var e in yt.prototype)r[e]=yt.prototype[e];return r}yt.prototype.on=yt.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this};yt.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this};yt.prototype.off=yt.prototype.removeListener=yt.prototype.removeAllListeners=yt.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,n=0;n<t.length;n++)if(i=t[n],i===e||i.fn===e){t.splice(n,1);break}return t.length===0&&delete this._callbacks["$"+r],this};yt.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,n=t.length;i<n;++i)t[i].apply(this,e)}return this};yt.prototype.emitReserved=yt.prototype.emit;yt.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};yt.prototype.hasListeners=function(r){return!!this.listeners(r).length}});var di=M(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.CookieJar=Nt.defaultBinaryType=Nt.globalThisShim=Nt.nextTick=void 0;Nt.createCookieJar=Gg;Nt.parse=Pu;Nt.nextTick=process.nextTick;Nt.globalThisShim=global;Nt.defaultBinaryType="nodebuffer";function Gg(){return new As}function Pu(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 n=e[0].substring(t+1).trim();n.charCodeAt(0)===34&&(n=n.slice(1,-1));let s={name:i,value:n};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":s.expires=new Date(d);break;case"Max-Age":let p=new Date;p.setUTCSeconds(p.getUTCSeconds()+parseInt(d,10)),s.expires=p;break;default:}}return s}var As=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let i=Pu(t);i&&this._cookies.set(i.name,i)})}get cookies(){let e=Date.now();return this._cookies.forEach((t,i)=>{var n;((n=t.expires)===null||n===void 0?void 0:n.getTime())<e&&this._cookies.delete(i)}),this._cookies.entries()}addCookies(e){let t=[];for(let[i,n]of this.cookies)t.push(`${i}=${n.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}`)}};Nt.CookieJar=As});var pi=M(Bi=>{"use strict";Object.defineProperty(Bi,"__esModule",{value:!0});Bi.pick=Yg;Bi.installTimerFunctions=Zg;Bi.byteLength=em;Bi.randomString=rm;var Hr=di();function Yg(r,...e){return e.reduce((t,i)=>(r.hasOwnProperty(i)&&(t[i]=r[i]),t),{})}var Xg=Hr.globalThisShim.setTimeout,Jg=Hr.globalThisShim.clearTimeout;function Zg(r,e){e.useNativeTimers?(r.setTimeoutFn=Xg.bind(Hr.globalThisShim),r.clearTimeoutFn=Jg.bind(Hr.globalThisShim)):(r.setTimeoutFn=Hr.globalThisShim.setTimeout.bind(Hr.globalThisShim),r.clearTimeoutFn=Hr.globalThisShim.clearTimeout.bind(Hr.globalThisShim))}var Qg=1.33;function em(r){return typeof r=="string"?tm(r):Math.ceil((r.byteLength||r.size)*Qg)}function tm(r){let e=0,t=0;for(let i=0,n=r.length;i<n;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 rm(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}});var aa=M(Rs=>{"use strict";Object.defineProperty(Rs,"__esModule",{value:!0});Rs.encode=im;Rs.decode=nm;function im(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function nm(r){let e={},t=r.split("&");for(let i=0,n=t.length;i<n;i++){let s=t[i].split("=");e[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return e}});var Ru=M((LE,Au)=>{var ji=1e3,Ui=ji*60,qi=Ui*60,gi=qi*24,sm=gi*7,om=gi*365.25;Au.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return am(r);if(t==="number"&&isFinite(r))return e.long?fm(r):cm(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function am(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*om;case"weeks":case"week":case"w":return t*sm;case"days":case"day":case"d":return t*gi;case"hours":case"hour":case"hrs":case"hr":case"h":return t*qi;case"minutes":case"minute":case"mins":case"min":case"m":return t*Ui;case"seconds":case"second":case"secs":case"sec":case"s":return t*ji;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function cm(r){var e=Math.abs(r);return e>=gi?Math.round(r/gi)+"d":e>=qi?Math.round(r/qi)+"h":e>=Ui?Math.round(r/Ui)+"m":e>=ji?Math.round(r/ji)+"s":r+"ms"}function fm(r){var e=Math.abs(r);return e>=gi?Is(r,e,gi,"day"):e>=qi?Is(r,e,qi,"hour"):e>=Ui?Is(r,e,Ui,"minute"):e>=ji?Is(r,e,ji,"second"):r+" ms"}function Is(r,e,t,i){var n=e>=t*1.5;return Math.round(r/t)+" "+i+(n?"s":"")}});var ca=M((NE,Iu)=>{function um(r){t.debug=t,t.default=t,t.coerce=u,t.disable=a,t.enable=n,t.enabled=c,t.humanize=Ru(),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 _=0;_<p.length;_++)m=(m<<5)-m+p.charCodeAt(_),m|=0;return t.colors[Math.abs(m)%t.colors.length]}t.selectColor=e;function t(p){let m,_=null,E,S;function T(...z){if(!T.enabled)return;let ge=T,ee=Number(new Date),A=ee-(m||ee);ge.diff=A,ge.prev=m,ge.curr=ee,m=ee,z[0]=t.coerce(z[0]),typeof z[0]!="string"&&z.unshift("%O");let B=0;z[0]=z[0].replace(/%([a-zA-Z%])/g,(q,U)=>{if(q==="%%")return"%";B++;let ye=t.formatters[U];if(typeof ye=="function"){let xe=z[B];q=ye.call(ge,xe),z.splice(B,1),B--}return q}),t.formatArgs.call(ge,z),(ge.log||t.log).apply(ge,z)}return T.namespace=p,T.useColors=t.useColors(),T.color=t.selectColor(p),T.extend=i,T.destroy=t.destroy,Object.defineProperty(T,"enabled",{enumerable:!0,configurable:!1,get:()=>_!==null?_:(E!==t.namespaces&&(E=t.namespaces,S=t.enabled(p)),S),set:z=>{_=z}}),typeof t.init=="function"&&t.init(T),T}function i(p,m){let _=t(this.namespace+(typeof m>"u"?":":m)+p);return _.log=this.log,_}function n(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 _ of m)_[0]==="-"?t.skips.push(_.slice(1)):t.names.push(_)}function s(p,m){let _=0,E=0,S=-1,T=0;for(;_<p.length;)if(E<m.length&&(m[E]===p[_]||m[E]==="*"))m[E]==="*"?(S=E,T=_,E++):(_++,E++);else if(S!==-1)E=S+1,T++,_=T;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(s(p,m))return!1;for(let m of t.names)if(s(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}Iu.exports=um});var Lu=M((Et,Ls)=>{Et.formatArgs=hm;Et.save=dm;Et.load=pm;Et.useColors=lm;Et.storage=gm();Et.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`."))}})();Et.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 lm(){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 hm(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ls.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,n=>{n!=="%%"&&(t++,n==="%c"&&(i=t))}),r.splice(i,0,e)}Et.log=console.debug||console.log||(()=>{});function dm(r){try{r?Et.storage.setItem("debug",r):Et.storage.removeItem("debug")}catch{}}function pm(){let r;try{r=Et.storage.getItem("debug")||Et.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function gm(){try{return localStorage}catch{}}Ls.exports=ca()(Et);var{formatters:mm}=Ls.exports;mm.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Mu=M((ME,Nu)=>{"use strict";Nu.exports=(r,e=process.argv)=>{let t=r.startsWith("-")?"":r.length===1?"-":"--",i=e.indexOf(t+r),n=e.indexOf("--");return i!==-1&&(n===-1||i<n)}});var Bu=M((FE,Du)=>{"use strict";var ym=require("os"),Fu=require("tty"),Mt=Mu(),{env:ot}=process,Vr;Mt("no-color")||Mt("no-colors")||Mt("color=false")||Mt("color=never")?Vr=0:(Mt("color")||Mt("colors")||Mt("color=true")||Mt("color=always"))&&(Vr=1);"FORCE_COLOR"in ot&&(ot.FORCE_COLOR==="true"?Vr=1:ot.FORCE_COLOR==="false"?Vr=0:Vr=ot.FORCE_COLOR.length===0?1:Math.min(parseInt(ot.FORCE_COLOR,10),3));function fa(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function ua(r,e){if(Vr===0)return 0;if(Mt("color=16m")||Mt("color=full")||Mt("color=truecolor"))return 3;if(Mt("color=256"))return 2;if(r&&!e&&Vr===void 0)return 0;let t=Vr||0;if(ot.TERM==="dumb")return t;if(process.platform==="win32"){let i=ym.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in ot)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(i=>i in ot)||ot.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in ot)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(ot.TEAMCITY_VERSION)?1:0;if(ot.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in ot){let i=parseInt((ot.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(ot.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(ot.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(ot.TERM)||"COLORTERM"in ot?1:t}function _m(r){let e=ua(r,r&&r.isTTY);return fa(e)}Du.exports={supportsColor:_m,stdout:fa(ua(!0,Fu.isatty(1))),stderr:fa(ua(!0,Fu.isatty(2)))}});var Uu=M((at,Ms)=>{var vm=require("tty"),Ns=require("util");at.init=Cm;at.log=xm;at.formatArgs=Em;at.save=Sm;at.load=Tm;at.useColors=bm;at.destroy=Ns.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");at.colors=[6,2,3,4,5,1];try{let r=Bu();r&&(r.stderr||r).level>=2&&(at.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{}at.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(n,s)=>s.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 bm(){return"colors"in at.inspectOpts?!!at.inspectOpts.colors:vm.isatty(process.stderr.fd)}function Em(r){let{namespace:e,useColors:t}=this;if(t){let i=this.color,n="\x1B[3"+(i<8?i:"8;5;"+i),s=` ${n};1m${e} \x1B[0m`;r[0]=s+r[0].split(`
17
+ `)}scheduleStatusUpdate(e,t){let i=this.states.get(e);i&&i.status!==t&&i.pendingStatus!==t&&(i.pendingUpdate&&clearTimeout(i.pendingUpdate),i.pendingStatus=t,i.pendingUpdate=setTimeout(()=>{i.pendingStatus=null,this.emitStatus(e,t),i.pendingUpdate=null},hi.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 n;if(t==="waiting"){let s=this.detectPrompt(i.outputBuffer);n=s&&s.type!=="free-input"?s:i.pendingPrompt||s||void 0,i.emittedPromptKey=n?this.promptKey(n):null,i.lastSeenPromptKey=i.emittedPromptKey}else i.pendingPrompt=null,i.emittedPromptKey=null,i.lastSeenPromptKey=null,i.promptRefreshTimer&&(clearTimeout(i.promptRefreshTimer),i.promptRefreshTimer=null);this.onStatusChange(e,t,n)}promptKey(e){let t=(e.choices||[]).map(i=>`${i.key}=${i.label}`).join("\xA7");return`${e.type}|${e.question}|${t}`}schedulePromptRefresh(e){let t=this.states.get(e);t&&(t.promptRefreshTimer&&clearTimeout(t.promptRefreshTimer),t.promptRefreshTimer=setTimeout(()=>{let i=this.states.get(e);if(!i||(i.promptRefreshTimer=null,i.status!=="waiting"||Date.now()<i.resolveGraceUntil))return;let n=this.detectPrompt(i.outputBuffer),s=n&&n.type!=="free-input"?n:i.pendingPrompt;if(!s)return;let a=this.promptKey(s);a!==i.emittedPromptKey&&(i.emittedPromptKey=a,i.lastSeenPromptKey=a,this.onStatusChange(e,"waiting",s))},hi.PROMPT_REFRESH_MS))}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))},hi.WORKING_TIMEOUT_MS))}resolvePrompt(e){let t=this.states.get(e);t&&t.status==="waiting"&&(t.resolveGraceUntil=Date.now()+hi.RESOLVE_GRACE_MS,t.pendingPrompt=null,t.emittedPromptKey=null,t.lastSeenPromptKey=null,t.promptRefreshTimer&&(clearTimeout(t.promptRefreshTimer),t.promptRefreshTimer=null),t.outputBuffer="",this.scheduleStatusUpdate(e,"working"))}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)}};Sn.StatusDetector=ta;function Fg(r){for(let e=0;e<r.length;e++){let t=r.charCodeAt(e);if(t===27){let i=r[e+1];if(i==="["||i==="O"){for(e+=2;e<r.length&&!/[A-Za-z~]/.test(r[e]);)e++;continue}if(i==="]"){for(e+=2;e<r.length&&r.charCodeAt(e)!==7;)e++;continue}return!0}if(t===13||t===10||t===3||t>=32&&t!==127)return!0}return!1}});var vu=M((SE,bu)=>{var Mi=require("fs"),_u=require("url"),Dg=require("child_process").spawn;bu.exports=ra;ra.XMLHttpRequest=ra;function ra(r){"use strict";r=r||{};var e=this,t=require("http"),i=require("https"),n,s,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"],_=!1,E=!1,S=!1,T={};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 z=function(R){return c||R&&p.indexOf(R.toLowerCase())===-1},ge=function(R){return R&&m.indexOf(R)===-1};this.open=function(R,B,re,K,U){if(this.abort(),E=!1,S=!1,!ge(R))throw new Error("SecurityError: Request method not allowed");a={method:R,url:B.toString(),async:typeof re!="boolean"?!0:re,user:K||null,password:U||null},ee(this.OPENED)},this.setDisableHeaderCheck=function(R){c=R},this.setRequestHeader=function(R,B){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");if(!z(R))return console.warn('Refused to set unsafe header "'+R+'"'),!1;if(_)throw new Error("INVALID_STATE_ERR: send flag is true");return d[R]=B,!0},this.getResponseHeader=function(R){return typeof R=="string"&&this.readyState>this.OPENED&&s.headers[R.toLowerCase()]&&!E?s.headers[R.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||E)return"";var R="";for(var B in s.headers)B!=="set-cookie"&&B!=="set-cookie2"&&(R+=B+": "+s.headers[B]+`\r
18
+ `);return R.substr(0,R.length-2)},this.getRequestHeader=function(R){return typeof R=="string"&&d[R]?d[R]:""},this.send=function(R){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");if(_)throw new Error("INVALID_STATE_ERR: send has already been called");var B=!1,re=!1,K=_u.parse(a.url),U;switch(K.protocol){case"https:":B=!0;case"http:":U=K.hostname;break;case"file:":re=!0;break;case void 0:case"":U="localhost";break;default:throw new Error("Protocol not supported.")}if(re){if(a.method!=="GET")throw new Error("XMLHttpRequest: Only GET method is supported");if(a.async)Mi.readFile(unescape(K.pathname),function(A,P){A?e.handleError(A,A.errno||-1):(e.status=200,e.responseText=P.toString("utf8"),e.response=P,ee(e.DONE))});else try{this.response=Mi.readFileSync(unescape(K.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,ee(e.DONE)}catch(A){this.handleError(A,A.errno||-1)}return}var ye=K.port||(B?443:80),xe=K.pathname+(K.search?K.search:"");if(d.Host=U,B&&ye===443||ye===80||(d.Host+=":"+K.port),a.user){typeof a.password>"u"&&(a.password="");var ue=new Buffer(a.user+":"+a.password);d.Authorization="Basic "+ue.toString("base64")}if(a.method==="GET"||a.method==="HEAD")R=null;else if(R){d["Content-Length"]=Buffer.isBuffer(R)?R.length:Buffer.byteLength(R);var rt=Object.keys(d);rt.some(function(A){return A.toLowerCase()==="content-type"})||(d["Content-Type"]="text/plain;charset=UTF-8")}else a.method==="POST"&&(d["Content-Length"]=0);var Ee=r.agent||!1,Se={host:U,port:ye,path:xe,method:a.method,headers:d,agent:Ee};if(B&&(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),E=!1,a.async){var ve=B?i.request:t.request;_=!0,e.dispatchEvent("readystatechange");var We=function(A){if(s=A,s.statusCode===302||s.statusCode===303||s.statusCode===307){a.url=s.headers.location;var P=_u.parse(a.url);U=P.hostname;var Z={hostname:P.hostname,port:P.port,path:P.path,method:s.statusCode===303?"GET":a.method,headers:d};B&&(Z.pfx=r.pfx,Z.key=r.key,Z.passphrase=r.passphrase,Z.cert=r.cert,Z.ca=r.ca,Z.ciphers=r.ciphers,Z.rejectUnauthorized=r.rejectUnauthorized!==!1),n=ve(Z,We).on("error",st),n.end();return}ee(e.HEADERS_RECEIVED),e.status=s.statusCode,s.on("data",function(Ne){if(Ne){var Xe=Buffer.from(Ne);e.response=Buffer.concat([e.response,Xe])}_&&ee(e.LOADING)}),s.on("end",function(){_&&(_=!1,ee(e.DONE),e.responseText=e.response.toString("utf8"))}),s.on("error",function(Ne){e.handleError(Ne)})},st=function(A){if(n.reusedSocket&&A.code==="ECONNRESET")return ve(Se,We).on("error",st);e.handleError(A)};n=ve(Se,We).on("error",st),r.autoUnref&&n.on("socket",A=>{A.unref()}),R&&n.write(R),n.end(),e.dispatchEvent("loadstart")}else{var Ze=".node-xmlhttprequest-content-"+process.pid,Te=".node-xmlhttprequest-sync-"+process.pid;Mi.writeFileSync(Te,"","utf8");for(var it="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(B?"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('"+Ze+"', 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('"+Ze+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Te+"');});}).on('error', function(error) {fs.writeFileSync('"+Ze+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Te+"');});"+(R?"req.write('"+JSON.stringify(R).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",ze=Dg(process.argv[0],["-e",it]),gt;Mi.existsSync(Te););if(e.responseText=Mi.readFileSync(Ze,"utf8"),ze.stdin.end(),Mi.unlinkSync(Ze),e.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var L=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,""));e.handleError(L,503)}else{e.status=e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/,"$1");var j=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"));s={statusCode:e.status,headers:j.data.headers},e.responseText=j.data.text,e.response=Buffer.from(j.data.data,"base64"),ee(e.DONE,!0)}}},this.handleError=function(R,B){this.status=B||0,this.statusText=R,this.responseText=R.stack,E=!0,ee(this.DONE)},this.abort=function(){n&&(n.abort(),n=null),d=Object.assign({},u),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),E=S=!0,this.readyState!==this.UNSENT&&(this.readyState!==this.OPENED||_)&&this.readyState!==this.DONE&&(_=!1,ee(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(R,B){R in T||(T[R]=[]),T[R].push(B)},this.removeEventListener=function(R,B){R in T&&(T[R]=T[R].filter(function(re){return re!==B}))},this.dispatchEvent=function(R){if(typeof e["on"+R]=="function"&&(this.readyState===this.DONE&&a.async?setTimeout(function(){e["on"+R]()},0):e["on"+R]()),R in T)for(let B=0,re=T[R].length;B<re;B++)this.readyState===this.DONE?setTimeout(function(){T[R][B].call(e)},0):T[R][B].call(e)};var ee=function(R){if(!(e.readyState===R||e.readyState===e.UNSENT&&S)&&(e.readyState=R,(a.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let B;S?B="abort":E?B="error":B="load",e.dispatchEvent(B),e.dispatchEvent("loadend")}}}});var Ts=M(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.ERROR_PACKET=Wr.PACKET_TYPES_REVERSE=Wr.PACKET_TYPES=void 0;var sr=Object.create(null);Wr.PACKET_TYPES=sr;sr.open="0";sr.close="1";sr.ping="2";sr.pong="3";sr.message="4";sr.upgrade="5";sr.noop="6";var Eu=Object.create(null);Wr.PACKET_TYPES_REVERSE=Eu;Object.keys(sr).forEach(r=>{Eu[sr[r]]=r});var Bg={type:"error",data:"parser error"};Wr.ERROR_PACKET=Bg});var xu=M(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});Fi.encodePacket=void 0;Fi.encodePacketToBinary=Kg;var jg=Ts(),Ug=({type:r,data:e},t,i)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?i(t?e:"b"+wu(e,!0).toString("base64")):i(jg.PACKET_TYPES[r]+(e||""));Fi.encodePacket=Ug;var wu=(r,e)=>Buffer.isBuffer(r)||r instanceof Uint8Array&&!e?r:r instanceof ArrayBuffer?Buffer.from(r):Buffer.from(r.buffer,r.byteOffset,r.byteLength),ia;function Kg(r,e){if(r.data instanceof ArrayBuffer||ArrayBuffer.isView(r.data))return e(wu(r.data,!1));(0,Fi.encodePacket)(r,!0,t=>{ia||(ia=new TextEncoder),e(ia.encode(t))})}});var Tu=M(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.decodePacket=void 0;var Cs=Ts(),qg=(r,e)=>{if(typeof r!="string")return{type:"message",data:Su(r,e)};let t=r.charAt(0);if(t==="b"){let i=Buffer.from(r.substring(1),"base64");return{type:"message",data:Su(i,e)}}return Cs.PACKET_TYPES_REVERSE[t]?r.length>1?{type:Cs.PACKET_TYPES_REVERSE[t],data:r.substring(1)}:{type:Cs.PACKET_TYPES_REVERSE[t]}:Cs.ERROR_PACKET};ks.decodePacket=qg;var Su=(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 Di=M(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.decodePayload=vt.decodePacket=vt.encodePayload=vt.encodePacket=vt.protocol=void 0;vt.createPacketEncoderStream=Vg;vt.createPacketDecoderStream=zg;var sa=xu();Object.defineProperty(vt,"encodePacket",{enumerable:!0,get:function(){return sa.encodePacket}});var oa=Tu();Object.defineProperty(vt,"decodePacket",{enumerable:!0,get:function(){return oa.decodePacket}});var Cu=Ts(),ku="",Wg=(r,e)=>{let t=r.length,i=new Array(t),n=0;r.forEach((s,a)=>{(0,sa.encodePacket)(s,!1,c=>{i[a]=c,++n===t&&e(i.join(ku))})})};vt.encodePayload=Wg;var Hg=(r,e)=>{let t=r.split(ku),i=[];for(let n=0;n<t.length;n++){let s=(0,oa.decodePacket)(t[n],e);if(i.push(s),s.type==="error")break}return i};vt.decodePayload=Hg;function Vg(){return new TransformStream({transform(r,e){(0,sa.encodePacketToBinary)(r,t=>{let i=t.length,n;if(i<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,i);else if(i<65536){n=new Uint8Array(3);let s=new DataView(n.buffer);s.setUint8(0,126),s.setUint16(1,i)}else{n=new Uint8Array(9);let s=new DataView(n.buffer);s.setUint8(0,127),s.setBigUint64(1,BigInt(i))}r.data&&typeof r.data!="string"&&(n[0]|=128),e.enqueue(n),e.enqueue(t)})}})}var na;function Os(r){return r.reduce((e,t)=>e+t.length,0)}function Ps(r,e){if(r[0].length===e)return r.shift();let t=new Uint8Array(e),i=0;for(let n=0;n<e;n++)t[n]=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 zg(r,e){na||(na=new TextDecoder);let t=[],i=0,n=-1,s=!1;return new TransformStream({transform(a,c){for(t.push(a);;){if(i===0){if(Os(t)<1)break;let u=Ps(t,1);s=(u[0]&128)===128,n=u[0]&127,n<126?i=3:n===126?i=1:i=2}else if(i===1){if(Os(t)<2)break;let u=Ps(t,2);n=new DataView(u.buffer,u.byteOffset,u.length).getUint16(0),i=3}else if(i===2){if(Os(t)<8)break;let u=Ps(t,8),d=new DataView(u.buffer,u.byteOffset,u.length),p=d.getUint32(0);if(p>Math.pow(2,21)-1){c.enqueue(Cu.ERROR_PACKET);break}n=p*Math.pow(2,32)+d.getUint32(4),i=3}else{if(Os(t)<n)break;let u=Ps(t,n);c.enqueue((0,oa.decodePacket)(s?u:na.decode(u),e)),i=0}if(n===0||n>r){c.enqueue(Cu.ERROR_PACKET);break}}}})}vt.protocol=4});var di=M(Ou=>{Ou.Emitter=yt;function yt(r){if(r)return $g(r)}function $g(r){for(var e in yt.prototype)r[e]=yt.prototype[e];return r}yt.prototype.on=yt.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this};yt.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this};yt.prototype.off=yt.prototype.removeListener=yt.prototype.removeAllListeners=yt.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,n=0;n<t.length;n++)if(i=t[n],i===e||i.fn===e){t.splice(n,1);break}return t.length===0&&delete this._callbacks["$"+r],this};yt.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,n=t.length;i<n;++i)t[i].apply(this,e)}return this};yt.prototype.emitReserved=yt.prototype.emit;yt.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};yt.prototype.hasListeners=function(r){return!!this.listeners(r).length}});var pi=M(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.CookieJar=Nt.defaultBinaryType=Nt.globalThisShim=Nt.nextTick=void 0;Nt.createCookieJar=Gg;Nt.parse=Pu;Nt.nextTick=process.nextTick;Nt.globalThisShim=global;Nt.defaultBinaryType="nodebuffer";function Gg(){return new Rs}function Pu(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 n=e[0].substring(t+1).trim();n.charCodeAt(0)===34&&(n=n.slice(1,-1));let s={name:i,value:n};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":s.expires=new Date(d);break;case"Max-Age":let p=new Date;p.setUTCSeconds(p.getUTCSeconds()+parseInt(d,10)),s.expires=p;break;default:}}return s}var Rs=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let i=Pu(t);i&&this._cookies.set(i.name,i)})}get cookies(){let e=Date.now();return this._cookies.forEach((t,i)=>{var n;((n=t.expires)===null||n===void 0?void 0:n.getTime())<e&&this._cookies.delete(i)}),this._cookies.entries()}addCookies(e){let t=[];for(let[i,n]of this.cookies)t.push(`${i}=${n.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}`)}};Nt.CookieJar=Rs});var gi=M(Bi=>{"use strict";Object.defineProperty(Bi,"__esModule",{value:!0});Bi.pick=Yg;Bi.installTimerFunctions=Zg;Bi.byteLength=em;Bi.randomString=rm;var Hr=pi();function Yg(r,...e){return e.reduce((t,i)=>(r.hasOwnProperty(i)&&(t[i]=r[i]),t),{})}var Xg=Hr.globalThisShim.setTimeout,Jg=Hr.globalThisShim.clearTimeout;function Zg(r,e){e.useNativeTimers?(r.setTimeoutFn=Xg.bind(Hr.globalThisShim),r.clearTimeoutFn=Jg.bind(Hr.globalThisShim)):(r.setTimeoutFn=Hr.globalThisShim.setTimeout.bind(Hr.globalThisShim),r.clearTimeoutFn=Hr.globalThisShim.clearTimeout.bind(Hr.globalThisShim))}var Qg=1.33;function em(r){return typeof r=="string"?tm(r):Math.ceil((r.byteLength||r.size)*Qg)}function tm(r){let e=0,t=0;for(let i=0,n=r.length;i<n;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 rm(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}});var aa=M(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});As.encode=im;As.decode=nm;function im(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function nm(r){let e={},t=r.split("&");for(let i=0,n=t.length;i<n;i++){let s=t[i].split("=");e[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return e}});var Au=M((LE,Ru)=>{var ji=1e3,Ui=ji*60,Ki=Ui*60,mi=Ki*24,sm=mi*7,om=mi*365.25;Ru.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return am(r);if(t==="number"&&isFinite(r))return e.long?fm(r):cm(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function am(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*om;case"weeks":case"week":case"w":return t*sm;case"days":case"day":case"d":return t*mi;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Ki;case"minutes":case"minute":case"mins":case"min":case"m":return t*Ui;case"seconds":case"second":case"secs":case"sec":case"s":return t*ji;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function cm(r){var e=Math.abs(r);return e>=mi?Math.round(r/mi)+"d":e>=Ki?Math.round(r/Ki)+"h":e>=Ui?Math.round(r/Ui)+"m":e>=ji?Math.round(r/ji)+"s":r+"ms"}function fm(r){var e=Math.abs(r);return e>=mi?Is(r,e,mi,"day"):e>=Ki?Is(r,e,Ki,"hour"):e>=Ui?Is(r,e,Ui,"minute"):e>=ji?Is(r,e,ji,"second"):r+" ms"}function Is(r,e,t,i){var n=e>=t*1.5;return Math.round(r/t)+" "+i+(n?"s":"")}});var ca=M((NE,Iu)=>{function um(r){t.debug=t,t.default=t,t.coerce=u,t.disable=a,t.enable=n,t.enabled=c,t.humanize=Au(),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 _=0;_<p.length;_++)m=(m<<5)-m+p.charCodeAt(_),m|=0;return t.colors[Math.abs(m)%t.colors.length]}t.selectColor=e;function t(p){let m,_=null,E,S;function T(...z){if(!T.enabled)return;let ge=T,ee=Number(new Date),R=ee-(m||ee);ge.diff=R,ge.prev=m,ge.curr=ee,m=ee,z[0]=t.coerce(z[0]),typeof z[0]!="string"&&z.unshift("%O");let B=0;z[0]=z[0].replace(/%([a-zA-Z%])/g,(K,U)=>{if(K==="%%")return"%";B++;let ye=t.formatters[U];if(typeof ye=="function"){let xe=z[B];K=ye.call(ge,xe),z.splice(B,1),B--}return K}),t.formatArgs.call(ge,z),(ge.log||t.log).apply(ge,z)}return T.namespace=p,T.useColors=t.useColors(),T.color=t.selectColor(p),T.extend=i,T.destroy=t.destroy,Object.defineProperty(T,"enabled",{enumerable:!0,configurable:!1,get:()=>_!==null?_:(E!==t.namespaces&&(E=t.namespaces,S=t.enabled(p)),S),set:z=>{_=z}}),typeof t.init=="function"&&t.init(T),T}function i(p,m){let _=t(this.namespace+(typeof m>"u"?":":m)+p);return _.log=this.log,_}function n(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 _ of m)_[0]==="-"?t.skips.push(_.slice(1)):t.names.push(_)}function s(p,m){let _=0,E=0,S=-1,T=0;for(;_<p.length;)if(E<m.length&&(m[E]===p[_]||m[E]==="*"))m[E]==="*"?(S=E,T=_,E++):(_++,E++);else if(S!==-1)E=S+1,T++,_=T;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(s(p,m))return!1;for(let m of t.names)if(s(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}Iu.exports=um});var Lu=M((Et,Ls)=>{Et.formatArgs=hm;Et.save=dm;Et.load=pm;Et.useColors=lm;Et.storage=gm();Et.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`."))}})();Et.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 lm(){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 hm(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ls.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,n=>{n!=="%%"&&(t++,n==="%c"&&(i=t))}),r.splice(i,0,e)}Et.log=console.debug||console.log||(()=>{});function dm(r){try{r?Et.storage.setItem("debug",r):Et.storage.removeItem("debug")}catch{}}function pm(){let r;try{r=Et.storage.getItem("debug")||Et.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function gm(){try{return localStorage}catch{}}Ls.exports=ca()(Et);var{formatters:mm}=Ls.exports;mm.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Mu=M((ME,Nu)=>{"use strict";Nu.exports=(r,e=process.argv)=>{let t=r.startsWith("-")?"":r.length===1?"-":"--",i=e.indexOf(t+r),n=e.indexOf("--");return i!==-1&&(n===-1||i<n)}});var Bu=M((FE,Du)=>{"use strict";var ym=require("os"),Fu=require("tty"),Mt=Mu(),{env:ot}=process,Vr;Mt("no-color")||Mt("no-colors")||Mt("color=false")||Mt("color=never")?Vr=0:(Mt("color")||Mt("colors")||Mt("color=true")||Mt("color=always"))&&(Vr=1);"FORCE_COLOR"in ot&&(ot.FORCE_COLOR==="true"?Vr=1:ot.FORCE_COLOR==="false"?Vr=0:Vr=ot.FORCE_COLOR.length===0?1:Math.min(parseInt(ot.FORCE_COLOR,10),3));function fa(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function ua(r,e){if(Vr===0)return 0;if(Mt("color=16m")||Mt("color=full")||Mt("color=truecolor"))return 3;if(Mt("color=256"))return 2;if(r&&!e&&Vr===void 0)return 0;let t=Vr||0;if(ot.TERM==="dumb")return t;if(process.platform==="win32"){let i=ym.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in ot)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(i=>i in ot)||ot.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in ot)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(ot.TEAMCITY_VERSION)?1:0;if(ot.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in ot){let i=parseInt((ot.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(ot.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(ot.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(ot.TERM)||"COLORTERM"in ot?1:t}function _m(r){let e=ua(r,r&&r.isTTY);return fa(e)}Du.exports={supportsColor:_m,stdout:fa(ua(!0,Fu.isatty(1))),stderr:fa(ua(!0,Fu.isatty(2)))}});var Uu=M((at,Ms)=>{var bm=require("tty"),Ns=require("util");at.init=Cm;at.log=xm;at.formatArgs=Em;at.save=Sm;at.load=Tm;at.useColors=vm;at.destroy=Ns.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");at.colors=[6,2,3,4,5,1];try{let r=Bu();r&&(r.stderr||r).level>=2&&(at.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{}at.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(n,s)=>s.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 vm(){return"colors"in at.inspectOpts?!!at.inspectOpts.colors:bm.isatty(process.stderr.fd)}function Em(r){let{namespace:e,useColors:t}=this;if(t){let i=this.color,n="\x1B[3"+(i<8?i:"8;5;"+i),s=` ${n};1m${e} \x1B[0m`;r[0]=s+r[0].split(`
19
19
  `).join(`
20
20
  `+s),r.push(n+"m+"+Ms.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=wm()+e+" "+r[0]}function wm(){return at.inspectOpts.hideDate?"":new Date().toISOString()+" "}function xm(...r){return process.stderr.write(Ns.formatWithOptions(at.inspectOpts,...r)+`
21
21
  `)}function Sm(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function Tm(){return process.env.DEBUG}function Cm(r){r.inspectOpts={};let e=Object.keys(at.inspectOpts);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=at.inspectOpts[e[t]]}Ms.exports=ca()(at);var{formatters:ju}=Ms.exports;ju.o=function(r){return this.inspectOpts.colors=this.useColors,Ns.inspect(r,this.inspectOpts).split(`
22
- `).map(e=>e.trim()).join(" ")};ju.O=function(r){return this.inspectOpts.colors=this.useColors,Ns.inspect(r,this.inspectOpts)}});var Ft=M((DE,la)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?la.exports=Lu():la.exports=Uu()});var Tn=M(zr=>{"use strict";var km=zr&&zr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(zr,"__esModule",{value:!0});zr.Transport=zr.TransportError=void 0;var Om=Di(),Pm=hi(),Am=pi(),Rm=aa(),Im=km(Ft()),Lm=(0,Im.default)("engine.io-client:transport"),Fs=class extends Error{constructor(e,t,i){super(e),this.description=t,this.context=i,this.type="TransportError"}};zr.TransportError=Fs;var ha=class extends Pm.Emitter{constructor(e){super(),this.writable=!1,(0,Am.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 Fs(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):Lm("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=(0,Om.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,Rm.encode)(e);return t.length?"?"+t:""}};zr.Transport=ha});var pa=M(Ki=>{"use strict";var Nm=Ki&&Ki.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ki,"__esModule",{value:!0});Ki.Polling=void 0;var Mm=Tn(),Fm=pi(),qu=Di(),Dm=Nm(Ft()),Ht=(0,Dm.default)("engine.io-client:polling"),da=class extends Mm.Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{Ht("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let i=0;this._polling&&(Ht("we are currently polling - waiting to pause"),i++,this.once("pollComplete",function(){Ht("pre-pause polling complete"),--i||t()})),this.writable||(Ht("we are currently writing - waiting to pause"),i++,this.once("drain",function(){Ht("pre-pause writing complete"),--i||t()}))}else t()}_poll(){Ht("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){Ht("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,qu.decodePayload)(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Ht('ignoring poll - transport state "%s"',this.readyState))}doClose(){let e=()=>{Ht("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Ht("transport open - closing"),e()):(Ht("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,(0,qu.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,Fm.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}};Ki.Polling=da});var Wu=M(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});Ds.hasCORS=void 0;var Ku=!1;try{Ku=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}Ds.hasCORS=Ku});var ya=M(or=>{"use strict";var Bm=or&&or.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(or,"__esModule",{value:!0});or.XHR=or.Request=or.BaseXHR=void 0;var jm=pa(),Um=hi(),Hu=pi(),zu=di(),qm=Wu(),Km=Bm(Ft()),ga=(0,Km.default)("engine.io-client:polling");function Wm(){}var Bs=class extends jm.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",(n,s)=>{this.onError("xhr post error",n,s)})}doPoll(){ga("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}};or.BaseXHR=Bs;var Tr=class r extends Um.Emitter{constructor(e,t,i){super(),this.createRequest=e,(0,Hu.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,Hu.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{ga("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 n in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(n)&&i.setRequestHeader(n,this._opts.extraHeaders[n])}}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 n;i.readyState===3&&((n=this._opts.cookieJar)===null||n===void 0||n.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))},ga("xhr data %s",this._data),i.send(this._data)}catch(n){this.setTimeoutFn(()=>{this._onError(n)},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=Wm,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()}};or.Request=Tr;Tr.requestsCount=0;Tr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Vu);else if(typeof addEventListener=="function"){let r="onpagehide"in zu.globalThisShim?"pagehide":"unload";addEventListener(r,Vu,!1)}}function Vu(){for(let r in Tr.requests)Tr.requests.hasOwnProperty(r)&&Tr.requests[r].abort()}var Hm=(function(){let r=$u({xdomain:!1});return r&&r.responseType!==null})(),ma=class extends Bs{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=Hm&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Tr($u,this.uri(),e)}};or.XHR=ma;function $u(r){let e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||qm.hasCORS))return new XMLHttpRequest}catch{}if(!e)try{return new zu.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}});var va=M(ar=>{"use strict";var Vm=ar&&ar.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),zm=ar&&ar.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),$m=ar&&ar.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&Vm(e,r,t);return zm(e,r),e};Object.defineProperty(ar,"__esModule",{value:!0});ar.XHR=void 0;var Gu=$m(bu()),Yu=ya(),Gm=Gu.default||Gu,_a=class extends Yu.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 Yu.Request(i=>new Gm(i),this.uri(),e)}};ar.XHR=_a});var Cr=M((WE,Zu)=>{"use strict";var Xu=["nodebuffer","arraybuffer","fragments"],Ju=typeof Blob<"u";Ju&&Xu.push("blob");Zu.exports={BINARY_TYPES:Xu,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ju,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Cn=M((HE,js)=>{"use strict";var{EMPTY_BUFFER:Ym}=Cr(),ba=Buffer[Symbol.species];function Xm(r,e){if(r.length===0)return Ym;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),i=0;for(let n=0;n<r.length;n++){let s=r[n];t.set(s,i),i+=s.length}return i<e?new ba(t.buffer,t.byteOffset,i):t}function Qu(r,e,t,i,n){for(let s=0;s<n;s++)t[i+s]=r[s]^e[s&3]}function el(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function Jm(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function Ea(r){if(Ea.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new ba(r):ArrayBuffer.isView(r)?e=new ba(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),Ea.readOnly=!1),e}js.exports={concat:Xm,mask:Qu,toArrayBuffer:Jm,toBuffer:Ea,unmask:el};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");js.exports.mask=function(e,t,i,n,s){s<48?Qu(e,t,i,n,s):r.mask(e,t,i,n,s)},js.exports.unmask=function(e,t){e.length<32?el(e,t):r.unmask(e,t)}}catch{}});var il=M((VE,rl)=>{"use strict";var tl=Symbol("kDone"),wa=Symbol("kRun"),xa=class{constructor(e){this[tl]=()=>{this.pending--,this[wa]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[wa]()}[wa](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[tl])}}};rl.exports=xa});var On=M((zE,al)=>{"use strict";var kn=require("zlib"),nl=Cn(),Zm=il(),{kStatusCode:sl}=Cr(),Qm=Buffer[Symbol.species],ey=Buffer.from([0,0,255,255]),qs=Symbol("permessage-deflate"),kr=Symbol("total-length"),Wi=Symbol("callback"),$r=Symbol("buffers"),Hi=Symbol("error"),Us,Sa=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,!Us){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Us=new Zm(n)}}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[Wi];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(n=>!(t.serverNoContextTakeover===!1&&n.server_no_context_takeover||n.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>n.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!n.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 n=t[i];if(n.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(n=n[0],i==="client_max_window_bits"){if(n!==!0){let s=+n;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${i}": ${n}`);n=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${n}`)}else if(i==="server_max_window_bits"){let s=+n;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${i}": ${n}`);n=s}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(n!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${n}`)}else throw new Error(`Unknown parameter "${i}"`);t[i]=n})}),e}decompress(e,t,i){Us.add(n=>{this._decompress(e,t,(s,a)=>{n(),i(s,a)})})}compress(e,t,i){Us.add(n=>{this._compress(e,t,(s,a)=>{n(),i(s,a)})})}_decompress(e,t,i){let n=this._isServer?"client":"server";if(!this._inflate){let s=`${n}_max_window_bits`,a=typeof this.params[s]!="number"?kn.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=kn.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[qs]=this,this._inflate[kr]=0,this._inflate[$r]=[],this._inflate.on("error",ry),this._inflate.on("data",ol)}this._inflate[Wi]=i,this._inflate.write(e),t&&this._inflate.write(ey),this._inflate.flush(()=>{let s=this._inflate[Hi];if(s){this._inflate.close(),this._inflate=null,i(s);return}let a=nl.concat(this._inflate[$r],this._inflate[kr]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[kr]=0,this._inflate[$r]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),i(null,a)})}_compress(e,t,i){let n=this._isServer?"server":"client";if(!this._deflate){let s=`${n}_max_window_bits`,a=typeof this.params[s]!="number"?kn.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=kn.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[kr]=0,this._deflate[$r]=[],this._deflate.on("data",ty)}this._deflate[Wi]=i,this._deflate.write(e),this._deflate.flush(kn.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=nl.concat(this._deflate[$r],this._deflate[kr]);t&&(s=new Qm(s.buffer,s.byteOffset,s.length-4)),this._deflate[Wi]=null,this._deflate[kr]=0,this._deflate[$r]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),i(null,s)})}};al.exports=Sa;function ty(r){this[$r].push(r),this[kr]+=r.length}function ol(r){if(this[kr]+=r.length,this[qs]._maxPayload<1||this[kr]<=this[qs]._maxPayload){this[$r].push(r);return}this[Hi]=new RangeError("Max payload size exceeded"),this[Hi].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Hi][sl]=1009,this.removeListener("data",ol),this.reset()}function ry(r){if(this[qs]._inflate=null,this[Hi]){this[Wi](this[Hi]);return}r[sl]=1007,this[Wi](r)}});var Vi=M(($E,Ks)=>{"use strict";var{isUtf8:cl}=require("buffer"),{hasBlob:iy}=Cr(),ny=[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 sy(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Ta(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 oy(r){return iy&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}Ks.exports={isBlob:oy,isValidStatusCode:sy,isValidUTF8:Ta,tokenChars:ny};if(cl)Ks.exports.isValidUTF8=function(r){return r.length<24?Ta(r):cl(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");Ks.exports.isValidUTF8=function(e){return e.length<32?Ta(e):r(e)}}catch{}});var Aa=M((GE,gl)=>{"use strict";var{Writable:ay}=require("stream"),fl=On(),{BINARY_TYPES:cy,EMPTY_BUFFER:ul,kStatusCode:fy,kWebSocket:uy}=Cr(),{concat:Ca,toArrayBuffer:ly,unmask:hy}=Cn(),{isValidStatusCode:dy,isValidUTF8:ll}=Vi(),Ws=Buffer[Symbol.species],Dt=0,hl=1,dl=2,pl=3,ka=4,Oa=5,Hs=6,Pa=class extends ay{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||cy[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[uy]=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=Dt}_write(e,t,i){if(this._opcode===8&&this._state==Dt)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 Ws(i.buffer,i.byteOffset+e,i.length-e),new Ws(i.buffer,i.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let i=this._buffers[0],n=t.length-e;e>=i.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(i.buffer,i.byteOffset,e),n),this._buffers[0]=new Ws(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 Dt:this.getInfo(e);break;case hl:this.getPayloadLength16(e);break;case dl:this.getPayloadLength64(e);break;case pl:this.getMask();break;case ka:this.getData(e);break;case Oa:case Hs: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 n=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(n);return}let i=(t[0]&64)===64;if(i&&!this._extensions[fl.extensionName]){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(i){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(!this._fragmented){let n=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let n=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(n);return}if(i){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let n=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(n);return}}else{let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let n=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(n);return}}else if(this._masked){let n=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(n);return}this._payloadLength===126?this._state=hl:this._payloadLength===127?this._state=dl: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 n=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(n);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=pl:this._state=ka}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ka}getData(e){let t=ul;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&&hy(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Oa,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[fl.extensionName].decompress(e,this._fin,(n,s)=>{if(n)return t(n);if(s.length){if(this._messageLength+=s.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(s)}this.dataMessage(t),this._state===Dt&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Dt;return}let t=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let n;this._binaryType==="nodebuffer"?n=Ca(i,t):this._binaryType==="arraybuffer"?n=ly(Ca(i,t)):this._binaryType==="blob"?n=new Blob(i):n=i,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=Dt):(this._state=Hs,setImmediate(()=>{this.emit("message",n,!0),this._state=Dt,this.startLoop(e)}))}else{let n=Ca(i,t);if(!this._skipUTF8Validation&&!ll(n)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===Oa||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=Dt):(this._state=Hs,setImmediate(()=>{this.emit("message",n,!1),this._state=Dt,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,ul),this.end();else{let i=e.readUInt16BE(0);if(!dy(i)){let s=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(s);return}let n=new Ws(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!ll(n)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(s);return}this._loop=!1,this.emit("conclude",i,n),this.end()}this._state=Dt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Dt):(this._state=Hs,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Dt,this.startLoop(t)}))}createError(e,t,i,n,s){this._loop=!1,this._errored=!0;let a=new e(i?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=s,a[fy]=n,a}};gl.exports=Pa});var La=M((XE,_l)=>{"use strict";var{Duplex:YE}=require("stream"),{randomFillSync:py}=require("crypto"),ml=On(),{EMPTY_BUFFER:gy,kWebSocket:my,NOOP:yy}=Cr(),{isBlob:zi,isValidStatusCode:_y}=Vi(),{mask:yl,toBuffer:mi}=Cn(),Bt=Symbol("kByteLength"),vy=Buffer.alloc(4),Vs=8*1024,yi,$i=Vs,Vt=0,by=1,Ey=2,Ra=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=Vt,this.onerror=yy,this[my]=void 0}static frame(e,t){let i,n=!1,s=2,a=!1;t.mask&&(i=t.maskBuffer||vy,t.generateMask?t.generateMask(i):($i===Vs&&(yi===void 0&&(yi=Buffer.alloc(Vs)),py(yi,0,Vs),$i=0),i[0]=yi[$i++],i[1]=yi[$i++],i[2]=yi[$i++],i[3]=yi[$i++]),a=(i[0]|i[1]|i[2]|i[3])===0,s=6);let c;typeof e=="string"?(!t.mask||a)&&t[Bt]!==void 0?c=t[Bt]:(e=Buffer.from(e),c=e.length):(c=e.length,n=t.mask&&t.readOnly&&!a);let u=c;c>=65536?(s+=8,u=127):c>125&&(s+=2,u=126);let d=Buffer.allocUnsafe(n?c+s:s);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[s-4]=i[0],d[s-3]=i[1],d[s-2]=i[2],d[s-1]=i[3],a?[d,e]:n?(yl(e,i,d,s,c),[d]):(yl(e,i,e,0,c),[d,e])):[d,e]}close(e,t,i,n){let s;if(e===void 0)s=gy;else{if(typeof e!="number"||!_y(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0);else{let c=Buffer.byteLength(t);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+c),s.writeUInt16BE(e,0),typeof t=="string"?s.write(t,2):s.set(t,2)}}let a={[Bt]:s.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Vt?this.enqueue([this.dispatch,s,!1,a,n]):this.sendFrame(r.frame(s,a),n)}ping(e,t,i){let n,s;if(typeof e=="string"?(n=Buffer.byteLength(e),s=!1):zi(e)?(n=e.size,s=!1):(e=mi(e),n=e.length,s=mi.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Bt]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};zi(e)?this._state!==Vt?this.enqueue([this.getBlobData,e,!1,a,i]):this.getBlobData(e,!1,a,i):this._state!==Vt?this.enqueue([this.dispatch,e,!1,a,i]):this.sendFrame(r.frame(e,a),i)}pong(e,t,i){let n,s;if(typeof e=="string"?(n=Buffer.byteLength(e),s=!1):zi(e)?(n=e.size,s=!1):(e=mi(e),n=e.length,s=mi.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Bt]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};zi(e)?this._state!==Vt?this.enqueue([this.getBlobData,e,!1,a,i]):this.getBlobData(e,!1,a,i):this._state!==Vt?this.enqueue([this.dispatch,e,!1,a,i]):this.sendFrame(r.frame(e,a),i)}send(e,t,i){let n=this._extensions[ml.extensionName],s=t.binary?2:1,a=t.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):zi(e)?(c=e.size,u=!1):(e=mi(e),c=e.length,u=mi.readOnly),this._firstFragment?(this._firstFragment=!1,a&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=c>=n._threshold),this._compress=a):(a=!1,s=0),t.fin&&(this._firstFragment=!0);let d={[Bt]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:u,rsv1:a};zi(e)?this._state!==Vt?this.enqueue([this.getBlobData,e,this._compress,d,i]):this.getBlobData(e,this._compress,d,i):this._state!==Vt?this.enqueue([this.dispatch,e,this._compress,d,i]):this.dispatch(e,this._compress,d,i)}getBlobData(e,t,i,n){this._bufferedBytes+=i[Bt],this._state=Ey,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(Ia,this,c,n);return}this._bufferedBytes-=i[Bt];let a=mi(s);t?this.dispatch(a,t,i,n):(this._state=Vt,this.sendFrame(r.frame(a,i),n),this.dequeue())}).catch(s=>{process.nextTick(wy,this,s,n)})}dispatch(e,t,i,n){if(!t){this.sendFrame(r.frame(e,i),n);return}let s=this._extensions[ml.extensionName];this._bufferedBytes+=i[Bt],this._state=by,s.compress(e,i.fin,(a,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");Ia(this,u,n);return}this._bufferedBytes-=i[Bt],this._state=Vt,i.readOnly=!1,this.sendFrame(r.frame(c,i),n),this.dequeue()})}dequeue(){for(;this._state===Vt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Bt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Bt],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)}};_l.exports=Ra;function Ia(r,e,t){typeof t=="function"&&t(e);for(let i=0;i<r._queue.length;i++){let n=r._queue[i],s=n[n.length-1];typeof s=="function"&&s(e)}}function wy(r,e,t){Ia(r,e,t),r.onerror(e)}});var kl=M((JE,Cl)=>{"use strict";var{kForOnEventAttribute:Pn,kListener:Na}=Cr(),vl=Symbol("kCode"),bl=Symbol("kData"),El=Symbol("kError"),wl=Symbol("kMessage"),xl=Symbol("kReason"),Gi=Symbol("kTarget"),Sl=Symbol("kType"),Tl=Symbol("kWasClean"),Or=class{constructor(e){this[Gi]=null,this[Sl]=e}get target(){return this[Gi]}get type(){return this[Sl]}};Object.defineProperty(Or.prototype,"target",{enumerable:!0});Object.defineProperty(Or.prototype,"type",{enumerable:!0});var _i=class extends Or{constructor(e,t={}){super(e),this[vl]=t.code===void 0?0:t.code,this[xl]=t.reason===void 0?"":t.reason,this[Tl]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[vl]}get reason(){return this[xl]}get wasClean(){return this[Tl]}};Object.defineProperty(_i.prototype,"code",{enumerable:!0});Object.defineProperty(_i.prototype,"reason",{enumerable:!0});Object.defineProperty(_i.prototype,"wasClean",{enumerable:!0});var Yi=class extends Or{constructor(e,t={}){super(e),this[El]=t.error===void 0?null:t.error,this[wl]=t.message===void 0?"":t.message}get error(){return this[El]}get message(){return this[wl]}};Object.defineProperty(Yi.prototype,"error",{enumerable:!0});Object.defineProperty(Yi.prototype,"message",{enumerable:!0});var An=class extends Or{constructor(e,t={}){super(e),this[bl]=t.data===void 0?null:t.data}get data(){return this[bl]}};Object.defineProperty(An.prototype,"data",{enumerable:!0});var xy={addEventListener(r,e,t={}){for(let n of this.listeners(r))if(!t[Pn]&&n[Na]===e&&!n[Pn])return;let i;if(r==="message")i=function(s,a){let c=new An("message",{data:a?s:s.toString()});c[Gi]=this,zs(e,this,c)};else if(r==="close")i=function(s,a){let c=new _i("close",{code:s,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[Gi]=this,zs(e,this,c)};else if(r==="error")i=function(s){let a=new Yi("error",{error:s,message:s.message});a[Gi]=this,zs(e,this,a)};else if(r==="open")i=function(){let s=new Or("open");s[Gi]=this,zs(e,this,s)};else return;i[Pn]=!!t[Pn],i[Na]=e,t.once?this.once(r,i):this.on(r,i)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[Na]===e&&!t[Pn]){this.removeListener(r,t);break}}};Cl.exports={CloseEvent:_i,ErrorEvent:Yi,Event:Or,EventTarget:xy,MessageEvent:An};function zs(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var Ma=M((ZE,Ol)=>{"use strict";var{tokenChars:Rn}=Vi();function cr(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function Sy(r){let e=Object.create(null),t=Object.create(null),i=!1,n=!1,s=!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&&Rn[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?(cr(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&&Rn[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),cr(t,r.slice(u,p),!0),d===44&&(cr(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(n){if(Rn[d]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);u===-1?u=m:i||(i=!0),n=!1}else if(s)if(Rn[d]===1)u===-1&&(u=m);else if(d===34&&u!==-1)s=!1,p=m;else if(d===92)n=!0;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(d===34&&r.charCodeAt(m-1)===61)s=!0;else if(p===-1&&Rn[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),cr(t,c,E),d===44&&(cr(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||s||d===32||d===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=m);let _=r.slice(u,p);return a===void 0?cr(e,_,t):(c===void 0?cr(t,_,!0):i?cr(t,c,_.replace(/\\/g,"")):cr(t,c,_),cr(e,a,t)),e}function Ty(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(n=>{let s=i[n];return Array.isArray(s)||(s=[s]),s.map(a=>a===!0?n:`${n}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Ol.exports={format:Ty,parse:Sy}});var Xs=M((tw,Ul)=>{"use strict";var Cy=require("events"),ky=require("https"),Oy=require("http"),Rl=require("net"),Py=require("tls"),{randomBytes:Ay,createHash:Ry}=require("crypto"),{Duplex:QE,Readable:ew}=require("stream"),{URL:Fa}=require("url"),Gr=On(),Iy=Aa(),Ly=La(),{isBlob:Ny}=Vi(),{BINARY_TYPES:Pl,EMPTY_BUFFER:$s,GUID:My,kForOnEventAttribute:Da,kListener:Fy,kStatusCode:Dy,kWebSocket:ct,NOOP:Il}=Cr(),{EventTarget:{addEventListener:By,removeEventListener:jy}}=kl(),{format:Uy,parse:qy}=Ma(),{toBuffer:Ky}=Cn(),Wy=30*1e3,Ll=Symbol("kAborted"),Ba=[8,13],Pr=["CONNECTING","OPEN","CLOSING","CLOSED"],Hy=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,qe=class r extends Cy{constructor(e,t,i){super(),this._binaryType=Pl[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=$s,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]),Nl(this,e,t,i)):(this._autoPong=i.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Pl.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 n=new Iy({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),s=new Ly(e,this._extensions,i.generateMask);this._receiver=n,this._sender=s,this._socket=e,n[ct]=this,s[ct]=this,e[ct]=this,n.on("conclude",$y),n.on("drain",Gy),n.on("error",Yy),n.on("message",Xy),n.on("ping",Jy),n.on("pong",Zy),s.onerror=Qy,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Dl),e.on("data",Ys),e.on("end",Bl),e.on("error",jl),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[Gr.extensionName]&&this._extensions[Gr.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){Pt(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())}),Fl(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){ja(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||$s,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){ja(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||$s,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){ja(this,e,i);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Gr.extensionName]||(n.compress=!1),this._sender.send(e||$s,n,i)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Pt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(qe,"CONNECTING",{enumerable:!0,value:Pr.indexOf("CONNECTING")});Object.defineProperty(qe.prototype,"CONNECTING",{enumerable:!0,value:Pr.indexOf("CONNECTING")});Object.defineProperty(qe,"OPEN",{enumerable:!0,value:Pr.indexOf("OPEN")});Object.defineProperty(qe.prototype,"OPEN",{enumerable:!0,value:Pr.indexOf("OPEN")});Object.defineProperty(qe,"CLOSING",{enumerable:!0,value:Pr.indexOf("CLOSING")});Object.defineProperty(qe.prototype,"CLOSING",{enumerable:!0,value:Pr.indexOf("CLOSING")});Object.defineProperty(qe,"CLOSED",{enumerable:!0,value:Pr.indexOf("CLOSED")});Object.defineProperty(qe.prototype,"CLOSED",{enumerable:!0,value:Pr.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(qe.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(qe.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[Da])return e[Fy];return null},set(e){for(let t of this.listeners(r))if(t[Da]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[Da]:!0})}})});qe.prototype.addEventListener=By;qe.prototype.removeEventListener=jy;Ul.exports=qe;function Nl(r,e,t,i){let n={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:Ba[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=n.autoPong,!Ba.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${Ba.join(", ")})`);let s;if(e instanceof Fa)s=e;else try{s=new Fa(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),r._url=s.href;let a=s.protocol==="wss:",c=s.protocol==="ws+unix:",u;if(s.protocol!=="ws:"&&!a&&!c?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!s.pathname?u="The URL's pathname is empty":s.hash&&(u="The URL contains a fragment identifier"),u){let T=new SyntaxError(u);if(r._redirects===0)throw T;Gs(r,T);return}let d=a?443:80,p=Ay(16).toString("base64"),m=a?ky.request:Oy.request,_=new Set,E;if(n.createConnection=n.createConnection||(a?zy:Vy),n.defaultPort=n.defaultPort||d,n.port=s.port||d,n.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},n.path=s.pathname+s.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(E=new Gr(n.perMessageDeflate!==!0?n.perMessageDeflate:{},!1,n.maxPayload),n.headers["Sec-WebSocket-Extensions"]=Uy({[Gr.extensionName]:E.offer()})),t.length){for(let T of t){if(typeof T!="string"||!Hy.test(T)||_.has(T))throw new SyntaxError("An invalid or duplicated subprotocol was specified");_.add(T)}n.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(s.username||s.password)&&(n.auth=`${s.username}:${s.password}`),c){let T=n.path.split(":");n.socketPath=T[0],n.path=T[1]}let S;if(n.followRedirects){if(r._redirects===0){r._originalIpc=c,r._originalSecure=a,r._originalHostOrSocketPath=c?n.socketPath:s.host;let T=i&&i.headers;if(i={...i,headers:{}},T)for(let[z,ge]of Object.entries(T))i.headers[z.toLowerCase()]=ge}else if(r.listenerCount("redirect")===0){let T=c?r._originalIpc?n.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:s.host===r._originalHostOrSocketPath;(!T||r._originalSecure&&!a)&&(delete n.headers.authorization,delete n.headers.cookie,T||delete n.headers.host,n.auth=void 0)}n.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),S=r._req=m(n),r._redirects&&r.emit("redirect",r.url,S)}else S=r._req=m(n);n.timeout&&S.on("timeout",()=>{Pt(r,S,"Opening handshake has timed out")}),S.on("error",T=>{S===null||S[Ll]||(S=r._req=null,Gs(r,T))}),S.on("response",T=>{let z=T.headers.location,ge=T.statusCode;if(z&&n.followRedirects&&ge>=300&&ge<400){if(++r._redirects>n.maxRedirects){Pt(r,S,"Maximum redirects exceeded");return}S.abort();let ee;try{ee=new Fa(z,e)}catch{let B=new SyntaxError(`Invalid URL: ${z}`);Gs(r,B);return}Nl(r,ee,t,i)}else r.emit("unexpected-response",S,T)||Pt(r,S,`Unexpected server response: ${T.statusCode}`)}),S.on("upgrade",(T,z,ge)=>{if(r.emit("upgrade",T),r.readyState!==qe.CONNECTING)return;S=r._req=null;let ee=T.headers.upgrade;if(ee===void 0||ee.toLowerCase()!=="websocket"){Pt(r,z,"Invalid Upgrade header");return}let A=Ry("sha1").update(p+My).digest("base64");if(T.headers["sec-websocket-accept"]!==A){Pt(r,z,"Invalid Sec-WebSocket-Accept header");return}let B=T.headers["sec-websocket-protocol"],re;if(B!==void 0?_.size?_.has(B)||(re="Server sent an invalid subprotocol"):re="Server sent a subprotocol but none was requested":_.size&&(re="Server sent no subprotocol"),re){Pt(r,z,re);return}B&&(r._protocol=B);let q=T.headers["sec-websocket-extensions"];if(q!==void 0){if(!E){Pt(r,z,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let U;try{U=qy(q)}catch{Pt(r,z,"Invalid Sec-WebSocket-Extensions header");return}let ye=Object.keys(U);if(ye.length!==1||ye[0]!==Gr.extensionName){Pt(r,z,"Server indicated an extension that was not requested");return}try{E.accept(U[Gr.extensionName])}catch{Pt(r,z,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Gr.extensionName]=E}r.setSocket(z,ge,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(S,r):S.end()}function Gs(r,e){r._readyState=qe.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function Vy(r){return r.path=r.socketPath,Rl.connect(r)}function zy(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=Rl.isIP(r.host)?"":r.host),Py.connect(r)}function Pt(r,e,t){r._readyState=qe.CLOSING;let i=new Error(t);Error.captureStackTrace(i,Pt),e.setHeader?(e[Ll]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Gs,r,i)):(e.destroy(i),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function ja(r,e,t){if(e){let i=Ny(e)?e.size:Ky(e).length;r._socket?r._sender._bufferedBytes+=i:r._bufferedAmount+=i}if(t){let i=new Error(`WebSocket is not open: readyState ${r.readyState} (${Pr[r.readyState]})`);process.nextTick(t,i)}}function $y(r,e){let t=this[ct];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[ct]!==void 0&&(t._socket.removeListener("data",Ys),process.nextTick(Ml,t._socket),r===1005?t.close():t.close(r,e))}function Gy(){let r=this[ct];r.isPaused||r._socket.resume()}function Yy(r){let e=this[ct];e._socket[ct]!==void 0&&(e._socket.removeListener("data",Ys),process.nextTick(Ml,e._socket),e.close(r[Dy])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Al(){this[ct].emitClose()}function Xy(r,e){this[ct].emit("message",r,e)}function Jy(r){let e=this[ct];e._autoPong&&e.pong(r,!this._isServer,Il),e.emit("ping",r)}function Zy(r){this[ct].emit("pong",r)}function Ml(r){r.resume()}function Qy(r){let e=this[ct];e.readyState!==qe.CLOSED&&(e.readyState===qe.OPEN&&(e._readyState=qe.CLOSING,Fl(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Fl(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),Wy)}function Dl(){let r=this[ct];this.removeListener("close",Dl),this.removeListener("data",Ys),this.removeListener("end",Bl),r._readyState=qe.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[ct]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Al),r._receiver.on("finish",Al))}function Ys(r){this[ct]._receiver.write(r)||this.pause()}function Bl(){let r=this[ct];r._readyState=qe.CLOSING,r._receiver.end(),this.end()}function jl(){let r=this[ct];this.removeListener("error",jl),this.on("error",Il),r&&(r._readyState=qe.CLOSING,this.destroy())}});var Hl=M((iw,Wl)=>{"use strict";var rw=Xs(),{Duplex:e_}=require("stream");function ql(r){r.emit("close")}function t_(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Kl(r){this.removeListener("error",Kl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function r_(r,e){let t=!0,i=new e_({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(s,a){let c=!a&&i._readableState.objectMode?s.toString():s;i.push(c)||r.pause()}),r.once("error",function(s){i.destroyed||(t=!1,i.destroy(s))}),r.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(n,s){if(r.readyState===r.CLOSED){s(n),process.nextTick(ql,i);return}let a=!1;r.once("error",function(u){a=!0,s(u)}),r.once("close",function(){a||s(n),process.nextTick(ql,i)}),t&&r.terminate()},i._final=function(n){if(r.readyState===r.CONNECTING){r.once("open",function(){i._final(n)});return}r._socket!==null&&(r._socket._writableState.finished?(n(),i._readableState.endEmitted&&i.destroy()):(r._socket.once("finish",function(){n()}),r.close()))},i._read=function(){r.isPaused&&r.resume()},i._write=function(n,s,a){if(r.readyState===r.CONNECTING){r.once("open",function(){i._write(n,s,a)});return}r.send(n,a)},i.on("end",t_),i.on("error",Kl),i}Wl.exports=r_});var zl=M((nw,Vl)=>{"use strict";var{tokenChars:i_}=Vi();function n_(r){let e=new Set,t=-1,i=-1,n=0;for(n;n<r.length;n++){let a=r.charCodeAt(n);if(i===-1&&i_[a]===1)t===-1&&(t=n);else if(n!==0&&(a===32||a===9))i===-1&&t!==-1&&(i=n);else if(a===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${n}`);i===-1&&(i=n);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 ${n}`)}if(t===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let s=r.slice(t,n);if(e.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return e.add(s),e}Vl.exports={parse:n_}});var Ql=M((ow,Zl)=>{"use strict";var s_=require("events"),Js=require("http"),{Duplex:sw}=require("stream"),{createHash:o_}=require("crypto"),$l=Ma(),vi=On(),a_=zl(),c_=Xs(),{GUID:f_,kWebSocket:u_}=Cr(),l_=/^[+/0-9A-Za-z]{22}==$/,Gl=0,Yl=1,Jl=2,Ua=class extends s_{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:c_,...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=Js.createServer((i,n)=>{let s=Js.STATUS_CODES[426];n.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),n.end(s)}),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=h_(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(n,s,a)=>{this.handleUpgrade(n,s,a,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Gl}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===Jl){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(In,this);return}if(e&&this.once("close",e),this._state!==Yl)if(this._state=Yl,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(In,this):process.nextTick(In,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{In(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,n){t.on("error",Xl);let s=e.headers["sec-websocket-key"],a=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){bi(this,e,t,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){bi(this,e,t,400,"Invalid Upgrade header");return}if(s===void 0||!l_.test(s)){bi(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){bi(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Ln(t,400);return}let u=e.headers["sec-websocket-protocol"],d=new Set;if(u!==void 0)try{d=a_.parse(u)}catch{bi(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 _=new vi(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let E=$l.parse(p);E[vi.extensionName]&&(_.accept(E[vi.extensionName]),m[vi.extensionName]=_)}catch{bi(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let _={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(_,(E,S,T,z)=>{if(!E)return Ln(t,S||401,T,z);this.completeUpgrade(m,s,d,e,t,i,n)});return}if(!this.options.verifyClient(_))return Ln(t,401)}this.completeUpgrade(m,s,d,e,t,i,n)}completeUpgrade(e,t,i,n,s,a,c){if(!s.readable||!s.writable)return s.destroy();if(s[u_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Gl)return Ln(s,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${o_("sha1").update(t+f_).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(i.size){let m=this.options.handleProtocols?this.options.handleProtocols(i,n):i.values().next().value;m&&(d.push(`Sec-WebSocket-Protocol: ${m}`),p._protocol=m)}if(e[vi.extensionName]){let m=e[vi.extensionName].params,_=$l.format({[vi.extensionName]:[m]});d.push(`Sec-WebSocket-Extensions: ${_}`),p._extensions=e}this.emit("headers",d,n),s.write(d.concat(`\r
22
+ `).map(e=>e.trim()).join(" ")};ju.O=function(r){return this.inspectOpts.colors=this.useColors,Ns.inspect(r,this.inspectOpts)}});var Ft=M((DE,la)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?la.exports=Lu():la.exports=Uu()});var Tn=M(zr=>{"use strict";var km=zr&&zr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(zr,"__esModule",{value:!0});zr.Transport=zr.TransportError=void 0;var Om=Di(),Pm=di(),Rm=gi(),Am=aa(),Im=km(Ft()),Lm=(0,Im.default)("engine.io-client:transport"),Fs=class extends Error{constructor(e,t,i){super(e),this.description=t,this.context=i,this.type="TransportError"}};zr.TransportError=Fs;var ha=class extends Pm.Emitter{constructor(e){super(),this.writable=!1,(0,Rm.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 Fs(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):Lm("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=(0,Om.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,Am.encode)(e);return t.length?"?"+t:""}};zr.Transport=ha});var pa=M(qi=>{"use strict";var Nm=qi&&qi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(qi,"__esModule",{value:!0});qi.Polling=void 0;var Mm=Tn(),Fm=gi(),Ku=Di(),Dm=Nm(Ft()),Ht=(0,Dm.default)("engine.io-client:polling"),da=class extends Mm.Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{Ht("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let i=0;this._polling&&(Ht("we are currently polling - waiting to pause"),i++,this.once("pollComplete",function(){Ht("pre-pause polling complete"),--i||t()})),this.writable||(Ht("we are currently writing - waiting to pause"),i++,this.once("drain",function(){Ht("pre-pause writing complete"),--i||t()}))}else t()}_poll(){Ht("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){Ht("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,Ku.decodePayload)(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Ht('ignoring poll - transport state "%s"',this.readyState))}doClose(){let e=()=>{Ht("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Ht("transport open - closing"),e()):(Ht("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,(0,Ku.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,Fm.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}};qi.Polling=da});var Wu=M(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});Ds.hasCORS=void 0;var qu=!1;try{qu=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}Ds.hasCORS=qu});var ya=M(or=>{"use strict";var Bm=or&&or.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(or,"__esModule",{value:!0});or.XHR=or.Request=or.BaseXHR=void 0;var jm=pa(),Um=di(),Hu=gi(),zu=pi(),Km=Wu(),qm=Bm(Ft()),ga=(0,qm.default)("engine.io-client:polling");function Wm(){}var Bs=class extends jm.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",(n,s)=>{this.onError("xhr post error",n,s)})}doPoll(){ga("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}};or.BaseXHR=Bs;var Tr=class r extends Um.Emitter{constructor(e,t,i){super(),this.createRequest=e,(0,Hu.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,Hu.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{ga("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 n in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(n)&&i.setRequestHeader(n,this._opts.extraHeaders[n])}}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 n;i.readyState===3&&((n=this._opts.cookieJar)===null||n===void 0||n.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))},ga("xhr data %s",this._data),i.send(this._data)}catch(n){this.setTimeoutFn(()=>{this._onError(n)},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=Wm,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()}};or.Request=Tr;Tr.requestsCount=0;Tr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Vu);else if(typeof addEventListener=="function"){let r="onpagehide"in zu.globalThisShim?"pagehide":"unload";addEventListener(r,Vu,!1)}}function Vu(){for(let r in Tr.requests)Tr.requests.hasOwnProperty(r)&&Tr.requests[r].abort()}var Hm=(function(){let r=$u({xdomain:!1});return r&&r.responseType!==null})(),ma=class extends Bs{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=Hm&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Tr($u,this.uri(),e)}};or.XHR=ma;function $u(r){let e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Km.hasCORS))return new XMLHttpRequest}catch{}if(!e)try{return new zu.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}});var ba=M(ar=>{"use strict";var Vm=ar&&ar.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),zm=ar&&ar.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),$m=ar&&ar.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&Vm(e,r,t);return zm(e,r),e};Object.defineProperty(ar,"__esModule",{value:!0});ar.XHR=void 0;var Gu=$m(vu()),Yu=ya(),Gm=Gu.default||Gu,_a=class extends Yu.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 Yu.Request(i=>new Gm(i),this.uri(),e)}};ar.XHR=_a});var Cr=M((WE,Zu)=>{"use strict";var Xu=["nodebuffer","arraybuffer","fragments"],Ju=typeof Blob<"u";Ju&&Xu.push("blob");Zu.exports={BINARY_TYPES:Xu,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ju,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Cn=M((HE,js)=>{"use strict";var{EMPTY_BUFFER:Ym}=Cr(),va=Buffer[Symbol.species];function Xm(r,e){if(r.length===0)return Ym;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),i=0;for(let n=0;n<r.length;n++){let s=r[n];t.set(s,i),i+=s.length}return i<e?new va(t.buffer,t.byteOffset,i):t}function Qu(r,e,t,i,n){for(let s=0;s<n;s++)t[i+s]=r[s]^e[s&3]}function el(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function Jm(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function Ea(r){if(Ea.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new va(r):ArrayBuffer.isView(r)?e=new va(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),Ea.readOnly=!1),e}js.exports={concat:Xm,mask:Qu,toArrayBuffer:Jm,toBuffer:Ea,unmask:el};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");js.exports.mask=function(e,t,i,n,s){s<48?Qu(e,t,i,n,s):r.mask(e,t,i,n,s)},js.exports.unmask=function(e,t){e.length<32?el(e,t):r.unmask(e,t)}}catch{}});var il=M((VE,rl)=>{"use strict";var tl=Symbol("kDone"),wa=Symbol("kRun"),xa=class{constructor(e){this[tl]=()=>{this.pending--,this[wa]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[wa]()}[wa](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[tl])}}};rl.exports=xa});var On=M((zE,al)=>{"use strict";var kn=require("zlib"),nl=Cn(),Zm=il(),{kStatusCode:sl}=Cr(),Qm=Buffer[Symbol.species],ey=Buffer.from([0,0,255,255]),Ks=Symbol("permessage-deflate"),kr=Symbol("total-length"),Wi=Symbol("callback"),$r=Symbol("buffers"),Hi=Symbol("error"),Us,Sa=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,!Us){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Us=new Zm(n)}}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[Wi];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(n=>!(t.serverNoContextTakeover===!1&&n.server_no_context_takeover||n.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>n.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!n.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 n=t[i];if(n.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(n=n[0],i==="client_max_window_bits"){if(n!==!0){let s=+n;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${i}": ${n}`);n=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${n}`)}else if(i==="server_max_window_bits"){let s=+n;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${i}": ${n}`);n=s}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(n!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${n}`)}else throw new Error(`Unknown parameter "${i}"`);t[i]=n})}),e}decompress(e,t,i){Us.add(n=>{this._decompress(e,t,(s,a)=>{n(),i(s,a)})})}compress(e,t,i){Us.add(n=>{this._compress(e,t,(s,a)=>{n(),i(s,a)})})}_decompress(e,t,i){let n=this._isServer?"client":"server";if(!this._inflate){let s=`${n}_max_window_bits`,a=typeof this.params[s]!="number"?kn.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=kn.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[Ks]=this,this._inflate[kr]=0,this._inflate[$r]=[],this._inflate.on("error",ry),this._inflate.on("data",ol)}this._inflate[Wi]=i,this._inflate.write(e),t&&this._inflate.write(ey),this._inflate.flush(()=>{let s=this._inflate[Hi];if(s){this._inflate.close(),this._inflate=null,i(s);return}let a=nl.concat(this._inflate[$r],this._inflate[kr]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[kr]=0,this._inflate[$r]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),i(null,a)})}_compress(e,t,i){let n=this._isServer?"server":"client";if(!this._deflate){let s=`${n}_max_window_bits`,a=typeof this.params[s]!="number"?kn.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=kn.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[kr]=0,this._deflate[$r]=[],this._deflate.on("data",ty)}this._deflate[Wi]=i,this._deflate.write(e),this._deflate.flush(kn.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=nl.concat(this._deflate[$r],this._deflate[kr]);t&&(s=new Qm(s.buffer,s.byteOffset,s.length-4)),this._deflate[Wi]=null,this._deflate[kr]=0,this._deflate[$r]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),i(null,s)})}};al.exports=Sa;function ty(r){this[$r].push(r),this[kr]+=r.length}function ol(r){if(this[kr]+=r.length,this[Ks]._maxPayload<1||this[kr]<=this[Ks]._maxPayload){this[$r].push(r);return}this[Hi]=new RangeError("Max payload size exceeded"),this[Hi].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Hi][sl]=1009,this.removeListener("data",ol),this.reset()}function ry(r){if(this[Ks]._inflate=null,this[Hi]){this[Wi](this[Hi]);return}r[sl]=1007,this[Wi](r)}});var Vi=M(($E,qs)=>{"use strict";var{isUtf8:cl}=require("buffer"),{hasBlob:iy}=Cr(),ny=[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 sy(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Ta(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 oy(r){return iy&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}qs.exports={isBlob:oy,isValidStatusCode:sy,isValidUTF8:Ta,tokenChars:ny};if(cl)qs.exports.isValidUTF8=function(r){return r.length<24?Ta(r):cl(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");qs.exports.isValidUTF8=function(e){return e.length<32?Ta(e):r(e)}}catch{}});var Ra=M((GE,gl)=>{"use strict";var{Writable:ay}=require("stream"),fl=On(),{BINARY_TYPES:cy,EMPTY_BUFFER:ul,kStatusCode:fy,kWebSocket:uy}=Cr(),{concat:Ca,toArrayBuffer:ly,unmask:hy}=Cn(),{isValidStatusCode:dy,isValidUTF8:ll}=Vi(),Ws=Buffer[Symbol.species],Dt=0,hl=1,dl=2,pl=3,ka=4,Oa=5,Hs=6,Pa=class extends ay{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||cy[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[uy]=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=Dt}_write(e,t,i){if(this._opcode===8&&this._state==Dt)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 Ws(i.buffer,i.byteOffset+e,i.length-e),new Ws(i.buffer,i.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let i=this._buffers[0],n=t.length-e;e>=i.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(i.buffer,i.byteOffset,e),n),this._buffers[0]=new Ws(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 Dt:this.getInfo(e);break;case hl:this.getPayloadLength16(e);break;case dl:this.getPayloadLength64(e);break;case pl:this.getMask();break;case ka:this.getData(e);break;case Oa:case Hs: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 n=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(n);return}let i=(t[0]&64)===64;if(i&&!this._extensions[fl.extensionName]){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(i){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(!this._fragmented){let n=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let n=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(n);return}if(i){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let n=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(n);return}}else{let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let n=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(n);return}}else if(this._masked){let n=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(n);return}this._payloadLength===126?this._state=hl:this._payloadLength===127?this._state=dl: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 n=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(n);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=pl:this._state=ka}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ka}getData(e){let t=ul;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&&hy(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Oa,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[fl.extensionName].decompress(e,this._fin,(n,s)=>{if(n)return t(n);if(s.length){if(this._messageLength+=s.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(s)}this.dataMessage(t),this._state===Dt&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Dt;return}let t=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let n;this._binaryType==="nodebuffer"?n=Ca(i,t):this._binaryType==="arraybuffer"?n=ly(Ca(i,t)):this._binaryType==="blob"?n=new Blob(i):n=i,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=Dt):(this._state=Hs,setImmediate(()=>{this.emit("message",n,!0),this._state=Dt,this.startLoop(e)}))}else{let n=Ca(i,t);if(!this._skipUTF8Validation&&!ll(n)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===Oa||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=Dt):(this._state=Hs,setImmediate(()=>{this.emit("message",n,!1),this._state=Dt,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,ul),this.end();else{let i=e.readUInt16BE(0);if(!dy(i)){let s=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(s);return}let n=new Ws(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!ll(n)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(s);return}this._loop=!1,this.emit("conclude",i,n),this.end()}this._state=Dt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Dt):(this._state=Hs,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Dt,this.startLoop(t)}))}createError(e,t,i,n,s){this._loop=!1,this._errored=!0;let a=new e(i?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=s,a[fy]=n,a}};gl.exports=Pa});var La=M((XE,_l)=>{"use strict";var{Duplex:YE}=require("stream"),{randomFillSync:py}=require("crypto"),ml=On(),{EMPTY_BUFFER:gy,kWebSocket:my,NOOP:yy}=Cr(),{isBlob:zi,isValidStatusCode:_y}=Vi(),{mask:yl,toBuffer:yi}=Cn(),Bt=Symbol("kByteLength"),by=Buffer.alloc(4),Vs=8*1024,_i,$i=Vs,Vt=0,vy=1,Ey=2,Aa=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=Vt,this.onerror=yy,this[my]=void 0}static frame(e,t){let i,n=!1,s=2,a=!1;t.mask&&(i=t.maskBuffer||by,t.generateMask?t.generateMask(i):($i===Vs&&(_i===void 0&&(_i=Buffer.alloc(Vs)),py(_i,0,Vs),$i=0),i[0]=_i[$i++],i[1]=_i[$i++],i[2]=_i[$i++],i[3]=_i[$i++]),a=(i[0]|i[1]|i[2]|i[3])===0,s=6);let c;typeof e=="string"?(!t.mask||a)&&t[Bt]!==void 0?c=t[Bt]:(e=Buffer.from(e),c=e.length):(c=e.length,n=t.mask&&t.readOnly&&!a);let u=c;c>=65536?(s+=8,u=127):c>125&&(s+=2,u=126);let d=Buffer.allocUnsafe(n?c+s:s);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[s-4]=i[0],d[s-3]=i[1],d[s-2]=i[2],d[s-1]=i[3],a?[d,e]:n?(yl(e,i,d,s,c),[d]):(yl(e,i,e,0,c),[d,e])):[d,e]}close(e,t,i,n){let s;if(e===void 0)s=gy;else{if(typeof e!="number"||!_y(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0);else{let c=Buffer.byteLength(t);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+c),s.writeUInt16BE(e,0),typeof t=="string"?s.write(t,2):s.set(t,2)}}let a={[Bt]:s.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Vt?this.enqueue([this.dispatch,s,!1,a,n]):this.sendFrame(r.frame(s,a),n)}ping(e,t,i){let n,s;if(typeof e=="string"?(n=Buffer.byteLength(e),s=!1):zi(e)?(n=e.size,s=!1):(e=yi(e),n=e.length,s=yi.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Bt]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};zi(e)?this._state!==Vt?this.enqueue([this.getBlobData,e,!1,a,i]):this.getBlobData(e,!1,a,i):this._state!==Vt?this.enqueue([this.dispatch,e,!1,a,i]):this.sendFrame(r.frame(e,a),i)}pong(e,t,i){let n,s;if(typeof e=="string"?(n=Buffer.byteLength(e),s=!1):zi(e)?(n=e.size,s=!1):(e=yi(e),n=e.length,s=yi.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Bt]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};zi(e)?this._state!==Vt?this.enqueue([this.getBlobData,e,!1,a,i]):this.getBlobData(e,!1,a,i):this._state!==Vt?this.enqueue([this.dispatch,e,!1,a,i]):this.sendFrame(r.frame(e,a),i)}send(e,t,i){let n=this._extensions[ml.extensionName],s=t.binary?2:1,a=t.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):zi(e)?(c=e.size,u=!1):(e=yi(e),c=e.length,u=yi.readOnly),this._firstFragment?(this._firstFragment=!1,a&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=c>=n._threshold),this._compress=a):(a=!1,s=0),t.fin&&(this._firstFragment=!0);let d={[Bt]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:u,rsv1:a};zi(e)?this._state!==Vt?this.enqueue([this.getBlobData,e,this._compress,d,i]):this.getBlobData(e,this._compress,d,i):this._state!==Vt?this.enqueue([this.dispatch,e,this._compress,d,i]):this.dispatch(e,this._compress,d,i)}getBlobData(e,t,i,n){this._bufferedBytes+=i[Bt],this._state=Ey,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(Ia,this,c,n);return}this._bufferedBytes-=i[Bt];let a=yi(s);t?this.dispatch(a,t,i,n):(this._state=Vt,this.sendFrame(r.frame(a,i),n),this.dequeue())}).catch(s=>{process.nextTick(wy,this,s,n)})}dispatch(e,t,i,n){if(!t){this.sendFrame(r.frame(e,i),n);return}let s=this._extensions[ml.extensionName];this._bufferedBytes+=i[Bt],this._state=vy,s.compress(e,i.fin,(a,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");Ia(this,u,n);return}this._bufferedBytes-=i[Bt],this._state=Vt,i.readOnly=!1,this.sendFrame(r.frame(c,i),n),this.dequeue()})}dequeue(){for(;this._state===Vt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Bt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Bt],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)}};_l.exports=Aa;function Ia(r,e,t){typeof t=="function"&&t(e);for(let i=0;i<r._queue.length;i++){let n=r._queue[i],s=n[n.length-1];typeof s=="function"&&s(e)}}function wy(r,e,t){Ia(r,e,t),r.onerror(e)}});var kl=M((JE,Cl)=>{"use strict";var{kForOnEventAttribute:Pn,kListener:Na}=Cr(),bl=Symbol("kCode"),vl=Symbol("kData"),El=Symbol("kError"),wl=Symbol("kMessage"),xl=Symbol("kReason"),Gi=Symbol("kTarget"),Sl=Symbol("kType"),Tl=Symbol("kWasClean"),Or=class{constructor(e){this[Gi]=null,this[Sl]=e}get target(){return this[Gi]}get type(){return this[Sl]}};Object.defineProperty(Or.prototype,"target",{enumerable:!0});Object.defineProperty(Or.prototype,"type",{enumerable:!0});var bi=class extends Or{constructor(e,t={}){super(e),this[bl]=t.code===void 0?0:t.code,this[xl]=t.reason===void 0?"":t.reason,this[Tl]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[bl]}get reason(){return this[xl]}get wasClean(){return this[Tl]}};Object.defineProperty(bi.prototype,"code",{enumerable:!0});Object.defineProperty(bi.prototype,"reason",{enumerable:!0});Object.defineProperty(bi.prototype,"wasClean",{enumerable:!0});var Yi=class extends Or{constructor(e,t={}){super(e),this[El]=t.error===void 0?null:t.error,this[wl]=t.message===void 0?"":t.message}get error(){return this[El]}get message(){return this[wl]}};Object.defineProperty(Yi.prototype,"error",{enumerable:!0});Object.defineProperty(Yi.prototype,"message",{enumerable:!0});var Rn=class extends Or{constructor(e,t={}){super(e),this[vl]=t.data===void 0?null:t.data}get data(){return this[vl]}};Object.defineProperty(Rn.prototype,"data",{enumerable:!0});var xy={addEventListener(r,e,t={}){for(let n of this.listeners(r))if(!t[Pn]&&n[Na]===e&&!n[Pn])return;let i;if(r==="message")i=function(s,a){let c=new Rn("message",{data:a?s:s.toString()});c[Gi]=this,zs(e,this,c)};else if(r==="close")i=function(s,a){let c=new bi("close",{code:s,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[Gi]=this,zs(e,this,c)};else if(r==="error")i=function(s){let a=new Yi("error",{error:s,message:s.message});a[Gi]=this,zs(e,this,a)};else if(r==="open")i=function(){let s=new Or("open");s[Gi]=this,zs(e,this,s)};else return;i[Pn]=!!t[Pn],i[Na]=e,t.once?this.once(r,i):this.on(r,i)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[Na]===e&&!t[Pn]){this.removeListener(r,t);break}}};Cl.exports={CloseEvent:bi,ErrorEvent:Yi,Event:Or,EventTarget:xy,MessageEvent:Rn};function zs(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var Ma=M((ZE,Ol)=>{"use strict";var{tokenChars:An}=Vi();function cr(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function Sy(r){let e=Object.create(null),t=Object.create(null),i=!1,n=!1,s=!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&&An[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?(cr(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&&An[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),cr(t,r.slice(u,p),!0),d===44&&(cr(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(n){if(An[d]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);u===-1?u=m:i||(i=!0),n=!1}else if(s)if(An[d]===1)u===-1&&(u=m);else if(d===34&&u!==-1)s=!1,p=m;else if(d===92)n=!0;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(d===34&&r.charCodeAt(m-1)===61)s=!0;else if(p===-1&&An[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),cr(t,c,E),d===44&&(cr(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||s||d===32||d===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=m);let _=r.slice(u,p);return a===void 0?cr(e,_,t):(c===void 0?cr(t,_,!0):i?cr(t,c,_.replace(/\\/g,"")):cr(t,c,_),cr(e,a,t)),e}function Ty(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(n=>{let s=i[n];return Array.isArray(s)||(s=[s]),s.map(a=>a===!0?n:`${n}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Ol.exports={format:Ty,parse:Sy}});var Xs=M((tw,Ul)=>{"use strict";var Cy=require("events"),ky=require("https"),Oy=require("http"),Al=require("net"),Py=require("tls"),{randomBytes:Ry,createHash:Ay}=require("crypto"),{Duplex:QE,Readable:ew}=require("stream"),{URL:Fa}=require("url"),Gr=On(),Iy=Ra(),Ly=La(),{isBlob:Ny}=Vi(),{BINARY_TYPES:Pl,EMPTY_BUFFER:$s,GUID:My,kForOnEventAttribute:Da,kListener:Fy,kStatusCode:Dy,kWebSocket:ct,NOOP:Il}=Cr(),{EventTarget:{addEventListener:By,removeEventListener:jy}}=kl(),{format:Uy,parse:Ky}=Ma(),{toBuffer:qy}=Cn(),Wy=30*1e3,Ll=Symbol("kAborted"),Ba=[8,13],Pr=["CONNECTING","OPEN","CLOSING","CLOSED"],Hy=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Ke=class r extends Cy{constructor(e,t,i){super(),this._binaryType=Pl[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=$s,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]),Nl(this,e,t,i)):(this._autoPong=i.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Pl.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 n=new Iy({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),s=new Ly(e,this._extensions,i.generateMask);this._receiver=n,this._sender=s,this._socket=e,n[ct]=this,s[ct]=this,e[ct]=this,n.on("conclude",$y),n.on("drain",Gy),n.on("error",Yy),n.on("message",Xy),n.on("ping",Jy),n.on("pong",Zy),s.onerror=Qy,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Dl),e.on("data",Ys),e.on("end",Bl),e.on("error",jl),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[Gr.extensionName]&&this._extensions[Gr.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){Pt(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())}),Fl(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){ja(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||$s,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){ja(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||$s,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){ja(this,e,i);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Gr.extensionName]||(n.compress=!1),this._sender.send(e||$s,n,i)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Pt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(Ke,"CONNECTING",{enumerable:!0,value:Pr.indexOf("CONNECTING")});Object.defineProperty(Ke.prototype,"CONNECTING",{enumerable:!0,value:Pr.indexOf("CONNECTING")});Object.defineProperty(Ke,"OPEN",{enumerable:!0,value:Pr.indexOf("OPEN")});Object.defineProperty(Ke.prototype,"OPEN",{enumerable:!0,value:Pr.indexOf("OPEN")});Object.defineProperty(Ke,"CLOSING",{enumerable:!0,value:Pr.indexOf("CLOSING")});Object.defineProperty(Ke.prototype,"CLOSING",{enumerable:!0,value:Pr.indexOf("CLOSING")});Object.defineProperty(Ke,"CLOSED",{enumerable:!0,value:Pr.indexOf("CLOSED")});Object.defineProperty(Ke.prototype,"CLOSED",{enumerable:!0,value:Pr.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(Ke.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(Ke.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[Da])return e[Fy];return null},set(e){for(let t of this.listeners(r))if(t[Da]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[Da]:!0})}})});Ke.prototype.addEventListener=By;Ke.prototype.removeEventListener=jy;Ul.exports=Ke;function Nl(r,e,t,i){let n={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:Ba[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=n.autoPong,!Ba.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${Ba.join(", ")})`);let s;if(e instanceof Fa)s=e;else try{s=new Fa(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),r._url=s.href;let a=s.protocol==="wss:",c=s.protocol==="ws+unix:",u;if(s.protocol!=="ws:"&&!a&&!c?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!s.pathname?u="The URL's pathname is empty":s.hash&&(u="The URL contains a fragment identifier"),u){let T=new SyntaxError(u);if(r._redirects===0)throw T;Gs(r,T);return}let d=a?443:80,p=Ry(16).toString("base64"),m=a?ky.request:Oy.request,_=new Set,E;if(n.createConnection=n.createConnection||(a?zy:Vy),n.defaultPort=n.defaultPort||d,n.port=s.port||d,n.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},n.path=s.pathname+s.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(E=new Gr(n.perMessageDeflate!==!0?n.perMessageDeflate:{},!1,n.maxPayload),n.headers["Sec-WebSocket-Extensions"]=Uy({[Gr.extensionName]:E.offer()})),t.length){for(let T of t){if(typeof T!="string"||!Hy.test(T)||_.has(T))throw new SyntaxError("An invalid or duplicated subprotocol was specified");_.add(T)}n.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(s.username||s.password)&&(n.auth=`${s.username}:${s.password}`),c){let T=n.path.split(":");n.socketPath=T[0],n.path=T[1]}let S;if(n.followRedirects){if(r._redirects===0){r._originalIpc=c,r._originalSecure=a,r._originalHostOrSocketPath=c?n.socketPath:s.host;let T=i&&i.headers;if(i={...i,headers:{}},T)for(let[z,ge]of Object.entries(T))i.headers[z.toLowerCase()]=ge}else if(r.listenerCount("redirect")===0){let T=c?r._originalIpc?n.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:s.host===r._originalHostOrSocketPath;(!T||r._originalSecure&&!a)&&(delete n.headers.authorization,delete n.headers.cookie,T||delete n.headers.host,n.auth=void 0)}n.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),S=r._req=m(n),r._redirects&&r.emit("redirect",r.url,S)}else S=r._req=m(n);n.timeout&&S.on("timeout",()=>{Pt(r,S,"Opening handshake has timed out")}),S.on("error",T=>{S===null||S[Ll]||(S=r._req=null,Gs(r,T))}),S.on("response",T=>{let z=T.headers.location,ge=T.statusCode;if(z&&n.followRedirects&&ge>=300&&ge<400){if(++r._redirects>n.maxRedirects){Pt(r,S,"Maximum redirects exceeded");return}S.abort();let ee;try{ee=new Fa(z,e)}catch{let B=new SyntaxError(`Invalid URL: ${z}`);Gs(r,B);return}Nl(r,ee,t,i)}else r.emit("unexpected-response",S,T)||Pt(r,S,`Unexpected server response: ${T.statusCode}`)}),S.on("upgrade",(T,z,ge)=>{if(r.emit("upgrade",T),r.readyState!==Ke.CONNECTING)return;S=r._req=null;let ee=T.headers.upgrade;if(ee===void 0||ee.toLowerCase()!=="websocket"){Pt(r,z,"Invalid Upgrade header");return}let R=Ay("sha1").update(p+My).digest("base64");if(T.headers["sec-websocket-accept"]!==R){Pt(r,z,"Invalid Sec-WebSocket-Accept header");return}let B=T.headers["sec-websocket-protocol"],re;if(B!==void 0?_.size?_.has(B)||(re="Server sent an invalid subprotocol"):re="Server sent a subprotocol but none was requested":_.size&&(re="Server sent no subprotocol"),re){Pt(r,z,re);return}B&&(r._protocol=B);let K=T.headers["sec-websocket-extensions"];if(K!==void 0){if(!E){Pt(r,z,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let U;try{U=Ky(K)}catch{Pt(r,z,"Invalid Sec-WebSocket-Extensions header");return}let ye=Object.keys(U);if(ye.length!==1||ye[0]!==Gr.extensionName){Pt(r,z,"Server indicated an extension that was not requested");return}try{E.accept(U[Gr.extensionName])}catch{Pt(r,z,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Gr.extensionName]=E}r.setSocket(z,ge,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(S,r):S.end()}function Gs(r,e){r._readyState=Ke.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function Vy(r){return r.path=r.socketPath,Al.connect(r)}function zy(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=Al.isIP(r.host)?"":r.host),Py.connect(r)}function Pt(r,e,t){r._readyState=Ke.CLOSING;let i=new Error(t);Error.captureStackTrace(i,Pt),e.setHeader?(e[Ll]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Gs,r,i)):(e.destroy(i),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function ja(r,e,t){if(e){let i=Ny(e)?e.size:qy(e).length;r._socket?r._sender._bufferedBytes+=i:r._bufferedAmount+=i}if(t){let i=new Error(`WebSocket is not open: readyState ${r.readyState} (${Pr[r.readyState]})`);process.nextTick(t,i)}}function $y(r,e){let t=this[ct];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[ct]!==void 0&&(t._socket.removeListener("data",Ys),process.nextTick(Ml,t._socket),r===1005?t.close():t.close(r,e))}function Gy(){let r=this[ct];r.isPaused||r._socket.resume()}function Yy(r){let e=this[ct];e._socket[ct]!==void 0&&(e._socket.removeListener("data",Ys),process.nextTick(Ml,e._socket),e.close(r[Dy])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Rl(){this[ct].emitClose()}function Xy(r,e){this[ct].emit("message",r,e)}function Jy(r){let e=this[ct];e._autoPong&&e.pong(r,!this._isServer,Il),e.emit("ping",r)}function Zy(r){this[ct].emit("pong",r)}function Ml(r){r.resume()}function Qy(r){let e=this[ct];e.readyState!==Ke.CLOSED&&(e.readyState===Ke.OPEN&&(e._readyState=Ke.CLOSING,Fl(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Fl(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),Wy)}function Dl(){let r=this[ct];this.removeListener("close",Dl),this.removeListener("data",Ys),this.removeListener("end",Bl),r._readyState=Ke.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[ct]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Rl),r._receiver.on("finish",Rl))}function Ys(r){this[ct]._receiver.write(r)||this.pause()}function Bl(){let r=this[ct];r._readyState=Ke.CLOSING,r._receiver.end(),this.end()}function jl(){let r=this[ct];this.removeListener("error",jl),this.on("error",Il),r&&(r._readyState=Ke.CLOSING,this.destroy())}});var Hl=M((iw,Wl)=>{"use strict";var rw=Xs(),{Duplex:e_}=require("stream");function Kl(r){r.emit("close")}function t_(){!this.destroyed&&this._writableState.finished&&this.destroy()}function ql(r){this.removeListener("error",ql),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function r_(r,e){let t=!0,i=new e_({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(s,a){let c=!a&&i._readableState.objectMode?s.toString():s;i.push(c)||r.pause()}),r.once("error",function(s){i.destroyed||(t=!1,i.destroy(s))}),r.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(n,s){if(r.readyState===r.CLOSED){s(n),process.nextTick(Kl,i);return}let a=!1;r.once("error",function(u){a=!0,s(u)}),r.once("close",function(){a||s(n),process.nextTick(Kl,i)}),t&&r.terminate()},i._final=function(n){if(r.readyState===r.CONNECTING){r.once("open",function(){i._final(n)});return}r._socket!==null&&(r._socket._writableState.finished?(n(),i._readableState.endEmitted&&i.destroy()):(r._socket.once("finish",function(){n()}),r.close()))},i._read=function(){r.isPaused&&r.resume()},i._write=function(n,s,a){if(r.readyState===r.CONNECTING){r.once("open",function(){i._write(n,s,a)});return}r.send(n,a)},i.on("end",t_),i.on("error",ql),i}Wl.exports=r_});var zl=M((nw,Vl)=>{"use strict";var{tokenChars:i_}=Vi();function n_(r){let e=new Set,t=-1,i=-1,n=0;for(n;n<r.length;n++){let a=r.charCodeAt(n);if(i===-1&&i_[a]===1)t===-1&&(t=n);else if(n!==0&&(a===32||a===9))i===-1&&t!==-1&&(i=n);else if(a===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${n}`);i===-1&&(i=n);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 ${n}`)}if(t===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let s=r.slice(t,n);if(e.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return e.add(s),e}Vl.exports={parse:n_}});var Ql=M((ow,Zl)=>{"use strict";var s_=require("events"),Js=require("http"),{Duplex:sw}=require("stream"),{createHash:o_}=require("crypto"),$l=Ma(),vi=On(),a_=zl(),c_=Xs(),{GUID:f_,kWebSocket:u_}=Cr(),l_=/^[+/0-9A-Za-z]{22}==$/,Gl=0,Yl=1,Jl=2,Ua=class extends s_{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:c_,...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=Js.createServer((i,n)=>{let s=Js.STATUS_CODES[426];n.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),n.end(s)}),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=h_(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(n,s,a)=>{this.handleUpgrade(n,s,a,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Gl}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===Jl){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(In,this);return}if(e&&this.once("close",e),this._state!==Yl)if(this._state=Yl,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(In,this):process.nextTick(In,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{In(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,n){t.on("error",Xl);let s=e.headers["sec-websocket-key"],a=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ei(this,e,t,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){Ei(this,e,t,400,"Invalid Upgrade header");return}if(s===void 0||!l_.test(s)){Ei(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){Ei(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Ln(t,400);return}let u=e.headers["sec-websocket-protocol"],d=new Set;if(u!==void 0)try{d=a_.parse(u)}catch{Ei(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 _=new vi(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let E=$l.parse(p);E[vi.extensionName]&&(_.accept(E[vi.extensionName]),m[vi.extensionName]=_)}catch{Ei(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let _={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(_,(E,S,T,z)=>{if(!E)return Ln(t,S||401,T,z);this.completeUpgrade(m,s,d,e,t,i,n)});return}if(!this.options.verifyClient(_))return Ln(t,401)}this.completeUpgrade(m,s,d,e,t,i,n)}completeUpgrade(e,t,i,n,s,a,c){if(!s.readable||!s.writable)return s.destroy();if(s[u_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Gl)return Ln(s,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${o_("sha1").update(t+f_).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(i.size){let m=this.options.handleProtocols?this.options.handleProtocols(i,n):i.values().next().value;m&&(d.push(`Sec-WebSocket-Protocol: ${m}`),p._protocol=m)}if(e[vi.extensionName]){let m=e[vi.extensionName].params,_=$l.format({[vi.extensionName]:[m]});d.push(`Sec-WebSocket-Extensions: ${_}`),p._extensions=e}this.emit("headers",d,n),s.write(d.concat(`\r
23
23
  `).join(`\r
24
24
  `)),s.removeListener("error",Xl),p.setSocket(s,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(In,this)})),c(p,n)}};Zl.exports=Ua;function h_(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 In(r){r._state=Jl,r.emit("close")}function Xl(){this.destroy()}function Ln(r,e,t,i){t=t||Js.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} ${Js.STATUS_CODES[e]}\r
25
25
  `+Object.keys(i).map(n=>`${n}: ${i[n]}`).join(`\r
26
26
  `)+`\r
27
27
  \r
28
- `+t)}function bi(r,e,t,i,n,s){if(r.listenerCount("wsClientError")){let a=new Error(n);Error.captureStackTrace(a,bi),r.emit("wsClientError",a,t,e)}else Ln(t,i,n,s)}});var th=M((aw,eh)=>{"use strict";var Ar=Xs();Ar.createWebSocketStream=Hl();Ar.Server=Ql();Ar.Receiver=Aa();Ar.Sender=La();Ar.WebSocket=Ar;Ar.WebSocketServer=Ar.Server;eh.exports=Ar});var Ha=M(Yr=>{"use strict";var d_=Yr&&Yr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Yr,"__esModule",{value:!0});Yr.WS=Yr.BaseWS=void 0;var p_=Tn(),rh=pi(),g_=Di(),Ka=di(),m_=d_(Ft()),y_=(0,m_.default)("engine.io-client:websocket"),ih=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Zs=class extends p_.Transport{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,i=ih?{}:(0,rh.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(n){return this.emitReserved("error",n)}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],n=t===e.length-1;(0,g_.encodePacket)(i,this.supportsBinary,s=>{try{this.doWrite(i,s)}catch{y_("websocket closed before onclose event")}n&&(0,Ka.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,rh.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}};Yr.BaseWS=Zs;var qa=Ka.globalThisShim.WebSocket||Ka.globalThisShim.MozWebSocket,Wa=class extends Zs{createSocket(e,t,i){return ih?new qa(e,t,i):t?new qa(e,t):new qa(e)}doWrite(e,t){this.ws.send(t)}};Yr.WS=Wa});var za=M(fr=>{"use strict";var __=fr&&fr.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),v_=fr&&fr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),b_=fr&&fr.__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)&&__(e,r,t);return v_(e,r),e};Object.defineProperty(fr,"__esModule",{value:!0});fr.WS=void 0;var E_=b_(th()),w_=Ha(),Va=class extends w_.BaseWS{createSocket(e,t,i){var n;if(!((n=this.socket)===null||n===void 0)&&n._cookieJar){i.headers=i.headers||{},i.headers.cookie=typeof i.headers.cookie=="string"?[i.headers.cookie]:i.headers.cookie||[];for(let[s,a]of this.socket._cookieJar.cookies)i.headers.cookie.push(`${s}=${a.value}`)}return new E_.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)}};fr.WS=Va});var Ga=M(Xi=>{"use strict";var x_=Xi&&Xi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Xi,"__esModule",{value:!0});Xi.WT=void 0;var S_=Tn(),T_=di(),nh=Di(),C_=x_(Ft()),Nn=(0,C_.default)("engine.io-client:webtransport"),$a=class extends S_.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(()=>{Nn("transport closed gracefully"),this.onClose()}).catch(e=>{Nn("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=(0,nh.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=e.readable.pipeThrough(t).getReader(),n=(0,nh.createPacketEncoderStream)();n.readable.pipeTo(e.writable),this._writer=n.writable.getWriter();let s=()=>{i.read().then(({done:c,value:u})=>{if(c){Nn("session is closed");return}Nn("received chunk: %o",u),this.onPacket(u),s()}).catch(c=>{Nn("an error occurred while reading: %s",c)})};s();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],n=t===e.length-1;this._writer.write(i).then(()=>{n&&(0,T_.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};Xi.WT=$a});var Ya=M(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});Qs.transports=void 0;var k_=va(),O_=za(),P_=Ga();Qs.transports={websocket:O_.WS,webtransport:P_.WT,polling:k_.XHR}});var Ja=M(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.parse=I_;var A_=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,R_=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function I_(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 n=A_.exec(r||""),s={},a=14;for(;a--;)s[R_[a]]=n[a]||"";return t!=-1&&i!=-1&&(s.source=e,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=L_(s,s.path),s.queryKey=N_(s,s.query),s}function L_(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 N_(r,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(i,n,s){n&&(t[n]=s)}),t}});var tc=M(ur=>{"use strict";var M_=ur&&ur.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ur,"__esModule",{value:!0});ur.Socket=ur.SocketWithUpgrade=ur.SocketWithoutUpgrade=void 0;var F_=Ya(),sh=pi(),D_=aa(),oh=Ja(),B_=hi(),ah=Di(),Za=di(),j_=M_(Ft()),De=(0,j_.default)("engine.io-client:socket"),Qa=typeof addEventListener=="function"&&typeof removeEventListener=="function",Mn=[];Qa&&addEventListener("offline",()=>{De("closing %d connection(s) because the network was lost",Mn.length),Mn.forEach(r=>r())},!1);var Ei=class r extends B_.Emitter{constructor(e,t){if(super(),this.binaryType=Za.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,oh.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,oh.parse)(t.host).host);(0,sh.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 n=i.prototype.name;this.transports.push(n),this._transportsByName[n]=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,D_.decode)(this.opts.query)),Qa&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(De("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Mn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,Za.createCookieJar)()),this._open()}createTransport(e){De('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=ah.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 De("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){De("setting transport %s",e.name),this.transport&&(De("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(){De("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(De('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 De('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();De("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 n=this.writeBuffer[i].data;if(n&&(t+=(0,sh.byteLength)(n)),i>0&&t>this._maxPayload)return De("only send %d out of %d packets",i,this.writeBuffer.length),this.writeBuffer.slice(0,i);t+=2}return De("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&&(De("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,Za.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,n){if(typeof t=="function"&&(n=t,t=void 0),typeof i=="function"&&(n=i,i=null),this.readyState==="closing"||this.readyState==="closed")return;i=i||{},i.compress=i.compress!==!1;let s={type:e,data:t,options:i};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),n&&this.once("flush",n),this.flush()}close(){let e=()=>{this._onClose("forced close"),De("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(De("socket error %j",e),r.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return De("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(De('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Qa&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let i=Mn.indexOf(this._offlineEventListener);i!==-1&&(De("removing listener for the 'offline' event"),Mn.splice(i,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};ur.SocketWithoutUpgrade=Ei;Ei.protocol=ah.protocol;var eo=class extends Ei{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){De("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){De('probing transport "%s"',e);let t=this.createTransport(e),i=!1;Ei.priorWebsocketSuccess=!1;let n=()=>{i||(De('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(De('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Ei.priorWebsocketSuccess=t.name==="websocket",De('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{i||this.readyState!=="closed"&&(De("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{De('probe transport "%s" failed',e);let _=new Error("probe error");_.transport=t.name,this.emitReserved("upgradeError",_)}}))};function s(){i||(i=!0,p(),t.close(),t=null)}let a=m=>{let _=new Error("probe error: "+m);_.transport=t.name,s(),De('probe transport "%s" failed because of error: %s',e,m),this.emitReserved("upgradeError",_)};function c(){a("transport closed")}function u(){a("socket closed")}function d(m){t&&m.name!==t.name&&(De('"%s" works - aborting "%s"',m.name,t.name),s())}let p=()=>{t.removeListener("open",n),t.removeListener("error",a),t.removeListener("close",c),this.off("close",u),this.off("upgrading",d)};t.once("open",n),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}};ur.SocketWithUpgrade=eo;var ec=class extends eo{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(n=>F_.transports[n]).filter(n=>!!n)),super(e,i)}};ur.Socket=ec});var ch=M(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.Fetch=void 0;var U_=pa(),rc=class extends U_.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,n=new Headers(this.opts.extraHeaders);return i&&n.set("content-type","text/plain;charset=UTF-8"),(t=this.socket._cookieJar)===null||t===void 0||t.appendCookies(n),fetch(this.uri(),{method:i?"POST":"GET",body:i?e:null,headers:n,credentials:this.opts.withCredentials?"include":"omit"}).then(s=>{var a;return(a=this.socket._cookieJar)===null||a===void 0||a.parseCookies(s.headers.getSetCookie()),s})}};to.Fetch=rc});var ro=M(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.WebTransport=Oe.WebSocket=Oe.NodeWebSocket=Oe.XHR=Oe.NodeXHR=Oe.Fetch=Oe.nextTick=Oe.parse=Oe.installTimerFunctions=Oe.transports=Oe.TransportError=Oe.Transport=Oe.protocol=Oe.SocketWithUpgrade=Oe.SocketWithoutUpgrade=Oe.Socket=void 0;var fh=tc();Object.defineProperty(Oe,"Socket",{enumerable:!0,get:function(){return fh.Socket}});var uh=tc();Object.defineProperty(Oe,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return uh.SocketWithoutUpgrade}});Object.defineProperty(Oe,"SocketWithUpgrade",{enumerable:!0,get:function(){return uh.SocketWithUpgrade}});Oe.protocol=fh.Socket.protocol;var lh=Tn();Object.defineProperty(Oe,"Transport",{enumerable:!0,get:function(){return lh.Transport}});Object.defineProperty(Oe,"TransportError",{enumerable:!0,get:function(){return lh.TransportError}});var q_=Ya();Object.defineProperty(Oe,"transports",{enumerable:!0,get:function(){return q_.transports}});var K_=pi();Object.defineProperty(Oe,"installTimerFunctions",{enumerable:!0,get:function(){return K_.installTimerFunctions}});var W_=Ja();Object.defineProperty(Oe,"parse",{enumerable:!0,get:function(){return W_.parse}});var H_=di();Object.defineProperty(Oe,"nextTick",{enumerable:!0,get:function(){return H_.nextTick}});var V_=ch();Object.defineProperty(Oe,"Fetch",{enumerable:!0,get:function(){return V_.Fetch}});var z_=va();Object.defineProperty(Oe,"NodeXHR",{enumerable:!0,get:function(){return z_.XHR}});var $_=ya();Object.defineProperty(Oe,"XHR",{enumerable:!0,get:function(){return $_.XHR}});var G_=za();Object.defineProperty(Oe,"NodeWebSocket",{enumerable:!0,get:function(){return G_.WS}});var Y_=Ha();Object.defineProperty(Oe,"WebSocket",{enumerable:!0,get:function(){return Y_.WS}});var X_=Ga();Object.defineProperty(Oe,"WebTransport",{enumerable:!0,get:function(){return X_.WT}})});var dh=M(Fn=>{"use strict";var J_=Fn&&Fn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Fn,"__esModule",{value:!0});Fn.url=e0;var Z_=ro(),Q_=J_(Ft()),hh=(0,Q_.default)("socket.io-client:url");function e0(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)||(hh("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),hh("parse %s",r),i=(0,Z_.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 s=i.host.indexOf(":")!==-1?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+s+":"+i.port+e,i.href=i.protocol+"://"+s+(t&&t.port===i.port?"":":"+i.port),i}});var ic=M(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.isBinary=gh;no.hasBinary=io;var t0=typeof ArrayBuffer=="function",r0=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,ph=Object.prototype.toString,i0=typeof Blob=="function"||typeof Blob<"u"&&ph.call(Blob)==="[object BlobConstructor]",n0=typeof File=="function"||typeof File<"u"&&ph.call(File)==="[object FileConstructor]";function gh(r){return t0&&(r instanceof ArrayBuffer||r0(r))||i0&&r instanceof Blob||n0&&r instanceof File}function io(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,i=r.length;t<i;t++)if(io(r[t]))return!0;return!1}if(gh(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return io(r.toJSON(),!0);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&io(r[t]))return!0;return!1}});var mh=M(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});so.deconstructPacket=o0;so.reconstructPacket=a0;var s0=ic();function o0(r){let e=[],t=r.data,i=r;return i.data=nc(t,e),i.attachments=e.length,{packet:i,buffers:e}}function nc(r,e){if(!r)return r;if((0,s0.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]=nc(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]=nc(r[i],e));return t}return r}function a0(r,e){return r.data=sc(r.data,e),delete r.attachments,r}function sc(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]=sc(r[t],e);else if(typeof r=="object")for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=sc(r[t],e));return r}});var ao=M(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.Decoder=zt.Encoder=zt.PacketType=zt.protocol=void 0;zt.isPacketValid=p0;var c0=hi(),yh=mh(),_h=ic(),f0=Ft(),oc=(0,f0.default)("socket.io-parser"),vh=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];zt.protocol=5;var Fe;(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"})(Fe||(zt.PacketType=Fe={}));var ac=class{constructor(e){this.replacer=e}encode(e){return oc("encoding packet %j",e),(e.type===Fe.EVENT||e.type===Fe.ACK)&&(0,_h.hasBinary)(e)?this.encodeAsBinary({type:e.type===Fe.EVENT?Fe.BINARY_EVENT:Fe.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===Fe.BINARY_EVENT||e.type===Fe.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)),oc("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=(0,yh.deconstructPacket)(e),i=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(i),n}};zt.Encoder=ac;var cc=class r extends c0.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===Fe.BINARY_EVENT;i||t.type===Fe.BINARY_ACK?(t.type=i?Fe.EVENT:Fe.ACK,this.reconstructor=new fc(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,_h.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(Fe[i.type]===void 0)throw new Error("unknown packet type "+i.type);if(i.type===Fe.BINARY_EVENT||i.type===Fe.BINARY_ACK){let s=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);let a=e.substring(s,t);if(a!=Number(a)||e.charAt(t)!=="-")throw new Error("Illegal attachments");i.attachments=Number(a)}if(e.charAt(t+1)==="/"){let s=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););i.nsp=e.substring(s,t)}else i.nsp="/";let n=e.charAt(t+1);if(n!==""&&Number(n)==n){let s=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(s,t+1))}if(e.charAt(++t)){let s=this.tryParse(e.substr(t));if(r.isPayloadValid(i.type,s))i.data=s;else throw new Error("invalid payload")}return oc("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 Fe.CONNECT:return oo(t);case Fe.DISCONNECT:return t===void 0;case Fe.CONNECT_ERROR:return typeof t=="string"||oo(t);case Fe.EVENT:case Fe.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&vh.indexOf(t[0])===-1);case Fe.ACK:case Fe.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};zt.Decoder=cc;var fc=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,yh.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function u0(r){return typeof r=="string"}var l0=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function h0(r){return r===void 0||l0(r)}function oo(r){return Object.prototype.toString.call(r)==="[object Object]"}function d0(r,e){switch(r){case Fe.CONNECT:return e===void 0||oo(e);case Fe.DISCONNECT:return e===void 0;case Fe.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&vh.indexOf(e[0])===-1);case Fe.ACK:return Array.isArray(e);case Fe.CONNECT_ERROR:return typeof e=="string"||oo(e);default:return!1}}function p0(r){return u0(r.nsp)&&h0(r.id)&&d0(r.type,r.data)}});var lc=M(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.on=g0;function g0(r,e,t){return r.on(e,t),function(){r.off(e,t)}}});var dc=M(Ji=>{"use strict";var m0=Ji&&Ji.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ji,"__esModule",{value:!0});Ji.Socket=void 0;var $t=ao(),co=lc(),y0=hi(),_0=m0(Ft()),et=(0,_0.default)("socket.io-client:socket"),v0=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),hc=class extends y0.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,co.on)(e,"open",this.onopen.bind(this)),(0,co.on)(e,"packet",this.onpacket.bind(this)),(0,co.on)(e,"error",this.onerror.bind(this)),(0,co.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,n,s;if(v0.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:$t.PacketType.EVENT,data:t};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let p=this.ids++;et("emitting packet with ack id %d",p);let m=t.pop();this._registerAckCallback(p,m),a.id=p}let c=(n=(i=this.io.engine)===null||i===void 0?void 0:i.transport)===null||n===void 0?void 0:n.writable,u=this.connected&&!(!((s=this.io.engine)===null||s===void 0)&&s._hasPingExpired());return this.flags.volatile&&!c?et("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 n=(i=this.flags.timeout)!==null&&i!==void 0?i:this._opts.ackTimeout;if(n===void 0){this.acks[e]=t;return}let s=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===e&&(et("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(c,1));et("event with ack id %d has timed out after %d ms",e,n),t.call(this,new Error("operation has timed out"))},n),a=(...c)=>{this.io.clearTimeoutFn(s),t.apply(this,c)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((i,n)=>{let s=(a,c)=>a?n(a):i(c);s.withError=!0,t.push(s),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((n,...s)=>i!==this._queue[0]?et("packet [%d] already acknowledged",i.id):(n!==null?i.tryCount>this._opts.retries&&(et("packet [%d] is discarded after %d tries",i.id,i.tryCount),this._queue.shift(),t&&t(n)):(et("packet [%d] was successfully sent",i.id),this._queue.shift(),t&&t(null,...s)),i.pending=!1,this._drainQueue())),this._queue.push(i),this._drainQueue()}_drainQueue(e=!1){if(et("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){et("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,et("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(){et("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:$t.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){et("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 $t.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 $t.PacketType.EVENT:case $t.PacketType.BINARY_EVENT:this.onevent(e);break;case $t.PacketType.ACK:case $t.PacketType.BINARY_ACK:this.onack(e);break;case $t.PacketType.DISCONNECT:this.ondisconnect();break;case $t.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||[];et("emitting event %j",t),e.id!=null&&(et("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(...n){i||(i=!0,et("sending ack %j",n),t.packet({type:$t.PacketType.ACK,id:e,data:n}))}}onack(e){let t=this.acks[e.id];if(typeof t!="function"){et("bad ack %s",e.id);return}delete this.acks[e.id],et("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){et("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(){et("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&&(et("performing disconnect (%s)",this.nsp),this.packet({type:$t.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)}}};Ji.Socket=hc});var bh=M(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.Backoff=Zi;function Zi(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}Zi.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};Zi.prototype.reset=function(){this.attempts=0};Zi.prototype.setMin=function(r){this.ms=r};Zi.prototype.setMax=function(r){this.max=r};Zi.prototype.setJitter=function(r){this.jitter=r}});var Eh=M(jt=>{"use strict";var b0=jt&&jt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),E0=jt&&jt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),w0=jt&&jt.__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)&&b0(e,r,t);return E0(e,r),e},x0=jt&&jt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(jt,"__esModule",{value:!0});jt.Manager=void 0;var gc=ro(),S0=dc(),T0=w0(ao()),wi=lc(),C0=bh(),k0=hi(),O0=x0(Ft()),ft=(0,O0.default)("socket.io-client:manager"),mc=class extends k0.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,gc.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 C0.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 n=t.parser||T0;this.encoder=new n.Encoder,this.decoder=new n.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(ft("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;ft("opening %s",this.uri),this.engine=new gc.Socket(this.uri,this.opts);let t=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;let n=(0,wi.on)(t,"open",function(){i.onopen(),e&&e()}),s=c=>{ft("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},a=(0,wi.on)(t,"error",s);if(this._timeout!==!1){let c=this._timeout;ft("connect attempt will timeout after %d",c);let u=this.setTimeoutFn(()=>{ft("connect attempt timed out after %d",c),n(),s(new Error("timeout")),t.close()},c);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(n),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){ft("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push((0,wi.on)(e,"ping",this.onping.bind(this)),(0,wi.on)(e,"data",this.ondata.bind(this)),(0,wi.on)(e,"error",this.onerror.bind(this)),(0,wi.on)(e,"close",this.onclose.bind(this)),(0,wi.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,gc.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){ft("error",e),this.emitReserved("error",e)}socket(e,t){let i=this.nsps[e];return i?this._autoConnect&&!i.active&&i.connect():(i=new S0.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){ft("socket %s is still active, skipping close",i);return}this._close()}_packet(e){ft("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(){ft("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){ft("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var i;ft("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)ft("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();ft("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let i=this.setTimeoutFn(()=>{e.skipReconnect||(ft("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(n=>{n?(ft("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",n)):(ft("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)}};jt.Manager=mc});var Th=M((Be,Sh)=>{"use strict";var P0=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=xi;Be.connect=xi;Be.default=xi;var A0=dh(),fo=Eh();Object.defineProperty(Be,"Manager",{enumerable:!0,get:function(){return fo.Manager}});var xh=dc();Object.defineProperty(Be,"Socket",{enumerable:!0,get:function(){return xh.Socket}});var R0=P0(Ft()),wh=(0,R0.default)("socket.io-client"),Dn={};function xi(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};let t=(0,A0.url)(r,e.path||"/socket.io"),i=t.source,n=t.id,s=t.path,a=Dn[n]&&s in Dn[n].nsps,c=e.forceNew||e["force new connection"]||e.multiplex===!1||a,u;return c?(wh("ignoring socket cache for %s",i),u=new fo.Manager(i,e)):(Dn[n]||(wh("new io instance for %s",i),Dn[n]=new fo.Manager(i,e)),u=Dn[n]),t.query&&!e.query&&(e.query=t.queryKey),u.socket(t.path,e)}Object.assign(xi,{Manager:fo.Manager,Socket:xh.Socket,io:xi,connect:xi});var I0=ao();Object.defineProperty(Be,"protocol",{enumerable:!0,get:function(){return I0.protocol}});var Qi=ro();Object.defineProperty(Be,"Fetch",{enumerable:!0,get:function(){return Qi.Fetch}});Object.defineProperty(Be,"NodeXHR",{enumerable:!0,get:function(){return Qi.NodeXHR}});Object.defineProperty(Be,"XHR",{enumerable:!0,get:function(){return Qi.XHR}});Object.defineProperty(Be,"NodeWebSocket",{enumerable:!0,get:function(){return Qi.NodeWebSocket}});Object.defineProperty(Be,"WebSocket",{enumerable:!0,get:function(){return Qi.WebSocket}});Object.defineProperty(Be,"WebTransport",{enumerable:!0,get:function(){return Qi.WebTransport}});Sh.exports=xi});var _c=M(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.InputStreamReceiver=void 0;var L0=64,N0=30,M0=4,F0=256,D0=16,yc=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??L0),this.ackThrottleMs=Math.max(0,i.ackThrottleMs??N0)}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 n=Math.max(this.windowSize*M0,F0);e-this.lastAppliedSeq>n||this.maybeResend(this.lastAppliedSeq+1)}maybeResend(e){if(e===this.lastResendFrom){if(++this.resendSuppressed<D0)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)}};uo.InputStreamReceiver=yc});var Ph=M(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.WebSocketService=void 0;var B0=Th(),Ch=Sr(),kh=fs(),Oh=os(),j0=_c(),vc=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;metaSessionEstablishedHandler=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;RESUME_WATCHDOG_INTERVAL=5e3;RESUME_WATCHDOG_THRESHOLD=15e3;resumeWatchdogTimer=null;resumeWatchdogExpectedAt=0;isManualDisconnect=!1;reconnectAttempts=0;reconnectTimer=null;networkCheckTimer=null;isOnline=!0;lastNetworkCheck=0;rekeyingTerminals=new Set;outputBuffer=new Map;OUTPUT_BUFFER_MAX_SIZE=1e3;invalidSessionSignalAt=new Map;INVALID_SESSION_SIGNAL_THROTTLE_MS=5e3;attachedClientCount=0;RECONNECT_BASE_DELAY=1e3;RECONNECT_MAX_DELAY=3e4;RECONNECT_JITTER=.2;NETWORK_CHECK_INTERVAL=5e3;constructor(e,t,i,n,s,a,c="vscode",u=[]){this.authService=e,this.cryptoService=t,this.config=i,this.logger=n,this.notification=s,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,kh.getWsUrl)(this.config);this.logger.info("Connecting to WebSocket",t),this.statusChangeHandler?.("connecting");let i=await this.cryptoService.getPublicKey();return new Promise((n,s)=>{let a=Array.from(new Set([...Ch.DEFAULT_CLIENT_CAPABILITIES,...this.extraCapabilities]));this.socket=(0,B0.io)(`${t}/agent`,{auth:{token:e,protocolVersion:Ch.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,n()}),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||s(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("meta:keyExchange",async(c,u)=>{let{ok:d,isNew:p}=await this.cryptoService.handleMetaKeyExchange(c.clientIdentityPub),m=await this.cryptoService.getPublicKey()||void 0;u?.({ok:d,agentPublicKey:m}),d&&p&&this.metaSessionEstablishedHandler?.()}),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);if(!p){this.signalInvalidSession(void 0,c.terminalId),u?.({success:!1,error:"No E2E session"});return}u?.({success:!0,encrypted:p}),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.attachedClientCount=c.clientCount,this.clientAttachedHandler?.(c)}),this.socket.on("workspace:clientDetached",c=>{this.attachedClientCount=c.clientCount,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}onMetaSessionEstablished(e){this.metaSessionEstablishedHandler=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,n){this.socket?.connected&&this.socket.emit("agent:ptyResized",{instanceId:e,terminalId:t,cols:i,rows:n})}sendClaimControl(e,t,i,n){this.socket?.connected&&this.socket.emit("agent:claimControl",{instanceId:e,terminalId:t,cols:i,rows:n})}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 n=this.cryptoService.encryptOutput(t,i);if(!n){this.attachedClientCount>0&&this.signalInvalidSession(e,t);return}let s={instanceId:e,terminalId:t,encrypted:n};this.socket?.emit("terminal:output",s)}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:n}of t){let s=this.cryptoService.encryptOutput(e,n);if(!s){this.signalInvalidSession(i,e);continue}let a={instanceId:i,terminalId:e,encrypted:s};this.socket?.emit("terminal:output",a)}}}signalInvalidSession(e,t){let i=Date.now(),n=this.invalidSessionSignalAt.get(t)??0;i-n<this.INVALID_SESSION_SIGNAL_THROTTLE_MS||(this.invalidSessionSignalAt.set(t,i),this.logger.warn("E2E session invalid/missing \u2014 signaling clients to rekey",t),this.socket?.emit("crypto:invalidSession",{instanceId:e??this.instanceIdForTerminal(t),terminalId:t}))}instanceIdForTerminal(e){return this.inputReceivers.get(e)?.instanceId}async updateStatus(e){await this.emit("terminal:status",e)}sendTerminalEvent(e,t,i){let n={instanceId:e,terminalId:t,event:i};this.socket?.emit("terminal:event",n)}hasCapability(e){return this.negotiatedCapabilities.includes(e)}sendFileChangedEvent(e,t,i){let n={instanceId:e,terminalId:t,event:i};this.socket?.emit("file:changed",n)}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,Oh.generateCorrelationId)(),n=t&&typeof t=="object"&&!Array.isArray(t)?{...t,_cid:i}:t;return(0,Oh.runWithCorrelation)(i,()=>new Promise((s,a)=>{if(!this.socket?.connected){a(new Error("WebSocket not connected"));return}this.socket.emit(e,n,c=>{c.success?s(c):a(new Error(c.error||"Unknown error"))})}))}startHeartbeat(){this.stopHeartbeat(),this.lastPongTime=Date.now(),this.startResumeWatchdog(),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, forcing teardown + reconnect"),this.statusChangeHandler?.("error"),this.socket?.disconnect()},this.HEARTBEAT_TIMEOUT)},this.HEARTBEAT_INTERVAL)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.clearPongTimeout(),this.stopResumeWatchdog()}startResumeWatchdog(){this.stopResumeWatchdog(),this.resumeWatchdogExpectedAt=Date.now()+this.RESUME_WATCHDOG_INTERVAL,this.resumeWatchdogTimer=setTimeout(()=>this.onResumeWatchdogTick(),this.RESUME_WATCHDOG_INTERVAL)}onResumeWatchdogTick(){let e=Date.now(),t=e-this.resumeWatchdogExpectedAt;if(t>this.RESUME_WATCHDOG_THRESHOLD&&(this.logger.warn(`Resume detected (clock drift ${t}ms) - forcing liveness re-check`),!this.isManualDisconnect&&this.socket)){this.statusChangeHandler?.("error"),this.socket.disconnect();return}this.isManualDisconnect||(this.resumeWatchdogExpectedAt=e+this.RESUME_WATCHDOG_INTERVAL,this.resumeWatchdogTimer=setTimeout(()=>this.onResumeWatchdogTick(),this.RESUME_WATCHDOG_INTERVAL))}stopResumeWatchdog(){this.resumeWatchdogTimer&&(clearTimeout(this.resumeWatchdogTimer),this.resumeWatchdogTimer=null)}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),this.signalInvalidSession(e.instanceId,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,n){let s=this.inputReceivers.get(e);if(this.terminalActiveCheck&&!this.terminalActiveCheck(e))return s&&this.disposeInputStream(e),null;if(s&&s.receiver.streamId===t)return n&&(s.routeId=n),i&&(s.instanceId=i),s.receiver;if(s&&s.receiver.dispose(),!s&&this.inputReceivers.size>=this.MAX_INPUT_RECEIVERS)return this.logger.error("inputReceivers map at cap, dropping frame",e),null;let a=new j0.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:n??e,instanceId:i??""}),a}setTerminalActiveCheck(e){this.terminalActiveCheck=e}routeIdFor(e){return this.inputReceivers.get(e)?.routeId??e}sendInputAck(e,t,i){let n=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:ack",{instanceId:n,terminalId:e,streamId:t,ackSeq:i})}sendInputResend(e,t,i){let n=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:resend",{instanceId:n,terminalId:e,streamId:t,fromSeq:i})}sendInputResume(e){let t=this.inputReceivers.get(e);if(!t)return;let{streamId:i,lastAckSeq:n}=t.receiver.resumeState();this.socket?.emit("input:resume",{instanceId:t.instanceId,terminalId:e,streamId:i,lastAckSeq:n})}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,kh.getApiUrl)(this.config)}/health`,i=new AbortController,n=setTimeout(()=>i.abort(),5e3),s=await fetch(t,{method:"GET",signal:i.signal});return clearTimeout(n),this.logger.debug("Network check OK",String(s.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)}};lo.WebSocketService=vc});var Rh=M(lr=>{"use strict";var U0=lr&&lr.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),q0=lr&&lr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Ec=lr&&lr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[i.length]=n);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),n=0;n<i.length;n++)i[n]!=="default"&&U0(t,e,i[n]);return q0(t,e),t}})();Object.defineProperty(lr,"__esModule",{value:!0});lr.FileTransferService=void 0;var ho=Ec(require("fs")),K0=Ec(require("path")),Ah=Ec(require("crypto")),je=Sr(),bc=class{socket=null;activeTransfers=new Map;instanceId="";logger;fallbackDir;cryptoService=null;constructor(e,t="/tmp"){this.logger=e,this.fallbackDir=t}setCrypto(e){this.cryptoService=e}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,n,s){let a=ho.readFileSync(t),c=t.split("/").pop()||"file";return this.initAndSendChunks(e,a,c,{mimeType:this.getMimeType(c),requestId:s,onProgress:i,onComplete:n})}async sendBuffer(e,t,i,n,s){return this.initAndSendChunks(e,t,i,{mimeType:n,purpose:s?.purpose,viewMetadata:s?.viewMetadata,requestId:s?.requestId,onProgress:s?.onProgress,onComplete:s?.onComplete})}async initAndSendChunks(e,t,i,n){if(!this.socket)throw new Error("Socket not connected");let s=t.length,a=(0,je.calculateTotalChunks)(s),c=this.calculateChecksum(t),u=Ah.randomUUID(),d={id:u,terminalId:e,filename:i,size:s,totalChunks:a,direction:je.TransferDirection.DOWNLOAD,status:je.TransferStatus.PENDING,deliveredChunks:new Set,pendingChunks:new Map,checksum:c,checksumAlgorithm:"sha256",onProgress:n.onProgress?(m,_)=>n.onProgress(u,m,_):void 0,onComplete:n.onComplete?(m,_)=>n.onComplete(u,m,_):void 0,ackTimeouts:new Map};d.chunks=[];for(let m=0;m<a;m++){let _=m*je.CHUNK_SIZE,E=Math.min(_+je.CHUNK_SIZE,s);d.chunks.push(t.subarray(_,E))}this.activeTransfers.set(u,d);let p={transferId:u,terminalId:e,filename:i,size:s,totalChunks:a,mimeType:n.mimeType||"application/octet-stream",checksum:c,direction:je.TransferDirection.DOWNLOAD,instanceId:this.instanceId};return n.requestId&&(p.requestId=n.requestId),n.purpose&&(p.purpose=n.purpose),n.viewMetadata&&(p.viewMetadata=n.viewMetadata),new Promise((m,_)=>{this.socket.emit("file:init",p,E=>{E.accepted?(d.status=je.TransferStatus.ACTIVE,this.startSendingChunks(u),m(u)):(this.activeTransfers.delete(u),_(new Error(E.error||"Transfer rejected")))})})}async receiveFile(e,t,i,n,s,a,c,u="sha256",d,p){let m={id:e,terminalId:t,filename:i,filePath:c,size:n,totalChunks:s,direction:je.TransferDirection.UPLOAD,status:je.TransferStatus.ACTIVE,deliveredChunks:new Set,pendingChunks:new Map,chunks:new Array(s).fill(null),checksum:a,checksumAlgorithm:u,onProgress:d?(_,E)=>d(e,_,E):void 0,onComplete:p?(_,E)=>p(e,_,E):void 0,ackTimeouts:new Map};this.activeTransfers.set(e,m)}cancelTransfer(e,t){let i=this.activeTransfers.get(e);if(i){for(let n of i.ackTimeouts.values())clearTimeout(n);if(i.status=je.TransferStatus.CANCELLED,i.onComplete?.(!1,t),this.socket){let n={transferId:e,reason:t};this.socket.emit("file:cancel",n)}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 n of i.deliveredChunks)t.deliveredChunks.add(n);if(t.direction===je.TransferDirection.DOWNLOAD&&i.missingChunks){t.status=je.TransferStatus.ACTIVE;for(let n of i.missingChunks)this.sendChunk(t,n)}})}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 n=e.pendingChunks.get(t),s={seq:t,data:i,retries:n?n.retries:0,sentAt:Date.now()};e.pendingChunks.set(t,s);let a=this.cryptoService?.encryptFileChunk(e.terminalId,new Uint8Array(i.buffer,i.byteOffset,i.byteLength));if(!a){this.cancelTransfer(e.id,"No E2E session for file transfer");return}let c={transferId:e.id,seq:t,encrypted:a};this.socket.emit("file:chunk",c,d=>{d&&!d.success&&this.cancelTransfer(e.id,d.error||"Server rejected chunk")});let u=setTimeout(()=>{this.handleAckTimeout(e.id,t)},je.ACK_TIMEOUT_MS);e.ackTimeouts.set(t,u)}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 n=e.seq+je.WINDOW_SIZE;n<t.totalChunks&&!t.deliveredChunks.has(n)&&this.sendChunk(t,n),t.deliveredChunks.size===t.totalChunks&&this.finishSending(t)}handleAckTimeout(e,t){let i=this.activeTransfers.get(e);if(!i)return;let n=i.pendingChunks.get(t);n&&(n.retries<je.MAX_RETRIES?(n.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)return;let i=e.encrypted?this.cryptoService?.decryptFileChunk(t.terminalId,e.encrypted):null;if(!i){this.cancelTransfer(e.transferId,"Chunk decryption failed (no E2E session?)");return}if(t.chunks[e.seq]=Buffer.from(i),t.deliveredChunks.add(e.seq),this.socket){let n={transferId:e.transferId,seq:e.seq};this.socket.emit("file:chunk:ack",n)}t.onProgress?.(t.deliveredChunks.size,t.totalChunks),t.deliveredChunks.size===t.totalChunks&&this.finishReceiving(t)}finishReceiving(e){if(!e.chunks||!e.filePath)return;let t=Buffer.concat(e.chunks);if(this.calculateChecksum(t,e.checksumAlgorithm)!==e.checksum){e.status=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 n=K0.dirname(e.filePath);ho.existsSync(n)||ho.mkdirSync(n,{recursive:!0}),ho.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(n){let s=n instanceof Error?n.message:String(n);e.status=je.TransferStatus.FAILED,e.onComplete?.(!1,`Failed to save file: ${s}`),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!1,error:`Failed to save file: ${s}`})}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 n=`${e.targetPath||this.fallbackDir}/${e.filename}`;this.receiveFile(e.transferId,e.terminalId,e.filename,e.size,e.totalChunks,e.checksum,n,e.checksumAlgorithm||"sha256").then(()=>t({accepted:!0})).catch(s=>t({accepted:!1,error:s.message}))}calculateChecksum(e,t="sha256"){return t==="fnv1a"?this.fnv1aHash(e):Ah.createHash("sha256").update(e).digest("hex")}fnv1aHash(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e[n],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"}};lr.FileTransferService=bc});var Oc=M((kw,mo)=>{function Nh(r){return Array.isArray(r)?r:[r]}var W0=void 0,xc="",Ih=" ",wc="\\",H0=/^\s+$/,V0=/(?:[^\\]|^)\\$/,z0=/^\\!/,$0=/^\\#/,G0=/\r?\n/g,Y0=/^\.{0,2}\/|^\.{1,2}$/,X0=/\/$/,en="/",Mh="node-ignore";typeof Symbol<"u"&&(Mh=Symbol.for("node-ignore"));var Fh=Mh,tn=(r,e,t)=>(Object.defineProperty(r,e,{value:t}),t),J0=/([0-z])-([0-z])/g,Dh=()=>!1,Z0=r=>r.replace(J0,(e,t,i)=>t.charCodeAt(0)<=i.charCodeAt(0)?e:xc),Q0=r=>{let{length:e}=r;return r.slice(0,e-e%2)},ev=[[/^\uFEFF/,()=>xc],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?Ih:xc)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+Ih}],[/[\\$.|*+(){^]/g,r=>`\\${r}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(r,e,t)=>e+6<t.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(r,e,t)=>{let i=t.replace(/\\\*/g,"[^\\/]*");return e+i}],[/\\\\\\(?=[$.|*+(){^])/g,()=>wc],[/\\\\/g,()=>wc],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,i,n)=>e===wc?`\\[${t}${Q0(i)}${n}`:n==="]"&&i.length%2===0?`[${Z0(t)}${i}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`]],tv=/(^|\\\/)?\\\*$/,Bn="regex",po="checkRegex",Lh="_",rv={[Bn](r,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[po](r,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},iv=r=>ev.reduce((e,[t,i])=>e.replace(t,i.bind(r)),r),go=r=>typeof r=="string",nv=r=>r&&go(r)&&!H0.test(r)&&!V0.test(r)&&r.indexOf("#")!==0,sv=r=>r.split(G0).filter(Boolean),Sc=class{constructor(e,t,i,n,s,a){this.pattern=e,this.mark=t,this.negative=s,tn(this,"body",i),tn(this,"ignoreCase",n),tn(this,"regexPrefix",a)}get regex(){let e=Lh+Bn;return this[e]?this[e]:this._make(Bn,e)}get checkRegex(){let e=Lh+po;return this[e]?this[e]:this._make(po,e)}_make(e,t){let i=this.regexPrefix.replace(tv,rv[e]),n=this.ignoreCase?new RegExp(i,"i"):new RegExp(i);return tn(this,t,n)}},ov=({pattern:r,mark:e},t)=>{let i=!1,n=r;n.indexOf("!")===0&&(i=!0,n=n.substr(1)),n=n.replace(z0,"!").replace($0,"#");let s=iv(n);return new Sc(r,e,n,t,i,s)},Tc=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[Fh]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(go(e)&&(e={pattern:e}),nv(e.pattern)){let t=ov(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,Nh(go(e)?sv(e):e).forEach(this._add,this),this._added}test(e,t,i){let n=!1,s=!1,a;this._rules.forEach(u=>{let{negative:d}=u;s===d&&n!==s||d&&!n&&!s&&!t||!u[i].test(e)||(n=!d,s=d,a=d?W0:u)});let c={ignored:n,unignored:s};return a&&(c.rule=a),c}},av=(r,e)=>{throw new e(r)},Rr=(r,e,t)=>go(r)?r?Rr.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),Bh=r=>Y0.test(r);Rr.isNotRelative=Bh;Rr.convert=r=>r;var Cc=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:i=!1}={}){tn(this,Fh,!0),this._rules=new Tc(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,n){let s=e&&Rr.convert(e);return Rr(s,e,this._strictPathCheck?av:Dh),this._t(s,t,i,n)}checkIgnore(e){if(!X0.test(e))return this.test(e);let t=e.split(en).filter(Boolean);if(t.pop(),t.length){let i=this._t(t.join(en)+en,this._testCache,!0,t);if(i.ignored)return i}return this._rules.test(e,!1,po)}_t(e,t,i,n){if(e in t)return t[e];if(n||(n=e.split(en).filter(Boolean)),n.pop(),!n.length)return t[e]=this._rules.test(e,i,Bn);let s=this._t(n.join(en)+en,t,i,n);return t[e]=s.ignored?s:this._rules.test(e,i,Bn)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return Nh(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},kc=r=>new Cc(r),cv=r=>Rr(r&&Rr.convert(r),r,Dh),jh=()=>{let r=t=>/^\\\\\?\\/.test(t)||/["<>|\u0000-\u001F]+/u.test(t)?t:t.replace(/\\/g,"/");Rr.convert=r;let e=/^[a-z]:\//i;Rr.isNotRelative=t=>e.test(t)||Bh(t)};typeof process<"u"&&process.platform==="win32"&&jh();mo.exports=kc;kc.default=kc;mo.exports.isPathValid=cv;tn(mo.exports,Symbol.for("setupWindows"),jh)});var qh=M(Ut=>{"use strict";var fv=Ut&&Ut.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),uv=Ut&&Ut.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Uh=Ut&&Ut.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[i.length]=n);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),n=0;n<i.length;n++)i[n]!=="default"&&fv(t,e,i[n]);return uv(t,e),t}})(),lv=Ut&&Ut.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ut,"__esModule",{value:!0});Ut.FileListService=void 0;var rn=Uh(require("path")),Pc=Uh(require("fs/promises")),hv=lv(Oc()),Ac=Sr(),dv=["node_modules",".pnpm","vendor",".git","dist","build","out",".next",".nuxt",".output",".cache",".turbo",".idea",".vscode",".DS_Store","Thumbs.db"],Rc=class{ignoreFilter;workspaceRoot;onResponseCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,hv.default)(),this.ignoreFilter.add(dv),this.workspaceRoot&&this.loadGitignore(),this.logger.info("FileListService initialized",t||"null")}async loadGitignore(){if(!this.workspaceRoot)return;let e=rn.join(this.workspaceRoot,".gitignore");try{let t=await Pc.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 Pc.readdir(e,{withFileTypes:!0}),n=[];for(let s of i){let a=t==="."||t===""?s.name:rn.join(t,s.name);if(this.shouldHide(a,s.isDirectory()))continue;let c=rn.join(e,s.name),u={name:s.name,path:a,type:s.isDirectory()?Ac.FileEntryType.DIRECTORY:Ac.FileEntryType.FILE};if(!s.isDirectory())try{let d=await Pc.stat(c);u.size=d.size,u.modified=d.mtime.toISOString()}catch{}n.push(u)}return n.sort((s,a)=>s.type!==a.type?s.type===Ac.FileEntryType.DIRECTORY?-1:1:s.name.localeCompare(a.name))}shouldHide(e,t){let i=e.split(rn.sep).join("/"),n=t?`${i}/`:i;return this.ignoreFilter.ignores(n)}resolvePath(e){if(!this.workspaceRoot)throw new Error("No workspace root");if(e==="."||e==="")return this.workspaceRoot;let t=rn.resolve(this.workspaceRoot,e);if(t!==this.workspaceRoot&&!t.startsWith(this.workspaceRoot+rn.sep))throw new Error("Path outside workspace");return t}sendResponse(e){this.onResponseCallback?.(e)}dispose(){this.onResponseCallback=null}};Ut.FileListService=Rc});var Wh=M(hr=>{"use strict";var pv=hr&&hr.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),gv=hr&&hr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Kh=hr&&hr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[i.length]=n);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),n=0;n<i.length;n++)i[n]!=="default"&&pv(t,e,i[n]);return gv(t,e),t}})();Object.defineProperty(hr,"__esModule",{value:!0});hr.FileTrackerService=void 0;var Ic=Kh(require("path")),Si=Kh(require("fs/promises")),mv=require("child_process"),yv=require("util"),Gt=Sr(),Lc=(0,yv.promisify)(mv.execFile),Nc={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},Mc=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(n){this.logger.error("Error parsing tool calls",n)}}async parseToolCalls(e,t){let i=this.stripAnsi(t),n=i.match(Nc.toolStart);if(n){let a=n[1],c=n[2],u=`${a}_${Date.now()}_${c}`;this.pendingToolCalls.has(u)||await this.handleToolStart(e,u,a,{file_path:c})}let s=i.match(Nc.toolSuccess);if(s){let a=s[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(Nc.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,n){if(!this.isFileModifyingTool(i))return;let s=this.extractFilePath(i,n);if(!s)return;let a=this.resolveFilePath(s),c={toolId:t,toolName:i,filePath:s,timestamp:new Date().toISOString()};this.pendingToolCalls.set(t,c);let u;try{u=await Si.readFile(a,"utf-8")}catch{u=void 0}let d={path:s,changeType:u===void 0?Gt.FileChangeType.CREATE:Gt.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,n){if(!this.isFileModifyingTool(i)||!this.pendingToolCalls.get(t))return;if(this.pendingToolCalls.delete(t),n==="error"){let p=this.trackedFiles.get(e)||[],m=p.findIndex(_=>_.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 Si.stat(u);c.size=p.size}catch{c.changeType=Gt.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),n=this.getViewableMimeType(t.path);if(n&&this.onFileViewTransferCallback){try{let a=await Si.readFile(i),c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:n};this.onFileViewTransferCallback(e,Buffer.from(a),c)}catch(a){let c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:n,error:a instanceof Error?a.message:"Unknown error"};this.onFileViewTransferCallback(e,Buffer.alloc(0),c)}return}let s;try{t.type===Gt.FileViewType.CONTENT?s=await this.getFileContent(t,i):s=await this.getFileDiff(e,t,i)}catch(a){s={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:s.type===Gt.FileViewType.CONTENT?"content":"diff",language:s.language,truncated:s.truncated,error:s.error},c=Buffer.from(s.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,n=await Si.stat(t),s=await Si.readFile(t,"utf-8"),a=!1,c=s;return s.length>i&&(c=s.slice(0,i),a=!0),{requestId:e.requestId,path:e.path,type:Gt.FileViewType.CONTENT,content:c,language:(0,Gt.getLanguageFromPath)(e.path),size:n.size,truncated:a}}async getFileDiff(e,t,i){let n=t.diffBase||Gt.DiffBase.GIT,s;return n===Gt.DiffBase.GIT?s=await this.getGitDiff(i):s=await this.getPreviousDiff(e,t.path,i),{requestId:t.requestId,path:t.path,type:Gt.FileViewType.DIFF,content:s,language:"diff"}}async getGitDiff(e){if(!this.workspaceRoot)throw new Error("No workspace root");try{let{stdout:t}=await Lc("git",["diff","--cached","--",e],{cwd:this.workspaceRoot});if(t.trim())return t;let{stdout:i}=await Lc("git",["diff","--",e],{cwd:this.workspaceRoot});if(i.trim())return i;let{stdout:n}=await Lc("git",["status","--porcelain","--",e],{cwd:this.workspaceRoot});if(n.startsWith("??")||n.startsWith("A ")){let a=(await Si.readFile(e,"utf-8")).split(`
28
+ `+t)}function Ei(r,e,t,i,n,s){if(r.listenerCount("wsClientError")){let a=new Error(n);Error.captureStackTrace(a,Ei),r.emit("wsClientError",a,t,e)}else Ln(t,i,n,s)}});var th=M((aw,eh)=>{"use strict";var Rr=Xs();Rr.createWebSocketStream=Hl();Rr.Server=Ql();Rr.Receiver=Ra();Rr.Sender=La();Rr.WebSocket=Rr;Rr.WebSocketServer=Rr.Server;eh.exports=Rr});var Ha=M(Yr=>{"use strict";var d_=Yr&&Yr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Yr,"__esModule",{value:!0});Yr.WS=Yr.BaseWS=void 0;var p_=Tn(),rh=gi(),g_=Di(),qa=pi(),m_=d_(Ft()),y_=(0,m_.default)("engine.io-client:websocket"),ih=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Zs=class extends p_.Transport{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,i=ih?{}:(0,rh.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(n){return this.emitReserved("error",n)}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],n=t===e.length-1;(0,g_.encodePacket)(i,this.supportsBinary,s=>{try{this.doWrite(i,s)}catch{y_("websocket closed before onclose event")}n&&(0,qa.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,rh.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}};Yr.BaseWS=Zs;var Ka=qa.globalThisShim.WebSocket||qa.globalThisShim.MozWebSocket,Wa=class extends Zs{createSocket(e,t,i){return ih?new Ka(e,t,i):t?new Ka(e,t):new Ka(e)}doWrite(e,t){this.ws.send(t)}};Yr.WS=Wa});var za=M(fr=>{"use strict";var __=fr&&fr.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),b_=fr&&fr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),v_=fr&&fr.__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)&&__(e,r,t);return b_(e,r),e};Object.defineProperty(fr,"__esModule",{value:!0});fr.WS=void 0;var E_=v_(th()),w_=Ha(),Va=class extends w_.BaseWS{createSocket(e,t,i){var n;if(!((n=this.socket)===null||n===void 0)&&n._cookieJar){i.headers=i.headers||{},i.headers.cookie=typeof i.headers.cookie=="string"?[i.headers.cookie]:i.headers.cookie||[];for(let[s,a]of this.socket._cookieJar.cookies)i.headers.cookie.push(`${s}=${a.value}`)}return new E_.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)}};fr.WS=Va});var Ga=M(Xi=>{"use strict";var x_=Xi&&Xi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Xi,"__esModule",{value:!0});Xi.WT=void 0;var S_=Tn(),T_=pi(),nh=Di(),C_=x_(Ft()),Nn=(0,C_.default)("engine.io-client:webtransport"),$a=class extends S_.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(()=>{Nn("transport closed gracefully"),this.onClose()}).catch(e=>{Nn("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=(0,nh.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=e.readable.pipeThrough(t).getReader(),n=(0,nh.createPacketEncoderStream)();n.readable.pipeTo(e.writable),this._writer=n.writable.getWriter();let s=()=>{i.read().then(({done:c,value:u})=>{if(c){Nn("session is closed");return}Nn("received chunk: %o",u),this.onPacket(u),s()}).catch(c=>{Nn("an error occurred while reading: %s",c)})};s();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],n=t===e.length-1;this._writer.write(i).then(()=>{n&&(0,T_.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};Xi.WT=$a});var Ya=M(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});Qs.transports=void 0;var k_=ba(),O_=za(),P_=Ga();Qs.transports={websocket:O_.WS,webtransport:P_.WT,polling:k_.XHR}});var Ja=M(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.parse=I_;var R_=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,A_=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function I_(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 n=R_.exec(r||""),s={},a=14;for(;a--;)s[A_[a]]=n[a]||"";return t!=-1&&i!=-1&&(s.source=e,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=L_(s,s.path),s.queryKey=N_(s,s.query),s}function L_(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 N_(r,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(i,n,s){n&&(t[n]=s)}),t}});var tc=M(ur=>{"use strict";var M_=ur&&ur.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ur,"__esModule",{value:!0});ur.Socket=ur.SocketWithUpgrade=ur.SocketWithoutUpgrade=void 0;var F_=Ya(),sh=gi(),D_=aa(),oh=Ja(),B_=di(),ah=Di(),Za=pi(),j_=M_(Ft()),De=(0,j_.default)("engine.io-client:socket"),Qa=typeof addEventListener=="function"&&typeof removeEventListener=="function",Mn=[];Qa&&addEventListener("offline",()=>{De("closing %d connection(s) because the network was lost",Mn.length),Mn.forEach(r=>r())},!1);var wi=class r extends B_.Emitter{constructor(e,t){if(super(),this.binaryType=Za.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,oh.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,oh.parse)(t.host).host);(0,sh.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 n=i.prototype.name;this.transports.push(n),this._transportsByName[n]=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,D_.decode)(this.opts.query)),Qa&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(De("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Mn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,Za.createCookieJar)()),this._open()}createTransport(e){De('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=ah.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 De("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){De("setting transport %s",e.name),this.transport&&(De("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(){De("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(De('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 De('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();De("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 n=this.writeBuffer[i].data;if(n&&(t+=(0,sh.byteLength)(n)),i>0&&t>this._maxPayload)return De("only send %d out of %d packets",i,this.writeBuffer.length),this.writeBuffer.slice(0,i);t+=2}return De("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&&(De("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,Za.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,n){if(typeof t=="function"&&(n=t,t=void 0),typeof i=="function"&&(n=i,i=null),this.readyState==="closing"||this.readyState==="closed")return;i=i||{},i.compress=i.compress!==!1;let s={type:e,data:t,options:i};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),n&&this.once("flush",n),this.flush()}close(){let e=()=>{this._onClose("forced close"),De("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(De("socket error %j",e),r.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return De("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(De('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Qa&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let i=Mn.indexOf(this._offlineEventListener);i!==-1&&(De("removing listener for the 'offline' event"),Mn.splice(i,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};ur.SocketWithoutUpgrade=wi;wi.protocol=ah.protocol;var eo=class extends wi{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){De("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){De('probing transport "%s"',e);let t=this.createTransport(e),i=!1;wi.priorWebsocketSuccess=!1;let n=()=>{i||(De('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(De('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;wi.priorWebsocketSuccess=t.name==="websocket",De('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{i||this.readyState!=="closed"&&(De("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{De('probe transport "%s" failed',e);let _=new Error("probe error");_.transport=t.name,this.emitReserved("upgradeError",_)}}))};function s(){i||(i=!0,p(),t.close(),t=null)}let a=m=>{let _=new Error("probe error: "+m);_.transport=t.name,s(),De('probe transport "%s" failed because of error: %s',e,m),this.emitReserved("upgradeError",_)};function c(){a("transport closed")}function u(){a("socket closed")}function d(m){t&&m.name!==t.name&&(De('"%s" works - aborting "%s"',m.name,t.name),s())}let p=()=>{t.removeListener("open",n),t.removeListener("error",a),t.removeListener("close",c),this.off("close",u),this.off("upgrading",d)};t.once("open",n),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}};ur.SocketWithUpgrade=eo;var ec=class extends eo{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(n=>F_.transports[n]).filter(n=>!!n)),super(e,i)}};ur.Socket=ec});var ch=M(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.Fetch=void 0;var U_=pa(),rc=class extends U_.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,n=new Headers(this.opts.extraHeaders);return i&&n.set("content-type","text/plain;charset=UTF-8"),(t=this.socket._cookieJar)===null||t===void 0||t.appendCookies(n),fetch(this.uri(),{method:i?"POST":"GET",body:i?e:null,headers:n,credentials:this.opts.withCredentials?"include":"omit"}).then(s=>{var a;return(a=this.socket._cookieJar)===null||a===void 0||a.parseCookies(s.headers.getSetCookie()),s})}};to.Fetch=rc});var ro=M(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.WebTransport=Oe.WebSocket=Oe.NodeWebSocket=Oe.XHR=Oe.NodeXHR=Oe.Fetch=Oe.nextTick=Oe.parse=Oe.installTimerFunctions=Oe.transports=Oe.TransportError=Oe.Transport=Oe.protocol=Oe.SocketWithUpgrade=Oe.SocketWithoutUpgrade=Oe.Socket=void 0;var fh=tc();Object.defineProperty(Oe,"Socket",{enumerable:!0,get:function(){return fh.Socket}});var uh=tc();Object.defineProperty(Oe,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return uh.SocketWithoutUpgrade}});Object.defineProperty(Oe,"SocketWithUpgrade",{enumerable:!0,get:function(){return uh.SocketWithUpgrade}});Oe.protocol=fh.Socket.protocol;var lh=Tn();Object.defineProperty(Oe,"Transport",{enumerable:!0,get:function(){return lh.Transport}});Object.defineProperty(Oe,"TransportError",{enumerable:!0,get:function(){return lh.TransportError}});var K_=Ya();Object.defineProperty(Oe,"transports",{enumerable:!0,get:function(){return K_.transports}});var q_=gi();Object.defineProperty(Oe,"installTimerFunctions",{enumerable:!0,get:function(){return q_.installTimerFunctions}});var W_=Ja();Object.defineProperty(Oe,"parse",{enumerable:!0,get:function(){return W_.parse}});var H_=pi();Object.defineProperty(Oe,"nextTick",{enumerable:!0,get:function(){return H_.nextTick}});var V_=ch();Object.defineProperty(Oe,"Fetch",{enumerable:!0,get:function(){return V_.Fetch}});var z_=ba();Object.defineProperty(Oe,"NodeXHR",{enumerable:!0,get:function(){return z_.XHR}});var $_=ya();Object.defineProperty(Oe,"XHR",{enumerable:!0,get:function(){return $_.XHR}});var G_=za();Object.defineProperty(Oe,"NodeWebSocket",{enumerable:!0,get:function(){return G_.WS}});var Y_=Ha();Object.defineProperty(Oe,"WebSocket",{enumerable:!0,get:function(){return Y_.WS}});var X_=Ga();Object.defineProperty(Oe,"WebTransport",{enumerable:!0,get:function(){return X_.WT}})});var dh=M(Fn=>{"use strict";var J_=Fn&&Fn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Fn,"__esModule",{value:!0});Fn.url=e0;var Z_=ro(),Q_=J_(Ft()),hh=(0,Q_.default)("socket.io-client:url");function e0(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)||(hh("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),hh("parse %s",r),i=(0,Z_.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 s=i.host.indexOf(":")!==-1?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+s+":"+i.port+e,i.href=i.protocol+"://"+s+(t&&t.port===i.port?"":":"+i.port),i}});var ic=M(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.isBinary=gh;no.hasBinary=io;var t0=typeof ArrayBuffer=="function",r0=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,ph=Object.prototype.toString,i0=typeof Blob=="function"||typeof Blob<"u"&&ph.call(Blob)==="[object BlobConstructor]",n0=typeof File=="function"||typeof File<"u"&&ph.call(File)==="[object FileConstructor]";function gh(r){return t0&&(r instanceof ArrayBuffer||r0(r))||i0&&r instanceof Blob||n0&&r instanceof File}function io(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,i=r.length;t<i;t++)if(io(r[t]))return!0;return!1}if(gh(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return io(r.toJSON(),!0);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&io(r[t]))return!0;return!1}});var mh=M(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});so.deconstructPacket=o0;so.reconstructPacket=a0;var s0=ic();function o0(r){let e=[],t=r.data,i=r;return i.data=nc(t,e),i.attachments=e.length,{packet:i,buffers:e}}function nc(r,e){if(!r)return r;if((0,s0.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]=nc(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]=nc(r[i],e));return t}return r}function a0(r,e){return r.data=sc(r.data,e),delete r.attachments,r}function sc(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]=sc(r[t],e);else if(typeof r=="object")for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=sc(r[t],e));return r}});var ao=M(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.Decoder=zt.Encoder=zt.PacketType=zt.protocol=void 0;zt.isPacketValid=p0;var c0=di(),yh=mh(),_h=ic(),f0=Ft(),oc=(0,f0.default)("socket.io-parser"),bh=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];zt.protocol=5;var Fe;(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"})(Fe||(zt.PacketType=Fe={}));var ac=class{constructor(e){this.replacer=e}encode(e){return oc("encoding packet %j",e),(e.type===Fe.EVENT||e.type===Fe.ACK)&&(0,_h.hasBinary)(e)?this.encodeAsBinary({type:e.type===Fe.EVENT?Fe.BINARY_EVENT:Fe.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===Fe.BINARY_EVENT||e.type===Fe.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)),oc("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=(0,yh.deconstructPacket)(e),i=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(i),n}};zt.Encoder=ac;var cc=class r extends c0.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===Fe.BINARY_EVENT;i||t.type===Fe.BINARY_ACK?(t.type=i?Fe.EVENT:Fe.ACK,this.reconstructor=new fc(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,_h.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(Fe[i.type]===void 0)throw new Error("unknown packet type "+i.type);if(i.type===Fe.BINARY_EVENT||i.type===Fe.BINARY_ACK){let s=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);let a=e.substring(s,t);if(a!=Number(a)||e.charAt(t)!=="-")throw new Error("Illegal attachments");i.attachments=Number(a)}if(e.charAt(t+1)==="/"){let s=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););i.nsp=e.substring(s,t)}else i.nsp="/";let n=e.charAt(t+1);if(n!==""&&Number(n)==n){let s=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(s,t+1))}if(e.charAt(++t)){let s=this.tryParse(e.substr(t));if(r.isPayloadValid(i.type,s))i.data=s;else throw new Error("invalid payload")}return oc("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 Fe.CONNECT:return oo(t);case Fe.DISCONNECT:return t===void 0;case Fe.CONNECT_ERROR:return typeof t=="string"||oo(t);case Fe.EVENT:case Fe.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&bh.indexOf(t[0])===-1);case Fe.ACK:case Fe.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};zt.Decoder=cc;var fc=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,yh.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function u0(r){return typeof r=="string"}var l0=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function h0(r){return r===void 0||l0(r)}function oo(r){return Object.prototype.toString.call(r)==="[object Object]"}function d0(r,e){switch(r){case Fe.CONNECT:return e===void 0||oo(e);case Fe.DISCONNECT:return e===void 0;case Fe.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&bh.indexOf(e[0])===-1);case Fe.ACK:return Array.isArray(e);case Fe.CONNECT_ERROR:return typeof e=="string"||oo(e);default:return!1}}function p0(r){return u0(r.nsp)&&h0(r.id)&&d0(r.type,r.data)}});var lc=M(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.on=g0;function g0(r,e,t){return r.on(e,t),function(){r.off(e,t)}}});var dc=M(Ji=>{"use strict";var m0=Ji&&Ji.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ji,"__esModule",{value:!0});Ji.Socket=void 0;var $t=ao(),co=lc(),y0=di(),_0=m0(Ft()),et=(0,_0.default)("socket.io-client:socket"),b0=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),hc=class extends y0.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,co.on)(e,"open",this.onopen.bind(this)),(0,co.on)(e,"packet",this.onpacket.bind(this)),(0,co.on)(e,"error",this.onerror.bind(this)),(0,co.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,n,s;if(b0.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:$t.PacketType.EVENT,data:t};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let p=this.ids++;et("emitting packet with ack id %d",p);let m=t.pop();this._registerAckCallback(p,m),a.id=p}let c=(n=(i=this.io.engine)===null||i===void 0?void 0:i.transport)===null||n===void 0?void 0:n.writable,u=this.connected&&!(!((s=this.io.engine)===null||s===void 0)&&s._hasPingExpired());return this.flags.volatile&&!c?et("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 n=(i=this.flags.timeout)!==null&&i!==void 0?i:this._opts.ackTimeout;if(n===void 0){this.acks[e]=t;return}let s=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===e&&(et("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(c,1));et("event with ack id %d has timed out after %d ms",e,n),t.call(this,new Error("operation has timed out"))},n),a=(...c)=>{this.io.clearTimeoutFn(s),t.apply(this,c)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((i,n)=>{let s=(a,c)=>a?n(a):i(c);s.withError=!0,t.push(s),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((n,...s)=>i!==this._queue[0]?et("packet [%d] already acknowledged",i.id):(n!==null?i.tryCount>this._opts.retries&&(et("packet [%d] is discarded after %d tries",i.id,i.tryCount),this._queue.shift(),t&&t(n)):(et("packet [%d] was successfully sent",i.id),this._queue.shift(),t&&t(null,...s)),i.pending=!1,this._drainQueue())),this._queue.push(i),this._drainQueue()}_drainQueue(e=!1){if(et("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){et("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,et("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(){et("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:$t.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){et("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 $t.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 $t.PacketType.EVENT:case $t.PacketType.BINARY_EVENT:this.onevent(e);break;case $t.PacketType.ACK:case $t.PacketType.BINARY_ACK:this.onack(e);break;case $t.PacketType.DISCONNECT:this.ondisconnect();break;case $t.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||[];et("emitting event %j",t),e.id!=null&&(et("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(...n){i||(i=!0,et("sending ack %j",n),t.packet({type:$t.PacketType.ACK,id:e,data:n}))}}onack(e){let t=this.acks[e.id];if(typeof t!="function"){et("bad ack %s",e.id);return}delete this.acks[e.id],et("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){et("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(){et("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&&(et("performing disconnect (%s)",this.nsp),this.packet({type:$t.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)}}};Ji.Socket=hc});var vh=M(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.Backoff=Zi;function Zi(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}Zi.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};Zi.prototype.reset=function(){this.attempts=0};Zi.prototype.setMin=function(r){this.ms=r};Zi.prototype.setMax=function(r){this.max=r};Zi.prototype.setJitter=function(r){this.jitter=r}});var Eh=M(jt=>{"use strict";var v0=jt&&jt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),E0=jt&&jt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),w0=jt&&jt.__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)&&v0(e,r,t);return E0(e,r),e},x0=jt&&jt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(jt,"__esModule",{value:!0});jt.Manager=void 0;var gc=ro(),S0=dc(),T0=w0(ao()),xi=lc(),C0=vh(),k0=di(),O0=x0(Ft()),ft=(0,O0.default)("socket.io-client:manager"),mc=class extends k0.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,gc.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 C0.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 n=t.parser||T0;this.encoder=new n.Encoder,this.decoder=new n.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(ft("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;ft("opening %s",this.uri),this.engine=new gc.Socket(this.uri,this.opts);let t=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;let n=(0,xi.on)(t,"open",function(){i.onopen(),e&&e()}),s=c=>{ft("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},a=(0,xi.on)(t,"error",s);if(this._timeout!==!1){let c=this._timeout;ft("connect attempt will timeout after %d",c);let u=this.setTimeoutFn(()=>{ft("connect attempt timed out after %d",c),n(),s(new Error("timeout")),t.close()},c);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(n),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){ft("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push((0,xi.on)(e,"ping",this.onping.bind(this)),(0,xi.on)(e,"data",this.ondata.bind(this)),(0,xi.on)(e,"error",this.onerror.bind(this)),(0,xi.on)(e,"close",this.onclose.bind(this)),(0,xi.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,gc.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){ft("error",e),this.emitReserved("error",e)}socket(e,t){let i=this.nsps[e];return i?this._autoConnect&&!i.active&&i.connect():(i=new S0.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){ft("socket %s is still active, skipping close",i);return}this._close()}_packet(e){ft("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(){ft("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){ft("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var i;ft("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)ft("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();ft("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let i=this.setTimeoutFn(()=>{e.skipReconnect||(ft("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(n=>{n?(ft("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",n)):(ft("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)}};jt.Manager=mc});var Th=M((Be,Sh)=>{"use strict";var P0=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=Si;Be.connect=Si;Be.default=Si;var R0=dh(),fo=Eh();Object.defineProperty(Be,"Manager",{enumerable:!0,get:function(){return fo.Manager}});var xh=dc();Object.defineProperty(Be,"Socket",{enumerable:!0,get:function(){return xh.Socket}});var A0=P0(Ft()),wh=(0,A0.default)("socket.io-client"),Dn={};function Si(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};let t=(0,R0.url)(r,e.path||"/socket.io"),i=t.source,n=t.id,s=t.path,a=Dn[n]&&s in Dn[n].nsps,c=e.forceNew||e["force new connection"]||e.multiplex===!1||a,u;return c?(wh("ignoring socket cache for %s",i),u=new fo.Manager(i,e)):(Dn[n]||(wh("new io instance for %s",i),Dn[n]=new fo.Manager(i,e)),u=Dn[n]),t.query&&!e.query&&(e.query=t.queryKey),u.socket(t.path,e)}Object.assign(Si,{Manager:fo.Manager,Socket:xh.Socket,io:Si,connect:Si});var I0=ao();Object.defineProperty(Be,"protocol",{enumerable:!0,get:function(){return I0.protocol}});var Qi=ro();Object.defineProperty(Be,"Fetch",{enumerable:!0,get:function(){return Qi.Fetch}});Object.defineProperty(Be,"NodeXHR",{enumerable:!0,get:function(){return Qi.NodeXHR}});Object.defineProperty(Be,"XHR",{enumerable:!0,get:function(){return Qi.XHR}});Object.defineProperty(Be,"NodeWebSocket",{enumerable:!0,get:function(){return Qi.NodeWebSocket}});Object.defineProperty(Be,"WebSocket",{enumerable:!0,get:function(){return Qi.WebSocket}});Object.defineProperty(Be,"WebTransport",{enumerable:!0,get:function(){return Qi.WebTransport}});Sh.exports=Si});var _c=M(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.InputStreamReceiver=void 0;var L0=64,N0=30,M0=4,F0=256,D0=16,yc=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??L0),this.ackThrottleMs=Math.max(0,i.ackThrottleMs??N0)}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 n=Math.max(this.windowSize*M0,F0);e-this.lastAppliedSeq>n||this.maybeResend(this.lastAppliedSeq+1)}maybeResend(e){if(e===this.lastResendFrom){if(++this.resendSuppressed<D0)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)}};uo.InputStreamReceiver=yc});var Ph=M(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.WebSocketService=void 0;var B0=Th(),Ch=Sr(),kh=fs(),Oh=os(),j0=_c(),bc=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;metaSessionEstablishedHandler=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;RESUME_WATCHDOG_INTERVAL=5e3;RESUME_WATCHDOG_THRESHOLD=15e3;resumeWatchdogTimer=null;resumeWatchdogExpectedAt=0;isManualDisconnect=!1;reconnectAttempts=0;reconnectTimer=null;networkCheckTimer=null;isOnline=!0;lastNetworkCheck=0;rekeyingTerminals=new Set;outputBuffer=new Map;OUTPUT_BUFFER_MAX_SIZE=1e3;invalidSessionSignalAt=new Map;INVALID_SESSION_SIGNAL_THROTTLE_MS=5e3;attachedClientCount=0;RECONNECT_BASE_DELAY=1e3;RECONNECT_MAX_DELAY=3e4;RECONNECT_JITTER=.2;NETWORK_CHECK_INTERVAL=5e3;constructor(e,t,i,n,s,a,c="vscode",u=[]){this.authService=e,this.cryptoService=t,this.config=i,this.logger=n,this.notification=s,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,kh.getWsUrl)(this.config);this.logger.info("Connecting to WebSocket",t),this.statusChangeHandler?.("connecting");let i=await this.cryptoService.getPublicKey();return new Promise((n,s)=>{let a=Array.from(new Set([...Ch.DEFAULT_CLIENT_CAPABILITIES,...this.extraCapabilities]));this.socket=(0,B0.io)(`${t}/agent`,{auth:{token:e,protocolVersion:Ch.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,n()}),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||s(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("meta:keyExchange",async(c,u)=>{let{ok:d,isNew:p}=await this.cryptoService.handleMetaKeyExchange(c.clientIdentityPub),m=await this.cryptoService.getPublicKey()||void 0;u?.({ok:d,agentPublicKey:m}),d&&p&&this.metaSessionEstablishedHandler?.()}),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);if(!p){this.signalInvalidSession(void 0,c.terminalId),u?.({success:!1,error:"No E2E session"});return}u?.({success:!0,encrypted:p}),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.attachedClientCount=c.clientCount,this.clientAttachedHandler?.(c)}),this.socket.on("workspace:clientDetached",c=>{this.attachedClientCount=c.clientCount,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}onMetaSessionEstablished(e){this.metaSessionEstablishedHandler=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,n){this.socket?.connected&&this.socket.emit("agent:ptyResized",{instanceId:e,terminalId:t,cols:i,rows:n})}sendClaimControl(e,t,i,n){this.socket?.connected&&this.socket.emit("agent:claimControl",{instanceId:e,terminalId:t,cols:i,rows:n})}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 n=this.cryptoService.encryptOutput(t,i);if(!n){this.attachedClientCount>0&&this.signalInvalidSession(e,t);return}let s={instanceId:e,terminalId:t,encrypted:n};this.socket?.emit("terminal:output",s)}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:n}of t){let s=this.cryptoService.encryptOutput(e,n);if(!s){this.signalInvalidSession(i,e);continue}let a={instanceId:i,terminalId:e,encrypted:s};this.socket?.emit("terminal:output",a)}}}signalInvalidSession(e,t){let i=Date.now(),n=this.invalidSessionSignalAt.get(t)??0;i-n<this.INVALID_SESSION_SIGNAL_THROTTLE_MS||(this.invalidSessionSignalAt.set(t,i),this.logger.warn("E2E session invalid/missing \u2014 signaling clients to rekey",t),this.socket?.emit("crypto:invalidSession",{instanceId:e??this.instanceIdForTerminal(t),terminalId:t}))}instanceIdForTerminal(e){return this.inputReceivers.get(e)?.instanceId}async updateStatus(e){await this.emit("terminal:status",e)}sendTerminalEvent(e,t,i){let n={instanceId:e,terminalId:t,event:i};this.socket?.emit("terminal:event",n)}hasCapability(e){return this.negotiatedCapabilities.includes(e)}sendFileChangedEvent(e,t,i){let n={instanceId:e,terminalId:t,event:i};this.socket?.emit("file:changed",n)}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,Oh.generateCorrelationId)(),n=t&&typeof t=="object"&&!Array.isArray(t)?{...t,_cid:i}:t;return(0,Oh.runWithCorrelation)(i,()=>new Promise((s,a)=>{if(!this.socket?.connected){a(new Error("WebSocket not connected"));return}this.socket.emit(e,n,c=>{c.success?s(c):a(new Error(c.error||"Unknown error"))})}))}startHeartbeat(){this.stopHeartbeat(),this.lastPongTime=Date.now(),this.startResumeWatchdog(),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, forcing teardown + reconnect"),this.statusChangeHandler?.("error"),this.socket?.disconnect()},this.HEARTBEAT_TIMEOUT)},this.HEARTBEAT_INTERVAL)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.clearPongTimeout(),this.stopResumeWatchdog()}startResumeWatchdog(){this.stopResumeWatchdog(),this.resumeWatchdogExpectedAt=Date.now()+this.RESUME_WATCHDOG_INTERVAL,this.resumeWatchdogTimer=setTimeout(()=>this.onResumeWatchdogTick(),this.RESUME_WATCHDOG_INTERVAL)}onResumeWatchdogTick(){let e=Date.now(),t=e-this.resumeWatchdogExpectedAt;if(t>this.RESUME_WATCHDOG_THRESHOLD&&(this.logger.warn(`Resume detected (clock drift ${t}ms) - forcing liveness re-check`),!this.isManualDisconnect&&this.socket)){this.statusChangeHandler?.("error"),this.socket.disconnect();return}this.isManualDisconnect||(this.resumeWatchdogExpectedAt=e+this.RESUME_WATCHDOG_INTERVAL,this.resumeWatchdogTimer=setTimeout(()=>this.onResumeWatchdogTick(),this.RESUME_WATCHDOG_INTERVAL))}stopResumeWatchdog(){this.resumeWatchdogTimer&&(clearTimeout(this.resumeWatchdogTimer),this.resumeWatchdogTimer=null)}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),this.signalInvalidSession(e.instanceId,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,n){let s=this.inputReceivers.get(e);if(this.terminalActiveCheck&&!this.terminalActiveCheck(e))return s&&this.disposeInputStream(e),null;if(s&&s.receiver.streamId===t)return n&&(s.routeId=n),i&&(s.instanceId=i),s.receiver;if(s&&s.receiver.dispose(),!s&&this.inputReceivers.size>=this.MAX_INPUT_RECEIVERS)return this.logger.error("inputReceivers map at cap, dropping frame",e),null;let a=new j0.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:n??e,instanceId:i??""}),a}setTerminalActiveCheck(e){this.terminalActiveCheck=e}routeIdFor(e){return this.inputReceivers.get(e)?.routeId??e}sendInputAck(e,t,i){let n=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:ack",{instanceId:n,terminalId:e,streamId:t,ackSeq:i})}sendInputResend(e,t,i){let n=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:resend",{instanceId:n,terminalId:e,streamId:t,fromSeq:i})}sendInputResume(e){let t=this.inputReceivers.get(e);if(!t)return;let{streamId:i,lastAckSeq:n}=t.receiver.resumeState();this.socket?.emit("input:resume",{instanceId:t.instanceId,terminalId:e,streamId:i,lastAckSeq:n})}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,kh.getApiUrl)(this.config)}/health`,i=new AbortController,n=setTimeout(()=>i.abort(),5e3),s=await fetch(t,{method:"GET",signal:i.signal});return clearTimeout(n),this.logger.debug("Network check OK",String(s.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)}};lo.WebSocketService=bc});var Ah=M(lr=>{"use strict";var U0=lr&&lr.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),K0=lr&&lr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Ec=lr&&lr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[i.length]=n);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),n=0;n<i.length;n++)i[n]!=="default"&&U0(t,e,i[n]);return K0(t,e),t}})();Object.defineProperty(lr,"__esModule",{value:!0});lr.FileTransferService=void 0;var ho=Ec(require("fs")),q0=Ec(require("path")),Rh=Ec(require("crypto")),je=Sr(),vc=class{socket=null;activeTransfers=new Map;instanceId="";logger;fallbackDir;cryptoService=null;constructor(e,t="/tmp"){this.logger=e,this.fallbackDir=t}setCrypto(e){this.cryptoService=e}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,n,s){let a=ho.readFileSync(t),c=t.split("/").pop()||"file";return this.initAndSendChunks(e,a,c,{mimeType:this.getMimeType(c),requestId:s,onProgress:i,onComplete:n})}async sendBuffer(e,t,i,n,s){return this.initAndSendChunks(e,t,i,{mimeType:n,purpose:s?.purpose,viewMetadata:s?.viewMetadata,requestId:s?.requestId,onProgress:s?.onProgress,onComplete:s?.onComplete})}async initAndSendChunks(e,t,i,n){if(!this.socket)throw new Error("Socket not connected");let s=t.length,a=(0,je.calculateTotalChunks)(s),c=this.calculateChecksum(t),u=Rh.randomUUID(),d={id:u,terminalId:e,filename:i,size:s,totalChunks:a,direction:je.TransferDirection.DOWNLOAD,status:je.TransferStatus.PENDING,deliveredChunks:new Set,pendingChunks:new Map,checksum:c,checksumAlgorithm:"sha256",onProgress:n.onProgress?(m,_)=>n.onProgress(u,m,_):void 0,onComplete:n.onComplete?(m,_)=>n.onComplete(u,m,_):void 0,ackTimeouts:new Map};d.chunks=[];for(let m=0;m<a;m++){let _=m*je.CHUNK_SIZE,E=Math.min(_+je.CHUNK_SIZE,s);d.chunks.push(t.subarray(_,E))}this.activeTransfers.set(u,d);let p={transferId:u,terminalId:e,filename:i,size:s,totalChunks:a,mimeType:n.mimeType||"application/octet-stream",checksum:c,direction:je.TransferDirection.DOWNLOAD,instanceId:this.instanceId};return n.requestId&&(p.requestId=n.requestId),n.purpose&&(p.purpose=n.purpose),n.viewMetadata&&(p.viewMetadata=n.viewMetadata),new Promise((m,_)=>{this.socket.emit("file:init",p,E=>{E.accepted?(d.status=je.TransferStatus.ACTIVE,this.startSendingChunks(u),m(u)):(this.activeTransfers.delete(u),_(new Error(E.error||"Transfer rejected")))})})}async receiveFile(e,t,i,n,s,a,c,u="sha256",d,p){let m={id:e,terminalId:t,filename:i,filePath:c,size:n,totalChunks:s,direction:je.TransferDirection.UPLOAD,status:je.TransferStatus.ACTIVE,deliveredChunks:new Set,pendingChunks:new Map,chunks:new Array(s).fill(null),checksum:a,checksumAlgorithm:u,onProgress:d?(_,E)=>d(e,_,E):void 0,onComplete:p?(_,E)=>p(e,_,E):void 0,ackTimeouts:new Map};this.activeTransfers.set(e,m)}cancelTransfer(e,t){let i=this.activeTransfers.get(e);if(i){for(let n of i.ackTimeouts.values())clearTimeout(n);if(i.status=je.TransferStatus.CANCELLED,i.onComplete?.(!1,t),this.socket){let n={transferId:e,reason:t};this.socket.emit("file:cancel",n)}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 n of i.deliveredChunks)t.deliveredChunks.add(n);if(t.direction===je.TransferDirection.DOWNLOAD&&i.missingChunks){t.status=je.TransferStatus.ACTIVE;for(let n of i.missingChunks)this.sendChunk(t,n)}})}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 n=e.pendingChunks.get(t),s={seq:t,data:i,retries:n?n.retries:0,sentAt:Date.now()};e.pendingChunks.set(t,s);let a=this.cryptoService?.encryptFileChunk(e.terminalId,new Uint8Array(i.buffer,i.byteOffset,i.byteLength));if(!a){this.cancelTransfer(e.id,"No E2E session for file transfer");return}let c={transferId:e.id,seq:t,encrypted:a};this.socket.emit("file:chunk",c,d=>{d&&!d.success&&this.cancelTransfer(e.id,d.error||"Server rejected chunk")});let u=setTimeout(()=>{this.handleAckTimeout(e.id,t)},je.ACK_TIMEOUT_MS);e.ackTimeouts.set(t,u)}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 n=e.seq+je.WINDOW_SIZE;n<t.totalChunks&&!t.deliveredChunks.has(n)&&this.sendChunk(t,n),t.deliveredChunks.size===t.totalChunks&&this.finishSending(t)}handleAckTimeout(e,t){let i=this.activeTransfers.get(e);if(!i)return;let n=i.pendingChunks.get(t);n&&(n.retries<je.MAX_RETRIES?(n.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)return;let i=e.encrypted?this.cryptoService?.decryptFileChunk(t.terminalId,e.encrypted):null;if(!i){this.cancelTransfer(e.transferId,"Chunk decryption failed (no E2E session?)");return}if(t.chunks[e.seq]=Buffer.from(i),t.deliveredChunks.add(e.seq),this.socket){let n={transferId:e.transferId,seq:e.seq};this.socket.emit("file:chunk:ack",n)}t.onProgress?.(t.deliveredChunks.size,t.totalChunks),t.deliveredChunks.size===t.totalChunks&&this.finishReceiving(t)}finishReceiving(e){if(!e.chunks||!e.filePath)return;let t=Buffer.concat(e.chunks);if(this.calculateChecksum(t,e.checksumAlgorithm)!==e.checksum){e.status=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 n=q0.dirname(e.filePath);ho.existsSync(n)||ho.mkdirSync(n,{recursive:!0}),ho.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(n){let s=n instanceof Error?n.message:String(n);e.status=je.TransferStatus.FAILED,e.onComplete?.(!1,`Failed to save file: ${s}`),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!1,error:`Failed to save file: ${s}`})}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 n=`${e.targetPath||this.fallbackDir}/${e.filename}`;this.receiveFile(e.transferId,e.terminalId,e.filename,e.size,e.totalChunks,e.checksum,n,e.checksumAlgorithm||"sha256").then(()=>t({accepted:!0})).catch(s=>t({accepted:!1,error:s.message}))}calculateChecksum(e,t="sha256"){return t==="fnv1a"?this.fnv1aHash(e):Rh.createHash("sha256").update(e).digest("hex")}fnv1aHash(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e[n],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"}};lr.FileTransferService=vc});var Oc=M((kw,mo)=>{function Nh(r){return Array.isArray(r)?r:[r]}var W0=void 0,xc="",Ih=" ",wc="\\",H0=/^\s+$/,V0=/(?:[^\\]|^)\\$/,z0=/^\\!/,$0=/^\\#/,G0=/\r?\n/g,Y0=/^\.{0,2}\/|^\.{1,2}$/,X0=/\/$/,en="/",Mh="node-ignore";typeof Symbol<"u"&&(Mh=Symbol.for("node-ignore"));var Fh=Mh,tn=(r,e,t)=>(Object.defineProperty(r,e,{value:t}),t),J0=/([0-z])-([0-z])/g,Dh=()=>!1,Z0=r=>r.replace(J0,(e,t,i)=>t.charCodeAt(0)<=i.charCodeAt(0)?e:xc),Q0=r=>{let{length:e}=r;return r.slice(0,e-e%2)},eb=[[/^\uFEFF/,()=>xc],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?Ih:xc)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+Ih}],[/[\\$.|*+(){^]/g,r=>`\\${r}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(r,e,t)=>e+6<t.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(r,e,t)=>{let i=t.replace(/\\\*/g,"[^\\/]*");return e+i}],[/\\\\\\(?=[$.|*+(){^])/g,()=>wc],[/\\\\/g,()=>wc],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,i,n)=>e===wc?`\\[${t}${Q0(i)}${n}`:n==="]"&&i.length%2===0?`[${Z0(t)}${i}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`]],tb=/(^|\\\/)?\\\*$/,Bn="regex",po="checkRegex",Lh="_",rb={[Bn](r,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[po](r,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},ib=r=>eb.reduce((e,[t,i])=>e.replace(t,i.bind(r)),r),go=r=>typeof r=="string",nb=r=>r&&go(r)&&!H0.test(r)&&!V0.test(r)&&r.indexOf("#")!==0,sb=r=>r.split(G0).filter(Boolean),Sc=class{constructor(e,t,i,n,s,a){this.pattern=e,this.mark=t,this.negative=s,tn(this,"body",i),tn(this,"ignoreCase",n),tn(this,"regexPrefix",a)}get regex(){let e=Lh+Bn;return this[e]?this[e]:this._make(Bn,e)}get checkRegex(){let e=Lh+po;return this[e]?this[e]:this._make(po,e)}_make(e,t){let i=this.regexPrefix.replace(tb,rb[e]),n=this.ignoreCase?new RegExp(i,"i"):new RegExp(i);return tn(this,t,n)}},ob=({pattern:r,mark:e},t)=>{let i=!1,n=r;n.indexOf("!")===0&&(i=!0,n=n.substr(1)),n=n.replace(z0,"!").replace($0,"#");let s=ib(n);return new Sc(r,e,n,t,i,s)},Tc=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[Fh]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(go(e)&&(e={pattern:e}),nb(e.pattern)){let t=ob(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,Nh(go(e)?sb(e):e).forEach(this._add,this),this._added}test(e,t,i){let n=!1,s=!1,a;this._rules.forEach(u=>{let{negative:d}=u;s===d&&n!==s||d&&!n&&!s&&!t||!u[i].test(e)||(n=!d,s=d,a=d?W0:u)});let c={ignored:n,unignored:s};return a&&(c.rule=a),c}},ab=(r,e)=>{throw new e(r)},Ar=(r,e,t)=>go(r)?r?Ar.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),Bh=r=>Y0.test(r);Ar.isNotRelative=Bh;Ar.convert=r=>r;var Cc=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:i=!1}={}){tn(this,Fh,!0),this._rules=new Tc(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,n){let s=e&&Ar.convert(e);return Ar(s,e,this._strictPathCheck?ab:Dh),this._t(s,t,i,n)}checkIgnore(e){if(!X0.test(e))return this.test(e);let t=e.split(en).filter(Boolean);if(t.pop(),t.length){let i=this._t(t.join(en)+en,this._testCache,!0,t);if(i.ignored)return i}return this._rules.test(e,!1,po)}_t(e,t,i,n){if(e in t)return t[e];if(n||(n=e.split(en).filter(Boolean)),n.pop(),!n.length)return t[e]=this._rules.test(e,i,Bn);let s=this._t(n.join(en)+en,t,i,n);return t[e]=s.ignored?s:this._rules.test(e,i,Bn)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return Nh(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},kc=r=>new Cc(r),cb=r=>Ar(r&&Ar.convert(r),r,Dh),jh=()=>{let r=t=>/^\\\\\?\\/.test(t)||/["<>|\u0000-\u001F]+/u.test(t)?t:t.replace(/\\/g,"/");Ar.convert=r;let e=/^[a-z]:\//i;Ar.isNotRelative=t=>e.test(t)||Bh(t)};typeof process<"u"&&process.platform==="win32"&&jh();mo.exports=kc;kc.default=kc;mo.exports.isPathValid=cb;tn(mo.exports,Symbol.for("setupWindows"),jh)});var Kh=M(Ut=>{"use strict";var fb=Ut&&Ut.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),ub=Ut&&Ut.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Uh=Ut&&Ut.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[i.length]=n);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),n=0;n<i.length;n++)i[n]!=="default"&&fb(t,e,i[n]);return ub(t,e),t}})(),lb=Ut&&Ut.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ut,"__esModule",{value:!0});Ut.FileListService=void 0;var rn=Uh(require("path")),Pc=Uh(require("fs/promises")),hb=lb(Oc()),Rc=Sr(),db=["node_modules",".pnpm","vendor",".git","dist","build","out",".next",".nuxt",".output",".cache",".turbo",".idea",".vscode",".DS_Store","Thumbs.db"],Ac=class{ignoreFilter;workspaceRoot;onResponseCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,hb.default)(),this.ignoreFilter.add(db),this.workspaceRoot&&this.loadGitignore(),this.logger.info("FileListService initialized",t||"null")}async loadGitignore(){if(!this.workspaceRoot)return;let e=rn.join(this.workspaceRoot,".gitignore");try{let t=await Pc.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 Pc.readdir(e,{withFileTypes:!0}),n=[];for(let s of i){let a=t==="."||t===""?s.name:rn.join(t,s.name);if(this.shouldHide(a,s.isDirectory()))continue;let c=rn.join(e,s.name),u={name:s.name,path:a,type:s.isDirectory()?Rc.FileEntryType.DIRECTORY:Rc.FileEntryType.FILE};if(!s.isDirectory())try{let d=await Pc.stat(c);u.size=d.size,u.modified=d.mtime.toISOString()}catch{}n.push(u)}return n.sort((s,a)=>s.type!==a.type?s.type===Rc.FileEntryType.DIRECTORY?-1:1:s.name.localeCompare(a.name))}shouldHide(e,t){let i=e.split(rn.sep).join("/"),n=t?`${i}/`:i;return this.ignoreFilter.ignores(n)}resolvePath(e){if(!this.workspaceRoot)throw new Error("No workspace root");if(e==="."||e==="")return this.workspaceRoot;let t=rn.resolve(this.workspaceRoot,e);if(t!==this.workspaceRoot&&!t.startsWith(this.workspaceRoot+rn.sep))throw new Error("Path outside workspace");return t}sendResponse(e){this.onResponseCallback?.(e)}dispose(){this.onResponseCallback=null}};Ut.FileListService=Ac});var Wh=M(hr=>{"use strict";var pb=hr&&hr.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),gb=hr&&hr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),qh=hr&&hr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[i.length]=n);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),n=0;n<i.length;n++)i[n]!=="default"&&pb(t,e,i[n]);return gb(t,e),t}})();Object.defineProperty(hr,"__esModule",{value:!0});hr.FileTrackerService=void 0;var Ic=qh(require("path")),Ti=qh(require("fs/promises")),mb=require("child_process"),yb=require("util"),Gt=Sr(),Lc=(0,yb.promisify)(mb.execFile),Nc={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},Mc=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(n){this.logger.error("Error parsing tool calls",n)}}async parseToolCalls(e,t){let i=this.stripAnsi(t),n=i.match(Nc.toolStart);if(n){let a=n[1],c=n[2],u=`${a}_${Date.now()}_${c}`;this.pendingToolCalls.has(u)||await this.handleToolStart(e,u,a,{file_path:c})}let s=i.match(Nc.toolSuccess);if(s){let a=s[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(Nc.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,n){if(!this.isFileModifyingTool(i))return;let s=this.extractFilePath(i,n);if(!s)return;let a=this.resolveFilePath(s),c={toolId:t,toolName:i,filePath:s,timestamp:new Date().toISOString()};this.pendingToolCalls.set(t,c);let u;try{u=await Ti.readFile(a,"utf-8")}catch{u=void 0}let d={path:s,changeType:u===void 0?Gt.FileChangeType.CREATE:Gt.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,n){if(!this.isFileModifyingTool(i)||!this.pendingToolCalls.get(t))return;if(this.pendingToolCalls.delete(t),n==="error"){let p=this.trackedFiles.get(e)||[],m=p.findIndex(_=>_.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 Ti.stat(u);c.size=p.size}catch{c.changeType=Gt.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),n=this.getViewableMimeType(t.path);if(n&&this.onFileViewTransferCallback){try{let a=await Ti.readFile(i),c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:n};this.onFileViewTransferCallback(e,Buffer.from(a),c)}catch(a){let c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:n,error:a instanceof Error?a.message:"Unknown error"};this.onFileViewTransferCallback(e,Buffer.alloc(0),c)}return}let s;try{t.type===Gt.FileViewType.CONTENT?s=await this.getFileContent(t,i):s=await this.getFileDiff(e,t,i)}catch(a){s={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:s.type===Gt.FileViewType.CONTENT?"content":"diff",language:s.language,truncated:s.truncated,error:s.error},c=Buffer.from(s.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,n=await Ti.stat(t),s=await Ti.readFile(t,"utf-8"),a=!1,c=s;return s.length>i&&(c=s.slice(0,i),a=!0),{requestId:e.requestId,path:e.path,type:Gt.FileViewType.CONTENT,content:c,language:(0,Gt.getLanguageFromPath)(e.path),size:n.size,truncated:a}}async getFileDiff(e,t,i){let n=t.diffBase||Gt.DiffBase.GIT,s;return n===Gt.DiffBase.GIT?s=await this.getGitDiff(i):s=await this.getPreviousDiff(e,t.path,i),{requestId:t.requestId,path:t.path,type:Gt.FileViewType.DIFF,content:s,language:"diff"}}async getGitDiff(e){if(!this.workspaceRoot)throw new Error("No workspace root");try{let{stdout:t}=await Lc("git",["diff","--cached","--",e],{cwd:this.workspaceRoot});if(t.trim())return t;let{stdout:i}=await Lc("git",["diff","--",e],{cwd:this.workspaceRoot});if(i.trim())return i;let{stdout:n}=await Lc("git",["status","--porcelain","--",e],{cwd:this.workspaceRoot});if(n.startsWith("??")||n.startsWith("A ")){let a=(await Ti.readFile(e,"utf-8")).split(`
29
29
  `),c=Ic.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(`
30
- `)}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 Si.readFile(i,"utf-8")}catch{c=""}let u=(0,Gt.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 n of i.lines)switch(n.type){case"add":t.push(`+${n.content}`);break;case"remove":t.push(`-${n.content}`);break;case"context":t.push(` ${n.content}`);break}}return t.join(`
31
- `)}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){let t=this.workspaceRoot;if(!t)throw new Error("No workspace root configured");let i=Ic.resolve(t,e);if(i!==t&&!i.startsWith(t+Ic.sep))throw new Error("Path escapes workspace root");return i}dispose(){this.trackedFiles.clear(),this.pendingToolCalls.clear(),this.onFileChangedCallback=null,this.onFileViewTransferCallback=null}};hr.FileTrackerService=Mc});var Vh=M(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.InputStreamReceiver=tt.FileTrackerService=tt.FileListService=tt.FileTransferService=tt.WebSocketService=tt.isAnswerKeystroke=tt.StatusDetector=tt.AuthService=tt.CryptoService=void 0;var _v=gu();Object.defineProperty(tt,"CryptoService",{enumerable:!0,get:function(){return _v.CryptoService}});var vv=mu();Object.defineProperty(tt,"AuthService",{enumerable:!0,get:function(){return vv.AuthService}});var Hh=yu();Object.defineProperty(tt,"StatusDetector",{enumerable:!0,get:function(){return Hh.StatusDetector}});Object.defineProperty(tt,"isAnswerKeystroke",{enumerable:!0,get:function(){return Hh.isAnswerKeystroke}});var bv=Ph();Object.defineProperty(tt,"WebSocketService",{enumerable:!0,get:function(){return bv.WebSocketService}});var Ev=Rh();Object.defineProperty(tt,"FileTransferService",{enumerable:!0,get:function(){return Ev.FileTransferService}});var wv=qh();Object.defineProperty(tt,"FileListService",{enumerable:!0,get:function(){return wv.FileListService}});var xv=Wh();Object.defineProperty(tt,"FileTrackerService",{enumerable:!0,get:function(){return xv.FileTrackerService}});var Sv=_c();Object.defineProperty(tt,"InputStreamReceiver",{enumerable:!0,get:function(){return Sv.InputStreamReceiver}})});var jn=M(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.FP_LABEL=X.KX_ACK_LABEL=X.KX_SIGN_LABEL=X.concatBytes=X.fingerprintShortHex=X.fingerprintIdentityKey=X.buildKxAckCanonical=X.buildKxCanonical=X.verifySessionKey=X.signSessionKey=X.identityPublicFromSecret=X.generateIdentityKeyPair=X.InputStreamReceiver=X.FileTrackerService=X.FileListService=X.FileTransferService=X.WebSocketService=X.isAnswerKeystroke=X.StatusDetector=X.AuthService=X.CryptoService=X.getCurrentCorrelationId=X.runWithCorrelation=X.generateCorrelationId=X.getWsUrl=X.getApiUrl=X.CircularBuffer=X.formatLogLine=X.shouldLog=X.LOG_LEVELS=void 0;var Fc=Lf();Object.defineProperty(X,"LOG_LEVELS",{enumerable:!0,get:function(){return Fc.LOG_LEVELS}});Object.defineProperty(X,"shouldLog",{enumerable:!0,get:function(){return Fc.shouldLog}});Object.defineProperty(X,"formatLogLine",{enumerable:!0,get:function(){return Fc.formatLogLine}});var nn=Ff();Object.defineProperty(X,"CircularBuffer",{enumerable:!0,get:function(){return nn.CircularBuffer}});Object.defineProperty(X,"getApiUrl",{enumerable:!0,get:function(){return nn.getApiUrl}});Object.defineProperty(X,"getWsUrl",{enumerable:!0,get:function(){return nn.getWsUrl}});Object.defineProperty(X,"generateCorrelationId",{enumerable:!0,get:function(){return nn.generateCorrelationId}});Object.defineProperty(X,"runWithCorrelation",{enumerable:!0,get:function(){return nn.runWithCorrelation}});Object.defineProperty(X,"getCurrentCorrelationId",{enumerable:!0,get:function(){return nn.getCurrentCorrelationId}});var Ir=Vh();Object.defineProperty(X,"CryptoService",{enumerable:!0,get:function(){return Ir.CryptoService}});Object.defineProperty(X,"AuthService",{enumerable:!0,get:function(){return Ir.AuthService}});Object.defineProperty(X,"StatusDetector",{enumerable:!0,get:function(){return Ir.StatusDetector}});Object.defineProperty(X,"isAnswerKeystroke",{enumerable:!0,get:function(){return Ir.isAnswerKeystroke}});Object.defineProperty(X,"WebSocketService",{enumerable:!0,get:function(){return Ir.WebSocketService}});Object.defineProperty(X,"FileTransferService",{enumerable:!0,get:function(){return Ir.FileTransferService}});Object.defineProperty(X,"FileListService",{enumerable:!0,get:function(){return Ir.FileListService}});Object.defineProperty(X,"FileTrackerService",{enumerable:!0,get:function(){return Ir.FileTrackerService}});Object.defineProperty(X,"InputStreamReceiver",{enumerable:!0,get:function(){return Ir.InputStreamReceiver}});var qt=Zo();Object.defineProperty(X,"generateIdentityKeyPair",{enumerable:!0,get:function(){return qt.generateIdentityKeyPair}});Object.defineProperty(X,"identityPublicFromSecret",{enumerable:!0,get:function(){return qt.identityPublicFromSecret}});Object.defineProperty(X,"signSessionKey",{enumerable:!0,get:function(){return qt.signSessionKey}});Object.defineProperty(X,"verifySessionKey",{enumerable:!0,get:function(){return qt.verifySessionKey}});Object.defineProperty(X,"buildKxCanonical",{enumerable:!0,get:function(){return qt.buildKxCanonical}});Object.defineProperty(X,"buildKxAckCanonical",{enumerable:!0,get:function(){return qt.buildKxAckCanonical}});Object.defineProperty(X,"fingerprintIdentityKey",{enumerable:!0,get:function(){return qt.fingerprintIdentityKey}});Object.defineProperty(X,"fingerprintShortHex",{enumerable:!0,get:function(){return qt.fingerprintShortHex}});Object.defineProperty(X,"concatBytes",{enumerable:!0,get:function(){return qt.concatBytes}});Object.defineProperty(X,"KX_SIGN_LABEL",{enumerable:!0,get:function(){return qt.KX_SIGN_LABEL}});Object.defineProperty(X,"KX_ACK_LABEL",{enumerable:!0,get:function(){return qt.KX_ACK_LABEL}});Object.defineProperty(X,"FP_LABEL",{enumerable:!0,get:function(){return qt.FP_LABEL}})});var Uc=M((qn,jc)=>{(function(r,e){typeof qn=="object"&&typeof jc=="object"?jc.exports=e(require("child_process"),require("crypto")):typeof define=="function"&&define.amd?define(["child_process","crypto"],e):typeof qn=="object"?qn["electron-machine-id"]=e(require("child_process"),require("crypto")):r["electron-machine-id"]=e(r.child_process,r.crypto)})(qn,function(r,e){return(function(t){function i(s){if(n[s])return n[s].exports;var a=n[s]={exports:{},id:s,loaded:!1};return t[s].call(a.exports,a,a.exports,i),a.loaded=!0,a.exports}var n={};return i.m=t,i.c=n,i.p="",i(0)})([function(t,i,n){t.exports=n(34)},function(t,i,n){var s=n(29)("wks"),a=n(33),c=n(2).Symbol,u=typeof c=="function",d=t.exports=function(p){return s[p]||(s[p]=u&&c[p]||(u?c:a)("Symbol."+p))};d.store=s},function(t,i){var n=t.exports=typeof window<"u"&&window.Math==Math?window:typeof self<"u"&&self.Math==Math?self:Function("return this")();typeof __g=="number"&&(__g=n)},function(t,i,n){var s=n(9);t.exports=function(a){if(!s(a))throw TypeError(a+" is not an object!");return a}},function(t,i,n){t.exports=!n(24)(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7})},function(t,i,n){var s=n(12),a=n(17);t.exports=n(4)?function(c,u,d){return s.f(c,u,a(1,d))}:function(c,u,d){return c[u]=d,c}},function(t,i){var n=t.exports={version:"2.4.0"};typeof __e=="number"&&(__e=n)},function(t,i,n){var s=n(14);t.exports=function(a,c,u){if(s(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 n={}.hasOwnProperty;t.exports=function(s,a){return n.call(s,a)}},function(t,i){t.exports=function(n){return typeof n=="object"?n!==null:typeof n=="function"}},function(t,i){t.exports={}},function(t,i){var n={}.toString;t.exports=function(s){return n.call(s).slice(8,-1)}},function(t,i,n){var s=n(3),a=n(26),c=n(32),u=Object.defineProperty;i.f=n(4)?Object.defineProperty:function(d,p,m){if(s(d),p=c(p,!0),s(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,n){var s=n(42),a=n(15);t.exports=function(c){return s(a(c))}},function(t,i){t.exports=function(n){if(typeof n!="function")throw TypeError(n+" is not a function!");return n}},function(t,i){t.exports=function(n){if(n==null)throw TypeError("Can't call method on "+n);return n}},function(t,i,n){var s=n(9),a=n(2).document,c=s(a)&&s(a.createElement);t.exports=function(u){return c?a.createElement(u):{}}},function(t,i){t.exports=function(n,s){return{enumerable:!(1&n),configurable:!(2&n),writable:!(4&n),value:s}}},function(t,i,n){var s=n(12).f,a=n(8),c=n(1)("toStringTag");t.exports=function(u,d,p){u&&!a(u=p?u:u.prototype,c)&&s(u,c,{configurable:!0,value:d})}},function(t,i,n){var s=n(29)("keys"),a=n(33);t.exports=function(c){return s[c]||(s[c]=a(c))}},function(t,i){var n=Math.ceil,s=Math.floor;t.exports=function(a){return isNaN(a=+a)?0:(a>0?s:n)(a)}},function(t,i,n){var s=n(11),a=n(1)("toStringTag"),c=s((function(){return arguments})())=="Arguments",u=function(d,p){try{return d[p]}catch{}};t.exports=function(d){var p,m,_;return d===void 0?"Undefined":d===null?"Null":typeof(m=u(p=Object(d),a))=="string"?m:c?s(p):(_=s(p))=="Object"&&typeof p.callee=="function"?"Arguments":_}},function(t,i){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,i,n){var s=n(2),a=n(6),c=n(7),u=n(5),d="prototype",p=function(m,_,E){var S,T,z,ge=m&p.F,ee=m&p.G,A=m&p.S,B=m&p.P,re=m&p.B,q=m&p.W,U=ee?a:a[_]||(a[_]={}),ye=U[d],xe=ee?s:A?s[_]:(s[_]||{})[d];ee&&(E=_);for(S in E)T=!ge&&xe&&xe[S]!==void 0,T&&S in U||(z=T?xe[S]:E[S],U[S]=ee&&typeof xe[S]!="function"?E[S]:re&&T?c(z,s):q&&xe[S]==z?(function(ue){var rt=function(Ee,Se,be){if(this instanceof ue){switch(arguments.length){case 0:return new ue;case 1:return new ue(Ee);case 2:return new ue(Ee,Se)}return new ue(Ee,Se,be)}return ue.apply(this,arguments)};return rt[d]=ue[d],rt})(z):B&&typeof z=="function"?c(Function.call,z):z,B&&((U.virtual||(U.virtual={}))[S]=z,m&p.R&&ye&&!ye[S]&&u(ye,S,z)))};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(n){try{return!!n()}catch{return!0}}},function(t,i,n){t.exports=n(2).document&&document.documentElement},function(t,i,n){t.exports=!n(4)&&!n(24)(function(){return Object.defineProperty(n(16)("div"),"a",{get:function(){return 7}}).a!=7})},function(t,i,n){"use strict";var s=n(28),a=n(23),c=n(57),u=n(5),d=n(8),p=n(10),m=n(45),_=n(18),E=n(52),S=n(1)("iterator"),T=!([].keys&&"next"in[].keys()),z="@@iterator",ge="keys",ee="values",A=function(){return this};t.exports=function(B,re,q,U,ye,xe,ue){m(q,re,U);var rt,Ee,Se,be=function(j){if(!T&&j in Te)return Te[j];switch(j){case ge:return function(){return new q(this,j)};case ee:return function(){return new q(this,j)}}return function(){return new q(this,j)}},We=re+" Iterator",st=ye==ee,Ze=!1,Te=B.prototype,it=Te[S]||Te[z]||ye&&Te[ye],ze=it||be(ye),gt=ye?st?be("entries"):ze:void 0,L=re=="Array"&&Te.entries||it;if(L&&(Se=E(L.call(new B)),Se!==Object.prototype&&(_(Se,We,!0),s||d(Se,S)||u(Se,S,A))),st&&it&&it.name!==ee&&(Ze=!0,ze=function(){return it.call(this)}),s&&!ue||!T&&!Ze&&Te[S]||u(Te,S,ze),p[re]=ze,p[We]=A,ye)if(rt={values:st?ze:be(ee),keys:xe?ze:be(ge),entries:gt},ue)for(Ee in rt)Ee in Te||c(Te,Ee,rt[Ee]);else a(a.P+a.F*(T||Ze),re,rt);return rt}},function(t,i){t.exports=!0},function(t,i,n){var s=n(2),a="__core-js_shared__",c=s[a]||(s[a]={});t.exports=function(u){return c[u]||(c[u]={})}},function(t,i,n){var s,a,c,u=n(7),d=n(41),p=n(25),m=n(16),_=n(2),E=_.process,S=_.setImmediate,T=_.clearImmediate,z=_.MessageChannel,ge=0,ee={},A="onreadystatechange",B=function(){var q=+this;if(ee.hasOwnProperty(q)){var U=ee[q];delete ee[q],U()}},re=function(q){B.call(q.data)};S&&T||(S=function(q){for(var U=[],ye=1;arguments.length>ye;)U.push(arguments[ye++]);return ee[++ge]=function(){d(typeof q=="function"?q:Function(q),U)},s(ge),ge},T=function(q){delete ee[q]},n(11)(E)=="process"?s=function(q){E.nextTick(u(B,q,1))}:z?(a=new z,c=a.port2,a.port1.onmessage=re,s=u(c.postMessage,c,1)):_.addEventListener&&typeof postMessage=="function"&&!_.importScripts?(s=function(q){_.postMessage(q+"","*")},_.addEventListener("message",re,!1)):s=A in m("script")?function(q){p.appendChild(m("script"))[A]=function(){p.removeChild(this),B.call(q)}}:function(q){setTimeout(u(B,q,1),0)}),t.exports={set:S,clear:T}},function(t,i,n){var s=n(20),a=Math.min;t.exports=function(c){return c>0?a(s(c),9007199254740991):0}},function(t,i,n){var s=n(9);t.exports=function(a,c){if(!s(a))return a;var u,d;if(c&&typeof(u=a.toString)=="function"&&!s(d=u.call(a))||typeof(u=a.valueOf)=="function"&&!s(d=u.call(a))||!c&&typeof(u=a.toString)=="function"&&!s(d=u.call(a)))return d;throw TypeError("Can't convert object to primitive value")}},function(t,i){var n=0,s=Math.random();t.exports=function(a){return"Symbol(".concat(a===void 0?"":a,")_",(++n+s).toString(36))}},function(t,i,n){"use strict";function s(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,S.createHash)("sha256").update(A).digest("hex")}function u(A){switch(z){case"darwin":return A.split("IOPlatformUUID")[1].split(`
32
- `)[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 B=u((0,E.execSync)(ee[z]).toString());return A?B:c(B)}function p(A){return new _.default(function(B,re){return(0,E.exec)(ee[z],{},function(q,U,ye){if(q)return re(new Error("Error while obtaining machine id: "+q.stack));var xe=u(U.toString());return B(A?xe:c(xe))})})}Object.defineProperty(i,"__esModule",{value:!0});var m=n(35),_=s(m);i.machineIdSync=d,i.machineId=p;var E=n(70),S=n(71),T=process,z=T.platform,ge={native:"%windir%\\System32",mixed:"%windir%\\sysnative\\cmd.exe /c %windir%\\System32"},ee={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,n){t.exports={default:n(36),__esModule:!0}},function(t,i,n){n(66),n(68),n(69),n(67),t.exports=n(6).Promise},function(t,i){t.exports=function(){}},function(t,i){t.exports=function(n,s,a,c){if(!(n instanceof s)||c!==void 0&&c in n)throw TypeError(a+": incorrect invocation!");return n}},function(t,i,n){var s=n(13),a=n(31),c=n(62);t.exports=function(u){return function(d,p,m){var _,E=s(d),S=a(E.length),T=c(m,S);if(u&&p!=p){for(;S>T;)if(_=E[T++],_!=_)return!0}else for(;S>T;T++)if((u||T in E)&&E[T]===p)return u||T||0;return!u&&-1}}},function(t,E,n){var s=n(7),a=n(44),c=n(43),u=n(3),d=n(31),p=n(64),m={},_={},E=t.exports=function(S,T,z,ge,ee){var A,B,re,q,U=ee?function(){return S}:p(S),ye=s(z,ge,T?2:1),xe=0;if(typeof U!="function")throw TypeError(S+" is not iterable!");if(c(U)){for(A=d(S.length);A>xe;xe++)if(q=T?ye(u(B=S[xe])[0],B[1]):ye(S[xe]),q===m||q===_)return q}else for(re=U.call(S);!(B=re.next()).done;)if(q=a(re,ye,B.value,T),q===m||q===_)return q};E.BREAK=m,E.RETURN=_},function(t,i){t.exports=function(n,s,a){var c=a===void 0;switch(s.length){case 0:return c?n():n.call(a);case 1:return c?n(s[0]):n.call(a,s[0]);case 2:return c?n(s[0],s[1]):n.call(a,s[0],s[1]);case 3:return c?n(s[0],s[1],s[2]):n.call(a,s[0],s[1],s[2]);case 4:return c?n(s[0],s[1],s[2],s[3]):n.call(a,s[0],s[1],s[2],s[3])}return n.apply(a,s)}},function(t,i,n){var s=n(11);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(a){return s(a)=="String"?a.split(""):Object(a)}},function(t,i,n){var s=n(10),a=n(1)("iterator"),c=Array.prototype;t.exports=function(u){return u!==void 0&&(s.Array===u||c[a]===u)}},function(t,i,n){var s=n(3);t.exports=function(a,c,u,d){try{return d?c(s(u)[0],u[1]):c(u)}catch(m){var p=a.return;throw p!==void 0&&s(p.call(a)),m}}},function(t,i,n){"use strict";var s=n(49),a=n(17),c=n(18),u={};n(5)(u,n(1)("iterator"),function(){return this}),t.exports=function(d,p,m){d.prototype=s(u,{next:a(1,m)}),c(d,p+" Iterator")}},function(t,i,n){var s=n(1)("iterator"),a=!1;try{var c=[7][s]();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],_=m[s]();_.next=function(){return{done:p=!0}},m[s]=function(){return _},u(m)}catch{}return p}},function(t,i){t.exports=function(n,s){return{value:s,done:!!n}}},function(t,i,n){var s=n(2),a=n(30).set,c=s.MutationObserver||s.WebKitMutationObserver,u=s.process,d=s.Promise,p=n(11)(u)=="process";t.exports=function(){var m,_,E,S=function(){var ee,A;for(p&&(ee=u.domain)&&ee.exit();m;){A=m.fn,m=m.next;try{A()}catch(B){throw m?E():_=void 0,B}}_=void 0,ee&&ee.enter()};if(p)E=function(){u.nextTick(S)};else if(c){var T=!0,z=document.createTextNode("");new c(S).observe(z,{characterData:!0}),E=function(){z.data=T=!T}}else if(d&&d.resolve){var ge=d.resolve();E=function(){ge.then(S)}}else E=function(){a.call(s,S)};return function(ee){var A={fn:ee,next:void 0};_&&(_.next=A),m||(m=A,E()),_=A}}},function(t,i,n){var s=n(3),a=n(50),c=n(22),u=n(19)("IE_PROTO"),d=function(){},p="prototype",m=function(){var _,E=n(16)("iframe"),S=c.length,T=">";for(E.style.display="none",n(25).appendChild(E),E.src="javascript:",_=E.contentWindow.document,_.open(),_.write("<script>document.F=Object</script"+T),_.close(),m=_.F;S--;)delete m[p][c[S]];return m()};t.exports=Object.create||function(_,E){var S;return _!==null?(d[p]=s(_),S=new d,d[p]=null,S[u]=_):S=m(),E===void 0?S:a(S,E)}},function(t,i,n){var s=n(12),a=n(3),c=n(54);t.exports=n(4)?Object.defineProperties:function(u,d){a(u);for(var p,m=c(d),_=m.length,E=0;_>E;)s.f(u,p=m[E++],d[p]);return u}},function(t,i,n){var s=n(55),a=n(17),c=n(13),u=n(32),d=n(8),p=n(26),m=Object.getOwnPropertyDescriptor;i.f=n(4)?m:function(_,E){if(_=c(_),E=u(E,!0),p)try{return m(_,E)}catch{}if(d(_,E))return a(!s.f.call(_,E),_[E])}},function(t,i,n){var s=n(8),a=n(63),c=n(19)("IE_PROTO"),u=Object.prototype;t.exports=Object.getPrototypeOf||function(d){return d=a(d),s(d,c)?d[c]:typeof d.constructor=="function"&&d instanceof d.constructor?d.constructor.prototype:d instanceof Object?u:null}},function(t,i,n){var s=n(8),a=n(13),c=n(39)(!1),u=n(19)("IE_PROTO");t.exports=function(d,p){var m,_=a(d),E=0,S=[];for(m in _)m!=u&&s(_,m)&&S.push(m);for(;p.length>E;)s(_,m=p[E++])&&(~c(S,m)||S.push(m));return S}},function(t,i,n){var s=n(53),a=n(22);t.exports=Object.keys||function(c){return s(c,a)}},function(t,i){i.f={}.propertyIsEnumerable},function(t,i,n){var s=n(5);t.exports=function(a,c,u){for(var d in c)u&&a[d]?a[d]=c[d]:s(a,d,c[d]);return a}},function(t,i,n){t.exports=n(5)},function(t,i,n){var s=n(9),a=n(3),c=function(u,d){if(a(u),!s(d)&&d!==null)throw TypeError(d+": can't set as prototype!")};t.exports={set:Object.setPrototypeOf||("__proto__"in{}?(function(u,d,p){try{p=n(7)(Function.call,n(51).f(Object.prototype,"__proto__").set,2),p(u,[]),d=!(u instanceof Array)}catch{d=!0}return function(m,_){return c(m,_),d?m.__proto__=_:p(m,_),m}})({},!1):void 0),check:c}},function(t,i,n){"use strict";var s=n(2),a=n(6),c=n(12),u=n(4),d=n(1)("species");t.exports=function(p){var m=typeof a[p]=="function"?a[p]:s[p];u&&m&&!m[d]&&c.f(m,d,{configurable:!0,get:function(){return this}})}},function(t,i,n){var s=n(3),a=n(14),c=n(1)("species");t.exports=function(u,d){var p,m=s(u).constructor;return m===void 0||(p=s(m)[c])==null?d:a(p)}},function(t,i,n){var s=n(20),a=n(15);t.exports=function(c){return function(u,d){var p,m,_=String(a(u)),E=s(d),S=_.length;return E<0||E>=S?c?"":void 0:(p=_.charCodeAt(E),p<55296||p>56319||E+1===S||(m=_.charCodeAt(E+1))<56320||m>57343?c?_.charAt(E):p:c?_.slice(E,E+2):(p-55296<<10)+(m-56320)+65536)}}},function(t,i,n){var s=n(20),a=Math.max,c=Math.min;t.exports=function(u,d){return u=s(u),u<0?a(u+d,0):c(u,d)}},function(t,i,n){var s=n(15);t.exports=function(a){return Object(s(a))}},function(t,i,n){var s=n(21),a=n(1)("iterator"),c=n(10);t.exports=n(6).getIteratorMethod=function(u){if(u!=null)return u[a]||u["@@iterator"]||c[s(u)]}},function(t,i,n){"use strict";var s=n(37),a=n(47),c=n(10),u=n(13);t.exports=n(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,s("keys"),s("values"),s("entries")},function(t,i){},function(t,i,n){"use strict";var s,a,c,u=n(28),d=n(2),p=n(7),m=n(21),_=n(23),E=n(9),S=(n(3),n(14)),T=n(38),z=n(40),ge=(n(58).set,n(60)),ee=n(30).set,A=n(48)(),B="Promise",re=d.TypeError,U=d.process,q=d[B],U=d.process,ye=m(U)=="process",xe=function(){},ue=!!(function(){try{var L=q.resolve(1),j=(L.constructor={})[n(1)("species")]=function(R){R(xe,xe)};return(ye||typeof PromiseRejectionEvent=="function")&&L.then(xe)instanceof j}catch{}})(),rt=function(L,j){return L===j||L===q&&j===c},Ee=function(L){var j;return!(!E(L)||typeof(j=L.then)!="function")&&j},Se=function(L){return rt(q,L)?new be(L):new a(L)},be=a=function(L){var j,R;this.promise=new L(function(P,Z){if(j!==void 0||R!==void 0)throw re("Bad Promise constructor");j=P,R=Z}),this.resolve=S(j),this.reject=S(R)},We=function(L){try{L()}catch(j){return{error:j}}},st=function(L,j){if(!L._n){L._n=!0;var R=L._c;A(function(){for(var P=L._v,Z=L._s==1,Ne=0,Xe=function(lt){var wt,mr,Mr=Z?lt.ok:lt.fail,ii=lt.resolve,Fr=lt.reject,ki=lt.domain;try{Mr?(Z||(L._h==2&&it(L),L._h=1),Mr===!0?wt=P:(ki&&ki.enter(),wt=Mr(P),ki&&ki.exit()),wt===lt.promise?Fr(re("Promise-chain cycle")):(mr=Ee(wt))?mr.call(wt,ii,Fr):ii(wt)):Fr(P)}catch(Xn){Fr(Xn)}};R.length>Ne;)Xe(R[Ne++]);L._c=[],L._n=!1,j&&!L._h&&Ze(L)})}},Ze=function(L){ee.call(d,function(){var j,R,P,Z=L._v;if(Te(L)&&(j=We(function(){ye?U.emit("unhandledRejection",Z,L):(R=d.onunhandledrejection)?R({promise:L,reason:Z}):(P=d.console)&&P.error&&P.error("Unhandled promise rejection",Z)}),L._h=ye||Te(L)?2:1),L._a=void 0,j)throw j.error})},Te=function(L){if(L._h==1)return!1;for(var j,R=L._a||L._c,P=0;R.length>P;)if(j=R[P++],j.fail||!Te(j.promise))return!1;return!0},it=function(L){ee.call(d,function(){var j;ye?U.emit("rejectionHandled",L):(j=d.onrejectionhandled)&&j({promise:L,reason:L._v})})},ze=function(L){var j=this;j._d||(j._d=!0,j=j._w||j,j._v=L,j._s=2,j._a||(j._a=j._c.slice()),st(j,!0))},gt=function(L){var j,R=this;if(!R._d){R._d=!0,R=R._w||R;try{if(R===L)throw re("Promise can't be resolved itself");(j=Ee(L))?A(function(){var P={_w:R,_d:!1};try{j.call(L,p(gt,P,1),p(ze,P,1))}catch(Z){ze.call(P,Z)}}):(R._v=L,R._s=1,st(R,!1))}catch(P){ze.call({_w:R,_d:!1},P)}}};ue||(q=function(L){T(this,q,B,"_h"),S(L),s.call(this);try{L(p(gt,this,1),p(ze,this,1))}catch(j){ze.call(this,j)}},s=function(L){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},s.prototype=n(56)(q.prototype,{then:function(L,j){var R=Se(ge(this,q));return R.ok=typeof L!="function"||L,R.fail=typeof j=="function"&&j,R.domain=ye?U.domain:void 0,this._c.push(R),this._a&&this._a.push(R),this._s&&st(this,!1),R.promise},catch:function(L){return this.then(void 0,L)}}),be=function(){var L=new s;this.promise=L,this.resolve=p(gt,L,1),this.reject=p(ze,L,1)}),_(_.G+_.W+_.F*!ue,{Promise:q}),n(18)(q,B),n(59)(B),c=n(6)[B],_(_.S+_.F*!ue,B,{reject:function(L){var j=Se(this),R=j.reject;return R(L),j.promise}}),_(_.S+_.F*(u||!ue),B,{resolve:function(L){if(L instanceof q&&rt(L.constructor,this))return L;var j=Se(this),R=j.resolve;return R(L),j.promise}}),_(_.S+_.F*!(ue&&n(46)(function(L){q.all(L).catch(xe)})),B,{all:function(L){var j=this,R=Se(j),P=R.resolve,Z=R.reject,Ne=We(function(){var Xe=[],lt=0,wt=1;z(L,!1,function(mr){var Mr=lt++,ii=!1;Xe.push(void 0),wt++,j.resolve(mr).then(function(Fr){ii||(ii=!0,Xe[Mr]=Fr,--wt||P(Xe))},Z)}),--wt||P(Xe)});return Ne&&Z(Ne.error),R.promise},race:function(L){var j=this,R=Se(j),P=R.reject,Z=We(function(){z(L,!1,function(Ne){j.resolve(Ne).then(R.resolve,P)})});return Z&&P(Z.error),R.promise}})},function(t,i,n){"use strict";var s=n(61)(!0);n(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=s(c,u),this._i+=a.length,{value:a,done:!1})})},function(t,i,n){n(65);for(var s=n(2),a=n(5),c=n(10),u=n(1)("toStringTag"),d=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],p=0;p<5;p++){var m=d[p],_=s[m],E=_&&_.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 Pv(){try{return Kc.default.statSync("/.dockerenv"),!0}catch{return!1}}function Av(){try{return Kc.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Wc(){return qc===void 0&&(qc=Pv()||Av()),qc}var Kc,qc,Xh=Kt(()=>{Kc=fe(require("node:fs"),1)});function sn(){return Hc===void 0&&(Hc=Rv()||Wc()),Hc}var Jh,Hc,Rv,Vc=Kt(()=>{Jh=fe(require("node:fs"),1);Xh();Rv=()=>{try{return Jh.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var zc,Qh,ed,Zh,Jr,$c=Kt(()=>{zc=fe(require("node:process"),1),Qh=fe(require("node:os"),1),ed=fe(require("node:fs"),1);Vc();Zh=()=>{if(zc.default.platform!=="linux")return!1;if(Qh.default.release().toLowerCase().includes("microsoft"))return!sn();try{return ed.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!sn():!1}catch{return!1}},Jr=zc.default.env.__IS_WSL_TEST__?Zh:Zh()});var Gc,Hn,Iv,Lv,Yc,td=Kt(()=>{Gc=fe(require("node:process"),1),Hn=fe(require("node:fs/promises"),1);$c();$c();Iv=(()=>{let r="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",i=!1;try{await Hn.default.access(t,Hn.constants.F_OK),i=!0}catch{}if(!i)return r;let n=await Hn.default.readFile(t,{encoding:"utf8"}),s=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(n);return s?(e=s.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):r}})(),Lv=async()=>`${await Iv()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Yc=async()=>Jr?Lv():`${Gc.default.env.SYSTEMROOT||Gc.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function Zr(r,e,t){let i=n=>Object.defineProperty(r,e,{value:n,enumerable:!0,writable:!0});return Object.defineProperty(r,e,{configurable:!0,enumerable:!0,get(){let n=t();return i(n),n},set(n){i(n)}}),r}var rd=Kt(()=>{});async function Xc(){if(nd.default.platform!=="darwin")throw new Error("macOS only");let{stdout:r}=await Nv("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 id,nd,sd,Nv,od=Kt(()=>{id=require("node:util"),nd=fe(require("node:process"),1),sd=require("node:child_process"),Nv=(0,id.promisify)(sd.execFile)});async function fd(r,{humanReadableOutput:e=!0,signal:t}={}){if(ad.default.platform!=="darwin")throw new Error("macOS only");let i=e?[]:["-ss"],n={};t&&(n.signal=t);let{stdout:s}=await Mv("osascript",["-e",r,i],n);return s.trim()}var ad,cd,Jc,Mv,ud=Kt(()=>{ad=fe(require("node:process"),1),cd=require("node:util"),Jc=require("node:child_process"),Mv=(0,cd.promisify)(Jc.execFile)});async function Zc(r){return fd(`tell application "Finder" to set app_path to application file id "${r}" as string
33
- tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var ld=Kt(()=>{ud()});async function ef(r=Fv){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 Qc(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:i}=t.groups,n=i.lastIndexOf("."),s=i.lastIndexOf("-"),a=n===-1?void 0:i.slice(0,n),c=s===-1?void 0:i.slice(0,s);return _o[i]??_o[a]??_o[c]??{name:i,id:i}}var hd,dd,Fv,_o,Gw,Qc,pd=Kt(()=>{hd=require("node:util"),dd=require("node:child_process"),Fv=(0,hd.promisify)(dd.execFile),_o={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"}},Gw=new Map(Object.entries(_o)),Qc=class extends Error{}});async function tf(){if(vo.default.platform==="darwin"){let r=await Xc();return{name:await Zc(r),id:r}}if(vo.default.platform==="linux"){let{stdout:r}=await Dv("xdg-mime",["query","default","x-scheme-handler/http"]),e=r.trim();return{name:Bv(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(vo.default.platform==="win32")return ef();throw new Error("Only macOS, Linux, and Windows are supported")}var gd,vo,md,Dv,Bv,yd=Kt(()=>{gd=require("node:util"),vo=fe(require("node:process"),1),md=require("node:child_process");od();ld();pd();Dv=(0,gd.promisify)(md.execFile),Bv=r=>r.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var Sd={};Ep(Sd,{apps:()=>Qr,default:()=>Wv,openApp:()=>Kv});async function Uv(){let r=await Yc(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=sf.Buffer.from(e,"utf16le").toString("base64"),{stdout:i}=await jv(r,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),n=i.trim(),s={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return s[n]?{id:s[n]}:{}}function Ed(r){if(typeof r=="string"||Array.isArray(r))return r;let{[vd]:e}=r;if(!e)throw new Error(`${vd} is not supported`);return e}function Eo({[on]:r},{wsl:e}){if(e&&Jr)return Ed(e);if(!r)throw new Error(`${on} is not supported`);return Ed(r)}var nf,sf,of,wd,xd,af,bo,Hv,jv,rf,_d,on,vd,bd,Vn,qv,Kv,Qr,Wv,Td=Kt(()=>{nf=fe(require("node:process"),1),sf=require("node:buffer"),of=fe(require("node:path"),1),wd=require("node:url"),xd=require("node:util"),af=fe(require("node:child_process"),1),bo=fe(require("node:fs/promises"),1);td();rd();yd();Vc();Hv={},jv=(0,xd.promisify)(af.default.execFile),rf=of.default.dirname((0,wd.fileURLToPath)(Hv.url)),_d=of.default.join(rf,"xdg-open"),{platform:on,arch:vd}=nf.default;bd=async(r,e)=>{let t;for(let i of r)try{return await e(i)}catch(n){t=n}throw t},Vn=async r=>{if(r={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...r},Array.isArray(r.app))return bd(r.app,c=>Vn({...r,app:c}));let{name:e,arguments:t=[]}=r.app??{};if(t=[...t],Array.isArray(e))return bd(e,c=>Vn({...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=Jr?await Uv():await tf();if(d.id in c){let p=c[d.id];return e==="browserPrivate"&&t.push(u[p]),Vn({...r,app:{name:Qr[p],arguments:t}})}throw new Error(`${d.name} is not supported as a default browser`)}let i,n=[],s={};if(on==="darwin")i="open",r.wait&&n.push("--wait-apps"),r.background&&n.push("--background"),r.newInstance&&n.push("--new"),e&&n.push("-a",e);else if(on==="win32"||Jr&&!sn()&&!e){i=await Yc(),n.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),Jr||(s.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=sf.Buffer.from(c.join(" "),"utf16le").toString("base64")}else{if(e)i=e;else{let c=!rf||rf==="/",u=!1;try{await bo.default.access(_d,bo.constants.X_OK),u=!0}catch{}i=nf.default.versions.electron??(on==="android"||c||!u)?"xdg-open":_d}t.length>0&&n.push(...t),r.wait||(s.stdio="ignore",s.detached=!0)}on==="darwin"&&t.length>0&&n.push("--args",...t),r.target&&n.push(r.target);let a=af.default.spawn(i,n,s);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)},qv=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a `target`");return Vn({...e,target:r})},Kv=(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 Vn({...e,app:{name:r,arguments:t}})};Qr={};Zr(Qr,"chrome",()=>Eo({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"]}}));Zr(Qr,"brave",()=>Eo({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"]}}));Zr(Qr,"firefox",()=>Eo({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Zr(Qr,"edge",()=>Eo({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Zr(Qr,"browser",()=>"browser");Zr(Qr,"browserPrivate",()=>"browserPrivate");Wv=qv});var _r=fe(require("fs")),ns=fe(require("path"));var Of=fe(require("os")),Pf=fe(require("path")),rs=fe(require("fs"));function is(){let r=Pf.join(Of.homedir(),".termiq");return rs.existsSync(r)||rs.mkdirSync(r,{recursive:!0,mode:448}),r}var pn=class{filePath;data={};constructor(){this.filePath=ns.join(is(),"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(_r.existsSync(this.filePath)){let e=_r.readFileSync(this.filePath,"utf-8");this.data=JSON.parse(e)}}catch{this.data={}}}save(){let e=ns.dirname(this.filePath);_r.existsSync(e)||_r.mkdirSync(e,{recursive:!0,mode:448}),_r.writeFileSync(this.filePath,JSON.stringify(this.data,null,2),{mode:384})}};var vr=fe(require("fs")),ss=fe(require("path"));var xp={serverUrl:"https://termiq.io",agentName:"",multiViewer:!1},gn=class{config;filePath;constructor(e){this.filePath=ss.join(is(),"config.json"),this.config={...xp,...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(vr.existsSync(this.filePath)){let e=vr.readFileSync(this.filePath,"utf-8");return JSON.parse(e)}}catch{}return{}}saveToFile(){let e=ss.dirname(this.filePath);vr.existsSync(e)||vr.mkdirSync(e,{recursive:!0,mode:448}),vr.writeFileSync(this.filePath,JSON.stringify(this.config,null,2))}};var _t=fe(require("fs")),Bc=fe(require("path")),$h=fe(require("os")),yo=fe(jn()),Tv="cli",Dc=Bc.join($h.homedir(),".termiq","logs"),Xr=Bc.join(Dc,"cli.log"),Cv=5*1024*1024,zh=3;function kv(){try{if(!_t.existsSync(Xr)||_t.statSync(Xr).size<Cv)return;for(let e=zh-1;e>=1;e--){let t=`${Xr}.${e}`,i=`${Xr}.${e+1}`;_t.existsSync(t)&&(e+1>zh?_t.unlinkSync(t):_t.renameSync(t,i))}_t.renameSync(Xr,`${Xr}.1`)}catch{}}function Ov(r){try{_t.existsSync(Dc)||_t.mkdirSync(Dc,{recursive:!0}),kv(),_t.appendFileSync(Xr,r+`
34
- `,{encoding:"utf8"})}catch{}}var Un=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 Xr}write(e,t,i){if(!(0,yo.shouldLog)(e,this.level))return;let n=(0,yo.formatLogLine)(e,Tv,t,i);this.toFile?Ov(n):process.stderr.write(n+`
35
- `)}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 Gh=fe(require("os")),Yh=fe(Uc()),Kn=class{cachedId=null;name;constructor(e){this.name=e||Gh.hostname()||"CLI"}async getMachineId(){if(this.cachedId)return this.cachedId;try{this.cachedId=(0,Yh.machineIdSync)()}catch{this.cachedId=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}return this.cachedId}getMachineName(){return this.name}};var Wn=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 zn=class{async openUrl(e){let{default:t}=await Promise.resolve().then(()=>(Td(),Sd));await t(e)}};var Cd=fe(require("fs")),cf=fe(require("path"));function wo(r){let e=r?[r]:[cf.join(__dirname,"..","package.json"),cf.join(__dirname,"..","..","package.json")];for(let t of e)try{let i=JSON.parse(Cd.readFileSync(t,"utf8"));if(typeof i.version=="string"&&i.version.length>0)return i.version}catch{}return"unknown"}function kd(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 ff=new Set(["--cid","--token","--server","--log-level"]),Od=new Set(["--help","-h","--version","-V","--verbose","-v","--watch","-w","--log-to-file","--statusline","--multi-viewer","--force"]);function Pd(r,e,t){for(let i=0;i<r.length;i++){let n=r[i];if(!n.startsWith("-"))continue;let s=n.includes("=")?n.slice(0,n.indexOf("=")):n;if(e.has(s)||t.has(s)){e.has(s)&&!n.includes("=")&&i++;continue}return n}}var ip=fe(require("path")),ut=fe(jn()),np=fe(Sr());var Ad=fe(require("os")),Rd=require("crypto"),Id=fe(require("node-pty")),Ld=fe(jn()),xo=class r{ptyProcess=null;outputBuffer=new Ld.CircularBuffer(100);streamId=null;logger;onOutput=null;onExit=null;preWriteHook=null;onResize=null;onLocalClaim=null;onLocalInput=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;constructor(e){this.logger=e}setMultiViewerMode(e){this.multiViewerMode!==e&&(this.multiViewerMode=e,this.logger.info("Multi-viewer mode",{enabled:e}))}spawn(e,t=0){let i=process.env.SHELL||(Ad.platform()==="win32"?"powershell.exe":"/bin/bash"),n=process.stdout.columns||80,s=process.stdout.rows||24,a=Math.max(1,s-t);this.reservedBottomRows=t,this.ptyProcess=Id.spawn(i,[],{name:"xterm-256color",cols:n,rows:a,cwd:e,env:{...process.env,TERMIQ_SESSION_ACTIVE:"1"}}),this.onResize?.(n,a),this.streamId=(0,Rd.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.multiViewerMode&&this.maybeClaimLocalControl(),this.onLocalInput?.(u.toString()),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.multiViewerMode){this.logger.info("Local resize claims control",{cols:u,rows:d}),this.resize(u,d),this.onLocalClaim?.(u,d);return}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.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)}}maybeClaimLocalControl(){if(!this.ptyProcess)return;let e=process.stdout.columns||80,t=Math.max(1,(process.stdout.rows||24)-this.reservedBottomRows);this.ptyProcess.cols===e&&this.ptyProcess.rows===t||(this.logger.info("Local input claims control",{cols:e,rows:t}),this.resize(e,t),this.onLocalClaim?.(e,t))}setOnLocalClaim(e){this.onLocalClaim=e}setOnLocalInput(e){this.onLocalInput=e}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 ei=fe(require("path")),cn=fe(require("fs"));var Yd=require("node:events"),Xd=require("node:fs"),Ro=require("node:fs/promises"),we=fe(require("node:path"),1);var Lr=require("node:fs/promises"),Nr=require("node:path"),Dd=require("node:stream"),At={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},uf={root:".",fileFilter:r=>!0,directoryFilter:r=>!0,type:At.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(uf);var Bd="READDIRP_RECURSIVE_ERROR",Vv=new Set(["ENOENT","EPERM","EACCES","ELOOP",Bd]),Nd=[At.DIR_TYPE,At.EVERYTHING_TYPE,At.FILE_DIR_TYPE,At.FILE_TYPE],zv=new Set([At.DIR_TYPE,At.EVERYTHING_TYPE,At.FILE_DIR_TYPE]),$v=new Set([At.EVERYTHING_TYPE,At.FILE_DIR_TYPE,At.FILE_TYPE]),Gv=r=>Vv.has(r.code),Yv=process.platform==="win32",Md=r=>!0,Fd=r=>{if(r===void 0)return Md;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 Md},lf=class extends Dd.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={...uf,...e},{root:i,type:n}=t;this._fileFilter=Fd(t.fileFilter),this._directoryFilter=Fd(t.directoryFilter);let s=t.lstat?Lr.lstat:Lr.stat;Yv?this._stat=a=>s(a,{bigint:!0}):this._stat=s,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:uf.depth,this._wantsDir=n?zv.has(n):!1,this._wantsFile=n?$v.has(n):!1,this._wantsEverything=n===At.EVERYTHING_TYPE,this._root=(0,Nr.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:n,depth:s}=t,a=i.splice(0,e).map(u=>this._formatEntry(u,n)),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)?(s<=this._maxDepth&&this.parents.push(this._exploreDir(u.fullPath,s+1)),this._wantsDir&&(this.push(u),e--)):(d==="file"||this._includeAsFile(u))&&this._fileFilter(u)&&this._wantsFile&&(this.push(u),e--)}}else{let n=this.parents.pop();if(!n){this.push(null);break}if(this.parent=await n,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let i;try{i=await(0,Lr.readdir)(e,this._rdOptions)}catch(n){this._onError(n)}return{files:i,depth:t,path:e}}async _formatEntry(e,t){let i,n=this._isDirent?e.name:e;try{let s=(0,Nr.resolve)((0,Nr.join)(t,n));i={path:(0,Nr.relative)(this._root,s),fullPath:s,basename:n},i[this._statsProp]=this._isDirent?e:await this._stat(s)}catch(s){this._onError(s);return}return i}_onError(e){Gv(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 n=await(0,Lr.realpath)(i),s=await(0,Lr.lstat)(n);if(s.isFile())return"file";if(s.isDirectory()){let a=n.length;if(i.startsWith(n)&&i.substr(a,1)===Nr.sep){let c=new Error(`Circular symlink detected: "${i}" points to "${n}"`);return c.code=Bd,this._onError(c)}return"directory"}}catch(n){return this._onError(n),""}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function jd(r,e={}){let t=e.entryType||e.type;if(t==="both"&&(t=At.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&&!Nd.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${Nd.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=r,new lf(e)}var Ci=require("node:fs"),Xt=require("node:fs/promises"),qd=require("node:os"),Ke=fe(require("node:path"),1),Xv="data",pf="end",Kd="close",Oo=()=>{};var Po=process.platform,gf=Po==="win32",Jv=Po==="darwin",Zv=Po==="linux",Qv=Po==="freebsd",Wd=(0,qd.type)()==="OS400",Ve={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},Yt=Ve,eb="watch",tb={lstat:Xt.lstat,stat:Xt.stat},Ti="listeners",So="errHandlers",an="rawEmitters",rb=[Ti,So,an],ib=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"]),nb=r=>ib.has(Ke.extname(r).slice(1).toLowerCase()),df=(r,e)=>{r instanceof Set?r.forEach(e):e(r)},$n=(r,e,t)=>{let i=r[e];i instanceof Set||(r[e]=i=new Set([i])),i.add(t)},sb=r=>e=>{let t=r[e];t instanceof Set?t.clear():delete r[e]},Gn=(r,e,t)=>{let i=r[e];i instanceof Set?i.delete(t):i===t&&delete r[e]},Hd=r=>r instanceof Set?r.size===0:!r,To=new Map;function Ud(r,e,t,i,n){let s=(a,c)=>{t(r),n(a,c,{watchedPath:r}),c&&r!==c&&Co(Ke.resolve(r,c),Ti,Ke.join(r,c))};try{return(0,Ci.watch)(r,{persistent:e.persistent},s)}catch(a){i(a);return}}var Co=(r,e,t,i,n)=>{let s=To.get(r);s&&df(s[e],a=>{a(t,i,n)})},ob=(r,e,t,i)=>{let{listener:n,errHandler:s,rawEmitter:a}=i,c=To.get(e),u;if(!t.persistent)return u=Ud(r,t,n,s,a),u?u.close.bind(u):void 0;if(c)$n(c,Ti,n),$n(c,So,s),$n(c,an,a);else{if(u=Ud(r,t,Co.bind(null,e,Ti),s,Co.bind(null,e,an)),!u)return;u.on(Yt.ERROR,async d=>{let p=Co.bind(null,e,So);if(c&&(c.watcherUnusable=!0),gf&&d.code==="EPERM")try{await(await(0,Xt.open)(r,"r")).close(),p(d)}catch{}else p(d)}),c={listeners:n,errHandlers:s,rawEmitters:a,watcher:u},To.set(e,c)}return()=>{Gn(c,Ti,n),Gn(c,So,s),Gn(c,an,a),Hd(c.listeners)&&(c.watcher.close(),To.delete(e),rb.forEach(sb(c)),c.watcher=void 0,Object.freeze(c))}},hf=new Map,ab=(r,e,t,i)=>{let{listener:n,rawEmitter:s}=i,a=hf.get(e),c=a&&a.options;return c&&(c.persistent<t.persistent||c.interval>t.interval)&&((0,Ci.unwatchFile)(e),a=void 0),a?($n(a,Ti,n),$n(a,an,s)):(a={listeners:n,rawEmitters:s,options:t,watcher:(0,Ci.watchFile)(e,t,(u,d)=>{df(a.rawEmitters,m=>{m(Yt.CHANGE,e,{curr:u,prev:d})});let p=u.mtimeMs;(u.size!==d.size||p>d.mtimeMs||p===0)&&df(a.listeners,m=>m(r,u))})},hf.set(e,a)),()=>{Gn(a,Ti,n),Gn(a,an,s),Hd(a.listeners)&&(hf.delete(e),(0,Ci.unwatchFile)(e),a.options=a.watcher=void 0,Object.freeze(a))}},ko=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let i=this.fsw.options,n=Ke.dirname(e),s=Ke.basename(e);this.fsw._getWatchedDir(n).add(s);let c=Ke.resolve(e),u={persistent:i.persistent};t||(t=Oo);let d;if(i.usePolling){let p=i.interval!==i.binaryInterval;u.interval=p&&nb(s)?i.binaryInterval:i.interval,d=ab(e,c,u,{listener:t,rawEmitter:this.fsw._emitRaw})}else d=ob(e,c,u,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return d}_handleFile(e,t,i){if(this.fsw.closed)return;let n=Ke.dirname(e),s=Ke.basename(e),a=this.fsw._getWatchedDir(n),c=t;if(a.has(s))return;let u=async(p,m)=>{if(this.fsw._throttle(eb,e,5)){if(!m||m.mtimeMs===0)try{let _=await(0,Xt.stat)(e);if(this.fsw.closed)return;let E=_.atimeMs,S=_.mtimeMs;if((!E||E<=S||S!==c.mtimeMs)&&this.fsw._emit(Yt.CHANGE,e,_),(Jv||Zv||Qv)&&c.ino!==_.ino){this.fsw._closeFile(p),c=_;let T=this._watchWithNodeFs(e,u);T&&this.fsw._addPathCloser(p,T)}else c=_}catch{this.fsw._remove(n,s)}else if(a.has(s)){let _=m.atimeMs,E=m.mtimeMs;(!_||_<=E||E!==c.mtimeMs)&&this.fsw._emit(Yt.CHANGE,e,m),c=m}}},d=this._watchWithNodeFs(e,u);if(!(i&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(Yt.ADD,e,0))return;this.fsw._emit(Yt.ADD,e,t)}return d}async _handleSymlink(e,t,i,n){if(this.fsw.closed)return;let s=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let c;try{c=await(0,Xt.realpath)(i)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(n)?this.fsw._symlinkPaths.get(s)!==c&&(this.fsw._symlinkPaths.set(s,c),this.fsw._emit(Yt.CHANGE,i,e.stats)):(a.add(n),this.fsw._symlinkPaths.set(s,c),this.fsw._emit(Yt.ADD,i,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(s))return!0;this.fsw._symlinkPaths.set(s,!0)}_handleRead(e,t,i,n,s,a,c){e=Ke.join(e,"");let u=n?`${e}:${n}`: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:_=>i.filterPath(_),directoryFilter:_=>i.filterDir(_)});if(m)return m.on(Xv,async _=>{if(this.fsw.closed){m=void 0;return}let E=_.path,S=Ke.join(e,E);if(p.add(E),!(_.stats.isSymbolicLink()&&await this._handleSymlink(_,e,S,E))){if(this.fsw.closed){m=void 0;return}(E===n||!n&&!d.has(E))&&(this.fsw._incrReadyCount(),S=Ke.join(s,Ke.relative(s,S)),this._addToNodeFs(S,t,i,a+1))}}).on(Yt.ERROR,this._boundHandleError),new Promise((_,E)=>{if(!m)return E();m.once(pf,()=>{if(this.fsw.closed){m=void 0;return}let S=c?c.clear():!1;_(void 0),d.getChildren().filter(T=>T!==e&&!p.has(T)).forEach(T=>{this.fsw._remove(e,T)}),m=void 0,S&&this._handleRead(e,!1,i,n,s,a,c)})})}async _handleDir(e,t,i,n,s,a,c){let u=this.fsw._getWatchedDir(Ke.dirname(e)),d=u.has(Ke.basename(e));!(i&&this.fsw.options.ignoreInitial)&&!s&&!d&&this.fsw._emit(Yt.ADD_DIR,e,t),u.add(Ke.basename(e)),this.fsw._getWatchedDir(e);let p,m,_=this.fsw.options.depth;if((_==null||n<=_)&&!this.fsw._symlinkPaths.has(c)){if(!s&&(await this._handleRead(e,i,a,s,e,n,p),this.fsw.closed))return;m=this._watchWithNodeFs(e,(E,S)=>{S&&S.mtimeMs===0||this._handleRead(E,!1,a,s,e,n,p)})}return m}async _addToNodeFs(e,t,i,n,s){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 tb[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=Ke.resolve(e),_=d?await(0,Xt.realpath)(e):e;if(this.fsw.closed||(p=await this._handleDir(c.watchPath,u,t,n,s,c,_),this.fsw.closed))return;m!==_&&_!==void 0&&this.fsw._symlinkPaths.set(m,_)}else if(u.isSymbolicLink()){let m=d?await(0,Xt.realpath)(e):e;if(this.fsw.closed)return;let _=Ke.dirname(c.watchPath);if(this.fsw._getWatchedDir(_).add(c.watchPath),this.fsw._emit(Yt.ADD,c.watchPath,u),p=await this._handleDir(_,u,t,n,e,c,m),this.fsw.closed)return;m!==void 0&&this.fsw._symlinkPaths.set(Ke.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 mf="/",cb="//",Jd=".",fb="..",ub="string",lb=/\\/g,Zd=/\/\//g,hb=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,db=/^\.[/\\]/;function Ao(r){return Array.isArray(r)?r:[r]}var yf=r=>typeof r=="object"&&r!==null&&!(r instanceof RegExp);function pb(r){return typeof r=="function"?r:typeof r=="string"?e=>r===e:r instanceof RegExp?e=>r.test(e):typeof r=="object"&&r!==null?e=>{if(r.path===e)return!0;if(r.recursive){let t=we.relative(r.path,e);return t?!t.startsWith("..")&&!we.isAbsolute(t):!1}return!1}:()=>!1}function gb(r){if(typeof r!="string")throw new Error("string expected");r=we.normalize(r),r=r.replace(/\\/g,"/");let e=!1;return r.startsWith("//")&&(e=!0),r=r.replace(Zd,"/"),e&&(r="/"+r),r}function Vd(r,e,t){let i=gb(e);for(let n=0;n<r.length;n++){let s=r[n];if(s(i,t))return!0}return!1}function mb(r,e){if(r==null)throw new TypeError("anymatch: specify first argument");let i=Ao(r).map(n=>pb(n));return e==null?(n,s)=>Vd(i,n,s):Vd(i,e)}var zd=r=>{let e=Ao(r).flat();if(!e.every(t=>typeof t===ub))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Qd)},$d=r=>{let e=r.replace(lb,mf),t=!1;return e.startsWith(cb)&&(t=!0),e=e.replace(Zd,mf),t&&(e=mf+e),e},Qd=r=>$d(we.normalize($d(r))),Gd=(r="")=>e=>typeof e=="string"?Qd(we.isAbsolute(e)?e:we.join(r,e)):e,yb=(r,e)=>we.isAbsolute(r)?r:we.join(e,r),_b=Object.freeze(new Set),_f=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!==Jd&&e!==fb&&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,Ro.readdir)(i)}catch{this._removeWatcher&&this._removeWatcher(we.dirname(i),we.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=Oo,this.items=_b,Object.freeze(this)}},vb="stat",bb="lstat",vf=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,t,i){this.fsw=i;let n=e;this.path=e=e.replace(db,""),this.watchPath=n,this.fullWatchPath=we.resolve(n),this.dirParts=[],this.dirParts.forEach(s=>{s.length>1&&s.pop()}),this.followSymlinks=t,this.statMethod=t?vb:bb}entryPath(e){return we.join(this.watchPath,we.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let 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)}},bf=class extends Yd.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},n={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?Ao(e.ignored):Ao([]),awaitWriteFinish:t===!0?i:typeof t=="object"?{...i,...t}:!1};Wd&&(n.usePolling=!0),n.atomic===void 0&&(n.atomic=!n.usePolling);let s=process.env.CHOKIDAR_USEPOLLING;if(s!==void 0){let u=s.toLowerCase();u==="false"||u==="0"?n.usePolling=!1:u==="true"||u==="1"?n.usePolling=!0:n.usePolling=!!u}let a=process.env.CHOKIDAR_INTERVAL;a&&(n.interval=Number.parseInt(a,10));let c=0;this._emitReady=()=>{c++,c>=this._readyCount&&(this._emitReady=Oo,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=n,this._nodeFsHandler=new ko(this),Object.freeze(n)}_addIgnoredPath(e){if(yf(e)){for(let t of this._ignoredPaths)if(yf(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)yf(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,i){let{cwd:n}=this.options;this.closed=!1,this._closePromise=void 0;let s=zd(e);return n&&(s=s.map(a=>yb(a,n))),s.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=s.length,Promise.all(s.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(we.dirname(c),we.basename(t||c))})}),this}unwatch(e){if(this.closed)return this;let t=zd(e),{cwd:i}=this.options;return t.forEach(n=>{!we.isAbsolute(n)&&!this._closers.has(n)&&(i&&(n=we.join(i,n)),n=we.resolve(n)),this._closePath(n),this._addIgnoredPath(n),this._watched.has(n)&&this._addIgnoredPath({path:n,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 n=i();n instanceof Promise&&e.push(n)})),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 s=(this.options.cwd?we.relative(this.options.cwd,i):i)||Jd;e[s]=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 n=this.options;gf&&(t=we.normalize(t)),n.cwd&&(t=we.relative(n.cwd,t));let s=[t];i!=null&&s.push(i);let a=n.awaitWriteFinish,c;if(a&&(c=this._pendingWrites.get(t)))return c.lastChange=new Date,this;if(n.atomic){if(e===Ve.UNLINK)return this._pendingUnlinks.set(t,[e,...s]),setTimeout(()=>{this._pendingUnlinks.forEach((u,d)=>{this.emit(...u),this.emit(Ve.ALL,...u),this._pendingUnlinks.delete(d)})},typeof n.atomic=="number"?n.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,p)=>{d?(e=Ve.ERROR,s[0]=d,this.emitWithAll(e,s)):p&&(s.length>1?s[1]=p:s.push(p),this.emitWithAll(e,s))};return this._awaitWriteFinish(t,a.stabilityThreshold,e,u),this}if(e===Ve.CHANGE&&!this._throttle(Ve.CHANGE,t,50))return this;if(n.alwaysStat&&i===void 0&&(e===Ve.ADD||e===Ve.ADD_DIR||e===Ve.CHANGE)){let u=n.cwd?we.join(n.cwd,t):t,d;try{d=await(0,Ro.stat)(u)}catch{}if(!d||this.closed)return;s.push(d)}return this.emitWithAll(e,s),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 n=this._throttled.get(e);if(!n)throw new Error("invalid throttle");let s=n.get(t);if(s)return s.count++,!1;let a,c=()=>{let d=n.get(t),p=d?d.count:0;return n.delete(t),clearTimeout(a),d&&clearTimeout(d.timeoutObject),p};a=setTimeout(c,i);let u={timeoutObject:a,clear:c,count:0};return n.set(t,u),u}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,i,n){let s=this.options.awaitWriteFinish;if(typeof s!="object")return;let a=s.pollInterval,c,u=e;this.options.cwd&&!we.isAbsolute(e)&&(u=we.join(this.options.cwd,e));let d=new Date,p=this._pendingWrites;function m(_){(0,Xd.stat)(u,(E,S)=>{if(E||!p.has(e)){E&&E.code!=="ENOENT"&&n(E);return}let T=Number(new Date);_&&S.size!==_.size&&(p.get(e).lastChange=T);let z=p.get(e);T-z.lastChange>=t?(p.delete(e),n(void 0,S)):c=setTimeout(m,a,S)})}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&&hb.test(e))return!0;if(!this._userIgnored){let{cwd:i}=this.options,s=(this.options.ignored||[]).map(Gd(i)),c=[...[...this._ignoredPaths].map(Gd(i)),...s];this._userIgnored=mb(c,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new vf(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=we.resolve(e);return this._watched.has(t)||this._watched.set(t,new _f(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,i){let n=we.join(e,t),s=we.resolve(n);if(i=i??(this._watched.has(n)||this._watched.has(s)),!this._throttle("remove",n,100))return;!i&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(n).getChildren().forEach(_=>this._remove(n,_));let u=this._getWatchedDir(e),d=u.has(t);u.remove(t),this._symlinkPaths.has(s)&&this._symlinkPaths.delete(s);let p=n;if(this.options.cwd&&(p=we.relative(this.options.cwd,n)),this.options.awaitWriteFinish&&this._pendingWrites.has(p)&&this._pendingWrites.get(p).cancelWait()===Ve.ADD)return;this._watched.delete(n),this._watched.delete(s);let m=i?Ve.UNLINK_DIR:Ve.UNLINK;d&&!this._isIgnored(n)&&this._emit(m,n),this._closePath(n)}_closePath(e){this._closeFile(e);let t=we.dirname(e);this._getWatchedDir(t).remove(we.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(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},n=jd(e,i);return this._streams.add(n),n.once(Kd,()=>{n=void 0}),n.once(pf,()=>{n&&(this._streams.delete(n),n=void 0)}),n}};function ep(r,e={}){let t=new bf(e);return t.add(r),t}var tp=fe(Oc()),dr=fe(Sr()),Eb=["**/node_modules/**","**/.git/**","**/dist/**","**/.next/**","**/.turbo/**","**/.cache/**","**/coverage/**","**/*.log"],wb=300,Io=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,tp.default)(),this.initializeIgnoreFilter()}initializeIgnoreFilter(){this.ignoreFilter.add(Eb);let e=ei.join(this.workspaceRoot,".gitignore");try{if(cn.existsSync(e)){let t=cn.readFileSync(e,"utf-8");this.ignoreFilter.add(t)}}catch{}}onFileChanged(e){this.onFileChangedCallback=e}start(){this.watcher||(this.watcher=ep(this.workspaceRoot,{ignored:e=>{let t=ei.relative(this.workspaceRoot,e);if(!t||t===".")return!1;let i=t.split(ei.sep).join("/");return this.ignoreFilter.ignores(i)},persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:200,pollInterval:50}}),this.watcher.on("add",e=>this.handleEvent(e,dr.FileChangeType.CREATE)),this.watcher.on("change",e=>this.handleEvent(e,dr.FileChangeType.MODIFY)),this.watcher.on("unlink",e=>this.handleEvent(e,dr.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=ei.relative(this.workspaceRoot,e);if(!i)return;let n=this.pendingEvents.get(i);n&&clearTimeout(n);let s=this.pendingTypes.get(i);this.pendingTypes.set(i,this.mergeTypes(s,t));let a=setTimeout(()=>{this.emit(i,this.pendingTypes.get(i)||t),this.pendingEvents.delete(i),this.pendingTypes.delete(i)},wb);this.pendingEvents.set(i,a)}mergeTypes(e,t){return e?t===dr.FileChangeType.DELETE||e===dr.FileChangeType.DELETE?dr.FileChangeType.DELETE:e===dr.FileChangeType.CREATE?dr.FileChangeType.CREATE:t:t}emit(e,t){let i={path:e,changeType:t,timestamp:new Date().toISOString(),source:"watcher"};if(t!==dr.FileChangeType.DELETE)try{let n=ei.join(this.workspaceRoot,e),s=cn.statSync(n);i.size=s.size}catch{}this.onFileChangedCallback?.(i)}dispose(){this.stop(),this.onFileChangedCallback=null}};var xb={online:!1,viewerCount:0},Lo=class r{enabled=!1;state={...xb};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 No(r,e,t,i){if(i)return process.stderr.write(`Logging in with API key...
30
+ `)}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 Ti.readFile(i,"utf-8")}catch{c=""}let u=(0,Gt.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 n of i.lines)switch(n.type){case"add":t.push(`+${n.content}`);break;case"remove":t.push(`-${n.content}`);break;case"context":t.push(` ${n.content}`);break}}return t.join(`
31
+ `)}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){let t=this.workspaceRoot;if(!t)throw new Error("No workspace root configured");let i=Ic.resolve(t,e);if(i!==t&&!i.startsWith(t+Ic.sep))throw new Error("Path escapes workspace root");return i}dispose(){this.trackedFiles.clear(),this.pendingToolCalls.clear(),this.onFileChangedCallback=null,this.onFileViewTransferCallback=null}};hr.FileTrackerService=Mc});var Vh=M(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.InputStreamReceiver=tt.FileTrackerService=tt.FileListService=tt.FileTransferService=tt.WebSocketService=tt.isAnswerKeystroke=tt.StatusDetector=tt.AuthService=tt.CryptoService=void 0;var _b=gu();Object.defineProperty(tt,"CryptoService",{enumerable:!0,get:function(){return _b.CryptoService}});var bb=mu();Object.defineProperty(tt,"AuthService",{enumerable:!0,get:function(){return bb.AuthService}});var Hh=yu();Object.defineProperty(tt,"StatusDetector",{enumerable:!0,get:function(){return Hh.StatusDetector}});Object.defineProperty(tt,"isAnswerKeystroke",{enumerable:!0,get:function(){return Hh.isAnswerKeystroke}});var vb=Ph();Object.defineProperty(tt,"WebSocketService",{enumerable:!0,get:function(){return vb.WebSocketService}});var Eb=Ah();Object.defineProperty(tt,"FileTransferService",{enumerable:!0,get:function(){return Eb.FileTransferService}});var wb=Kh();Object.defineProperty(tt,"FileListService",{enumerable:!0,get:function(){return wb.FileListService}});var xb=Wh();Object.defineProperty(tt,"FileTrackerService",{enumerable:!0,get:function(){return xb.FileTrackerService}});var Sb=_c();Object.defineProperty(tt,"InputStreamReceiver",{enumerable:!0,get:function(){return Sb.InputStreamReceiver}})});var jn=M(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.FP_LABEL=X.KX_ACK_LABEL=X.KX_SIGN_LABEL=X.concatBytes=X.fingerprintShortHex=X.fingerprintIdentityKey=X.buildKxAckCanonical=X.buildKxCanonical=X.verifySessionKey=X.signSessionKey=X.identityPublicFromSecret=X.generateIdentityKeyPair=X.InputStreamReceiver=X.FileTrackerService=X.FileListService=X.FileTransferService=X.WebSocketService=X.isAnswerKeystroke=X.StatusDetector=X.AuthService=X.CryptoService=X.getCurrentCorrelationId=X.runWithCorrelation=X.generateCorrelationId=X.getWsUrl=X.getApiUrl=X.CircularBuffer=X.formatLogLine=X.shouldLog=X.LOG_LEVELS=void 0;var Fc=Lf();Object.defineProperty(X,"LOG_LEVELS",{enumerable:!0,get:function(){return Fc.LOG_LEVELS}});Object.defineProperty(X,"shouldLog",{enumerable:!0,get:function(){return Fc.shouldLog}});Object.defineProperty(X,"formatLogLine",{enumerable:!0,get:function(){return Fc.formatLogLine}});var nn=Ff();Object.defineProperty(X,"CircularBuffer",{enumerable:!0,get:function(){return nn.CircularBuffer}});Object.defineProperty(X,"getApiUrl",{enumerable:!0,get:function(){return nn.getApiUrl}});Object.defineProperty(X,"getWsUrl",{enumerable:!0,get:function(){return nn.getWsUrl}});Object.defineProperty(X,"generateCorrelationId",{enumerable:!0,get:function(){return nn.generateCorrelationId}});Object.defineProperty(X,"runWithCorrelation",{enumerable:!0,get:function(){return nn.runWithCorrelation}});Object.defineProperty(X,"getCurrentCorrelationId",{enumerable:!0,get:function(){return nn.getCurrentCorrelationId}});var Ir=Vh();Object.defineProperty(X,"CryptoService",{enumerable:!0,get:function(){return Ir.CryptoService}});Object.defineProperty(X,"AuthService",{enumerable:!0,get:function(){return Ir.AuthService}});Object.defineProperty(X,"StatusDetector",{enumerable:!0,get:function(){return Ir.StatusDetector}});Object.defineProperty(X,"isAnswerKeystroke",{enumerable:!0,get:function(){return Ir.isAnswerKeystroke}});Object.defineProperty(X,"WebSocketService",{enumerable:!0,get:function(){return Ir.WebSocketService}});Object.defineProperty(X,"FileTransferService",{enumerable:!0,get:function(){return Ir.FileTransferService}});Object.defineProperty(X,"FileListService",{enumerable:!0,get:function(){return Ir.FileListService}});Object.defineProperty(X,"FileTrackerService",{enumerable:!0,get:function(){return Ir.FileTrackerService}});Object.defineProperty(X,"InputStreamReceiver",{enumerable:!0,get:function(){return Ir.InputStreamReceiver}});var Kt=Zo();Object.defineProperty(X,"generateIdentityKeyPair",{enumerable:!0,get:function(){return Kt.generateIdentityKeyPair}});Object.defineProperty(X,"identityPublicFromSecret",{enumerable:!0,get:function(){return Kt.identityPublicFromSecret}});Object.defineProperty(X,"signSessionKey",{enumerable:!0,get:function(){return Kt.signSessionKey}});Object.defineProperty(X,"verifySessionKey",{enumerable:!0,get:function(){return Kt.verifySessionKey}});Object.defineProperty(X,"buildKxCanonical",{enumerable:!0,get:function(){return Kt.buildKxCanonical}});Object.defineProperty(X,"buildKxAckCanonical",{enumerable:!0,get:function(){return Kt.buildKxAckCanonical}});Object.defineProperty(X,"fingerprintIdentityKey",{enumerable:!0,get:function(){return Kt.fingerprintIdentityKey}});Object.defineProperty(X,"fingerprintShortHex",{enumerable:!0,get:function(){return Kt.fingerprintShortHex}});Object.defineProperty(X,"concatBytes",{enumerable:!0,get:function(){return Kt.concatBytes}});Object.defineProperty(X,"KX_SIGN_LABEL",{enumerable:!0,get:function(){return Kt.KX_SIGN_LABEL}});Object.defineProperty(X,"KX_ACK_LABEL",{enumerable:!0,get:function(){return Kt.KX_ACK_LABEL}});Object.defineProperty(X,"FP_LABEL",{enumerable:!0,get:function(){return Kt.FP_LABEL}})});var Uc=M((Kn,jc)=>{(function(r,e){typeof Kn=="object"&&typeof jc=="object"?jc.exports=e(require("child_process"),require("crypto")):typeof define=="function"&&define.amd?define(["child_process","crypto"],e):typeof Kn=="object"?Kn["electron-machine-id"]=e(require("child_process"),require("crypto")):r["electron-machine-id"]=e(r.child_process,r.crypto)})(Kn,function(r,e){return(function(t){function i(s){if(n[s])return n[s].exports;var a=n[s]={exports:{},id:s,loaded:!1};return t[s].call(a.exports,a,a.exports,i),a.loaded=!0,a.exports}var n={};return i.m=t,i.c=n,i.p="",i(0)})([function(t,i,n){t.exports=n(34)},function(t,i,n){var s=n(29)("wks"),a=n(33),c=n(2).Symbol,u=typeof c=="function",d=t.exports=function(p){return s[p]||(s[p]=u&&c[p]||(u?c:a)("Symbol."+p))};d.store=s},function(t,i){var n=t.exports=typeof window<"u"&&window.Math==Math?window:typeof self<"u"&&self.Math==Math?self:Function("return this")();typeof __g=="number"&&(__g=n)},function(t,i,n){var s=n(9);t.exports=function(a){if(!s(a))throw TypeError(a+" is not an object!");return a}},function(t,i,n){t.exports=!n(24)(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7})},function(t,i,n){var s=n(12),a=n(17);t.exports=n(4)?function(c,u,d){return s.f(c,u,a(1,d))}:function(c,u,d){return c[u]=d,c}},function(t,i){var n=t.exports={version:"2.4.0"};typeof __e=="number"&&(__e=n)},function(t,i,n){var s=n(14);t.exports=function(a,c,u){if(s(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 n={}.hasOwnProperty;t.exports=function(s,a){return n.call(s,a)}},function(t,i){t.exports=function(n){return typeof n=="object"?n!==null:typeof n=="function"}},function(t,i){t.exports={}},function(t,i){var n={}.toString;t.exports=function(s){return n.call(s).slice(8,-1)}},function(t,i,n){var s=n(3),a=n(26),c=n(32),u=Object.defineProperty;i.f=n(4)?Object.defineProperty:function(d,p,m){if(s(d),p=c(p,!0),s(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,n){var s=n(42),a=n(15);t.exports=function(c){return s(a(c))}},function(t,i){t.exports=function(n){if(typeof n!="function")throw TypeError(n+" is not a function!");return n}},function(t,i){t.exports=function(n){if(n==null)throw TypeError("Can't call method on "+n);return n}},function(t,i,n){var s=n(9),a=n(2).document,c=s(a)&&s(a.createElement);t.exports=function(u){return c?a.createElement(u):{}}},function(t,i){t.exports=function(n,s){return{enumerable:!(1&n),configurable:!(2&n),writable:!(4&n),value:s}}},function(t,i,n){var s=n(12).f,a=n(8),c=n(1)("toStringTag");t.exports=function(u,d,p){u&&!a(u=p?u:u.prototype,c)&&s(u,c,{configurable:!0,value:d})}},function(t,i,n){var s=n(29)("keys"),a=n(33);t.exports=function(c){return s[c]||(s[c]=a(c))}},function(t,i){var n=Math.ceil,s=Math.floor;t.exports=function(a){return isNaN(a=+a)?0:(a>0?s:n)(a)}},function(t,i,n){var s=n(11),a=n(1)("toStringTag"),c=s((function(){return arguments})())=="Arguments",u=function(d,p){try{return d[p]}catch{}};t.exports=function(d){var p,m,_;return d===void 0?"Undefined":d===null?"Null":typeof(m=u(p=Object(d),a))=="string"?m:c?s(p):(_=s(p))=="Object"&&typeof p.callee=="function"?"Arguments":_}},function(t,i){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,i,n){var s=n(2),a=n(6),c=n(7),u=n(5),d="prototype",p=function(m,_,E){var S,T,z,ge=m&p.F,ee=m&p.G,R=m&p.S,B=m&p.P,re=m&p.B,K=m&p.W,U=ee?a:a[_]||(a[_]={}),ye=U[d],xe=ee?s:R?s[_]:(s[_]||{})[d];ee&&(E=_);for(S in E)T=!ge&&xe&&xe[S]!==void 0,T&&S in U||(z=T?xe[S]:E[S],U[S]=ee&&typeof xe[S]!="function"?E[S]:re&&T?c(z,s):K&&xe[S]==z?(function(ue){var rt=function(Ee,Se,ve){if(this instanceof ue){switch(arguments.length){case 0:return new ue;case 1:return new ue(Ee);case 2:return new ue(Ee,Se)}return new ue(Ee,Se,ve)}return ue.apply(this,arguments)};return rt[d]=ue[d],rt})(z):B&&typeof z=="function"?c(Function.call,z):z,B&&((U.virtual||(U.virtual={}))[S]=z,m&p.R&&ye&&!ye[S]&&u(ye,S,z)))};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(n){try{return!!n()}catch{return!0}}},function(t,i,n){t.exports=n(2).document&&document.documentElement},function(t,i,n){t.exports=!n(4)&&!n(24)(function(){return Object.defineProperty(n(16)("div"),"a",{get:function(){return 7}}).a!=7})},function(t,i,n){"use strict";var s=n(28),a=n(23),c=n(57),u=n(5),d=n(8),p=n(10),m=n(45),_=n(18),E=n(52),S=n(1)("iterator"),T=!([].keys&&"next"in[].keys()),z="@@iterator",ge="keys",ee="values",R=function(){return this};t.exports=function(B,re,K,U,ye,xe,ue){m(K,re,U);var rt,Ee,Se,ve=function(j){if(!T&&j in Te)return Te[j];switch(j){case ge:return function(){return new K(this,j)};case ee:return function(){return new K(this,j)}}return function(){return new K(this,j)}},We=re+" Iterator",st=ye==ee,Ze=!1,Te=B.prototype,it=Te[S]||Te[z]||ye&&Te[ye],ze=it||ve(ye),gt=ye?st?ve("entries"):ze:void 0,L=re=="Array"&&Te.entries||it;if(L&&(Se=E(L.call(new B)),Se!==Object.prototype&&(_(Se,We,!0),s||d(Se,S)||u(Se,S,R))),st&&it&&it.name!==ee&&(Ze=!0,ze=function(){return it.call(this)}),s&&!ue||!T&&!Ze&&Te[S]||u(Te,S,ze),p[re]=ze,p[We]=R,ye)if(rt={values:st?ze:ve(ee),keys:xe?ze:ve(ge),entries:gt},ue)for(Ee in rt)Ee in Te||c(Te,Ee,rt[Ee]);else a(a.P+a.F*(T||Ze),re,rt);return rt}},function(t,i){t.exports=!0},function(t,i,n){var s=n(2),a="__core-js_shared__",c=s[a]||(s[a]={});t.exports=function(u){return c[u]||(c[u]={})}},function(t,i,n){var s,a,c,u=n(7),d=n(41),p=n(25),m=n(16),_=n(2),E=_.process,S=_.setImmediate,T=_.clearImmediate,z=_.MessageChannel,ge=0,ee={},R="onreadystatechange",B=function(){var K=+this;if(ee.hasOwnProperty(K)){var U=ee[K];delete ee[K],U()}},re=function(K){B.call(K.data)};S&&T||(S=function(K){for(var U=[],ye=1;arguments.length>ye;)U.push(arguments[ye++]);return ee[++ge]=function(){d(typeof K=="function"?K:Function(K),U)},s(ge),ge},T=function(K){delete ee[K]},n(11)(E)=="process"?s=function(K){E.nextTick(u(B,K,1))}:z?(a=new z,c=a.port2,a.port1.onmessage=re,s=u(c.postMessage,c,1)):_.addEventListener&&typeof postMessage=="function"&&!_.importScripts?(s=function(K){_.postMessage(K+"","*")},_.addEventListener("message",re,!1)):s=R in m("script")?function(K){p.appendChild(m("script"))[R]=function(){p.removeChild(this),B.call(K)}}:function(K){setTimeout(u(B,K,1),0)}),t.exports={set:S,clear:T}},function(t,i,n){var s=n(20),a=Math.min;t.exports=function(c){return c>0?a(s(c),9007199254740991):0}},function(t,i,n){var s=n(9);t.exports=function(a,c){if(!s(a))return a;var u,d;if(c&&typeof(u=a.toString)=="function"&&!s(d=u.call(a))||typeof(u=a.valueOf)=="function"&&!s(d=u.call(a))||!c&&typeof(u=a.toString)=="function"&&!s(d=u.call(a)))return d;throw TypeError("Can't convert object to primitive value")}},function(t,i){var n=0,s=Math.random();t.exports=function(a){return"Symbol(".concat(a===void 0?"":a,")_",(++n+s).toString(36))}},function(t,i,n){"use strict";function s(R){return R&&R.__esModule?R:{default:R}}function a(){return process.platform!=="win32"?"":process.arch==="ia32"&&process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432")?"mixed":"native"}function c(R){return(0,S.createHash)("sha256").update(R).digest("hex")}function u(R){switch(z){case"darwin":return R.split("IOPlatformUUID")[1].split(`
32
+ `)[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return R.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return R.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"freebsd":return R.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error("Unsupported platform: "+process.platform)}}function d(R){var B=u((0,E.execSync)(ee[z]).toString());return R?B:c(B)}function p(R){return new _.default(function(B,re){return(0,E.exec)(ee[z],{},function(K,U,ye){if(K)return re(new Error("Error while obtaining machine id: "+K.stack));var xe=u(U.toString());return B(R?xe:c(xe))})})}Object.defineProperty(i,"__esModule",{value:!0});var m=n(35),_=s(m);i.machineIdSync=d,i.machineId=p;var E=n(70),S=n(71),T=process,z=T.platform,ge={native:"%windir%\\System32",mixed:"%windir%\\sysnative\\cmd.exe /c %windir%\\System32"},ee={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,n){t.exports={default:n(36),__esModule:!0}},function(t,i,n){n(66),n(68),n(69),n(67),t.exports=n(6).Promise},function(t,i){t.exports=function(){}},function(t,i){t.exports=function(n,s,a,c){if(!(n instanceof s)||c!==void 0&&c in n)throw TypeError(a+": incorrect invocation!");return n}},function(t,i,n){var s=n(13),a=n(31),c=n(62);t.exports=function(u){return function(d,p,m){var _,E=s(d),S=a(E.length),T=c(m,S);if(u&&p!=p){for(;S>T;)if(_=E[T++],_!=_)return!0}else for(;S>T;T++)if((u||T in E)&&E[T]===p)return u||T||0;return!u&&-1}}},function(t,E,n){var s=n(7),a=n(44),c=n(43),u=n(3),d=n(31),p=n(64),m={},_={},E=t.exports=function(S,T,z,ge,ee){var R,B,re,K,U=ee?function(){return S}:p(S),ye=s(z,ge,T?2:1),xe=0;if(typeof U!="function")throw TypeError(S+" is not iterable!");if(c(U)){for(R=d(S.length);R>xe;xe++)if(K=T?ye(u(B=S[xe])[0],B[1]):ye(S[xe]),K===m||K===_)return K}else for(re=U.call(S);!(B=re.next()).done;)if(K=a(re,ye,B.value,T),K===m||K===_)return K};E.BREAK=m,E.RETURN=_},function(t,i){t.exports=function(n,s,a){var c=a===void 0;switch(s.length){case 0:return c?n():n.call(a);case 1:return c?n(s[0]):n.call(a,s[0]);case 2:return c?n(s[0],s[1]):n.call(a,s[0],s[1]);case 3:return c?n(s[0],s[1],s[2]):n.call(a,s[0],s[1],s[2]);case 4:return c?n(s[0],s[1],s[2],s[3]):n.call(a,s[0],s[1],s[2],s[3])}return n.apply(a,s)}},function(t,i,n){var s=n(11);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(a){return s(a)=="String"?a.split(""):Object(a)}},function(t,i,n){var s=n(10),a=n(1)("iterator"),c=Array.prototype;t.exports=function(u){return u!==void 0&&(s.Array===u||c[a]===u)}},function(t,i,n){var s=n(3);t.exports=function(a,c,u,d){try{return d?c(s(u)[0],u[1]):c(u)}catch(m){var p=a.return;throw p!==void 0&&s(p.call(a)),m}}},function(t,i,n){"use strict";var s=n(49),a=n(17),c=n(18),u={};n(5)(u,n(1)("iterator"),function(){return this}),t.exports=function(d,p,m){d.prototype=s(u,{next:a(1,m)}),c(d,p+" Iterator")}},function(t,i,n){var s=n(1)("iterator"),a=!1;try{var c=[7][s]();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],_=m[s]();_.next=function(){return{done:p=!0}},m[s]=function(){return _},u(m)}catch{}return p}},function(t,i){t.exports=function(n,s){return{value:s,done:!!n}}},function(t,i,n){var s=n(2),a=n(30).set,c=s.MutationObserver||s.WebKitMutationObserver,u=s.process,d=s.Promise,p=n(11)(u)=="process";t.exports=function(){var m,_,E,S=function(){var ee,R;for(p&&(ee=u.domain)&&ee.exit();m;){R=m.fn,m=m.next;try{R()}catch(B){throw m?E():_=void 0,B}}_=void 0,ee&&ee.enter()};if(p)E=function(){u.nextTick(S)};else if(c){var T=!0,z=document.createTextNode("");new c(S).observe(z,{characterData:!0}),E=function(){z.data=T=!T}}else if(d&&d.resolve){var ge=d.resolve();E=function(){ge.then(S)}}else E=function(){a.call(s,S)};return function(ee){var R={fn:ee,next:void 0};_&&(_.next=R),m||(m=R,E()),_=R}}},function(t,i,n){var s=n(3),a=n(50),c=n(22),u=n(19)("IE_PROTO"),d=function(){},p="prototype",m=function(){var _,E=n(16)("iframe"),S=c.length,T=">";for(E.style.display="none",n(25).appendChild(E),E.src="javascript:",_=E.contentWindow.document,_.open(),_.write("<script>document.F=Object</script"+T),_.close(),m=_.F;S--;)delete m[p][c[S]];return m()};t.exports=Object.create||function(_,E){var S;return _!==null?(d[p]=s(_),S=new d,d[p]=null,S[u]=_):S=m(),E===void 0?S:a(S,E)}},function(t,i,n){var s=n(12),a=n(3),c=n(54);t.exports=n(4)?Object.defineProperties:function(u,d){a(u);for(var p,m=c(d),_=m.length,E=0;_>E;)s.f(u,p=m[E++],d[p]);return u}},function(t,i,n){var s=n(55),a=n(17),c=n(13),u=n(32),d=n(8),p=n(26),m=Object.getOwnPropertyDescriptor;i.f=n(4)?m:function(_,E){if(_=c(_),E=u(E,!0),p)try{return m(_,E)}catch{}if(d(_,E))return a(!s.f.call(_,E),_[E])}},function(t,i,n){var s=n(8),a=n(63),c=n(19)("IE_PROTO"),u=Object.prototype;t.exports=Object.getPrototypeOf||function(d){return d=a(d),s(d,c)?d[c]:typeof d.constructor=="function"&&d instanceof d.constructor?d.constructor.prototype:d instanceof Object?u:null}},function(t,i,n){var s=n(8),a=n(13),c=n(39)(!1),u=n(19)("IE_PROTO");t.exports=function(d,p){var m,_=a(d),E=0,S=[];for(m in _)m!=u&&s(_,m)&&S.push(m);for(;p.length>E;)s(_,m=p[E++])&&(~c(S,m)||S.push(m));return S}},function(t,i,n){var s=n(53),a=n(22);t.exports=Object.keys||function(c){return s(c,a)}},function(t,i){i.f={}.propertyIsEnumerable},function(t,i,n){var s=n(5);t.exports=function(a,c,u){for(var d in c)u&&a[d]?a[d]=c[d]:s(a,d,c[d]);return a}},function(t,i,n){t.exports=n(5)},function(t,i,n){var s=n(9),a=n(3),c=function(u,d){if(a(u),!s(d)&&d!==null)throw TypeError(d+": can't set as prototype!")};t.exports={set:Object.setPrototypeOf||("__proto__"in{}?(function(u,d,p){try{p=n(7)(Function.call,n(51).f(Object.prototype,"__proto__").set,2),p(u,[]),d=!(u instanceof Array)}catch{d=!0}return function(m,_){return c(m,_),d?m.__proto__=_:p(m,_),m}})({},!1):void 0),check:c}},function(t,i,n){"use strict";var s=n(2),a=n(6),c=n(12),u=n(4),d=n(1)("species");t.exports=function(p){var m=typeof a[p]=="function"?a[p]:s[p];u&&m&&!m[d]&&c.f(m,d,{configurable:!0,get:function(){return this}})}},function(t,i,n){var s=n(3),a=n(14),c=n(1)("species");t.exports=function(u,d){var p,m=s(u).constructor;return m===void 0||(p=s(m)[c])==null?d:a(p)}},function(t,i,n){var s=n(20),a=n(15);t.exports=function(c){return function(u,d){var p,m,_=String(a(u)),E=s(d),S=_.length;return E<0||E>=S?c?"":void 0:(p=_.charCodeAt(E),p<55296||p>56319||E+1===S||(m=_.charCodeAt(E+1))<56320||m>57343?c?_.charAt(E):p:c?_.slice(E,E+2):(p-55296<<10)+(m-56320)+65536)}}},function(t,i,n){var s=n(20),a=Math.max,c=Math.min;t.exports=function(u,d){return u=s(u),u<0?a(u+d,0):c(u,d)}},function(t,i,n){var s=n(15);t.exports=function(a){return Object(s(a))}},function(t,i,n){var s=n(21),a=n(1)("iterator"),c=n(10);t.exports=n(6).getIteratorMethod=function(u){if(u!=null)return u[a]||u["@@iterator"]||c[s(u)]}},function(t,i,n){"use strict";var s=n(37),a=n(47),c=n(10),u=n(13);t.exports=n(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,s("keys"),s("values"),s("entries")},function(t,i){},function(t,i,n){"use strict";var s,a,c,u=n(28),d=n(2),p=n(7),m=n(21),_=n(23),E=n(9),S=(n(3),n(14)),T=n(38),z=n(40),ge=(n(58).set,n(60)),ee=n(30).set,R=n(48)(),B="Promise",re=d.TypeError,U=d.process,K=d[B],U=d.process,ye=m(U)=="process",xe=function(){},ue=!!(function(){try{var L=K.resolve(1),j=(L.constructor={})[n(1)("species")]=function(A){A(xe,xe)};return(ye||typeof PromiseRejectionEvent=="function")&&L.then(xe)instanceof j}catch{}})(),rt=function(L,j){return L===j||L===K&&j===c},Ee=function(L){var j;return!(!E(L)||typeof(j=L.then)!="function")&&j},Se=function(L){return rt(K,L)?new ve(L):new a(L)},ve=a=function(L){var j,A;this.promise=new L(function(P,Z){if(j!==void 0||A!==void 0)throw re("Bad Promise constructor");j=P,A=Z}),this.resolve=S(j),this.reject=S(A)},We=function(L){try{L()}catch(j){return{error:j}}},st=function(L,j){if(!L._n){L._n=!0;var A=L._c;R(function(){for(var P=L._v,Z=L._s==1,Ne=0,Xe=function(lt){var wt,mr,Mr=Z?lt.ok:lt.fail,ii=lt.resolve,Fr=lt.reject,Oi=lt.domain;try{Mr?(Z||(L._h==2&&it(L),L._h=1),Mr===!0?wt=P:(Oi&&Oi.enter(),wt=Mr(P),Oi&&Oi.exit()),wt===lt.promise?Fr(re("Promise-chain cycle")):(mr=Ee(wt))?mr.call(wt,ii,Fr):ii(wt)):Fr(P)}catch(Xn){Fr(Xn)}};A.length>Ne;)Xe(A[Ne++]);L._c=[],L._n=!1,j&&!L._h&&Ze(L)})}},Ze=function(L){ee.call(d,function(){var j,A,P,Z=L._v;if(Te(L)&&(j=We(function(){ye?U.emit("unhandledRejection",Z,L):(A=d.onunhandledrejection)?A({promise:L,reason:Z}):(P=d.console)&&P.error&&P.error("Unhandled promise rejection",Z)}),L._h=ye||Te(L)?2:1),L._a=void 0,j)throw j.error})},Te=function(L){if(L._h==1)return!1;for(var j,A=L._a||L._c,P=0;A.length>P;)if(j=A[P++],j.fail||!Te(j.promise))return!1;return!0},it=function(L){ee.call(d,function(){var j;ye?U.emit("rejectionHandled",L):(j=d.onrejectionhandled)&&j({promise:L,reason:L._v})})},ze=function(L){var j=this;j._d||(j._d=!0,j=j._w||j,j._v=L,j._s=2,j._a||(j._a=j._c.slice()),st(j,!0))},gt=function(L){var j,A=this;if(!A._d){A._d=!0,A=A._w||A;try{if(A===L)throw re("Promise can't be resolved itself");(j=Ee(L))?R(function(){var P={_w:A,_d:!1};try{j.call(L,p(gt,P,1),p(ze,P,1))}catch(Z){ze.call(P,Z)}}):(A._v=L,A._s=1,st(A,!1))}catch(P){ze.call({_w:A,_d:!1},P)}}};ue||(K=function(L){T(this,K,B,"_h"),S(L),s.call(this);try{L(p(gt,this,1),p(ze,this,1))}catch(j){ze.call(this,j)}},s=function(L){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},s.prototype=n(56)(K.prototype,{then:function(L,j){var A=Se(ge(this,K));return A.ok=typeof L!="function"||L,A.fail=typeof j=="function"&&j,A.domain=ye?U.domain:void 0,this._c.push(A),this._a&&this._a.push(A),this._s&&st(this,!1),A.promise},catch:function(L){return this.then(void 0,L)}}),ve=function(){var L=new s;this.promise=L,this.resolve=p(gt,L,1),this.reject=p(ze,L,1)}),_(_.G+_.W+_.F*!ue,{Promise:K}),n(18)(K,B),n(59)(B),c=n(6)[B],_(_.S+_.F*!ue,B,{reject:function(L){var j=Se(this),A=j.reject;return A(L),j.promise}}),_(_.S+_.F*(u||!ue),B,{resolve:function(L){if(L instanceof K&&rt(L.constructor,this))return L;var j=Se(this),A=j.resolve;return A(L),j.promise}}),_(_.S+_.F*!(ue&&n(46)(function(L){K.all(L).catch(xe)})),B,{all:function(L){var j=this,A=Se(j),P=A.resolve,Z=A.reject,Ne=We(function(){var Xe=[],lt=0,wt=1;z(L,!1,function(mr){var Mr=lt++,ii=!1;Xe.push(void 0),wt++,j.resolve(mr).then(function(Fr){ii||(ii=!0,Xe[Mr]=Fr,--wt||P(Xe))},Z)}),--wt||P(Xe)});return Ne&&Z(Ne.error),A.promise},race:function(L){var j=this,A=Se(j),P=A.reject,Z=We(function(){z(L,!1,function(Ne){j.resolve(Ne).then(A.resolve,P)})});return Z&&P(Z.error),A.promise}})},function(t,i,n){"use strict";var s=n(61)(!0);n(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=s(c,u),this._i+=a.length,{value:a,done:!1})})},function(t,i,n){n(65);for(var s=n(2),a=n(5),c=n(10),u=n(1)("toStringTag"),d=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],p=0;p<5;p++){var m=d[p],_=s[m],E=_&&_.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 Pb(){try{return qc.default.statSync("/.dockerenv"),!0}catch{return!1}}function Rb(){try{return qc.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Wc(){return Kc===void 0&&(Kc=Pb()||Rb()),Kc}var qc,Kc,Xh=qt(()=>{qc=fe(require("node:fs"),1)});function sn(){return Hc===void 0&&(Hc=Ab()||Wc()),Hc}var Jh,Hc,Ab,Vc=qt(()=>{Jh=fe(require("node:fs"),1);Xh();Ab=()=>{try{return Jh.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var zc,Qh,ed,Zh,Jr,$c=qt(()=>{zc=fe(require("node:process"),1),Qh=fe(require("node:os"),1),ed=fe(require("node:fs"),1);Vc();Zh=()=>{if(zc.default.platform!=="linux")return!1;if(Qh.default.release().toLowerCase().includes("microsoft"))return!sn();try{return ed.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!sn():!1}catch{return!1}},Jr=zc.default.env.__IS_WSL_TEST__?Zh:Zh()});var Gc,Hn,Ib,Lb,Yc,td=qt(()=>{Gc=fe(require("node:process"),1),Hn=fe(require("node:fs/promises"),1);$c();$c();Ib=(()=>{let r="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",i=!1;try{await Hn.default.access(t,Hn.constants.F_OK),i=!0}catch{}if(!i)return r;let n=await Hn.default.readFile(t,{encoding:"utf8"}),s=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(n);return s?(e=s.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):r}})(),Lb=async()=>`${await Ib()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Yc=async()=>Jr?Lb():`${Gc.default.env.SYSTEMROOT||Gc.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function Zr(r,e,t){let i=n=>Object.defineProperty(r,e,{value:n,enumerable:!0,writable:!0});return Object.defineProperty(r,e,{configurable:!0,enumerable:!0,get(){let n=t();return i(n),n},set(n){i(n)}}),r}var rd=qt(()=>{});async function Xc(){if(nd.default.platform!=="darwin")throw new Error("macOS only");let{stdout:r}=await Nb("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 id,nd,sd,Nb,od=qt(()=>{id=require("node:util"),nd=fe(require("node:process"),1),sd=require("node:child_process"),Nb=(0,id.promisify)(sd.execFile)});async function fd(r,{humanReadableOutput:e=!0,signal:t}={}){if(ad.default.platform!=="darwin")throw new Error("macOS only");let i=e?[]:["-ss"],n={};t&&(n.signal=t);let{stdout:s}=await Mb("osascript",["-e",r,i],n);return s.trim()}var ad,cd,Jc,Mb,ud=qt(()=>{ad=fe(require("node:process"),1),cd=require("node:util"),Jc=require("node:child_process"),Mb=(0,cd.promisify)(Jc.execFile)});async function Zc(r){return fd(`tell application "Finder" to set app_path to application file id "${r}" as string
33
+ tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var ld=qt(()=>{ud()});async function ef(r=Fb){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 Qc(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:i}=t.groups,n=i.lastIndexOf("."),s=i.lastIndexOf("-"),a=n===-1?void 0:i.slice(0,n),c=s===-1?void 0:i.slice(0,s);return _o[i]??_o[a]??_o[c]??{name:i,id:i}}var hd,dd,Fb,_o,Gw,Qc,pd=qt(()=>{hd=require("node:util"),dd=require("node:child_process"),Fb=(0,hd.promisify)(dd.execFile),_o={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"}},Gw=new Map(Object.entries(_o)),Qc=class extends Error{}});async function tf(){if(bo.default.platform==="darwin"){let r=await Xc();return{name:await Zc(r),id:r}}if(bo.default.platform==="linux"){let{stdout:r}=await Db("xdg-mime",["query","default","x-scheme-handler/http"]),e=r.trim();return{name:Bb(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(bo.default.platform==="win32")return ef();throw new Error("Only macOS, Linux, and Windows are supported")}var gd,bo,md,Db,Bb,yd=qt(()=>{gd=require("node:util"),bo=fe(require("node:process"),1),md=require("node:child_process");od();ld();pd();Db=(0,gd.promisify)(md.execFile),Bb=r=>r.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var Sd={};Ep(Sd,{apps:()=>Qr,default:()=>Wb,openApp:()=>qb});async function Ub(){let r=await Yc(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=sf.Buffer.from(e,"utf16le").toString("base64"),{stdout:i}=await jb(r,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),n=i.trim(),s={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return s[n]?{id:s[n]}:{}}function Ed(r){if(typeof r=="string"||Array.isArray(r))return r;let{[bd]:e}=r;if(!e)throw new Error(`${bd} is not supported`);return e}function Eo({[on]:r},{wsl:e}){if(e&&Jr)return Ed(e);if(!r)throw new Error(`${on} is not supported`);return Ed(r)}var nf,sf,of,wd,xd,af,vo,Hb,jb,rf,_d,on,bd,vd,Vn,Kb,qb,Qr,Wb,Td=qt(()=>{nf=fe(require("node:process"),1),sf=require("node:buffer"),of=fe(require("node:path"),1),wd=require("node:url"),xd=require("node:util"),af=fe(require("node:child_process"),1),vo=fe(require("node:fs/promises"),1);td();rd();yd();Vc();Hb={},jb=(0,xd.promisify)(af.default.execFile),rf=of.default.dirname((0,wd.fileURLToPath)(Hb.url)),_d=of.default.join(rf,"xdg-open"),{platform:on,arch:bd}=nf.default;vd=async(r,e)=>{let t;for(let i of r)try{return await e(i)}catch(n){t=n}throw t},Vn=async r=>{if(r={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...r},Array.isArray(r.app))return vd(r.app,c=>Vn({...r,app:c}));let{name:e,arguments:t=[]}=r.app??{};if(t=[...t],Array.isArray(e))return vd(e,c=>Vn({...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=Jr?await Ub():await tf();if(d.id in c){let p=c[d.id];return e==="browserPrivate"&&t.push(u[p]),Vn({...r,app:{name:Qr[p],arguments:t}})}throw new Error(`${d.name} is not supported as a default browser`)}let i,n=[],s={};if(on==="darwin")i="open",r.wait&&n.push("--wait-apps"),r.background&&n.push("--background"),r.newInstance&&n.push("--new"),e&&n.push("-a",e);else if(on==="win32"||Jr&&!sn()&&!e){i=await Yc(),n.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),Jr||(s.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=sf.Buffer.from(c.join(" "),"utf16le").toString("base64")}else{if(e)i=e;else{let c=!rf||rf==="/",u=!1;try{await vo.default.access(_d,vo.constants.X_OK),u=!0}catch{}i=nf.default.versions.electron??(on==="android"||c||!u)?"xdg-open":_d}t.length>0&&n.push(...t),r.wait||(s.stdio="ignore",s.detached=!0)}on==="darwin"&&t.length>0&&n.push("--args",...t),r.target&&n.push(r.target);let a=af.default.spawn(i,n,s);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)},Kb=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a `target`");return Vn({...e,target:r})},qb=(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 Vn({...e,app:{name:r,arguments:t}})};Qr={};Zr(Qr,"chrome",()=>Eo({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"]}}));Zr(Qr,"brave",()=>Eo({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"]}}));Zr(Qr,"firefox",()=>Eo({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Zr(Qr,"edge",()=>Eo({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Zr(Qr,"browser",()=>"browser");Zr(Qr,"browserPrivate",()=>"browserPrivate");Wb=Kb});var _r=fe(require("fs")),ns=fe(require("path"));var Of=fe(require("os")),Pf=fe(require("path")),rs=fe(require("fs"));function is(){let r=Pf.join(Of.homedir(),".termiq");return rs.existsSync(r)||rs.mkdirSync(r,{recursive:!0,mode:448}),r}var pn=class{filePath;data={};constructor(){this.filePath=ns.join(is(),"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(_r.existsSync(this.filePath)){let e=_r.readFileSync(this.filePath,"utf-8");this.data=JSON.parse(e)}}catch{this.data={}}}save(){let e=ns.dirname(this.filePath);_r.existsSync(e)||_r.mkdirSync(e,{recursive:!0,mode:448}),_r.writeFileSync(this.filePath,JSON.stringify(this.data,null,2),{mode:384})}};var br=fe(require("fs")),ss=fe(require("path"));var xp={serverUrl:"https://termiq.io",agentName:"",multiViewer:!1},gn=class{config;filePath;constructor(e){this.filePath=ss.join(is(),"config.json"),this.config={...xp,...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(br.existsSync(this.filePath)){let e=br.readFileSync(this.filePath,"utf-8");return JSON.parse(e)}}catch{}return{}}saveToFile(){let e=ss.dirname(this.filePath);br.existsSync(e)||br.mkdirSync(e,{recursive:!0,mode:448}),br.writeFileSync(this.filePath,JSON.stringify(this.config,null,2))}};var _t=fe(require("fs")),Bc=fe(require("path")),$h=fe(require("os")),yo=fe(jn()),Tb="cli",Dc=Bc.join($h.homedir(),".termiq","logs"),Xr=Bc.join(Dc,"cli.log"),Cb=5*1024*1024,zh=3;function kb(){try{if(!_t.existsSync(Xr)||_t.statSync(Xr).size<Cb)return;for(let e=zh-1;e>=1;e--){let t=`${Xr}.${e}`,i=`${Xr}.${e+1}`;_t.existsSync(t)&&(e+1>zh?_t.unlinkSync(t):_t.renameSync(t,i))}_t.renameSync(Xr,`${Xr}.1`)}catch{}}function Ob(r){try{_t.existsSync(Dc)||_t.mkdirSync(Dc,{recursive:!0}),kb(),_t.appendFileSync(Xr,r+`
34
+ `,{encoding:"utf8"})}catch{}}var Un=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 Xr}write(e,t,i){if(!(0,yo.shouldLog)(e,this.level))return;let n=(0,yo.formatLogLine)(e,Tb,t,i);this.toFile?Ob(n):process.stderr.write(n+`
35
+ `)}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 Gh=fe(require("os")),Yh=fe(Uc()),qn=class{cachedId=null;name;constructor(e){this.name=e||Gh.hostname()||"CLI"}async getMachineId(){if(this.cachedId)return this.cachedId;try{this.cachedId=(0,Yh.machineIdSync)()}catch{this.cachedId=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}return this.cachedId}getMachineName(){return this.name}};var Wn=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 zn=class{async openUrl(e){let{default:t}=await Promise.resolve().then(()=>(Td(),Sd));await t(e)}};var Cd=fe(require("fs")),cf=fe(require("path"));function wo(r){let e=r?[r]:[cf.join(__dirname,"..","package.json"),cf.join(__dirname,"..","..","package.json")];for(let t of e)try{let i=JSON.parse(Cd.readFileSync(t,"utf8"));if(typeof i.version=="string"&&i.version.length>0)return i.version}catch{}return"unknown"}function kd(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 ff=new Set(["--cid","--token","--server","--log-level"]),Od=new Set(["--help","-h","--version","-V","--verbose","-v","--watch","-w","--log-to-file","--statusline","--multi-viewer","--force"]);function Pd(r,e,t){for(let i=0;i<r.length;i++){let n=r[i];if(!n.startsWith("-"))continue;let s=n.includes("=")?n.slice(0,n.indexOf("=")):n;if(e.has(s)||t.has(s)){e.has(s)&&!n.includes("=")&&i++;continue}return n}}var ip=fe(require("path")),ut=fe(jn()),np=fe(Sr());var Rd=fe(require("os")),Ad=require("crypto"),Id=fe(require("node-pty")),Ld=fe(jn()),xo=class r{ptyProcess=null;outputBuffer=new Ld.CircularBuffer(100);streamId=null;logger;onOutput=null;onExit=null;preWriteHook=null;onResize=null;onLocalClaim=null;onLocalInput=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;constructor(e){this.logger=e}setMultiViewerMode(e){this.multiViewerMode!==e&&(this.multiViewerMode=e,this.logger.info("Multi-viewer mode",{enabled:e}))}spawn(e,t=0){let i=process.env.SHELL||(Rd.platform()==="win32"?"powershell.exe":"/bin/bash"),n=process.stdout.columns||80,s=process.stdout.rows||24,a=Math.max(1,s-t);this.reservedBottomRows=t,this.ptyProcess=Id.spawn(i,[],{name:"xterm-256color",cols:n,rows:a,cwd:e,env:{...process.env,TERMIQ_SESSION_ACTIVE:"1"}}),this.onResize?.(n,a),this.streamId=(0,Ad.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.multiViewerMode&&this.maybeClaimLocalControl(),this.onLocalInput?.(u.toString()),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.multiViewerMode){this.logger.info("Local resize claims control",{cols:u,rows:d}),this.resize(u,d),this.onLocalClaim?.(u,d);return}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.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)}}maybeClaimLocalControl(){if(!this.ptyProcess)return;let e=process.stdout.columns||80,t=Math.max(1,(process.stdout.rows||24)-this.reservedBottomRows);this.ptyProcess.cols===e&&this.ptyProcess.rows===t||(this.logger.info("Local input claims control",{cols:e,rows:t}),this.resize(e,t),this.onLocalClaim?.(e,t))}setOnLocalClaim(e){this.onLocalClaim=e}setOnLocalInput(e){this.onLocalInput=e}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 ei=fe(require("path")),cn=fe(require("fs"));var Yd=require("node:events"),Xd=require("node:fs"),Ao=require("node:fs/promises"),we=fe(require("node:path"),1);var Lr=require("node:fs/promises"),Nr=require("node:path"),Dd=require("node:stream"),Rt={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},uf={root:".",fileFilter:r=>!0,directoryFilter:r=>!0,type:Rt.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(uf);var Bd="READDIRP_RECURSIVE_ERROR",Vb=new Set(["ENOENT","EPERM","EACCES","ELOOP",Bd]),Nd=[Rt.DIR_TYPE,Rt.EVERYTHING_TYPE,Rt.FILE_DIR_TYPE,Rt.FILE_TYPE],zb=new Set([Rt.DIR_TYPE,Rt.EVERYTHING_TYPE,Rt.FILE_DIR_TYPE]),$b=new Set([Rt.EVERYTHING_TYPE,Rt.FILE_DIR_TYPE,Rt.FILE_TYPE]),Gb=r=>Vb.has(r.code),Yb=process.platform==="win32",Md=r=>!0,Fd=r=>{if(r===void 0)return Md;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 Md},lf=class extends Dd.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={...uf,...e},{root:i,type:n}=t;this._fileFilter=Fd(t.fileFilter),this._directoryFilter=Fd(t.directoryFilter);let s=t.lstat?Lr.lstat:Lr.stat;Yb?this._stat=a=>s(a,{bigint:!0}):this._stat=s,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:uf.depth,this._wantsDir=n?zb.has(n):!1,this._wantsFile=n?$b.has(n):!1,this._wantsEverything=n===Rt.EVERYTHING_TYPE,this._root=(0,Nr.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:n,depth:s}=t,a=i.splice(0,e).map(u=>this._formatEntry(u,n)),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)?(s<=this._maxDepth&&this.parents.push(this._exploreDir(u.fullPath,s+1)),this._wantsDir&&(this.push(u),e--)):(d==="file"||this._includeAsFile(u))&&this._fileFilter(u)&&this._wantsFile&&(this.push(u),e--)}}else{let n=this.parents.pop();if(!n){this.push(null);break}if(this.parent=await n,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let i;try{i=await(0,Lr.readdir)(e,this._rdOptions)}catch(n){this._onError(n)}return{files:i,depth:t,path:e}}async _formatEntry(e,t){let i,n=this._isDirent?e.name:e;try{let s=(0,Nr.resolve)((0,Nr.join)(t,n));i={path:(0,Nr.relative)(this._root,s),fullPath:s,basename:n},i[this._statsProp]=this._isDirent?e:await this._stat(s)}catch(s){this._onError(s);return}return i}_onError(e){Gb(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 n=await(0,Lr.realpath)(i),s=await(0,Lr.lstat)(n);if(s.isFile())return"file";if(s.isDirectory()){let a=n.length;if(i.startsWith(n)&&i.substr(a,1)===Nr.sep){let c=new Error(`Circular symlink detected: "${i}" points to "${n}"`);return c.code=Bd,this._onError(c)}return"directory"}}catch(n){return this._onError(n),""}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function jd(r,e={}){let t=e.entryType||e.type;if(t==="both"&&(t=Rt.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&&!Nd.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${Nd.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=r,new lf(e)}var ki=require("node:fs"),Xt=require("node:fs/promises"),Kd=require("node:os"),qe=fe(require("node:path"),1),Xb="data",pf="end",qd="close",Oo=()=>{};var Po=process.platform,gf=Po==="win32",Jb=Po==="darwin",Zb=Po==="linux",Qb=Po==="freebsd",Wd=(0,Kd.type)()==="OS400",Ve={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},Yt=Ve,ev="watch",tv={lstat:Xt.lstat,stat:Xt.stat},Ci="listeners",So="errHandlers",an="rawEmitters",rv=[Ci,So,an],iv=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"]),nv=r=>iv.has(qe.extname(r).slice(1).toLowerCase()),df=(r,e)=>{r instanceof Set?r.forEach(e):e(r)},$n=(r,e,t)=>{let i=r[e];i instanceof Set||(r[e]=i=new Set([i])),i.add(t)},sv=r=>e=>{let t=r[e];t instanceof Set?t.clear():delete r[e]},Gn=(r,e,t)=>{let i=r[e];i instanceof Set?i.delete(t):i===t&&delete r[e]},Hd=r=>r instanceof Set?r.size===0:!r,To=new Map;function Ud(r,e,t,i,n){let s=(a,c)=>{t(r),n(a,c,{watchedPath:r}),c&&r!==c&&Co(qe.resolve(r,c),Ci,qe.join(r,c))};try{return(0,ki.watch)(r,{persistent:e.persistent},s)}catch(a){i(a);return}}var Co=(r,e,t,i,n)=>{let s=To.get(r);s&&df(s[e],a=>{a(t,i,n)})},ov=(r,e,t,i)=>{let{listener:n,errHandler:s,rawEmitter:a}=i,c=To.get(e),u;if(!t.persistent)return u=Ud(r,t,n,s,a),u?u.close.bind(u):void 0;if(c)$n(c,Ci,n),$n(c,So,s),$n(c,an,a);else{if(u=Ud(r,t,Co.bind(null,e,Ci),s,Co.bind(null,e,an)),!u)return;u.on(Yt.ERROR,async d=>{let p=Co.bind(null,e,So);if(c&&(c.watcherUnusable=!0),gf&&d.code==="EPERM")try{await(await(0,Xt.open)(r,"r")).close(),p(d)}catch{}else p(d)}),c={listeners:n,errHandlers:s,rawEmitters:a,watcher:u},To.set(e,c)}return()=>{Gn(c,Ci,n),Gn(c,So,s),Gn(c,an,a),Hd(c.listeners)&&(c.watcher.close(),To.delete(e),rv.forEach(sv(c)),c.watcher=void 0,Object.freeze(c))}},hf=new Map,av=(r,e,t,i)=>{let{listener:n,rawEmitter:s}=i,a=hf.get(e),c=a&&a.options;return c&&(c.persistent<t.persistent||c.interval>t.interval)&&((0,ki.unwatchFile)(e),a=void 0),a?($n(a,Ci,n),$n(a,an,s)):(a={listeners:n,rawEmitters:s,options:t,watcher:(0,ki.watchFile)(e,t,(u,d)=>{df(a.rawEmitters,m=>{m(Yt.CHANGE,e,{curr:u,prev:d})});let p=u.mtimeMs;(u.size!==d.size||p>d.mtimeMs||p===0)&&df(a.listeners,m=>m(r,u))})},hf.set(e,a)),()=>{Gn(a,Ci,n),Gn(a,an,s),Hd(a.listeners)&&(hf.delete(e),(0,ki.unwatchFile)(e),a.options=a.watcher=void 0,Object.freeze(a))}},ko=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let i=this.fsw.options,n=qe.dirname(e),s=qe.basename(e);this.fsw._getWatchedDir(n).add(s);let c=qe.resolve(e),u={persistent:i.persistent};t||(t=Oo);let d;if(i.usePolling){let p=i.interval!==i.binaryInterval;u.interval=p&&nv(s)?i.binaryInterval:i.interval,d=av(e,c,u,{listener:t,rawEmitter:this.fsw._emitRaw})}else d=ov(e,c,u,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return d}_handleFile(e,t,i){if(this.fsw.closed)return;let n=qe.dirname(e),s=qe.basename(e),a=this.fsw._getWatchedDir(n),c=t;if(a.has(s))return;let u=async(p,m)=>{if(this.fsw._throttle(ev,e,5)){if(!m||m.mtimeMs===0)try{let _=await(0,Xt.stat)(e);if(this.fsw.closed)return;let E=_.atimeMs,S=_.mtimeMs;if((!E||E<=S||S!==c.mtimeMs)&&this.fsw._emit(Yt.CHANGE,e,_),(Jb||Zb||Qb)&&c.ino!==_.ino){this.fsw._closeFile(p),c=_;let T=this._watchWithNodeFs(e,u);T&&this.fsw._addPathCloser(p,T)}else c=_}catch{this.fsw._remove(n,s)}else if(a.has(s)){let _=m.atimeMs,E=m.mtimeMs;(!_||_<=E||E!==c.mtimeMs)&&this.fsw._emit(Yt.CHANGE,e,m),c=m}}},d=this._watchWithNodeFs(e,u);if(!(i&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(Yt.ADD,e,0))return;this.fsw._emit(Yt.ADD,e,t)}return d}async _handleSymlink(e,t,i,n){if(this.fsw.closed)return;let s=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let c;try{c=await(0,Xt.realpath)(i)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(n)?this.fsw._symlinkPaths.get(s)!==c&&(this.fsw._symlinkPaths.set(s,c),this.fsw._emit(Yt.CHANGE,i,e.stats)):(a.add(n),this.fsw._symlinkPaths.set(s,c),this.fsw._emit(Yt.ADD,i,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(s))return!0;this.fsw._symlinkPaths.set(s,!0)}_handleRead(e,t,i,n,s,a,c){e=qe.join(e,"");let u=n?`${e}:${n}`: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:_=>i.filterPath(_),directoryFilter:_=>i.filterDir(_)});if(m)return m.on(Xb,async _=>{if(this.fsw.closed){m=void 0;return}let E=_.path,S=qe.join(e,E);if(p.add(E),!(_.stats.isSymbolicLink()&&await this._handleSymlink(_,e,S,E))){if(this.fsw.closed){m=void 0;return}(E===n||!n&&!d.has(E))&&(this.fsw._incrReadyCount(),S=qe.join(s,qe.relative(s,S)),this._addToNodeFs(S,t,i,a+1))}}).on(Yt.ERROR,this._boundHandleError),new Promise((_,E)=>{if(!m)return E();m.once(pf,()=>{if(this.fsw.closed){m=void 0;return}let S=c?c.clear():!1;_(void 0),d.getChildren().filter(T=>T!==e&&!p.has(T)).forEach(T=>{this.fsw._remove(e,T)}),m=void 0,S&&this._handleRead(e,!1,i,n,s,a,c)})})}async _handleDir(e,t,i,n,s,a,c){let u=this.fsw._getWatchedDir(qe.dirname(e)),d=u.has(qe.basename(e));!(i&&this.fsw.options.ignoreInitial)&&!s&&!d&&this.fsw._emit(Yt.ADD_DIR,e,t),u.add(qe.basename(e)),this.fsw._getWatchedDir(e);let p,m,_=this.fsw.options.depth;if((_==null||n<=_)&&!this.fsw._symlinkPaths.has(c)){if(!s&&(await this._handleRead(e,i,a,s,e,n,p),this.fsw.closed))return;m=this._watchWithNodeFs(e,(E,S)=>{S&&S.mtimeMs===0||this._handleRead(E,!1,a,s,e,n,p)})}return m}async _addToNodeFs(e,t,i,n,s){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 tv[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=qe.resolve(e),_=d?await(0,Xt.realpath)(e):e;if(this.fsw.closed||(p=await this._handleDir(c.watchPath,u,t,n,s,c,_),this.fsw.closed))return;m!==_&&_!==void 0&&this.fsw._symlinkPaths.set(m,_)}else if(u.isSymbolicLink()){let m=d?await(0,Xt.realpath)(e):e;if(this.fsw.closed)return;let _=qe.dirname(c.watchPath);if(this.fsw._getWatchedDir(_).add(c.watchPath),this.fsw._emit(Yt.ADD,c.watchPath,u),p=await this._handleDir(_,u,t,n,e,c,m),this.fsw.closed)return;m!==void 0&&this.fsw._symlinkPaths.set(qe.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 mf="/",cv="//",Jd=".",fv="..",uv="string",lv=/\\/g,Zd=/\/\//g,hv=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,dv=/^\.[/\\]/;function Ro(r){return Array.isArray(r)?r:[r]}var yf=r=>typeof r=="object"&&r!==null&&!(r instanceof RegExp);function pv(r){return typeof r=="function"?r:typeof r=="string"?e=>r===e:r instanceof RegExp?e=>r.test(e):typeof r=="object"&&r!==null?e=>{if(r.path===e)return!0;if(r.recursive){let t=we.relative(r.path,e);return t?!t.startsWith("..")&&!we.isAbsolute(t):!1}return!1}:()=>!1}function gv(r){if(typeof r!="string")throw new Error("string expected");r=we.normalize(r),r=r.replace(/\\/g,"/");let e=!1;return r.startsWith("//")&&(e=!0),r=r.replace(Zd,"/"),e&&(r="/"+r),r}function Vd(r,e,t){let i=gv(e);for(let n=0;n<r.length;n++){let s=r[n];if(s(i,t))return!0}return!1}function mv(r,e){if(r==null)throw new TypeError("anymatch: specify first argument");let i=Ro(r).map(n=>pv(n));return e==null?(n,s)=>Vd(i,n,s):Vd(i,e)}var zd=r=>{let e=Ro(r).flat();if(!e.every(t=>typeof t===uv))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Qd)},$d=r=>{let e=r.replace(lv,mf),t=!1;return e.startsWith(cv)&&(t=!0),e=e.replace(Zd,mf),t&&(e=mf+e),e},Qd=r=>$d(we.normalize($d(r))),Gd=(r="")=>e=>typeof e=="string"?Qd(we.isAbsolute(e)?e:we.join(r,e)):e,yv=(r,e)=>we.isAbsolute(r)?r:we.join(e,r),_v=Object.freeze(new Set),_f=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!==Jd&&e!==fv&&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,Ao.readdir)(i)}catch{this._removeWatcher&&this._removeWatcher(we.dirname(i),we.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=Oo,this.items=_v,Object.freeze(this)}},bv="stat",vv="lstat",bf=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,t,i){this.fsw=i;let n=e;this.path=e=e.replace(dv,""),this.watchPath=n,this.fullWatchPath=we.resolve(n),this.dirParts=[],this.dirParts.forEach(s=>{s.length>1&&s.pop()}),this.followSymlinks=t,this.statMethod=t?bv:vv}entryPath(e){return we.join(this.watchPath,we.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let 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)}},vf=class extends Yd.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},n={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?Ro(e.ignored):Ro([]),awaitWriteFinish:t===!0?i:typeof t=="object"?{...i,...t}:!1};Wd&&(n.usePolling=!0),n.atomic===void 0&&(n.atomic=!n.usePolling);let s=process.env.CHOKIDAR_USEPOLLING;if(s!==void 0){let u=s.toLowerCase();u==="false"||u==="0"?n.usePolling=!1:u==="true"||u==="1"?n.usePolling=!0:n.usePolling=!!u}let a=process.env.CHOKIDAR_INTERVAL;a&&(n.interval=Number.parseInt(a,10));let c=0;this._emitReady=()=>{c++,c>=this._readyCount&&(this._emitReady=Oo,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=n,this._nodeFsHandler=new ko(this),Object.freeze(n)}_addIgnoredPath(e){if(yf(e)){for(let t of this._ignoredPaths)if(yf(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)yf(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,i){let{cwd:n}=this.options;this.closed=!1,this._closePromise=void 0;let s=zd(e);return n&&(s=s.map(a=>yv(a,n))),s.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=s.length,Promise.all(s.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(we.dirname(c),we.basename(t||c))})}),this}unwatch(e){if(this.closed)return this;let t=zd(e),{cwd:i}=this.options;return t.forEach(n=>{!we.isAbsolute(n)&&!this._closers.has(n)&&(i&&(n=we.join(i,n)),n=we.resolve(n)),this._closePath(n),this._addIgnoredPath(n),this._watched.has(n)&&this._addIgnoredPath({path:n,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 n=i();n instanceof Promise&&e.push(n)})),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 s=(this.options.cwd?we.relative(this.options.cwd,i):i)||Jd;e[s]=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 n=this.options;gf&&(t=we.normalize(t)),n.cwd&&(t=we.relative(n.cwd,t));let s=[t];i!=null&&s.push(i);let a=n.awaitWriteFinish,c;if(a&&(c=this._pendingWrites.get(t)))return c.lastChange=new Date,this;if(n.atomic){if(e===Ve.UNLINK)return this._pendingUnlinks.set(t,[e,...s]),setTimeout(()=>{this._pendingUnlinks.forEach((u,d)=>{this.emit(...u),this.emit(Ve.ALL,...u),this._pendingUnlinks.delete(d)})},typeof n.atomic=="number"?n.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,p)=>{d?(e=Ve.ERROR,s[0]=d,this.emitWithAll(e,s)):p&&(s.length>1?s[1]=p:s.push(p),this.emitWithAll(e,s))};return this._awaitWriteFinish(t,a.stabilityThreshold,e,u),this}if(e===Ve.CHANGE&&!this._throttle(Ve.CHANGE,t,50))return this;if(n.alwaysStat&&i===void 0&&(e===Ve.ADD||e===Ve.ADD_DIR||e===Ve.CHANGE)){let u=n.cwd?we.join(n.cwd,t):t,d;try{d=await(0,Ao.stat)(u)}catch{}if(!d||this.closed)return;s.push(d)}return this.emitWithAll(e,s),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 n=this._throttled.get(e);if(!n)throw new Error("invalid throttle");let s=n.get(t);if(s)return s.count++,!1;let a,c=()=>{let d=n.get(t),p=d?d.count:0;return n.delete(t),clearTimeout(a),d&&clearTimeout(d.timeoutObject),p};a=setTimeout(c,i);let u={timeoutObject:a,clear:c,count:0};return n.set(t,u),u}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,i,n){let s=this.options.awaitWriteFinish;if(typeof s!="object")return;let a=s.pollInterval,c,u=e;this.options.cwd&&!we.isAbsolute(e)&&(u=we.join(this.options.cwd,e));let d=new Date,p=this._pendingWrites;function m(_){(0,Xd.stat)(u,(E,S)=>{if(E||!p.has(e)){E&&E.code!=="ENOENT"&&n(E);return}let T=Number(new Date);_&&S.size!==_.size&&(p.get(e).lastChange=T);let z=p.get(e);T-z.lastChange>=t?(p.delete(e),n(void 0,S)):c=setTimeout(m,a,S)})}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&&hv.test(e))return!0;if(!this._userIgnored){let{cwd:i}=this.options,s=(this.options.ignored||[]).map(Gd(i)),c=[...[...this._ignoredPaths].map(Gd(i)),...s];this._userIgnored=mv(c,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new bf(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=we.resolve(e);return this._watched.has(t)||this._watched.set(t,new _f(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,i){let n=we.join(e,t),s=we.resolve(n);if(i=i??(this._watched.has(n)||this._watched.has(s)),!this._throttle("remove",n,100))return;!i&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(n).getChildren().forEach(_=>this._remove(n,_));let u=this._getWatchedDir(e),d=u.has(t);u.remove(t),this._symlinkPaths.has(s)&&this._symlinkPaths.delete(s);let p=n;if(this.options.cwd&&(p=we.relative(this.options.cwd,n)),this.options.awaitWriteFinish&&this._pendingWrites.has(p)&&this._pendingWrites.get(p).cancelWait()===Ve.ADD)return;this._watched.delete(n),this._watched.delete(s);let m=i?Ve.UNLINK_DIR:Ve.UNLINK;d&&!this._isIgnored(n)&&this._emit(m,n),this._closePath(n)}_closePath(e){this._closeFile(e);let t=we.dirname(e);this._getWatchedDir(t).remove(we.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(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},n=jd(e,i);return this._streams.add(n),n.once(qd,()=>{n=void 0}),n.once(pf,()=>{n&&(this._streams.delete(n),n=void 0)}),n}};function ep(r,e={}){let t=new vf(e);return t.add(r),t}var tp=fe(Oc()),dr=fe(Sr()),Ev=["**/node_modules/**","**/.git/**","**/dist/**","**/.next/**","**/.turbo/**","**/.cache/**","**/coverage/**","**/*.log"],wv=300,Io=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,tp.default)(),this.initializeIgnoreFilter()}initializeIgnoreFilter(){this.ignoreFilter.add(Ev);let e=ei.join(this.workspaceRoot,".gitignore");try{if(cn.existsSync(e)){let t=cn.readFileSync(e,"utf-8");this.ignoreFilter.add(t)}}catch{}}onFileChanged(e){this.onFileChangedCallback=e}start(){this.watcher||(this.watcher=ep(this.workspaceRoot,{ignored:e=>{let t=ei.relative(this.workspaceRoot,e);if(!t||t===".")return!1;let i=t.split(ei.sep).join("/");return this.ignoreFilter.ignores(i)},persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:200,pollInterval:50}}),this.watcher.on("add",e=>this.handleEvent(e,dr.FileChangeType.CREATE)),this.watcher.on("change",e=>this.handleEvent(e,dr.FileChangeType.MODIFY)),this.watcher.on("unlink",e=>this.handleEvent(e,dr.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=ei.relative(this.workspaceRoot,e);if(!i)return;let n=this.pendingEvents.get(i);n&&clearTimeout(n);let s=this.pendingTypes.get(i);this.pendingTypes.set(i,this.mergeTypes(s,t));let a=setTimeout(()=>{this.emit(i,this.pendingTypes.get(i)||t),this.pendingEvents.delete(i),this.pendingTypes.delete(i)},wv);this.pendingEvents.set(i,a)}mergeTypes(e,t){return e?t===dr.FileChangeType.DELETE||e===dr.FileChangeType.DELETE?dr.FileChangeType.DELETE:e===dr.FileChangeType.CREATE?dr.FileChangeType.CREATE:t:t}emit(e,t){let i={path:e,changeType:t,timestamp:new Date().toISOString(),source:"watcher"};if(t!==dr.FileChangeType.DELETE)try{let n=ei.join(this.workspaceRoot,e),s=cn.statSync(n);i.size=s.size}catch{}this.onFileChangedCallback?.(i)}dispose(){this.stop(),this.onFileChangedCallback=null}};var xv={online:!1,viewerCount:0},Lo=class r{enabled=!1;state={...xv};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 No(r,e,t,i){if(i)return process.stderr.write(`Logging in with API key...
36
36
  `),await r.loginWithApiKey(i)?(process.stderr.write(`Login successful.
37
37
  `),!0):(process.stderr.write(`Login failed. Check your API key.
38
38
  `),!1);try{let n=await r.startDeviceCodeFlow();process.stderr.write(`
@@ -45,15 +45,15 @@ tell application "System Events" to get value of property list item "CFBundleNam
45
45
  `),!0):(process.stderr.write(` Login failed or expired.
46
46
 
47
47
  `),!1)}catch(n){return t.error("Login error",n),process.stderr.write(`Login error: ${n instanceof Error?n.message:String(n)}
48
- `),!1}}var fn=fe(Sr());function Sb(r){switch(r){case"numbered-choice":return"select";case"free-input":return"input";default:return"confirmation"}}function rp(r,e,t){let i=new Date().toISOString();switch(r){case"working":return e==="idle"?{type:fn.TerminalEventType.SESSION_START,timestamp:i}:null;case"waiting":return{type:fn.TerminalEventType.WAITING_INPUT,timestamp:i,promptType:Sb(t?.type),question:t?.question||"Confirm action?",options:t?.choices?.map(n=>n.label)};case"completed":return{type:fn.TerminalEventType.SESSION_END,timestamp:i,status:"success"};case"error":return e==="working"?{type:fn.TerminalEventType.SESSION_END,timestamp:i,status:"error"}:{type:fn.TerminalEventType.ERROR,timestamp:i,severity:"error",message:"Command failed"};default:return null}}async function sp(r){let{storage:e,config:t,logger:i,machineId:n,notification:s,browser:a,cwd:c,watch:u,statusLine:d,multiViewer:p}=r,m=new Lo(i);d&&m.enable();let _=t.getServerUrl(),E=new URL(_).host,S=await n.getMachineId(),T=new ut.CryptoService(e,i,E,S);await T.initialize();let z=await T.getShortFingerprint();process.stderr.write(`Agent fingerprint: ${z} (verify in the web app; run 'termiq fingerprint' for the full safety number)
48
+ `),!1}}var fn=fe(Sr());function Sv(r){switch(r){case"numbered-choice":return"select";case"free-input":return"input";default:return"confirmation"}}function rp(r,e,t){let i=new Date().toISOString();switch(r){case"working":return e==="idle"?{type:fn.TerminalEventType.SESSION_START,timestamp:i}:null;case"waiting":return{type:fn.TerminalEventType.WAITING_INPUT,timestamp:i,promptType:Sv(t?.type),question:t?.question||"Confirm action?",options:t?.choices?.map(n=>n.label)};case"completed":return{type:fn.TerminalEventType.SESSION_END,timestamp:i,status:"success"};case"error":return e==="working"?{type:fn.TerminalEventType.SESSION_END,timestamp:i,status:"error"}:{type:fn.TerminalEventType.ERROR,timestamp:i,severity:"error",message:"Command failed"};default:return null}}async function sp(r){let{storage:e,config:t,logger:i,machineId:n,notification:s,browser:a,cwd:c,watch:u,statusLine:d,multiViewer:p}=r,m=new Lo(i);d&&m.enable();let _=t.getServerUrl(),E=new URL(_).host,S=await n.getMachineId(),T=new ut.CryptoService(e,i,E,S);await T.initialize();let z=await T.getShortFingerprint();process.stderr.write(`Agent fingerprint: ${z} (verify in the web app; run 'termiq fingerprint' for the full safety number)
49
49
  `);let ge=new ut.AuthService(e,T,n,t,i,s,a,E,S),ee=await ge.hasValidToken();ee||await ge.refreshAccessToken()||(process.stderr.write(`Not logged in. Starting login flow...
50
- `),await No(ge,a,i)||process.exit(1),ee=!0);let A;try{let{machineIdSync:P}=await Promise.resolve().then(()=>fe(Uc()));A=P()}catch{A=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}let B,re=new ut.StatusDetector((P,Z,Ne)=>{if(!U.getStatus().connected)return;let Xe=B;B=Z,U.updateStatus({instanceId:ue,terminalId:P,status:Z,encryptedPrompt:Ne&&T.encryptPromptInfo(Ne)||void 0}).catch(()=>{});let lt=rp(Z,Xe,Ne);lt&&U.sendTerminalEvent(ue,P,lt)}),q=p?[np.Capability.MULTI_VIEWER_RENDER]:[],U=new ut.WebSocketService(ge,T,t,i,s,A,"cli",q);p&&i.info("Multi-viewer rendering capability advertised");let ye=!1;U.onStatusChange(P=>{if(P==="connected"){if(ye)i.info("Reconnected to termiq.io");else{let Z=p?" (multi-viewer mode)":"";process.stderr.write(`Connected to termiq.io${Z}
50
+ `),await No(ge,a,i)||process.exit(1),ee=!0);let R;try{let{machineIdSync:P}=await Promise.resolve().then(()=>fe(Uc()));R=P()}catch{R=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}let B,re=new ut.StatusDetector((P,Z,Ne)=>{if(!U.getStatus().connected)return;let Xe=B;B=Z,U.updateStatus({instanceId:ue,terminalId:P,status:Z,encryptedPrompt:Ne&&T.encryptPromptInfo(Ne)||void 0}).catch(()=>{});let lt=rp(Z,Xe,Ne);lt&&U.sendTerminalEvent(ue,P,lt)}),K=p?[np.Capability.MULTI_VIEWER_RENDER]:[],U=new ut.WebSocketService(ge,T,t,i,s,R,"cli",K);p&&i.info("Multi-viewer rendering capability advertised");let ye=!1;U.onStatusChange(P=>{if(P==="connected"){if(ye)i.info("Reconnected to termiq.io");else{let Z=p?" (multi-viewer mode)":"";process.stderr.write(`Connected to termiq.io${Z}
51
51
  `),ye=!0}m.update({online:!0})}else P==="disconnected"?(i.info("Disconnected from termiq.io (will retry)"),m.update({online:!1})):P==="error"&&(i.warn("Connection degraded (no server response) \u2014 reconnecting"),m.update({online:!1}))}),U.onAuthFailure(()=>{process.stderr.write(`Session expired. Please run "termiq login" again.
52
- `),R(),process.exit(1)});try{await U.connect()}catch(P){process.stderr.write(`Connection failed: ${P instanceof Error?P.message:String(P)}
53
- `),process.exit(1)}let xe=ip.basename(c),ue=`cli_${Date.now()}`,rt=T.encryptWorkspaceInfo({name:xe,path:c});await U.registerWorkspace({instanceId:ue,encryptedInfo:rt||void 0});let Ee=new xo(i);p&&Ee.setMultiViewerMode(!0),Ee.setPreWriteHook(P=>m.inspectPtyOutput(P));let Se=null;Ee.setOnResize((P,Z)=>{m.update({ptyCols:P,ptyRows:Z}),p&&Se&&U.sendPtyResized(ue,Se,P,Z)}),Ee.setOnLocalClaim((P,Z)=>{p&&Se&&U.sendClaimControl(ue,Se,P,Z)});let be=Ee.spawn(c,m.reservedRows()),We=`CLI: ${xe}`,st=process.env.SHELL||"/bin/bash",Ze=T.encryptTerminalInfo({name:We,command:st,cwd:c});await U.terminalCreated({instanceId:ue,terminalId:be,encryptedInfo:Ze||void 0,streamId:Ee.getStreamId()??void 0}),Se=be,p&&U.sendPtyResized(ue,be,Ee.getPtyCols(),Ee.getPtyRows());let Te=new ut.FileTransferService(i);Te.setCrypto(T);let it=new ut.FileTrackerService(i,c),ze=new ut.FileListService(i,c),gt=u?new Io(i,c):null,L=U.getSocket();L&&Te.attach(L,ue),it.onFileChanged((P,Z)=>{U.sendFileChangedEvent(ue,P,Z)}),it.onFileViewTransfer(async(P,Z,Ne)=>{try{await Te.sendBuffer(P,Z,Ne.path.split("/").pop()||"view",Ne.mimeType||"text/plain",{purpose:"view",viewMetadata:Ne})}catch(Xe){i.error("File view transfer failed",Xe)}}),U.onFileViewRequest((P,Z)=>{it.handleViewRequest(P,Z)}),U.onFileListRequest((P,Z)=>{ze.handleListRequest(Z)}),ze.onResponse(P=>{U.sendFileListResponse(ue,P)}),U.onFileDownloadRequest(async(P,Z,Ne)=>{try{await Te.sendFile(P,Z,void 0,void 0,Ne)}catch(Xe){i.error("File download failed",Xe)}}),gt&&(gt.onFileChanged(P=>{U.sendFileChangedEvent(ue,be,P)}),gt.start()),re.startTracking(be),Ee.setOnOutput(P=>{U.sendOutput(ue,be,P),re.processOutput(be,P),it.processOutput(be,P)}),Ee.setOnLocalInput(P=>{(0,ut.isAnswerKeystroke)(P)&&re.resolvePrompt(be)}),U.onInput((P,Z,Ne,Xe)=>{P===be&&((0,ut.isAnswerKeystroke)(Z)&&re.resolvePrompt(be),Ee.write(Z,Xe))}),U.setTerminalActiveCheck(P=>P===be&&Ee.isAlive()),U.onResizeRequest((P,Z,Ne)=>{P===be&&(i.info("Remote resize received",{terminalId:P,cols:Z,rows:Ne}),Ee.resize(Z,Ne))}),U.onClientAttached(({clientCount:P})=>{Ee.setSigwinchEnabled(!1),m.update({viewerCount:P}),U.sendInputResume(be)}),U.onClientDetached(({clientCount:P})=>{P===0&&Ee.setSigwinchEnabled(!0),m.update({viewerCount:P})}),U.onGetBufferRequest(P=>P===be?Ee.getBuffer():null),U.onRedrawRequest(P=>{P===be&&Ee.redrawNoResize()});async function j(){let P=T.encryptWorkspaceInfo({name:xe,path:c});await U.registerWorkspace({instanceId:ue,encryptedInfo:P||void 0});let Z=T.encryptTerminalInfo({name:We,command:st,cwd:c});await U.terminalCreated({instanceId:ue,terminalId:be,encryptedInfo:Z||void 0,streamId:Ee.getStreamId()??void 0})}U.onMetaSessionEstablished(()=>{j().catch(P=>{i.error("Failed to re-register metadata after meta session",P)})}),U.onReconnect(async()=>{try{await j();let P=U.getSocket();P&&Te.attach(P,ue)}catch(P){i.error("Failed to re-register on reconnect",P)}});function R(){gt?.dispose(),Te.detach(),it.dispose(),ze.dispose(),re.stopTracking(be),re.dispose(),U.disposeInputStream(be),U.terminalClosed({instanceId:ue,terminalId:be}).catch(()=>{}),U.unregisterWorkspace(ue).catch(()=>{}),U.disconnect(),Ee.dispose()}Ee.setOnExit(()=>{m.disable(),process.stderr.write(`Session ended.
54
- `),R(),process.exit(0)}),process.on("SIGINT",()=>{m.disable(),process.stderr.write(`Session ended.
55
- `),R(),process.exit(0)}),process.on("SIGTERM",()=>{m.disable(),process.stderr.write(`Session ended.
56
- `),R(),process.exit(0)})}async function op(r){await r.logout(),process.stderr.write(`Logged out.
52
+ `),A(),process.exit(1)});try{await U.connect()}catch(P){process.stderr.write(`Connection failed: ${P instanceof Error?P.message:String(P)}
53
+ `),process.exit(1)}let xe=ip.basename(c),ue=`cli_${Date.now()}`,rt=T.encryptWorkspaceInfo({name:xe,path:c});await U.registerWorkspace({instanceId:ue,encryptedInfo:rt||void 0});let Ee=new xo(i);p&&Ee.setMultiViewerMode(!0),Ee.setPreWriteHook(P=>m.inspectPtyOutput(P));let Se=null;Ee.setOnResize((P,Z)=>{m.update({ptyCols:P,ptyRows:Z}),p&&Se&&U.sendPtyResized(ue,Se,P,Z)}),Ee.setOnLocalClaim((P,Z)=>{p&&Se&&U.sendClaimControl(ue,Se,P,Z)});let ve=Ee.spawn(c,m.reservedRows()),We=`CLI: ${xe}`,st=process.env.SHELL||"/bin/bash",Ze=T.encryptTerminalInfo({name:We,command:st,cwd:c});await U.terminalCreated({instanceId:ue,terminalId:ve,encryptedInfo:Ze||void 0,streamId:Ee.getStreamId()??void 0}),Se=ve,p&&U.sendPtyResized(ue,ve,Ee.getPtyCols(),Ee.getPtyRows());let Te=new ut.FileTransferService(i);Te.setCrypto(T);let it=new ut.FileTrackerService(i,c),ze=new ut.FileListService(i,c),gt=u?new Io(i,c):null,L=U.getSocket();L&&Te.attach(L,ue),it.onFileChanged((P,Z)=>{U.sendFileChangedEvent(ue,P,Z)}),it.onFileViewTransfer(async(P,Z,Ne)=>{try{await Te.sendBuffer(P,Z,Ne.path.split("/").pop()||"view",Ne.mimeType||"text/plain",{purpose:"view",viewMetadata:Ne})}catch(Xe){i.error("File view transfer failed",Xe)}}),U.onFileViewRequest((P,Z)=>{it.handleViewRequest(P,Z)}),U.onFileListRequest((P,Z)=>{ze.handleListRequest(Z)}),ze.onResponse(P=>{U.sendFileListResponse(ue,P)}),U.onFileDownloadRequest(async(P,Z,Ne)=>{try{await Te.sendFile(P,Z,void 0,void 0,Ne)}catch(Xe){i.error("File download failed",Xe)}}),gt&&(gt.onFileChanged(P=>{U.sendFileChangedEvent(ue,ve,P)}),gt.start()),re.startTracking(ve),Ee.setOnOutput(P=>{U.sendOutput(ue,ve,P),re.processOutput(ve,P),it.processOutput(ve,P)}),Ee.setOnLocalInput(P=>{(0,ut.isAnswerKeystroke)(P)&&re.resolvePrompt(ve)}),U.onInput((P,Z,Ne,Xe)=>{P===ve&&((0,ut.isAnswerKeystroke)(Z)&&re.resolvePrompt(ve),Ee.write(Z,Xe))}),U.setTerminalActiveCheck(P=>P===ve&&Ee.isAlive()),U.onResizeRequest((P,Z,Ne)=>{P===ve&&(i.info("Remote resize received",{terminalId:P,cols:Z,rows:Ne}),Ee.resize(Z,Ne))}),U.onClientAttached(({clientCount:P})=>{Ee.setSigwinchEnabled(!1),m.update({viewerCount:P}),U.sendInputResume(ve)}),U.onClientDetached(({clientCount:P})=>{P===0&&Ee.setSigwinchEnabled(!0),m.update({viewerCount:P})}),U.onGetBufferRequest(P=>P===ve?Ee.getBuffer():null),U.onRedrawRequest(P=>{P===ve&&Ee.redrawNoResize()});async function j(){let P=T.encryptWorkspaceInfo({name:xe,path:c});await U.registerWorkspace({instanceId:ue,encryptedInfo:P||void 0});let Z=T.encryptTerminalInfo({name:We,command:st,cwd:c});await U.terminalCreated({instanceId:ue,terminalId:ve,encryptedInfo:Z||void 0,streamId:Ee.getStreamId()??void 0})}U.onMetaSessionEstablished(()=>{j().catch(P=>{i.error("Failed to re-register metadata after meta session",P)})}),U.onReconnect(async()=>{try{await j();let P=U.getSocket();P&&Te.attach(P,ue)}catch(P){i.error("Failed to re-register on reconnect",P)}});function A(){gt?.dispose(),Te.detach(),it.dispose(),ze.dispose(),re.stopTracking(ve),re.dispose(),U.disposeInputStream(ve),U.terminalClosed({instanceId:ue,terminalId:ve}).catch(()=>{}),U.unregisterWorkspace(ue).catch(()=>{}),U.disconnect(),Ee.dispose()}Ee.setOnExit(()=>{m.disable(),process.stderr.write(`Session ended.
54
+ `),A(),process.exit(0)}),process.on("SIGINT",()=>{m.disable(),process.stderr.write(`Session ended.
55
+ `),A(),process.exit(0)}),process.on("SIGTERM",()=>{m.disable(),process.stderr.write(`Session ended.
56
+ `),A(),process.exit(0)})}async function op(r){await r.logout(),process.stderr.write(`Logged out.
57
57
  `)}async function ap(r,e){let t=await r.hasValidToken(),i=await r.getAgentId();if(t?(process.stderr.write(`Status: logged in
58
58
  `),i&&process.stderr.write(`Agent ID: ${i}
59
59
  `)):(process.stderr.write(`Status: not logged in
@@ -69,7 +69,7 @@ Short fingerprint: ${t}
69
69
  Compare these with the value shown in the TermIQ web app to verify
70
70
  you are connected to THIS agent (no server-in-the-middle).
71
71
 
72
- `)}var Rt=fe(jn()),Le=process.argv.slice(2);(Le.includes("--help")||Le.includes("-h"))&&(process.stderr.write(`
72
+ `)}var At=fe(jn()),Le=process.argv.slice(2);(Le.includes("--help")||Le.includes("-h"))&&(process.stderr.write(`
73
73
  termiq v${wo()} \u2014 Access terminals from anywhere
74
74
 
75
75
  Usage:
@@ -102,13 +102,13 @@ you are connected to THIS agent (no server-in-the-middle).
102
102
  `),process.exit(0));(Le.includes("--version")||Le.includes("-V"))&&(process.stdout.write(`${wo()}
103
103
  `),process.exit(0));var fp=Pd(Le,ff,Od);fp&&(process.stderr.write(`Unknown flag: ${fp}
104
104
  Run 'termiq --help' for usage.
105
- `),process.exit(1));var up=kd(Le,ff)??"start",Tb=Le.includes("--verbose")||Le.includes("-v"),Cb=Le.includes("--watch")||Le.includes("-w"),kb=Le.includes("--log-to-file"),Ob=Le.includes("--statusline"),Pb=Le.includes("--multi-viewer"),Ab=Le.includes("--force"),Rb=Le.find(r=>r.startsWith("--token="))?.split("=")[1]||(Le.includes("--token")?Le[Le.indexOf("--token")+1]:void 0),lp=Le.find(r=>r.startsWith("--server="))?.split("=")[1]||(Le.includes("--server")?Le[Le.indexOf("--server")+1]:void 0),Ef=Le.find(r=>r.startsWith("--log-level="))?.split("=")[1]||(Le.includes("--log-level")?Le[Le.indexOf("--log-level")+1]:void 0),Ib=["silent","error","warn","info","debug"],Lb=Ef&&Ib.includes(Ef)?Ef:Tb?"info":"silent",Nb=Le.find(r=>r.startsWith("--cid="))?.split("=")[1]||(Le.includes("--cid")?Le[Le.indexOf("--cid")+1]:void 0),Mb=Nb||(0,Rt.generateCorrelationId)(),Fb=process.env.TERMIQ_TOKEN,gr=new Un(Lb,kb),ti=new pn,pr=new gn(lp?{serverUrl:lp}:void 0),ri=new Kn,Mo=new Wn(gr),Yn=new zn;async function Db(){switch(up){case"start":case void 0:{process.env.TERMIQ_SESSION_ACTIVE==="1"&&!Ab&&(process.stderr.write(`termiq \u0443\u0436\u0435 \u0437\u0430\u043F\u0443\u0449\u0435\u043D \u0432 \u044D\u0442\u043E\u043C \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B\u0435 (\u0432\u044B \u0432\u043D\u0443\u0442\u0440\u0438 termiq-\u0441\u0435\u0441\u0441\u0438\u0438).
105
+ `),process.exit(1));var up=kd(Le,ff)??"start",Tv=Le.includes("--verbose")||Le.includes("-v"),Cv=Le.includes("--watch")||Le.includes("-w"),kv=Le.includes("--log-to-file"),Ov=Le.includes("--statusline"),Pv=Le.includes("--multi-viewer"),Rv=Le.includes("--force"),Av=Le.find(r=>r.startsWith("--token="))?.split("=")[1]||(Le.includes("--token")?Le[Le.indexOf("--token")+1]:void 0),lp=Le.find(r=>r.startsWith("--server="))?.split("=")[1]||(Le.includes("--server")?Le[Le.indexOf("--server")+1]:void 0),Ef=Le.find(r=>r.startsWith("--log-level="))?.split("=")[1]||(Le.includes("--log-level")?Le[Le.indexOf("--log-level")+1]:void 0),Iv=["silent","error","warn","info","debug"],Lv=Ef&&Iv.includes(Ef)?Ef:Tv?"info":"silent",Nv=Le.find(r=>r.startsWith("--cid="))?.split("=")[1]||(Le.includes("--cid")?Le[Le.indexOf("--cid")+1]:void 0),Mv=Nv||(0,At.generateCorrelationId)(),Fv=process.env.TERMIQ_TOKEN,gr=new Un(Lv,kv),ti=new pn,pr=new gn(lp?{serverUrl:lp}:void 0),ri=new qn,Mo=new Wn(gr),Yn=new zn;async function Dv(){switch(up){case"start":case void 0:{process.env.TERMIQ_SESSION_ACTIVE==="1"&&!Rv&&(process.stderr.write(`termiq \u0443\u0436\u0435 \u0437\u0430\u043F\u0443\u0449\u0435\u043D \u0432 \u044D\u0442\u043E\u043C \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B\u0435 (\u0432\u044B \u0432\u043D\u0443\u0442\u0440\u0438 termiq-\u0441\u0435\u0441\u0441\u0438\u0438).
106
106
  \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 \u0442\u0435\u043A\u0443\u0449\u0443\u044E \u0441\u0435\u0441\u0441\u0438\u044E, \u0438\u043B\u0438 --force \u0434\u043B\u044F \u0432\u043B\u043E\u0436\u0435\u043D\u043D\u043E\u0433\u043E \u0437\u0430\u043F\u0443\u0441\u043A\u0430.
107
- `),process.exit(1)),Pb&&await pr.setMultiViewer(!0);let r=pr.getMultiViewer();await sp({storage:ti,config:pr,logger:gr,machineId:ri,notification:Mo,browser:Yn,cwd:process.cwd(),watch:Cb,statusLine:Ob,multiViewer:r});break}case"login":{let r=new URL(pr.getServerUrl()).host,e=await ri.getMachineId(),t=new Rt.CryptoService(ti,gr,r,e);await t.initialize();let i=new Rt.AuthService(ti,t,ri,pr,gr,Mo,Yn,r,e),n=await No(i,Yn,gr,Rb||Fb);process.exit(n?0:1);break}case"logout":{let r=new URL(pr.getServerUrl()).host,e=await ri.getMachineId(),t=new Rt.CryptoService(ti,gr,r,e);await t.initialize();let i=new Rt.AuthService(ti,t,ri,pr,gr,Mo,Yn,r,e);await op(i),process.exit(0);break}case"status":{let r=new URL(pr.getServerUrl()).host,e=await ri.getMachineId(),t=new Rt.CryptoService(ti,gr,r,e);await t.initialize();let i=new Rt.AuthService(ti,t,ri,pr,gr,Mo,Yn,r,e);await ap(i,t),process.exit(0);break}case"fingerprint":{let r=new URL(pr.getServerUrl()).host,e=await ri.getMachineId(),t=new Rt.CryptoService(ti,gr,r,e);await t.initialize(),await cp(t),process.exit(0);break}case"version":{process.stdout.write(`${wo()}
107
+ `),process.exit(1)),Pv&&await pr.setMultiViewer(!0);let r=pr.getMultiViewer();await sp({storage:ti,config:pr,logger:gr,machineId:ri,notification:Mo,browser:Yn,cwd:process.cwd(),watch:Cv,statusLine:Ov,multiViewer:r});break}case"login":{let r=new URL(pr.getServerUrl()).host,e=await ri.getMachineId(),t=new At.CryptoService(ti,gr,r,e);await t.initialize();let i=new At.AuthService(ti,t,ri,pr,gr,Mo,Yn,r,e),n=await No(i,Yn,gr,Av||Fv);process.exit(n?0:1);break}case"logout":{let r=new URL(pr.getServerUrl()).host,e=await ri.getMachineId(),t=new At.CryptoService(ti,gr,r,e);await t.initialize();let i=new At.AuthService(ti,t,ri,pr,gr,Mo,Yn,r,e);await op(i),process.exit(0);break}case"status":{let r=new URL(pr.getServerUrl()).host,e=await ri.getMachineId(),t=new At.CryptoService(ti,gr,r,e);await t.initialize();let i=new At.AuthService(ti,t,ri,pr,gr,Mo,Yn,r,e);await ap(i,t),process.exit(0);break}case"fingerprint":{let r=new URL(pr.getServerUrl()).host,e=await ri.getMachineId(),t=new At.CryptoService(ti,gr,r,e);await t.initialize(),await cp(t),process.exit(0);break}case"version":{process.stdout.write(`${wo()}
108
108
  `),process.exit(0);break}case"help":{process.stderr.write(`Run 'termiq --help' for full usage.
109
109
  `),process.exit(0);break}default:process.stderr.write(`Unknown command: ${up}
110
110
  Run 'termiq --help' for usage.
111
- `),process.exit(1)}}(0,Rt.runWithCorrelation)(Mb,()=>Db().catch(r=>{process.stderr.write(`Fatal error: ${r instanceof Error?r.message:String(r)}
111
+ `),process.exit(1)}}(0,At.runWithCorrelation)(Mv,()=>Dv().catch(r=>{process.stderr.write(`Fatal error: ${r instanceof Error?r.message:String(r)}
112
112
  `),process.exit(1)}));
113
113
  /*! Bundled license information:
114
114