@termiq/cli 3.47.0 → 3.48.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -7
- package/dist/bin.js +158 -50
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -1,40 +1,144 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Np=Object.create;var ea=Object.defineProperty;var Mp=Object.getOwnPropertyDescriptor;var Fp=Object.getOwnPropertyNames;var Dp=Object.getPrototypeOf,Bp=Object.prototype.hasOwnProperty;var $t=(r,e)=>()=>(r&&(e=r(r=0)),e);var L=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),jp=(r,e)=>{for(var t in e)ea(r,t,{get:e[t],enumerable:!0})},Up=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Fp(e))!Bp.call(r,i)&&i!==t&&ea(r,i,{get:()=>e[i],enumerable:!(n=Mp(e,i))||n.enumerable});return r};var he=(r,e,t)=>(t=r!=null?Np(Dp(r)):{},Up(e||!r||!r.__esModule?ea(t,"default",{value:r,enumerable:!0}):t,r));var hs=L(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});Si.generateCorrelationId=Wp;Si.runWithCorrelation=Hp;Si.getCurrentCorrelationId=Vp;var qp=require("async_hooks");function Wp(){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 qf=new qp.AsyncLocalStorage;function Hp(r,e){return qf.run(r,e)}function Vp(){return qf.getStore()}});var Hf=L(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.LOG_LEVELS=void 0;Dn.shouldLog=zp;Dn.formatLogLine=Gp;var $p=hs();Dn.LOG_LEVELS=["silent","error","warn","info","debug"];var Wf={silent:0,error:1,warn:2,info:3,debug:4};function zp(r,e){return Wf[r]<=Wf[e]}function Gp(r,e,t,n){let i={ts:new Date().toISOString(),level:r,src:e,msg:t},s=(0,$p.getCurrentCorrelationId)();s&&(i.cid=s);let a=n;a.length>0&&typeof a[0]=="object"&&a[0]!==null&&!(a[0]instanceof Error)&&!Array.isArray(a[0])&&(i.ctx=a[0],a=a.slice(1));let f=[...a].reverse().find(c=>c instanceof Error);f&&(i.err={message:f.message,stack:f.stack,name:f.name},a=a.filter(c=>c!==f)),a.length>0&&(i.args=a);try{return JSON.stringify(i)}catch{return JSON.stringify({ts:i.ts,level:r,src:e,msg:t,_unserializable:!0})}}});var Vf=L(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.formatLogLine=Ur.shouldLog=Ur.LOG_LEVELS=void 0;var ta=Hf();Object.defineProperty(Ur,"LOG_LEVELS",{enumerable:!0,get:function(){return ta.LOG_LEVELS}});Object.defineProperty(Ur,"shouldLog",{enumerable:!0,get:function(){return ta.shouldLog}});Object.defineProperty(Ur,"formatLogLine",{enumerable:!0,get:function(){return ta.formatLogLine}})});var $f=L(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});ds.CircularBuffer=void 0;var ra=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}};ds.CircularBuffer=ra});var gs=L(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.getApiUrl=Yp;ps.getWsUrl=Xp;function Yp(r){return`${r.getServerUrl()}/api`}function Xp(r){let e=r.getServerUrl();return e.startsWith("https://")?e.replace(/^https:\/\//,"wss://"):e.replace(/^http:\/\//,"ws://")}});var Gf=L(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.getCurrentCorrelationId=wt.runWithCorrelation=wt.generateCorrelationId=wt.getWsUrl=wt.getApiUrl=wt.CircularBuffer=void 0;var Jp=$f();Object.defineProperty(wt,"CircularBuffer",{enumerable:!0,get:function(){return Jp.CircularBuffer}});var zf=gs();Object.defineProperty(wt,"getApiUrl",{enumerable:!0,get:function(){return zf.getApiUrl}});Object.defineProperty(wt,"getWsUrl",{enumerable:!0,get:function(){return zf.getWsUrl}});var na=hs();Object.defineProperty(wt,"generateCorrelationId",{enumerable:!0,get:function(){return na.generateCorrelationId}});Object.defineProperty(wt,"runWithCorrelation",{enumerable:!0,get:function(){return na.runWithCorrelation}});Object.defineProperty(wt,"getCurrentCorrelationId",{enumerable:!0,get:function(){return na.getCurrentCorrelationId}})});var Xf=L(Yf=>{"use strict";Object.defineProperty(Yf,"__esModule",{value:!0})});var Zf=L(Jf=>{"use strict";Object.defineProperty(Jf,"__esModule",{value:!0})});var Qf=L(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});ms.PLAN_LIMITS=void 0;ms.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 tu=L(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0})});var ru=L(nr=>{"use strict";var Zp=nr&&nr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),ys=nr&&nr.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Zp(e,r,t)};Object.defineProperty(nr,"__esModule",{value:!0});ys(Xf(),nr);ys(Zf(),nr);ys(Qf(),nr);ys(tu(),nr)});var nu=L(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.API_VERSION=Mt.WS_NAMESPACES=Mt.TIMEOUTS=Mt.STATUS_PATTERNS=Mt.TERMINAL_STATUSES=void 0;Mt.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"}};Mt.STATUS_PATTERNS={idle:[/[❯$]\s*$/,/>\s*$/],waiting:[/\[Y\/n\]/i,/\(y\/N\)/i,/Continue\?/i,/proceed\?/i],completed:[/✓/,/Done/,/Completed/,/Success/],error:[/Error/,/Failed/,/✕/,/Exception/]};Mt.TIMEOUTS={HEARTBEAT_INTERVAL:3e4,OFFLINE_THRESHOLD:6e4,DEVICE_CODE_EXPIRY:9e5,DEVICE_CODE_POLL_INTERVAL:5e3};Mt.WS_NAMESPACES={AGENT:"/agent",CLIENT:"/client"};Mt.API_VERSION="v1"});var iu=L(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});_s.isMultiRecipientPayload=Qp;_s.isEncryptedPayload=eg;function Qp(r){return typeof r=="object"&&r!==null&&"v"in r&&r.v===2&&"recipients"in r&&Array.isArray(r.recipients)}function eg(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 ia=L(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.KX_SIG_VERSION=ir.KX_FINGERPRINT_LABEL=ir.KX_ACK_LABEL=ir.KX_SIGN_LABEL=void 0;ir.KX_SIGN_LABEL="termiq-kx-v1";ir.KX_ACK_LABEL="termiq-kxack-v1";ir.KX_FINGERPRINT_LABEL="termiq-fp-v1";ir.KX_SIG_VERSION=1});var xi=L((Bv,Es)=>{(function(r){"use strict";var e=function(u){var d,h=new Float64Array(16);if(u)for(d=0;d<u.length;d++)h[d]=u[d];return h},t=function(){throw new Error("no PRNG")},n=new Uint8Array(16),i=new Uint8Array(32);i[0]=9;var s=e(),a=e([1]),f=e([56129,1]),c=e([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),l=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 b(u,d,h,o){u[d]=h>>24&255,u[d+1]=h>>16&255,u[d+2]=h>>8&255,u[d+3]=h&255,u[d+4]=o>>24&255,u[d+5]=o>>16&255,u[d+6]=o>>8&255,u[d+7]=o&255}function x(u,d,h,o,g){var E,v=0;for(E=0;E<g;E++)v|=u[d+E]^h[o+E];return(1&v-1>>>8)-1}function C(u,d,h,o){return x(u,d,h,o,16)}function H(u,d,h,o){return x(u,d,h,o,32)}function ie(u,d,h,o){for(var g=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,E=h[0]&255|(h[1]&255)<<8|(h[2]&255)<<16|(h[3]&255)<<24,v=h[4]&255|(h[5]&255)<<8|(h[6]&255)<<16|(h[7]&255)<<24,O=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,D=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,Z=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,W=d[0]&255|(d[1]&255)<<8|(d[2]&255)<<16|(d[3]&255)<<24,Ae=d[4]&255|(d[5]&255)<<8|(d[6]&255)<<16|(d[7]&255)<<24,$=d[8]&255|(d[9]&255)<<8|(d[10]&255)<<16|(d[11]&255)<<24,oe=d[12]&255|(d[13]&255)<<8|(d[14]&255)<<16|(d[15]&255)<<24,ae=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,ge=h[16]&255|(h[17]&255)<<8|(h[18]&255)<<16|(h[19]&255)<<24,de=h[20]&255|(h[21]&255)<<8|(h[22]&255)<<16|(h[23]&255)<<24,ce=h[24]&255|(h[25]&255)<<8|(h[26]&255)<<16|(h[27]&255)<<24,le=h[28]&255|(h[29]&255)<<8|(h[30]&255)<<16|(h[31]&255)<<24,fe=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,Y=g,Q=E,V=v,X=O,J=D,q=Z,w=W,S=Ae,R=$,k=oe,P=ae,M=ge,ne=de,me=ce,_e=le,ye=fe,y,ve=0;ve<20;ve+=2)y=Y+ne|0,J^=y<<7|y>>>25,y=J+Y|0,R^=y<<9|y>>>23,y=R+J|0,ne^=y<<13|y>>>19,y=ne+R|0,Y^=y<<18|y>>>14,y=q+Q|0,k^=y<<7|y>>>25,y=k+q|0,me^=y<<9|y>>>23,y=me+k|0,Q^=y<<13|y>>>19,y=Q+me|0,q^=y<<18|y>>>14,y=P+w|0,_e^=y<<7|y>>>25,y=_e+P|0,V^=y<<9|y>>>23,y=V+_e|0,w^=y<<13|y>>>19,y=w+V|0,P^=y<<18|y>>>14,y=ye+M|0,X^=y<<7|y>>>25,y=X+ye|0,S^=y<<9|y>>>23,y=S+X|0,M^=y<<13|y>>>19,y=M+S|0,ye^=y<<18|y>>>14,y=Y+X|0,Q^=y<<7|y>>>25,y=Q+Y|0,V^=y<<9|y>>>23,y=V+Q|0,X^=y<<13|y>>>19,y=X+V|0,Y^=y<<18|y>>>14,y=q+J|0,w^=y<<7|y>>>25,y=w+q|0,S^=y<<9|y>>>23,y=S+w|0,J^=y<<13|y>>>19,y=J+S|0,q^=y<<18|y>>>14,y=P+k|0,M^=y<<7|y>>>25,y=M+P|0,R^=y<<9|y>>>23,y=R+M|0,k^=y<<13|y>>>19,y=k+R|0,P^=y<<18|y>>>14,y=ye+_e|0,ne^=y<<7|y>>>25,y=ne+ye|0,me^=y<<9|y>>>23,y=me+ne|0,_e^=y<<13|y>>>19,y=_e+me|0,ye^=y<<18|y>>>14;Y=Y+g|0,Q=Q+E|0,V=V+v|0,X=X+O|0,J=J+D|0,q=q+Z|0,w=w+W|0,S=S+Ae|0,R=R+$|0,k=k+oe|0,P=P+ae|0,M=M+ge|0,ne=ne+de|0,me=me+ce|0,_e=_e+le|0,ye=ye+fe|0,u[0]=Y>>>0&255,u[1]=Y>>>8&255,u[2]=Y>>>16&255,u[3]=Y>>>24&255,u[4]=Q>>>0&255,u[5]=Q>>>8&255,u[6]=Q>>>16&255,u[7]=Q>>>24&255,u[8]=V>>>0&255,u[9]=V>>>8&255,u[10]=V>>>16&255,u[11]=V>>>24&255,u[12]=X>>>0&255,u[13]=X>>>8&255,u[14]=X>>>16&255,u[15]=X>>>24&255,u[16]=J>>>0&255,u[17]=J>>>8&255,u[18]=J>>>16&255,u[19]=J>>>24&255,u[20]=q>>>0&255,u[21]=q>>>8&255,u[22]=q>>>16&255,u[23]=q>>>24&255,u[24]=w>>>0&255,u[25]=w>>>8&255,u[26]=w>>>16&255,u[27]=w>>>24&255,u[28]=S>>>0&255,u[29]=S>>>8&255,u[30]=S>>>16&255,u[31]=S>>>24&255,u[32]=R>>>0&255,u[33]=R>>>8&255,u[34]=R>>>16&255,u[35]=R>>>24&255,u[36]=k>>>0&255,u[37]=k>>>8&255,u[38]=k>>>16&255,u[39]=k>>>24&255,u[40]=P>>>0&255,u[41]=P>>>8&255,u[42]=P>>>16&255,u[43]=P>>>24&255,u[44]=M>>>0&255,u[45]=M>>>8&255,u[46]=M>>>16&255,u[47]=M>>>24&255,u[48]=ne>>>0&255,u[49]=ne>>>8&255,u[50]=ne>>>16&255,u[51]=ne>>>24&255,u[52]=me>>>0&255,u[53]=me>>>8&255,u[54]=me>>>16&255,u[55]=me>>>24&255,u[56]=_e>>>0&255,u[57]=_e>>>8&255,u[58]=_e>>>16&255,u[59]=_e>>>24&255,u[60]=ye>>>0&255,u[61]=ye>>>8&255,u[62]=ye>>>16&255,u[63]=ye>>>24&255}function z(u,d,h,o){for(var g=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,E=h[0]&255|(h[1]&255)<<8|(h[2]&255)<<16|(h[3]&255)<<24,v=h[4]&255|(h[5]&255)<<8|(h[6]&255)<<16|(h[7]&255)<<24,O=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,D=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,Z=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,W=d[0]&255|(d[1]&255)<<8|(d[2]&255)<<16|(d[3]&255)<<24,Ae=d[4]&255|(d[5]&255)<<8|(d[6]&255)<<16|(d[7]&255)<<24,$=d[8]&255|(d[9]&255)<<8|(d[10]&255)<<16|(d[11]&255)<<24,oe=d[12]&255|(d[13]&255)<<8|(d[14]&255)<<16|(d[15]&255)<<24,ae=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,ge=h[16]&255|(h[17]&255)<<8|(h[18]&255)<<16|(h[19]&255)<<24,de=h[20]&255|(h[21]&255)<<8|(h[22]&255)<<16|(h[23]&255)<<24,ce=h[24]&255|(h[25]&255)<<8|(h[26]&255)<<16|(h[27]&255)<<24,le=h[28]&255|(h[29]&255)<<8|(h[30]&255)<<16|(h[31]&255)<<24,fe=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,Y=g,Q=E,V=v,X=O,J=D,q=Z,w=W,S=Ae,R=$,k=oe,P=ae,M=ge,ne=de,me=ce,_e=le,ye=fe,y,ve=0;ve<20;ve+=2)y=Y+ne|0,J^=y<<7|y>>>25,y=J+Y|0,R^=y<<9|y>>>23,y=R+J|0,ne^=y<<13|y>>>19,y=ne+R|0,Y^=y<<18|y>>>14,y=q+Q|0,k^=y<<7|y>>>25,y=k+q|0,me^=y<<9|y>>>23,y=me+k|0,Q^=y<<13|y>>>19,y=Q+me|0,q^=y<<18|y>>>14,y=P+w|0,_e^=y<<7|y>>>25,y=_e+P|0,V^=y<<9|y>>>23,y=V+_e|0,w^=y<<13|y>>>19,y=w+V|0,P^=y<<18|y>>>14,y=ye+M|0,X^=y<<7|y>>>25,y=X+ye|0,S^=y<<9|y>>>23,y=S+X|0,M^=y<<13|y>>>19,y=M+S|0,ye^=y<<18|y>>>14,y=Y+X|0,Q^=y<<7|y>>>25,y=Q+Y|0,V^=y<<9|y>>>23,y=V+Q|0,X^=y<<13|y>>>19,y=X+V|0,Y^=y<<18|y>>>14,y=q+J|0,w^=y<<7|y>>>25,y=w+q|0,S^=y<<9|y>>>23,y=S+w|0,J^=y<<13|y>>>19,y=J+S|0,q^=y<<18|y>>>14,y=P+k|0,M^=y<<7|y>>>25,y=M+P|0,R^=y<<9|y>>>23,y=R+M|0,k^=y<<13|y>>>19,y=k+R|0,P^=y<<18|y>>>14,y=ye+_e|0,ne^=y<<7|y>>>25,y=ne+ye|0,me^=y<<9|y>>>23,y=me+ne|0,_e^=y<<13|y>>>19,y=_e+me|0,ye^=y<<18|y>>>14;u[0]=Y>>>0&255,u[1]=Y>>>8&255,u[2]=Y>>>16&255,u[3]=Y>>>24&255,u[4]=q>>>0&255,u[5]=q>>>8&255,u[6]=q>>>16&255,u[7]=q>>>24&255,u[8]=P>>>0&255,u[9]=P>>>8&255,u[10]=P>>>16&255,u[11]=P>>>24&255,u[12]=ye>>>0&255,u[13]=ye>>>8&255,u[14]=ye>>>16&255,u[15]=ye>>>24&255,u[16]=w>>>0&255,u[17]=w>>>8&255,u[18]=w>>>16&255,u[19]=w>>>24&255,u[20]=S>>>0&255,u[21]=S>>>8&255,u[22]=S>>>16&255,u[23]=S>>>24&255,u[24]=R>>>0&255,u[25]=R>>>8&255,u[26]=R>>>16&255,u[27]=R>>>24&255,u[28]=k>>>0&255,u[29]=k>>>8&255,u[30]=k>>>16&255,u[31]=k>>>24&255}function T(u,d,h,o){ie(u,d,h,o)}function F(u,d,h,o){z(u,d,h,o)}var te=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function U(u,d,h,o,g,E,v){var O=new Uint8Array(16),D=new Uint8Array(64),Z,W;for(W=0;W<16;W++)O[W]=0;for(W=0;W<8;W++)O[W]=E[W];for(;g>=64;){for(T(D,O,v,te),W=0;W<64;W++)u[d+W]=h[o+W]^D[W];for(Z=1,W=8;W<16;W++)Z=Z+(O[W]&255)|0,O[W]=Z&255,Z>>>=8;g-=64,d+=64,o+=64}if(g>0)for(T(D,O,v,te),W=0;W<g;W++)u[d+W]=h[o+W]^D[W];return 0}function ee(u,d,h,o,g){var E=new Uint8Array(16),v=new Uint8Array(64),O,D;for(D=0;D<16;D++)E[D]=0;for(D=0;D<8;D++)E[D]=o[D];for(;h>=64;){for(T(v,E,g,te),D=0;D<64;D++)u[d+D]=v[D];for(O=1,D=8;D<16;D++)O=O+(E[D]&255)|0,E[D]=O&255,O>>>=8;h-=64,d+=64}if(h>0)for(T(v,E,g,te),D=0;D<h;D++)u[d+D]=v[D];return 0}function pe(u,d,h,o,g){var E=new Uint8Array(32);F(E,o,g,te);for(var v=new Uint8Array(8),O=0;O<8;O++)v[O]=o[O+16];return ee(u,d,h,v,E)}function K(u,d,h,o,g,E,v){var O=new Uint8Array(32);F(O,E,v,te);for(var D=new Uint8Array(8),Z=0;Z<8;Z++)D[Z]=E[Z+16];return U(u,d,h,o,g,D,O)}var Ne=function(u){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 d,h,o,g,E,v,O,D;d=u[0]&255|(u[1]&255)<<8,this.r[0]=d&8191,h=u[2]&255|(u[3]&255)<<8,this.r[1]=(d>>>13|h<<3)&8191,o=u[4]&255|(u[5]&255)<<8,this.r[2]=(h>>>10|o<<6)&7939,g=u[6]&255|(u[7]&255)<<8,this.r[3]=(o>>>7|g<<9)&8191,E=u[8]&255|(u[9]&255)<<8,this.r[4]=(g>>>4|E<<12)&255,this.r[5]=E>>>1&8190,v=u[10]&255|(u[11]&255)<<8,this.r[6]=(E>>>14|v<<2)&8191,O=u[12]&255|(u[13]&255)<<8,this.r[7]=(v>>>11|O<<5)&8065,D=u[14]&255|(u[15]&255)<<8,this.r[8]=(O>>>8|D<<8)&8191,this.r[9]=D>>>5&127,this.pad[0]=u[16]&255|(u[17]&255)<<8,this.pad[1]=u[18]&255|(u[19]&255)<<8,this.pad[2]=u[20]&255|(u[21]&255)<<8,this.pad[3]=u[22]&255|(u[23]&255)<<8,this.pad[4]=u[24]&255|(u[25]&255)<<8,this.pad[5]=u[26]&255|(u[27]&255)<<8,this.pad[6]=u[28]&255|(u[29]&255)<<8,this.pad[7]=u[30]&255|(u[31]&255)<<8};Ne.prototype.blocks=function(u,d,h){for(var o=this.fin?0:2048,g,E,v,O,D,Z,W,Ae,$,oe,ae,ge,de,ce,le,fe,Y,Q,V,X=this.h[0],J=this.h[1],q=this.h[2],w=this.h[3],S=this.h[4],R=this.h[5],k=this.h[6],P=this.h[7],M=this.h[8],ne=this.h[9],me=this.r[0],_e=this.r[1],ye=this.r[2],y=this.r[3],ve=this.r[4],Re=this.r[5],Ie=this.r[6],Ee=this.r[7],Te=this.r[8],Ce=this.r[9];h>=16;)g=u[d+0]&255|(u[d+1]&255)<<8,X+=g&8191,E=u[d+2]&255|(u[d+3]&255)<<8,J+=(g>>>13|E<<3)&8191,v=u[d+4]&255|(u[d+5]&255)<<8,q+=(E>>>10|v<<6)&8191,O=u[d+6]&255|(u[d+7]&255)<<8,w+=(v>>>7|O<<9)&8191,D=u[d+8]&255|(u[d+9]&255)<<8,S+=(O>>>4|D<<12)&8191,R+=D>>>1&8191,Z=u[d+10]&255|(u[d+11]&255)<<8,k+=(D>>>14|Z<<2)&8191,W=u[d+12]&255|(u[d+13]&255)<<8,P+=(Z>>>11|W<<5)&8191,Ae=u[d+14]&255|(u[d+15]&255)<<8,M+=(W>>>8|Ae<<8)&8191,ne+=Ae>>>5|o,$=0,oe=$,oe+=X*me,oe+=J*(5*Ce),oe+=q*(5*Te),oe+=w*(5*Ee),oe+=S*(5*Ie),$=oe>>>13,oe&=8191,oe+=R*(5*Re),oe+=k*(5*ve),oe+=P*(5*y),oe+=M*(5*ye),oe+=ne*(5*_e),$+=oe>>>13,oe&=8191,ae=$,ae+=X*_e,ae+=J*me,ae+=q*(5*Ce),ae+=w*(5*Te),ae+=S*(5*Ee),$=ae>>>13,ae&=8191,ae+=R*(5*Ie),ae+=k*(5*Re),ae+=P*(5*ve),ae+=M*(5*y),ae+=ne*(5*ye),$+=ae>>>13,ae&=8191,ge=$,ge+=X*ye,ge+=J*_e,ge+=q*me,ge+=w*(5*Ce),ge+=S*(5*Te),$=ge>>>13,ge&=8191,ge+=R*(5*Ee),ge+=k*(5*Ie),ge+=P*(5*Re),ge+=M*(5*ve),ge+=ne*(5*y),$+=ge>>>13,ge&=8191,de=$,de+=X*y,de+=J*ye,de+=q*_e,de+=w*me,de+=S*(5*Ce),$=de>>>13,de&=8191,de+=R*(5*Te),de+=k*(5*Ee),de+=P*(5*Ie),de+=M*(5*Re),de+=ne*(5*ve),$+=de>>>13,de&=8191,ce=$,ce+=X*ve,ce+=J*y,ce+=q*ye,ce+=w*_e,ce+=S*me,$=ce>>>13,ce&=8191,ce+=R*(5*Ce),ce+=k*(5*Te),ce+=P*(5*Ee),ce+=M*(5*Ie),ce+=ne*(5*Re),$+=ce>>>13,ce&=8191,le=$,le+=X*Re,le+=J*ve,le+=q*y,le+=w*ye,le+=S*_e,$=le>>>13,le&=8191,le+=R*me,le+=k*(5*Ce),le+=P*(5*Te),le+=M*(5*Ee),le+=ne*(5*Ie),$+=le>>>13,le&=8191,fe=$,fe+=X*Ie,fe+=J*Re,fe+=q*ve,fe+=w*y,fe+=S*ye,$=fe>>>13,fe&=8191,fe+=R*_e,fe+=k*me,fe+=P*(5*Ce),fe+=M*(5*Te),fe+=ne*(5*Ee),$+=fe>>>13,fe&=8191,Y=$,Y+=X*Ee,Y+=J*Ie,Y+=q*Re,Y+=w*ve,Y+=S*y,$=Y>>>13,Y&=8191,Y+=R*ye,Y+=k*_e,Y+=P*me,Y+=M*(5*Ce),Y+=ne*(5*Te),$+=Y>>>13,Y&=8191,Q=$,Q+=X*Te,Q+=J*Ee,Q+=q*Ie,Q+=w*Re,Q+=S*ve,$=Q>>>13,Q&=8191,Q+=R*y,Q+=k*ye,Q+=P*_e,Q+=M*me,Q+=ne*(5*Ce),$+=Q>>>13,Q&=8191,V=$,V+=X*Ce,V+=J*Te,V+=q*Ee,V+=w*Ie,V+=S*Re,$=V>>>13,V&=8191,V+=R*ve,V+=k*y,V+=P*ye,V+=M*_e,V+=ne*me,$+=V>>>13,V&=8191,$=($<<2)+$|0,$=$+oe|0,oe=$&8191,$=$>>>13,ae+=$,X=oe,J=ae,q=ge,w=de,S=ce,R=le,k=fe,P=Y,M=Q,ne=V,d+=16,h-=16;this.h[0]=X,this.h[1]=J,this.h[2]=q,this.h[3]=w,this.h[4]=S,this.h[5]=R,this.h[6]=k,this.h[7]=P,this.h[8]=M,this.h[9]=ne},Ne.prototype.finish=function(u,d){var h=new Uint16Array(10),o,g,E,v;if(this.leftover){for(v=this.leftover,this.buffer[v++]=1;v<16;v++)this.buffer[v]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(o=this.h[1]>>>13,this.h[1]&=8191,v=2;v<10;v++)this.h[v]+=o,o=this.h[v]>>>13,this.h[v]&=8191;for(this.h[0]+=o*5,o=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=o,o=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=o,h[0]=this.h[0]+5,o=h[0]>>>13,h[0]&=8191,v=1;v<10;v++)h[v]=this.h[v]+o,o=h[v]>>>13,h[v]&=8191;for(h[9]-=8192,g=(o^1)-1,v=0;v<10;v++)h[v]&=g;for(g=~g,v=0;v<10;v++)this.h[v]=this.h[v]&g|h[v];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,E=this.h[0]+this.pad[0],this.h[0]=E&65535,v=1;v<8;v++)E=(this.h[v]+this.pad[v]|0)+(E>>>16)|0,this.h[v]=E&65535;u[d+0]=this.h[0]>>>0&255,u[d+1]=this.h[0]>>>8&255,u[d+2]=this.h[1]>>>0&255,u[d+3]=this.h[1]>>>8&255,u[d+4]=this.h[2]>>>0&255,u[d+5]=this.h[2]>>>8&255,u[d+6]=this.h[3]>>>0&255,u[d+7]=this.h[3]>>>8&255,u[d+8]=this.h[4]>>>0&255,u[d+9]=this.h[4]>>>8&255,u[d+10]=this.h[5]>>>0&255,u[d+11]=this.h[5]>>>8&255,u[d+12]=this.h[6]>>>0&255,u[d+13]=this.h[6]>>>8&255,u[d+14]=this.h[7]>>>0&255,u[d+15]=this.h[7]>>>8&255},Ne.prototype.update=function(u,d,h){var o,g;if(this.leftover){for(g=16-this.leftover,g>h&&(g=h),o=0;o<g;o++)this.buffer[this.leftover+o]=u[d+o];if(h-=g,d+=g,this.leftover+=g,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(h>=16&&(g=h-h%16,this.blocks(u,d,g),d+=g,h-=g),h){for(o=0;o<h;o++)this.buffer[this.leftover+o]=u[d+o];this.leftover+=h}};function tt(u,d,h,o,g,E){var v=new Ne(E);return v.update(h,o,g),v.finish(u,d),0}function xe(u,d,h,o,g,E){var v=new Uint8Array(16);return tt(v,0,h,o,g,E),C(u,d,v,0)}function Me(u,d,h,o,g){var E;if(h<32)return-1;for(K(u,0,d,0,h,o,g),tt(u,16,u,32,h-32,u),E=0;E<16;E++)u[E]=0;return 0}function we(u,d,h,o,g){var E,v=new Uint8Array(32);if(h<32||(pe(v,0,32,o,g),xe(d,16,d,32,h-32,v)!==0))return-1;for(K(u,0,d,0,h,o,g),E=0;E<32;E++)u[E]=0;return 0}function qe(u,d){var h;for(h=0;h<16;h++)u[h]=d[h]|0}function be(u){var d,h,o=1;for(d=0;d<16;d++)h=u[d]+o+65535,o=Math.floor(h/65536),u[d]=h-o*65536;u[0]+=o-1+37*(o-1)}function rt(u,d,h){for(var o,g=~(h-1),E=0;E<16;E++)o=g&(u[E]^d[E]),u[E]^=o,d[E]^=o}function Fe(u,d){var h,o,g,E=e(),v=e();for(h=0;h<16;h++)v[h]=d[h];for(be(v),be(v),be(v),o=0;o<2;o++){for(E[0]=v[0]-65517,h=1;h<15;h++)E[h]=v[h]-65535-(E[h-1]>>16&1),E[h-1]&=65535;E[15]=v[15]-32767-(E[14]>>16&1),g=E[15]>>16&1,E[14]&=65535,rt(v,E,1-g)}for(h=0;h<16;h++)u[2*h]=v[h]&255,u[2*h+1]=v[h]>>8}function yt(u,d){var h=new Uint8Array(32),o=new Uint8Array(32);return Fe(h,u),Fe(o,d),H(h,0,o,0)}function We(u){var d=new Uint8Array(32);return Fe(d,u),d[0]&1}function dt(u,d){var h;for(h=0;h<16;h++)u[h]=d[2*h]+(d[2*h+1]<<8);u[15]&=32767}function N(u,d,h){for(var o=0;o<16;o++)u[o]=d[o]+h[o]}function B(u,d,h){for(var o=0;o<16;o++)u[o]=d[o]-h[o]}function I(u,d,h){var o,g,E=0,v=0,O=0,D=0,Z=0,W=0,Ae=0,$=0,oe=0,ae=0,ge=0,de=0,ce=0,le=0,fe=0,Y=0,Q=0,V=0,X=0,J=0,q=0,w=0,S=0,R=0,k=0,P=0,M=0,ne=0,me=0,_e=0,ye=0,y=h[0],ve=h[1],Re=h[2],Ie=h[3],Ee=h[4],Te=h[5],Ce=h[6],it=h[7],De=h[8],Ze=h[9],Qe=h[10],et=h[11],at=h[12],pt=h[13],gt=h[14],mt=h[15];o=d[0],E+=o*y,v+=o*ve,O+=o*Re,D+=o*Ie,Z+=o*Ee,W+=o*Te,Ae+=o*Ce,$+=o*it,oe+=o*De,ae+=o*Ze,ge+=o*Qe,de+=o*et,ce+=o*at,le+=o*pt,fe+=o*gt,Y+=o*mt,o=d[1],v+=o*y,O+=o*ve,D+=o*Re,Z+=o*Ie,W+=o*Ee,Ae+=o*Te,$+=o*Ce,oe+=o*it,ae+=o*De,ge+=o*Ze,de+=o*Qe,ce+=o*et,le+=o*at,fe+=o*pt,Y+=o*gt,Q+=o*mt,o=d[2],O+=o*y,D+=o*ve,Z+=o*Re,W+=o*Ie,Ae+=o*Ee,$+=o*Te,oe+=o*Ce,ae+=o*it,ge+=o*De,de+=o*Ze,ce+=o*Qe,le+=o*et,fe+=o*at,Y+=o*pt,Q+=o*gt,V+=o*mt,o=d[3],D+=o*y,Z+=o*ve,W+=o*Re,Ae+=o*Ie,$+=o*Ee,oe+=o*Te,ae+=o*Ce,ge+=o*it,de+=o*De,ce+=o*Ze,le+=o*Qe,fe+=o*et,Y+=o*at,Q+=o*pt,V+=o*gt,X+=o*mt,o=d[4],Z+=o*y,W+=o*ve,Ae+=o*Re,$+=o*Ie,oe+=o*Ee,ae+=o*Te,ge+=o*Ce,de+=o*it,ce+=o*De,le+=o*Ze,fe+=o*Qe,Y+=o*et,Q+=o*at,V+=o*pt,X+=o*gt,J+=o*mt,o=d[5],W+=o*y,Ae+=o*ve,$+=o*Re,oe+=o*Ie,ae+=o*Ee,ge+=o*Te,de+=o*Ce,ce+=o*it,le+=o*De,fe+=o*Ze,Y+=o*Qe,Q+=o*et,V+=o*at,X+=o*pt,J+=o*gt,q+=o*mt,o=d[6],Ae+=o*y,$+=o*ve,oe+=o*Re,ae+=o*Ie,ge+=o*Ee,de+=o*Te,ce+=o*Ce,le+=o*it,fe+=o*De,Y+=o*Ze,Q+=o*Qe,V+=o*et,X+=o*at,J+=o*pt,q+=o*gt,w+=o*mt,o=d[7],$+=o*y,oe+=o*ve,ae+=o*Re,ge+=o*Ie,de+=o*Ee,ce+=o*Te,le+=o*Ce,fe+=o*it,Y+=o*De,Q+=o*Ze,V+=o*Qe,X+=o*et,J+=o*at,q+=o*pt,w+=o*gt,S+=o*mt,o=d[8],oe+=o*y,ae+=o*ve,ge+=o*Re,de+=o*Ie,ce+=o*Ee,le+=o*Te,fe+=o*Ce,Y+=o*it,Q+=o*De,V+=o*Ze,X+=o*Qe,J+=o*et,q+=o*at,w+=o*pt,S+=o*gt,R+=o*mt,o=d[9],ae+=o*y,ge+=o*ve,de+=o*Re,ce+=o*Ie,le+=o*Ee,fe+=o*Te,Y+=o*Ce,Q+=o*it,V+=o*De,X+=o*Ze,J+=o*Qe,q+=o*et,w+=o*at,S+=o*pt,R+=o*gt,k+=o*mt,o=d[10],ge+=o*y,de+=o*ve,ce+=o*Re,le+=o*Ie,fe+=o*Ee,Y+=o*Te,Q+=o*Ce,V+=o*it,X+=o*De,J+=o*Ze,q+=o*Qe,w+=o*et,S+=o*at,R+=o*pt,k+=o*gt,P+=o*mt,o=d[11],de+=o*y,ce+=o*ve,le+=o*Re,fe+=o*Ie,Y+=o*Ee,Q+=o*Te,V+=o*Ce,X+=o*it,J+=o*De,q+=o*Ze,w+=o*Qe,S+=o*et,R+=o*at,k+=o*pt,P+=o*gt,M+=o*mt,o=d[12],ce+=o*y,le+=o*ve,fe+=o*Re,Y+=o*Ie,Q+=o*Ee,V+=o*Te,X+=o*Ce,J+=o*it,q+=o*De,w+=o*Ze,S+=o*Qe,R+=o*et,k+=o*at,P+=o*pt,M+=o*gt,ne+=o*mt,o=d[13],le+=o*y,fe+=o*ve,Y+=o*Re,Q+=o*Ie,V+=o*Ee,X+=o*Te,J+=o*Ce,q+=o*it,w+=o*De,S+=o*Ze,R+=o*Qe,k+=o*et,P+=o*at,M+=o*pt,ne+=o*gt,me+=o*mt,o=d[14],fe+=o*y,Y+=o*ve,Q+=o*Re,V+=o*Ie,X+=o*Ee,J+=o*Te,q+=o*Ce,w+=o*it,S+=o*De,R+=o*Ze,k+=o*Qe,P+=o*et,M+=o*at,ne+=o*pt,me+=o*gt,_e+=o*mt,o=d[15],Y+=o*y,Q+=o*ve,V+=o*Re,X+=o*Ie,J+=o*Ee,q+=o*Te,w+=o*Ce,S+=o*it,R+=o*De,k+=o*Ze,P+=o*Qe,M+=o*et,ne+=o*at,me+=o*pt,_e+=o*gt,ye+=o*mt,E+=38*Q,v+=38*V,O+=38*X,D+=38*J,Z+=38*q,W+=38*w,Ae+=38*S,$+=38*R,oe+=38*k,ae+=38*P,ge+=38*M,de+=38*ne,ce+=38*me,le+=38*_e,fe+=38*ye,g=1,o=E+g+65535,g=Math.floor(o/65536),E=o-g*65536,o=v+g+65535,g=Math.floor(o/65536),v=o-g*65536,o=O+g+65535,g=Math.floor(o/65536),O=o-g*65536,o=D+g+65535,g=Math.floor(o/65536),D=o-g*65536,o=Z+g+65535,g=Math.floor(o/65536),Z=o-g*65536,o=W+g+65535,g=Math.floor(o/65536),W=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,o=oe+g+65535,g=Math.floor(o/65536),oe=o-g*65536,o=ae+g+65535,g=Math.floor(o/65536),ae=o-g*65536,o=ge+g+65535,g=Math.floor(o/65536),ge=o-g*65536,o=de+g+65535,g=Math.floor(o/65536),de=o-g*65536,o=ce+g+65535,g=Math.floor(o/65536),ce=o-g*65536,o=le+g+65535,g=Math.floor(o/65536),le=o-g*65536,o=fe+g+65535,g=Math.floor(o/65536),fe=o-g*65536,o=Y+g+65535,g=Math.floor(o/65536),Y=o-g*65536,E+=g-1+37*(g-1),g=1,o=E+g+65535,g=Math.floor(o/65536),E=o-g*65536,o=v+g+65535,g=Math.floor(o/65536),v=o-g*65536,o=O+g+65535,g=Math.floor(o/65536),O=o-g*65536,o=D+g+65535,g=Math.floor(o/65536),D=o-g*65536,o=Z+g+65535,g=Math.floor(o/65536),Z=o-g*65536,o=W+g+65535,g=Math.floor(o/65536),W=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,o=oe+g+65535,g=Math.floor(o/65536),oe=o-g*65536,o=ae+g+65535,g=Math.floor(o/65536),ae=o-g*65536,o=ge+g+65535,g=Math.floor(o/65536),ge=o-g*65536,o=de+g+65535,g=Math.floor(o/65536),de=o-g*65536,o=ce+g+65535,g=Math.floor(o/65536),ce=o-g*65536,o=le+g+65535,g=Math.floor(o/65536),le=o-g*65536,o=fe+g+65535,g=Math.floor(o/65536),fe=o-g*65536,o=Y+g+65535,g=Math.floor(o/65536),Y=o-g*65536,E+=g-1+37*(g-1),u[0]=E,u[1]=v,u[2]=O,u[3]=D,u[4]=Z,u[5]=W,u[6]=Ae,u[7]=$,u[8]=oe,u[9]=ae,u[10]=ge,u[11]=de,u[12]=ce,u[13]=le,u[14]=fe,u[15]=Y}function se(u,d){I(u,d,d)}function Pe(u,d){var h=e(),o;for(o=0;o<16;o++)h[o]=d[o];for(o=253;o>=0;o--)se(h,h),o!==2&&o!==4&&I(h,h,d);for(o=0;o<16;o++)u[o]=h[o]}function j(u,d){var h=e(),o;for(o=0;o<16;o++)h[o]=d[o];for(o=250;o>=0;o--)se(h,h),o!==1&&I(h,h,d);for(o=0;o<16;o++)u[o]=h[o]}function ue(u,d,h){var o=new Uint8Array(32),g=new Float64Array(80),E,v,O=e(),D=e(),Z=e(),W=e(),Ae=e(),$=e();for(v=0;v<31;v++)o[v]=d[v];for(o[31]=d[31]&127|64,o[0]&=248,dt(g,h),v=0;v<16;v++)D[v]=g[v],W[v]=O[v]=Z[v]=0;for(O[0]=W[0]=1,v=254;v>=0;--v)E=o[v>>>3]>>>(v&7)&1,rt(O,D,E),rt(Z,W,E),N(Ae,O,Z),B(O,O,Z),N(Z,D,W),B(D,D,W),se(W,Ae),se($,O),I(O,Z,O),I(Z,D,Ae),N(Ae,O,Z),B(O,O,Z),se(D,O),B(Z,W,$),I(O,Z,f),N(O,O,W),I(Z,Z,O),I(O,W,$),I(W,D,g),se(D,Ae),rt(O,D,E),rt(Z,W,E);for(v=0;v<16;v++)g[v+16]=O[v],g[v+32]=Z[v],g[v+48]=D[v],g[v+64]=W[v];var oe=g.subarray(32),ae=g.subarray(16);return Pe(oe,oe),I(ae,ae,oe),Fe(u,ae),0}function je(u,d){return ue(u,d,i)}function nt(u,d){return t(d,32),je(u,d)}function _t(u,d,h){var o=new Uint8Array(32);return ue(o,h,d),F(u,n,o,te)}var Vt=Me,cn=we;function jr(u,d,h,o,g,E){var v=new Uint8Array(32);return _t(v,g,E),Vt(u,d,h,o,v)}function Nn(u,d,h,o,g,E){var v=new Uint8Array(32);return _t(v,g,E),cn(u,d,h,o,v)}var rs=[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 Nf(u,d,h,o){for(var g=new Int32Array(16),E=new Int32Array(16),v,O,D,Z,W,Ae,$,oe,ae,ge,de,ce,le,fe,Y,Q,V,X,J,q,w,S,R,k,P,M,ne=u[0],me=u[1],_e=u[2],ye=u[3],y=u[4],ve=u[5],Re=u[6],Ie=u[7],Ee=d[0],Te=d[1],Ce=d[2],it=d[3],De=d[4],Ze=d[5],Qe=d[6],et=d[7],at=0;o>=128;){for(J=0;J<16;J++)q=8*J+at,g[J]=h[q+0]<<24|h[q+1]<<16|h[q+2]<<8|h[q+3],E[J]=h[q+4]<<24|h[q+5]<<16|h[q+6]<<8|h[q+7];for(J=0;J<80;J++)if(v=ne,O=me,D=_e,Z=ye,W=y,Ae=ve,$=Re,oe=Ie,ae=Ee,ge=Te,de=Ce,ce=it,le=De,fe=Ze,Y=Qe,Q=et,w=Ie,S=et,R=S&65535,k=S>>>16,P=w&65535,M=w>>>16,w=(y>>>14|De<<18)^(y>>>18|De<<14)^(De>>>9|y<<23),S=(De>>>14|y<<18)^(De>>>18|y<<14)^(y>>>9|De<<23),R+=S&65535,k+=S>>>16,P+=w&65535,M+=w>>>16,w=y&ve^~y&Re,S=De&Ze^~De&Qe,R+=S&65535,k+=S>>>16,P+=w&65535,M+=w>>>16,w=rs[J*2],S=rs[J*2+1],R+=S&65535,k+=S>>>16,P+=w&65535,M+=w>>>16,w=g[J%16],S=E[J%16],R+=S&65535,k+=S>>>16,P+=w&65535,M+=w>>>16,k+=R>>>16,P+=k>>>16,M+=P>>>16,V=P&65535|M<<16,X=R&65535|k<<16,w=V,S=X,R=S&65535,k=S>>>16,P=w&65535,M=w>>>16,w=(ne>>>28|Ee<<4)^(Ee>>>2|ne<<30)^(Ee>>>7|ne<<25),S=(Ee>>>28|ne<<4)^(ne>>>2|Ee<<30)^(ne>>>7|Ee<<25),R+=S&65535,k+=S>>>16,P+=w&65535,M+=w>>>16,w=ne&me^ne&_e^me&_e,S=Ee&Te^Ee&Ce^Te&Ce,R+=S&65535,k+=S>>>16,P+=w&65535,M+=w>>>16,k+=R>>>16,P+=k>>>16,M+=P>>>16,oe=P&65535|M<<16,Q=R&65535|k<<16,w=Z,S=ce,R=S&65535,k=S>>>16,P=w&65535,M=w>>>16,w=V,S=X,R+=S&65535,k+=S>>>16,P+=w&65535,M+=w>>>16,k+=R>>>16,P+=k>>>16,M+=P>>>16,Z=P&65535|M<<16,ce=R&65535|k<<16,me=v,_e=O,ye=D,y=Z,ve=W,Re=Ae,Ie=$,ne=oe,Te=ae,Ce=ge,it=de,De=ce,Ze=le,Qe=fe,et=Y,Ee=Q,J%16===15)for(q=0;q<16;q++)w=g[q],S=E[q],R=S&65535,k=S>>>16,P=w&65535,M=w>>>16,w=g[(q+9)%16],S=E[(q+9)%16],R+=S&65535,k+=S>>>16,P+=w&65535,M+=w>>>16,V=g[(q+1)%16],X=E[(q+1)%16],w=(V>>>1|X<<31)^(V>>>8|X<<24)^V>>>7,S=(X>>>1|V<<31)^(X>>>8|V<<24)^(X>>>7|V<<25),R+=S&65535,k+=S>>>16,P+=w&65535,M+=w>>>16,V=g[(q+14)%16],X=E[(q+14)%16],w=(V>>>19|X<<13)^(X>>>29|V<<3)^V>>>6,S=(X>>>19|V<<13)^(V>>>29|X<<3)^(X>>>6|V<<26),R+=S&65535,k+=S>>>16,P+=w&65535,M+=w>>>16,k+=R>>>16,P+=k>>>16,M+=P>>>16,g[q]=P&65535|M<<16,E[q]=R&65535|k<<16;w=ne,S=Ee,R=S&65535,k=S>>>16,P=w&65535,M=w>>>16,w=u[0],S=d[0],R+=S&65535,k+=S>>>16,P+=w&65535,M+=w>>>16,k+=R>>>16,P+=k>>>16,M+=P>>>16,u[0]=ne=P&65535|M<<16,d[0]=Ee=R&65535|k<<16,w=me,S=Te,R=S&65535,k=S>>>16,P=w&65535,M=w>>>16,w=u[1],S=d[1],R+=S&65535,k+=S>>>16,P+=w&65535,M+=w>>>16,k+=R>>>16,P+=k>>>16,M+=P>>>16,u[1]=me=P&65535|M<<16,d[1]=Te=R&65535|k<<16,w=_e,S=Ce,R=S&65535,k=S>>>16,P=w&65535,M=w>>>16,w=u[2],S=d[2],R+=S&65535,k+=S>>>16,P+=w&65535,M+=w>>>16,k+=R>>>16,P+=k>>>16,M+=P>>>16,u[2]=_e=P&65535|M<<16,d[2]=Ce=R&65535|k<<16,w=ye,S=it,R=S&65535,k=S>>>16,P=w&65535,M=w>>>16,w=u[3],S=d[3],R+=S&65535,k+=S>>>16,P+=w&65535,M+=w>>>16,k+=R>>>16,P+=k>>>16,M+=P>>>16,u[3]=ye=P&65535|M<<16,d[3]=it=R&65535|k<<16,w=y,S=De,R=S&65535,k=S>>>16,P=w&65535,M=w>>>16,w=u[4],S=d[4],R+=S&65535,k+=S>>>16,P+=w&65535,M+=w>>>16,k+=R>>>16,P+=k>>>16,M+=P>>>16,u[4]=y=P&65535|M<<16,d[4]=De=R&65535|k<<16,w=ve,S=Ze,R=S&65535,k=S>>>16,P=w&65535,M=w>>>16,w=u[5],S=d[5],R+=S&65535,k+=S>>>16,P+=w&65535,M+=w>>>16,k+=R>>>16,P+=k>>>16,M+=P>>>16,u[5]=ve=P&65535|M<<16,d[5]=Ze=R&65535|k<<16,w=Re,S=Qe,R=S&65535,k=S>>>16,P=w&65535,M=w>>>16,w=u[6],S=d[6],R+=S&65535,k+=S>>>16,P+=w&65535,M+=w>>>16,k+=R>>>16,P+=k>>>16,M+=P>>>16,u[6]=Re=P&65535|M<<16,d[6]=Qe=R&65535|k<<16,w=Ie,S=et,R=S&65535,k=S>>>16,P=w&65535,M=w>>>16,w=u[7],S=d[7],R+=S&65535,k+=S>>>16,P+=w&65535,M+=w>>>16,k+=R>>>16,P+=k>>>16,M+=P>>>16,u[7]=Ie=P&65535|M<<16,d[7]=et=R&65535|k<<16,at+=128,o-=128}return o}function fn(u,d,h){var o=new Int32Array(8),g=new Int32Array(8),E=new Uint8Array(256),v,O=h;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,Nf(o,g,d,h),h%=128,v=0;v<h;v++)E[v]=d[O-h+v];for(E[h]=128,h=256-128*(h<112?1:0),E[h-9]=0,b(E,h-8,O/536870912|0,O<<3),Nf(o,g,E,h),v=0;v<8;v++)b(u,8*v,o[v],g[v]);return 0}function ns(u,d){var h=e(),o=e(),g=e(),E=e(),v=e(),O=e(),D=e(),Z=e(),W=e();B(h,u[1],u[0]),B(W,d[1],d[0]),I(h,h,W),N(o,u[0],u[1]),N(W,d[0],d[1]),I(o,o,W),I(g,u[3],d[3]),I(g,g,l),I(E,u[2],d[2]),N(E,E,E),B(v,o,h),B(O,E,g),N(D,E,g),N(Z,o,h),I(u[0],v,O),I(u[1],Z,D),I(u[2],D,O),I(u[3],v,Z)}function Mf(u,d,h){var o;for(o=0;o<4;o++)rt(u[o],d[o],h)}function Ho(u,d){var h=e(),o=e(),g=e();Pe(g,d[2]),I(h,d[0],g),I(o,d[1],g),Fe(u,o),u[31]^=We(h)<<7}function Vo(u,d,h){var o,g;for(qe(u[0],s),qe(u[1],a),qe(u[2],a),qe(u[3],s),g=255;g>=0;--g)o=h[g/8|0]>>(g&7)&1,Mf(u,d,o),ns(d,u),ns(u,u),Mf(u,d,o)}function is(u,d){var h=[e(),e(),e(),e()];qe(h[0],p),qe(h[1],m),qe(h[2],a),I(h[3],p,m),Vo(u,h,d)}function $o(u,d,h){var o=new Uint8Array(64),g=[e(),e(),e(),e()],E;for(h||t(d,32),fn(o,d,32),o[0]&=248,o[31]&=127,o[31]|=64,is(g,o),Ho(u,g),E=0;E<32;E++)d[E+32]=u[E];return 0}var ss=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 zo(u,d){var h,o,g,E;for(o=63;o>=32;--o){for(h=0,g=o-32,E=o-12;g<E;++g)d[g]+=h-16*d[o]*ss[g-(o-32)],h=Math.floor((d[g]+128)/256),d[g]-=h*256;d[g]+=h,d[o]=0}for(h=0,g=0;g<32;g++)d[g]+=h-(d[31]>>4)*ss[g],h=d[g]>>8,d[g]&=255;for(g=0;g<32;g++)d[g]-=h*ss[g];for(o=0;o<32;o++)d[o+1]+=d[o]>>8,u[o]=d[o]&255}function Go(u){var d=new Float64Array(64),h;for(h=0;h<64;h++)d[h]=u[h];for(h=0;h<64;h++)u[h]=0;zo(u,d)}function Ff(u,d,h,o){var g=new Uint8Array(64),E=new Uint8Array(64),v=new Uint8Array(64),O,D,Z=new Float64Array(64),W=[e(),e(),e(),e()];fn(g,o,32),g[0]&=248,g[31]&=127,g[31]|=64;var Ae=h+64;for(O=0;O<h;O++)u[64+O]=d[O];for(O=0;O<32;O++)u[32+O]=g[32+O];for(fn(v,u.subarray(32),h+32),Go(v),is(W,v),Ho(u,W),O=32;O<64;O++)u[O]=o[O];for(fn(E,u,h+64),Go(E),O=0;O<64;O++)Z[O]=0;for(O=0;O<32;O++)Z[O]=v[O];for(O=0;O<32;O++)for(D=0;D<32;D++)Z[O+D]+=E[O]*g[D];return zo(u.subarray(32),Z),Ae}function Ap(u,d){var h=e(),o=e(),g=e(),E=e(),v=e(),O=e(),D=e();return qe(u[2],a),dt(u[1],d),se(g,u[1]),I(E,g,c),B(g,g,u[2]),N(E,u[2],E),se(v,E),se(O,v),I(D,O,v),I(h,D,g),I(h,h,E),j(h,h),I(h,h,g),I(h,h,E),I(h,h,E),I(u[0],h,E),se(o,u[0]),I(o,o,E),yt(o,g)&&I(u[0],u[0],_),se(o,u[0]),I(o,o,E),yt(o,g)?-1:(We(u[0])===d[31]>>7&&B(u[0],s,u[0]),I(u[3],u[0],u[1]),0)}function Yo(u,d,h,o){var g,E=new Uint8Array(32),v=new Uint8Array(64),O=[e(),e(),e(),e()],D=[e(),e(),e(),e()];if(h<64||Ap(D,o))return-1;for(g=0;g<h;g++)u[g]=d[g];for(g=0;g<32;g++)u[g+32]=o[g];if(fn(v,u,h),Go(v),Vo(O,D,v),is(D,d.subarray(32)),ns(O,D),Ho(E,O),h-=64,H(d,0,E,0)){for(g=0;g<h;g++)u[g]=0;return-1}for(g=0;g<h;g++)u[g]=d[g+64];return h}var Xo=32,os=24,yi=32,Mn=16,_i=32,as=32,Ei=32,bi=32,Jo=32,Df=os,Rp=yi,Ip=Mn,br=64,un=32,Fn=64,Zo=32,Qo=64;r.lowlevel={crypto_core_hsalsa20:F,crypto_stream_xor:K,crypto_stream:pe,crypto_stream_salsa20_xor:U,crypto_stream_salsa20:ee,crypto_onetimeauth:tt,crypto_onetimeauth_verify:xe,crypto_verify_16:C,crypto_verify_32:H,crypto_secretbox:Me,crypto_secretbox_open:we,crypto_scalarmult:ue,crypto_scalarmult_base:je,crypto_box_beforenm:_t,crypto_box_afternm:Vt,crypto_box:jr,crypto_box_open:Nn,crypto_box_keypair:nt,crypto_hash:fn,crypto_sign:Ff,crypto_sign_keypair:$o,crypto_sign_open:Yo,crypto_secretbox_KEYBYTES:Xo,crypto_secretbox_NONCEBYTES:os,crypto_secretbox_ZEROBYTES:yi,crypto_secretbox_BOXZEROBYTES:Mn,crypto_scalarmult_BYTES:_i,crypto_scalarmult_SCALARBYTES:as,crypto_box_PUBLICKEYBYTES:Ei,crypto_box_SECRETKEYBYTES:bi,crypto_box_BEFORENMBYTES:Jo,crypto_box_NONCEBYTES:Df,crypto_box_ZEROBYTES:Rp,crypto_box_BOXZEROBYTES:Ip,crypto_sign_BYTES:br,crypto_sign_PUBLICKEYBYTES:un,crypto_sign_SECRETKEYBYTES:Fn,crypto_sign_SEEDBYTES:Zo,crypto_hash_BYTES:Qo,gf:e,D:c,L:ss,pack25519:Fe,unpack25519:dt,M:I,A:N,S:se,Z:B,pow2523:j,add:ns,set25519:qe,modL:zo,scalarmult:Vo,scalarbase:is};function Bf(u,d){if(u.length!==Xo)throw new Error("bad key size");if(d.length!==os)throw new Error("bad nonce size")}function Lp(u,d){if(u.length!==Ei)throw new Error("bad public key size");if(d.length!==bi)throw new Error("bad secret key size")}function Ct(){for(var u=0;u<arguments.length;u++)if(!(arguments[u]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function jf(u){for(var d=0;d<u.length;d++)u[d]=0}r.randomBytes=function(u){var d=new Uint8Array(u);return t(d,u),d},r.secretbox=function(u,d,h){Ct(u,d,h),Bf(h,d);for(var o=new Uint8Array(yi+u.length),g=new Uint8Array(o.length),E=0;E<u.length;E++)o[E+yi]=u[E];return Me(g,o,o.length,d,h),g.subarray(Mn)},r.secretbox.open=function(u,d,h){Ct(u,d,h),Bf(h,d);for(var o=new Uint8Array(Mn+u.length),g=new Uint8Array(o.length),E=0;E<u.length;E++)o[E+Mn]=u[E];return o.length<32||we(g,o,o.length,d,h)!==0?null:g.subarray(yi)},r.secretbox.keyLength=Xo,r.secretbox.nonceLength=os,r.secretbox.overheadLength=Mn,r.scalarMult=function(u,d){if(Ct(u,d),u.length!==as)throw new Error("bad n size");if(d.length!==_i)throw new Error("bad p size");var h=new Uint8Array(_i);return ue(h,u,d),h},r.scalarMult.base=function(u){if(Ct(u),u.length!==as)throw new Error("bad n size");var d=new Uint8Array(_i);return je(d,u),d},r.scalarMult.scalarLength=as,r.scalarMult.groupElementLength=_i,r.box=function(u,d,h,o){var g=r.box.before(h,o);return r.secretbox(u,d,g)},r.box.before=function(u,d){Ct(u,d),Lp(u,d);var h=new Uint8Array(Jo);return _t(h,u,d),h},r.box.after=r.secretbox,r.box.open=function(u,d,h,o){var g=r.box.before(h,o);return r.secretbox.open(u,d,g)},r.box.open.after=r.secretbox.open,r.box.keyPair=function(){var u=new Uint8Array(Ei),d=new Uint8Array(bi);return nt(u,d),{publicKey:u,secretKey:d}},r.box.keyPair.fromSecretKey=function(u){if(Ct(u),u.length!==bi)throw new Error("bad secret key size");var d=new Uint8Array(Ei);return je(d,u),{publicKey:d,secretKey:new Uint8Array(u)}},r.box.publicKeyLength=Ei,r.box.secretKeyLength=bi,r.box.sharedKeyLength=Jo,r.box.nonceLength=Df,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(u,d){if(Ct(u,d),d.length!==Fn)throw new Error("bad secret key size");var h=new Uint8Array(br+u.length);return Ff(h,u,u.length,d),h},r.sign.open=function(u,d){if(Ct(u,d),d.length!==un)throw new Error("bad public key size");var h=new Uint8Array(u.length),o=Yo(h,u,u.length,d);if(o<0)return null;for(var g=new Uint8Array(o),E=0;E<g.length;E++)g[E]=h[E];return g},r.sign.detached=function(u,d){for(var h=r.sign(u,d),o=new Uint8Array(br),g=0;g<o.length;g++)o[g]=h[g];return o},r.sign.detached.verify=function(u,d,h){if(Ct(u,d,h),d.length!==br)throw new Error("bad signature size");if(h.length!==un)throw new Error("bad public key size");var o=new Uint8Array(br+u.length),g=new Uint8Array(br+u.length),E;for(E=0;E<br;E++)o[E]=d[E];for(E=0;E<u.length;E++)o[E+br]=u[E];return Yo(g,o,o.length,h)>=0},r.sign.keyPair=function(){var u=new Uint8Array(un),d=new Uint8Array(Fn);return $o(u,d),{publicKey:u,secretKey:d}},r.sign.keyPair.fromSecretKey=function(u){if(Ct(u),u.length!==Fn)throw new Error("bad secret key size");for(var d=new Uint8Array(un),h=0;h<d.length;h++)d[h]=u[32+h];return{publicKey:d,secretKey:new Uint8Array(u)}},r.sign.keyPair.fromSeed=function(u){if(Ct(u),u.length!==Zo)throw new Error("bad seed size");for(var d=new Uint8Array(un),h=new Uint8Array(Fn),o=0;o<32;o++)h[o]=u[o];return $o(d,h,!0),{publicKey:d,secretKey:h}},r.sign.publicKeyLength=un,r.sign.secretKeyLength=Fn,r.sign.seedLength=Zo,r.sign.signatureLength=br,r.hash=function(u){Ct(u);var d=new Uint8Array(Qo);return fn(d,u,u.length),d},r.hash.hashLength=Qo,r.verify=function(u,d){return Ct(u,d),u.length===0||d.length===0||u.length!==d.length?!1:x(u,0,d,0,u.length)===0},r.setPRNG=function(u){t=u},(function(){var u=typeof self<"u"?self.crypto||self.msCrypto:null;if(u&&u.getRandomValues){var d=65536;r.setPRNG(function(h,o){var g,E=new Uint8Array(o);for(g=0;g<o;g+=d)u.getRandomValues(E.subarray(g,g+Math.min(o-g,d)));for(g=0;g<o;g++)h[g]=E[g];jf(E)})}else typeof require<"u"&&(u=require("crypto"),u&&u.randomBytes&&r.setPRNG(function(h,o){var g,E=u.randomBytes(o);for(g=0;g<o;g++)h[g]=E[g];jf(E)}))})()})(typeof Es<"u"&&Es.exports?Es.exports:self.nacl=self.nacl||{})});var Ti=L((su,bs)=>{(function(r,e){"use strict";typeof bs<"u"&&bs.exports?bs.exports=e():(r.nacl||(r.nacl={}),r.nacl.util=e())})(su,function(){"use strict";var r={};function e(t){if(!/^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(t))throw new TypeError("invalid encoding")}return r.decodeUTF8=function(t){if(typeof t!="string")throw new TypeError("expected string");var n,i=unescape(encodeURIComponent(t)),s=new Uint8Array(i.length);for(n=0;n<i.length;n++)s[n]=i.charCodeAt(n);return s},r.encodeUTF8=function(t){var n,i=[];for(n=0;n<t.length;n++)i.push(String.fromCharCode(t[n]));return decodeURIComponent(escape(i.join("")))},typeof atob>"u"?typeof Buffer.from<"u"?(r.encodeBase64=function(t){return Buffer.from(t).toString("base64")},r.decodeBase64=function(t){return e(t),new Uint8Array(Array.prototype.slice.call(Buffer.from(t,"base64"),0))}):(r.encodeBase64=function(t){return new Buffer(t).toString("base64")},r.decodeBase64=function(t){return e(t),new Uint8Array(Array.prototype.slice.call(new Buffer(t,"base64"),0))}):(r.encodeBase64=function(t){var n,i=[],s=t.length;for(n=0;n<s;n++)i.push(String.fromCharCode(t[n]));return btoa(i.join(""))},r.decodeBase64=function(t){e(t);var n,i=atob(t),s=new Uint8Array(i.length);for(n=0;n<i.length;n++)s[n]=i.charCodeAt(n);return s}),r})});var ou=L(Ot=>{"use strict";var tg=Ot&&Ot.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ot,"__esModule",{value:!0});Ot.concatBytes=Ci;Ot.generateIdentityKeyPair=rg;Ot.identityPublicFromSecret=ng;Ot.signSessionKey=ig;Ot.verifySessionKey=sg;Ot.buildKxCanonical=og;Ot.buildKxAckCanonical=ag;Ot.fingerprintIdentityKey=cg;Ot.fingerprintShortHex=fg;var sr=tg(xi()),kt=Ti(),vs=ia();function Ci(...r){let e=0;for(let i of r)e+=i.length;let t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}function rg(){let r=sr.default.sign.keyPair();return{identityPublicKey:(0,kt.encodeBase64)(r.publicKey),identitySecretKey:(0,kt.encodeBase64)(r.secretKey)}}function ng(r){let e=(0,kt.decodeBase64)(r);if(e.length!==sr.default.sign.secretKeyLength)throw new Error("bad identity secret key length");let t=sr.default.sign.keyPair.fromSecretKey(e);return(0,kt.encodeBase64)(t.publicKey)}function ig(r,e){let t=(0,kt.decodeBase64)(e);if(t.length!==sr.default.sign.secretKeyLength)throw new Error("bad identity secret key length");return(0,kt.encodeBase64)(sr.default.sign.detached(r,t))}function sg(r,e,t){try{let n=(0,kt.decodeBase64)(e),i=(0,kt.decodeBase64)(t);return i.length!==sr.default.sign.publicKeyLength||n.length!==sr.default.sign.signatureLength?!1:sr.default.sign.detached.verify(r,n,i)}catch{return!1}}var ln=new Uint8Array([0]);function og(r){let e=new TextEncoder,t=e.encode(vs.KX_SIGN_LABEL),n=e.encode(r.agentId),i=e.encode(String(r.keyVersion)),s=(0,kt.decodeBase64)(r.boxPublicKey);return Ci(t,ln,n,ln,i,ln,s)}function ag(r){let e=new TextEncoder;return Ci(e.encode(vs.KX_ACK_LABEL),ln,e.encode(r.agentId),ln,e.encode(String(r.keyVersion)),ln,(0,kt.decodeBase64)(r.boxPublicKey),ln,(0,kt.decodeBase64)(r.boundClientKey))}function cg(r){let e=(0,kt.decodeBase64)(r),t=Ci(new TextEncoder().encode(vs.KX_FINGERPRINT_LABEL),e),n=sr.default.hash(t),i=[];for(let s=0;s<12;s++){let a=s*5,c=(((n[a]<<24>>>0)+(n[a+1]<<16)+(n[a+2]<<8)+n[a+3]^n[a+4])>>>0)%1e5;i.push(String(c).padStart(5,"0"))}return i.join(" ")}function fg(r){let e=(0,kt.decodeBase64)(r),t=Ci(new TextEncoder().encode(vs.KX_FINGERPRINT_LABEL),e),n=sr.default.hash(t).slice(0,8);return Array.from(n).map(i=>i.toString(16).padStart(2,"0")).join(":").toUpperCase()}});var au=L(qr=>{"use strict";var ug=qr&&qr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(qr,"__esModule",{value:!0});qr.encrypt=lg;qr.decrypt=hg;qr.encryptBinary=dg;qr.decryptBinary=pg;var Sr=ug(xi()),Kr=Ti();function lg(r,e,t){let n=Sr.default.randomBytes(Sr.default.secretbox.nonceLength),i=new TextEncoder().encode(r),s=Sr.default.secretbox(i,n,e);return{v:1,sid:t,n:(0,Kr.encodeBase64)(n),c:(0,Kr.encodeBase64)(s)}}function hg(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Kr.decodeBase64)(r.n),n=(0,Kr.decodeBase64)(r.c);if(t.length!==Sr.default.secretbox.nonceLength)throw new Error(`Invalid nonce length: ${t.length}`);let i=Sr.default.secretbox.open(n,t,e);if(!i)throw new Error("Decryption failed: invalid ciphertext or wrong key");return new TextDecoder().decode(i)}function dg(r,e,t){let n=Sr.default.randomBytes(Sr.default.secretbox.nonceLength),i=Sr.default.secretbox(r,n,e);return{v:1,sid:t,n:(0,Kr.encodeBase64)(n),c:(0,Kr.encodeBase64)(i)}}function pg(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Kr.decodeBase64)(r.n),n=(0,Kr.decodeBase64)(r.c),i=Sr.default.secretbox.open(n,t,e);if(!i)throw new Error("Decryption failed: invalid ciphertext or wrong key");return i}});var cu=L(zt=>{"use strict";var gg=zt&&zt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(zt,"__esModule",{value:!0});zt.generateKeyPair=mg;zt.deriveSharedSecret=yg;zt.deriveMetaSid=_g;zt.isValidPublicKey=Eg;zt.clearKey=bg;zt.keyToBase64=vg;zt.base64ToKey=wg;var Bn=gg(xi()),or=Ti();function mg(){let r=Bn.default.box.keyPair();return{publicKey:(0,or.encodeBase64)(r.publicKey),secretKey:(0,or.encodeBase64)(r.secretKey)}}function yg(r,e){let t=(0,or.decodeBase64)(r),n=(0,or.decodeBase64)(e);if(t.length!==Bn.default.box.publicKeyLength)throw new Error(`Invalid public key length: ${t.length}`);if(n.length!==Bn.default.box.secretKeyLength)throw new Error(`Invalid secret key length: ${n.length}`);return Bn.default.box.before(t,n)}function _g(r,e){let t=new TextEncoder().encode("termiq-meta-v1"),n=(0,or.decodeBase64)(r),i=(0,or.decodeBase64)(e),s=new Uint8Array(t.length+n.length+i.length);return s.set(t,0),s.set(n,t.length),s.set(i,t.length+n.length),(0,or.encodeBase64)(Bn.default.hash(s).slice(0,32))}function Eg(r){try{return(0,or.decodeBase64)(r).length===Bn.default.box.publicKeyLength}catch{return!1}}function bg(r){r.fill(0)}function vg(r){return(0,or.encodeBase64)(r)}function wg(r){return(0,or.decodeBase64)(r)}});var uu=L(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.base64ToKey=re.keyToBase64=re.clearKey=re.isValidPublicKey=re.deriveMetaSid=re.deriveSharedSecret=re.generateKeyPair=re.decryptBinary=re.encryptBinary=re.decrypt=re.encrypt=re.concatBytes=re.fingerprintShortHex=re.fingerprintIdentityKey=re.buildKxAckCanonical=re.buildKxCanonical=re.verifySessionKey=re.signSessionKey=re.identityPublicFromSecret=re.generateIdentityKeyPair=re.KX_SIG_VERSION=re.KX_FINGERPRINT_LABEL=re.KX_ACK_LABEL=re.KX_SIGN_LABEL=re.isMultiRecipientPayload=re.isEncryptedPayload=void 0;var fu=iu();Object.defineProperty(re,"isEncryptedPayload",{enumerable:!0,get:function(){return fu.isEncryptedPayload}});Object.defineProperty(re,"isMultiRecipientPayload",{enumerable:!0,get:function(){return fu.isMultiRecipientPayload}});var ws=ia();Object.defineProperty(re,"KX_SIGN_LABEL",{enumerable:!0,get:function(){return ws.KX_SIGN_LABEL}});Object.defineProperty(re,"KX_ACK_LABEL",{enumerable:!0,get:function(){return ws.KX_ACK_LABEL}});Object.defineProperty(re,"KX_FINGERPRINT_LABEL",{enumerable:!0,get:function(){return ws.KX_FINGERPRINT_LABEL}});Object.defineProperty(re,"KX_SIG_VERSION",{enumerable:!0,get:function(){return ws.KX_SIG_VERSION}});var xr=ou();Object.defineProperty(re,"generateIdentityKeyPair",{enumerable:!0,get:function(){return xr.generateIdentityKeyPair}});Object.defineProperty(re,"identityPublicFromSecret",{enumerable:!0,get:function(){return xr.identityPublicFromSecret}});Object.defineProperty(re,"signSessionKey",{enumerable:!0,get:function(){return xr.signSessionKey}});Object.defineProperty(re,"verifySessionKey",{enumerable:!0,get:function(){return xr.verifySessionKey}});Object.defineProperty(re,"buildKxCanonical",{enumerable:!0,get:function(){return xr.buildKxCanonical}});Object.defineProperty(re,"buildKxAckCanonical",{enumerable:!0,get:function(){return xr.buildKxAckCanonical}});Object.defineProperty(re,"fingerprintIdentityKey",{enumerable:!0,get:function(){return xr.fingerprintIdentityKey}});Object.defineProperty(re,"fingerprintShortHex",{enumerable:!0,get:function(){return xr.fingerprintShortHex}});Object.defineProperty(re,"concatBytes",{enumerable:!0,get:function(){return xr.concatBytes}});var Ss=au();Object.defineProperty(re,"encrypt",{enumerable:!0,get:function(){return Ss.encrypt}});Object.defineProperty(re,"decrypt",{enumerable:!0,get:function(){return Ss.decrypt}});Object.defineProperty(re,"encryptBinary",{enumerable:!0,get:function(){return Ss.encryptBinary}});Object.defineProperty(re,"decryptBinary",{enumerable:!0,get:function(){return Ss.decryptBinary}});var hn=cu();Object.defineProperty(re,"generateKeyPair",{enumerable:!0,get:function(){return hn.generateKeyPair}});Object.defineProperty(re,"deriveSharedSecret",{enumerable:!0,get:function(){return hn.deriveSharedSecret}});Object.defineProperty(re,"deriveMetaSid",{enumerable:!0,get:function(){return hn.deriveMetaSid}});Object.defineProperty(re,"isValidPublicKey",{enumerable:!0,get:function(){return hn.isValidPublicKey}});Object.defineProperty(re,"clearKey",{enumerable:!0,get:function(){return hn.clearKey}});Object.defineProperty(re,"keyToBase64",{enumerable:!0,get:function(){return hn.keyToBase64}});Object.defineProperty(re,"base64ToKey",{enumerable:!0,get:function(){return hn.base64ToKey}})});var lu=L(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.MIN_CLIENT_VERSION=Pt.PROTOCOL_VERSION_MINOR=Pt.PROTOCOL_VERSION_MAJOR=Pt.PROTOCOL_VERSION=void 0;Pt.isCompatibleVersion=Sg;Pt.compareVersions=xg;Pt.PROTOCOL_VERSION="2.1";Pt.PROTOCOL_VERSION_MAJOR=2;Pt.PROTOCOL_VERSION_MINOR=1;Pt.MIN_CLIENT_VERSION="2.0";function Sg(r){let[e]=r.split(".").map(Number);return e===Pt.PROTOCOL_VERSION_MAJOR}function xg(r,e){let[t,n]=r.split(".").map(Number),[i,s]=e.split(".").map(Number);return t!==i?t<i?-1:1:n!==s?n<s?-1:1:0}});var hu=L(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.SERVER_CAPABILITIES=ar.DEFAULT_CLIENT_CAPABILITIES=ar.Capability=void 0;ar.hasCapability=Tg;ar.negotiateCapabilities=Cg;var jn;(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",r.SCREEN="screen"})(jn||(ar.Capability=jn={}));ar.DEFAULT_CLIENT_CAPABILITIES=[jn.E2E_ENCRYPTION,jn.TERMINAL_EVENTS,jn.RELIABLE_INPUT];ar.SERVER_CAPABILITIES=Object.values(jn);function Tg(r,e){return r.includes(e)}function Cg(r,e){return r.filter(t=>e.includes(t))}});var du=L(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.DEFAULT_PRIORITY=Tr.PRIORITY_NAMES=Tr.Priority=void 0;Tr.comparePriority=kg;var dn;(function(r){r[r.CRITICAL=0]="CRITICAL",r[r.HIGH=1]="HIGH",r[r.NORMAL=2]="NORMAL",r[r.LOW=3]="LOW"})(dn||(Tr.Priority=dn={}));Tr.PRIORITY_NAMES={[dn.CRITICAL]:"CRITICAL",[dn.HIGH]:"HIGH",[dn.NORMAL]:"NORMAL",[dn.LOW]:"LOW"};Tr.DEFAULT_PRIORITY=dn.NORMAL;function kg(r,e){return r-e}});var pu=L(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.DEFAULT_RELIABILITY=cr.RELIABILITY_NAMES=cr.Reliability=void 0;cr.requiresAck=Og;cr.requiresBuffer=Pg;var Wr;(function(r){r[r.FIRE_FORGET=0]="FIRE_FORGET",r[r.BUFFERED=1]="BUFFERED",r[r.GUARANTEED=2]="GUARANTEED"})(Wr||(cr.Reliability=Wr={}));cr.RELIABILITY_NAMES={[Wr.FIRE_FORGET]:"FIRE_FORGET",[Wr.BUFFERED]:"BUFFERED",[Wr.GUARANTEED]:"GUARANTEED"};cr.DEFAULT_RELIABILITY=Wr.FIRE_FORGET;function Og(r){return r===Wr.GUARANTEED}function Pg(r){return r>=Wr.BUFFERED}});var gu=L(sa=>{"use strict";Object.defineProperty(sa,"__esModule",{value:!0});sa.createMessage=Ag;function Ag(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 mu=L(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.TerminalEventType=void 0;pn.deriveStatusFromEvent=Rg;pn.shouldTriggerPushNotification=Ig;pn.getPushNotificationMessage=Lg;var Et;(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"})(Et||(pn.TerminalEventType=Et={}));function Rg(r){switch(r.type){case Et.SESSION_START:case Et.TOOL_START:case Et.MESSAGE:return"working";case Et.WAITING_INPUT:return"waiting";case Et.SESSION_END:return r.status==="success"?"completed":"error";case Et.ERROR:return r.severity==="fatal"?"error":"working";case Et.TOOL_END:return r.status==="error"?"error":"working";default:return"idle"}}function Ig(r){switch(r.type){case Et.WAITING_INPUT:return!0;case Et.SESSION_END:return!0;case Et.ERROR:return r.severity!=="warning";default:return!1}}function Lg(r,e){switch(r.type){case Et.WAITING_INPUT:{let t=r.question;return{title:`${e}: Input Required`,body:t?t.slice(0,100):"Waiting for your input"}}case Et.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 Et.ERROR:{let t=r;return t.severity==="warning"?null:{title:`${e}: Error`,body:t.message.slice(0,100)}}default:return null}}});var Eu=L($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.TransferDirection=$e.TransferStatus=$e.CHUNK_TTL_SECONDS=$e.TRANSFER_TTL_SECONDS=$e.MAX_RETRIES=$e.ACK_TIMEOUT_MS=$e.WINDOW_SIZE=$e.DEFAULT_MAX_FILE_SIZE=$e.CHUNK_SIZE=void 0;$e.calculateTotalChunks=Ng;$e.getMissingChunks=Mg;$e.isTransferComplete=Fg;$e.CHUNK_SIZE=64*1024;$e.DEFAULT_MAX_FILE_SIZE=100*1024*1024;$e.WINDOW_SIZE=10;$e.ACK_TIMEOUT_MS=3e4;$e.MAX_RETRIES=3;$e.TRANSFER_TTL_SECONDS=1440*60;$e.CHUNK_TTL_SECONDS=1440*60;var yu;(function(r){r.PENDING="pending",r.ACTIVE="active",r.PAUSED="paused",r.COMPLETED="completed",r.FAILED="failed",r.CANCELLED="cancelled",r.EXPIRED="expired"})(yu||($e.TransferStatus=yu={}));var _u;(function(r){r.DOWNLOAD="download",r.UPLOAD="upload"})(_u||($e.TransferDirection=_u={}));function Ng(r,e=$e.CHUNK_SIZE){return Math.ceil(r/e)}function Mg(r,e){let t=new Set(e),n=[];for(let i=0;i<r;i++)t.has(i)||n.push(i);return n}function Fg(r,e){return e.length===r}});var bu=L(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.ERROR_MESSAGES=Cr.ErrorCode=void 0;Cr.createError=Dg;Cr.isRetryableError=Bg;var ke;(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",r.HANDSHAKE_UNAUTHORIZED="E401",r.HANDSHAKE_FORBIDDEN="E403"})(ke||(Cr.ErrorCode=ke={}));Cr.ERROR_MESSAGES={[ke.AUTH_FAILED]:"Authentication failed",[ke.TOKEN_EXPIRED]:"Token expired",[ke.TOKEN_INVALID]:"Invalid token",[ke.NOT_FOUND]:"Resource not found",[ke.ALREADY_EXISTS]:"Resource already exists",[ke.ACCESS_DENIED]:"Access denied",[ke.FORBIDDEN]:"Operation forbidden",[ke.RATE_LIMITED]:"Rate limit exceeded",[ke.TOO_MANY_CONNECTIONS]:"Too many connections",[ke.QUOTA_EXCEEDED]:"Plan quota exceeded",[ke.FILE_TOO_LARGE]:"File size exceeds limit",[ke.QUEUE_FULL]:"Message queue is full",[ke.TRANSFERS_LIMIT]:"Daily transfers limit reached",[ke.TRANSFER_FAILED]:"File transfer failed",[ke.TRANSFER_EXPIRED]:"Transfer expired",[ke.TRANSFER_CANCELLED]:"Transfer cancelled",[ke.CHECKSUM_MISMATCH]:"File checksum mismatch",[ke.CHUNK_MISSING]:"Chunk missing or corrupted",[ke.INVALID_MESSAGE]:"Invalid message format",[ke.UNSUPPORTED_VERSION]:"Unsupported protocol version",[ke.CAPABILITY_REQUIRED]:"Required capability not supported",[ke.INVALID_STATE]:"Invalid state for this operation",[ke.TIMEOUT]:"Operation timed out",[ke.CONNECTION_LOST]:"Connection lost",[ke.INTERNAL_ERROR]:"Internal server error",[ke.SERVICE_UNAVAILABLE]:"Service temporarily unavailable",[ke.HANDSHAKE_UNAUTHORIZED]:"Authentication failed",[ke.HANDSHAKE_FORBIDDEN]:"Connection not allowed by plan"};function Dg(r,e={}){return{code:r,message:e.message||Cr.ERROR_MESSAGES[r],details:e.details,retryable:e.retryable??!1,retryAfter:e.retryAfter}}function Bg(r){return[ke.RATE_LIMITED,ke.TIMEOUT,ke.CONNECTION_LOST,ke.SERVICE_UNAVAILABLE].includes(r)}});var vu=L(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.SERVER_TO_AGENT_EVENT_NAMES=Un.AGENT_EVENT_NAMES=void 0;Un.AGENT_EVENT_NAMES=["ping","agent:rename","workspace:register","workspace:unregister","terminal:created","terminal:closed","terminal:notFound","terminal:output","terminal:status","terminal:event","agent:claimControl","agent:ptyResized","crypto:invalidSession","input:ack","input:resume","input:resend","agent:keyExchangeAck","file:changed","file:content","file:list:response","file:init","file:chunk","file:chunk:ack","file:end","file:complete","file:cancel","file:sync"];Un.SERVER_TO_AGENT_EVENT_NAMES=["error","protocol:info","pong","agent:renamed","terminal:input","terminal:resize","terminal:createRequest","terminal:getBuffer","workspace:clientAttached","workspace:clientDetached","crypto:keyExchange","crypto:sessionCleanup","agent:keyExchangeRequest","meta:keyExchange","agent:sessionEnd","file:view","file:list","file:download:request","file:init","file:chunk","file:end","file:chunk:ack","file:cancel"]});var wu=L(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.SCREEN_EVENTS=kr.SCREEN_EVENT_PREFIX=void 0;kr.isScreenEvent=jg;kr.SCREEN_EVENT_PREFIX="screen:";kr.SCREEN_EVENTS=["screen:request","screen:offer","screen:answer","screen:ice"];function jg(r){return typeof r=="string"&&r.length>kr.SCREEN_EVENT_PREFIX.length&&r.startsWith(kr.SCREEN_EVENT_PREFIX)}});var Cu=L(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.FileEntryType=At.DiffBase=At.FileViewType=At.FileChangeType=void 0;At.getLanguageFromPath=Ug;At.parseUnifiedDiff=Kg;At.createSimpleDiff=qg;var Hr;(function(r){r.CREATE="create",r.MODIFY="modify",r.DELETE="delete"})(Hr||(At.FileChangeType=Hr={}));var Su;(function(r){r.CONTENT="content",r.DIFF="diff"})(Su||(At.FileViewType=Su={}));var xu;(function(r){r.GIT="git",r.PREVIOUS="previous"})(xu||(At.DiffBase=xu={}));function Ug(r){let e=r.split(".").pop()?.toLowerCase(),t={js:"javascript",jsx:"javascript",ts:"typescript",tsx:"typescript",mjs:"javascript",cjs:"javascript",html:"html",htm:"html",css:"css",scss:"scss",sass:"scss",less:"less",json:"json",yaml:"yaml",yml:"yaml",xml:"xml",toml:"toml",md:"markdown",mdx:"markdown",env:"plaintext",gitignore:"plaintext",dockerignore:"plaintext",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",py:"python",pyw:"python",pyi:"python",go:"go",rs:"rust",java:"java",kt:"kotlin",kts:"kotlin",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp",hpp:"cpp",sql:"sql",graphql:"graphql",gql:"graphql",prisma:"prisma",dockerfile:"dockerfile"},n=r.split("/").pop()?.toLowerCase()||"";return{dockerfile:"dockerfile",makefile:"makefile",".gitignore":"plaintext",".env":"plaintext",".env.local":"plaintext",".env.development":"plaintext",".env.production":"plaintext"}[n]||t[e||""]||"plaintext"}function Kg(r,e){let t=r.split(`
|
|
3
|
-
`),n=[],i=0,s=0,a=null,f=0,c=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&&n.push(a);let _=parseInt(m[1],10),b=parseInt(m[2]||"1",10),x=parseInt(m[3],10),
|
|
2
|
+
"use strict";var ig=Object.create;var oa=Object.defineProperty;var sg=Object.getOwnPropertyDescriptor;var og=Object.getOwnPropertyNames;var ag=Object.getPrototypeOf,cg=Object.prototype.hasOwnProperty;var Yt=(r,e)=>()=>(r&&(e=r(r=0)),e);var I=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),fg=(r,e)=>{for(var t in e)oa(r,t,{get:e[t],enumerable:!0})},ug=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of og(e))!cg.call(r,i)&&i!==t&&oa(r,i,{get:()=>e[i],enumerable:!(n=sg(e,i))||n.enumerable});return r};var he=(r,e,t)=>(t=r!=null?ig(ag(r)):{},ug(e||!r||!r.__esModule?oa(t,"default",{value:r,enumerable:!0}):t,r));var gs=I(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.generateCorrelationId=dg;Ti.runWithCorrelation=pg;Ti.getCurrentCorrelationId=gg;var hg=require("async_hooks");function dg(){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 Qf=new hg.AsyncLocalStorage;function pg(r,e){return Qf.run(r,e)}function gg(){return Qf.getStore()}});var eu=I(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.LOG_LEVELS=void 0;Un.shouldLog=yg;Un.formatLogLine=_g;var mg=gs();Un.LOG_LEVELS=["silent","error","warn","info","debug"];var Jf={silent:0,error:1,warn:2,info:3,debug:4};function yg(r,e){return Jf[r]<=Jf[e]}function _g(r,e,t,n){let i={ts:new Date().toISOString(),level:r,src:e,msg:t},s=(0,mg.getCurrentCorrelationId)();s&&(i.cid=s);let a=n;a.length>0&&typeof a[0]=="object"&&a[0]!==null&&!(a[0]instanceof Error)&&!Array.isArray(a[0])&&(i.ctx=a[0],a=a.slice(1));let f=[...a].reverse().find(c=>c instanceof Error);f&&(i.err={message:f.message,stack:f.stack,name:f.name},a=a.filter(c=>c!==f)),a.length>0&&(i.args=a);try{return JSON.stringify(i)}catch{return JSON.stringify({ts:i.ts,level:r,src:e,msg:t,_unserializable:!0})}}});var tu=I(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.formatLogLine=Wr.shouldLog=Wr.LOG_LEVELS=void 0;var aa=eu();Object.defineProperty(Wr,"LOG_LEVELS",{enumerable:!0,get:function(){return aa.LOG_LEVELS}});Object.defineProperty(Wr,"shouldLog",{enumerable:!0,get:function(){return aa.shouldLog}});Object.defineProperty(Wr,"formatLogLine",{enumerable:!0,get:function(){return aa.formatLogLine}})});var ru=I(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});ms.CircularBuffer=void 0;var ca=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}};ms.CircularBuffer=ca});var _s=I(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});ys.getApiUrl=Eg;ys.getWsUrl=bg;function Eg(r){return`${r.getServerUrl()}/api`}function bg(r){let e=r.getServerUrl();return e.startsWith("https://")?e.replace(/^https:\/\//,"wss://"):e.replace(/^http:\/\//,"ws://")}});var iu=I(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.getCurrentCorrelationId=xt.runWithCorrelation=xt.generateCorrelationId=xt.getWsUrl=xt.getApiUrl=xt.CircularBuffer=void 0;var wg=ru();Object.defineProperty(xt,"CircularBuffer",{enumerable:!0,get:function(){return wg.CircularBuffer}});var nu=_s();Object.defineProperty(xt,"getApiUrl",{enumerable:!0,get:function(){return nu.getApiUrl}});Object.defineProperty(xt,"getWsUrl",{enumerable:!0,get:function(){return nu.getWsUrl}});var fa=gs();Object.defineProperty(xt,"generateCorrelationId",{enumerable:!0,get:function(){return fa.generateCorrelationId}});Object.defineProperty(xt,"runWithCorrelation",{enumerable:!0,get:function(){return fa.runWithCorrelation}});Object.defineProperty(xt,"getCurrentCorrelationId",{enumerable:!0,get:function(){return fa.getCurrentCorrelationId}})});var ou=I(su=>{"use strict";Object.defineProperty(su,"__esModule",{value:!0})});var cu=I(au=>{"use strict";Object.defineProperty(au,"__esModule",{value:!0})});var fu=I(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});Es.PLAN_LIMITS=void 0;Es.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 lu=I(uu=>{"use strict";Object.defineProperty(uu,"__esModule",{value:!0})});var hu=I(or=>{"use strict";var vg=or&&or.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),bs=or&&or.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&vg(e,r,t)};Object.defineProperty(or,"__esModule",{value:!0});bs(ou(),or);bs(cu(),or);bs(fu(),or);bs(lu(),or)});var du=I(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.API_VERSION=Ft.WS_NAMESPACES=Ft.TIMEOUTS=Ft.STATUS_PATTERNS=Ft.TERMINAL_STATUSES=void 0;Ft.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"}};Ft.STATUS_PATTERNS={idle:[/[❯$]\s*$/,/>\s*$/],waiting:[/\[Y\/n\]/i,/\(y\/N\)/i,/Continue\?/i,/proceed\?/i],completed:[/✓/,/Done/,/Completed/,/Success/],error:[/Error/,/Failed/,/✕/,/Exception/]};Ft.TIMEOUTS={HEARTBEAT_INTERVAL:3e4,OFFLINE_THRESHOLD:6e4,DEVICE_CODE_EXPIRY:9e5,DEVICE_CODE_POLL_INTERVAL:5e3};Ft.WS_NAMESPACES={AGENT:"/agent",CLIENT:"/client"};Ft.API_VERSION="v1"});var pu=I(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});ws.isMultiRecipientPayload=Sg;ws.isEncryptedPayload=xg;function Sg(r){return typeof r=="object"&&r!==null&&"v"in r&&r.v===2&&"recipients"in r&&Array.isArray(r.recipients)}function xg(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 ua=I(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.KX_SIG_VERSION=ar.KX_FINGERPRINT_LABEL=ar.KX_ACK_LABEL=ar.KX_SIGN_LABEL=void 0;ar.KX_SIGN_LABEL="termiq-kx-v1";ar.KX_ACK_LABEL="termiq-kxack-v1";ar.KX_FINGERPRINT_LABEL="termiq-fp-v1";ar.KX_SIG_VERSION=1});var Oi=I((_v,vs)=>{(function(r){"use strict";var e=function(u){var d,h=new Float64Array(16);if(u)for(d=0;d<u.length;d++)h[d]=u[d];return h},t=function(){throw new Error("no PRNG")},n=new Uint8Array(16),i=new Uint8Array(32);i[0]=9;var s=e(),a=e([1]),f=e([56129,1]),c=e([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),l=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 b(u,d,h,o){u[d]=h>>24&255,u[d+1]=h>>16&255,u[d+2]=h>>8&255,u[d+3]=h&255,u[d+4]=o>>24&255,u[d+5]=o>>16&255,u[d+6]=o>>8&255,u[d+7]=o&255}function x(u,d,h,o,g){var E,w=0;for(E=0;E<g;E++)w|=u[d+E]^h[o+E];return(1&w-1>>>8)-1}function O(u,d,h,o){return x(u,d,h,o,16)}function V(u,d,h,o){return x(u,d,h,o,32)}function ie(u,d,h,o){for(var g=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,E=h[0]&255|(h[1]&255)<<8|(h[2]&255)<<16|(h[3]&255)<<24,w=h[4]&255|(h[5]&255)<<8|(h[6]&255)<<16|(h[7]&255)<<24,P=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,F=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,Q=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,H=d[0]&255|(d[1]&255)<<8|(d[2]&255)<<16|(d[3]&255)<<24,Re=d[4]&255|(d[5]&255)<<8|(d[6]&255)<<16|(d[7]&255)<<24,G=d[8]&255|(d[9]&255)<<8|(d[10]&255)<<16|(d[11]&255)<<24,ae=d[12]&255|(d[13]&255)<<8|(d[14]&255)<<16|(d[15]&255)<<24,ce=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,ge=h[16]&255|(h[17]&255)<<8|(h[18]&255)<<16|(h[19]&255)<<24,de=h[20]&255|(h[21]&255)<<8|(h[22]&255)<<16|(h[23]&255)<<24,fe=h[24]&255|(h[25]&255)<<8|(h[26]&255)<<16|(h[27]&255)<<24,le=h[28]&255|(h[29]&255)<<8|(h[30]&255)<<16|(h[31]&255)<<24,ue=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,Y=g,J=E,$=w,X=P,Z=F,W=Q,v=H,S=Re,R=G,C=ae,k=ce,M=ge,ne=de,me=fe,Ee=le,ye=ue,y,Se=0;Se<20;Se+=2)y=Y+ne|0,Z^=y<<7|y>>>25,y=Z+Y|0,R^=y<<9|y>>>23,y=R+Z|0,ne^=y<<13|y>>>19,y=ne+R|0,Y^=y<<18|y>>>14,y=W+J|0,C^=y<<7|y>>>25,y=C+W|0,me^=y<<9|y>>>23,y=me+C|0,J^=y<<13|y>>>19,y=J+me|0,W^=y<<18|y>>>14,y=k+v|0,Ee^=y<<7|y>>>25,y=Ee+k|0,$^=y<<9|y>>>23,y=$+Ee|0,v^=y<<13|y>>>19,y=v+$|0,k^=y<<18|y>>>14,y=ye+M|0,X^=y<<7|y>>>25,y=X+ye|0,S^=y<<9|y>>>23,y=S+X|0,M^=y<<13|y>>>19,y=M+S|0,ye^=y<<18|y>>>14,y=Y+X|0,J^=y<<7|y>>>25,y=J+Y|0,$^=y<<9|y>>>23,y=$+J|0,X^=y<<13|y>>>19,y=X+$|0,Y^=y<<18|y>>>14,y=W+Z|0,v^=y<<7|y>>>25,y=v+W|0,S^=y<<9|y>>>23,y=S+v|0,Z^=y<<13|y>>>19,y=Z+S|0,W^=y<<18|y>>>14,y=k+C|0,M^=y<<7|y>>>25,y=M+k|0,R^=y<<9|y>>>23,y=R+M|0,C^=y<<13|y>>>19,y=C+R|0,k^=y<<18|y>>>14,y=ye+Ee|0,ne^=y<<7|y>>>25,y=ne+ye|0,me^=y<<9|y>>>23,y=me+ne|0,Ee^=y<<13|y>>>19,y=Ee+me|0,ye^=y<<18|y>>>14;Y=Y+g|0,J=J+E|0,$=$+w|0,X=X+P|0,Z=Z+F|0,W=W+Q|0,v=v+H|0,S=S+Re|0,R=R+G|0,C=C+ae|0,k=k+ce|0,M=M+ge|0,ne=ne+de|0,me=me+fe|0,Ee=Ee+le|0,ye=ye+ue|0,u[0]=Y>>>0&255,u[1]=Y>>>8&255,u[2]=Y>>>16&255,u[3]=Y>>>24&255,u[4]=J>>>0&255,u[5]=J>>>8&255,u[6]=J>>>16&255,u[7]=J>>>24&255,u[8]=$>>>0&255,u[9]=$>>>8&255,u[10]=$>>>16&255,u[11]=$>>>24&255,u[12]=X>>>0&255,u[13]=X>>>8&255,u[14]=X>>>16&255,u[15]=X>>>24&255,u[16]=Z>>>0&255,u[17]=Z>>>8&255,u[18]=Z>>>16&255,u[19]=Z>>>24&255,u[20]=W>>>0&255,u[21]=W>>>8&255,u[22]=W>>>16&255,u[23]=W>>>24&255,u[24]=v>>>0&255,u[25]=v>>>8&255,u[26]=v>>>16&255,u[27]=v>>>24&255,u[28]=S>>>0&255,u[29]=S>>>8&255,u[30]=S>>>16&255,u[31]=S>>>24&255,u[32]=R>>>0&255,u[33]=R>>>8&255,u[34]=R>>>16&255,u[35]=R>>>24&255,u[36]=C>>>0&255,u[37]=C>>>8&255,u[38]=C>>>16&255,u[39]=C>>>24&255,u[40]=k>>>0&255,u[41]=k>>>8&255,u[42]=k>>>16&255,u[43]=k>>>24&255,u[44]=M>>>0&255,u[45]=M>>>8&255,u[46]=M>>>16&255,u[47]=M>>>24&255,u[48]=ne>>>0&255,u[49]=ne>>>8&255,u[50]=ne>>>16&255,u[51]=ne>>>24&255,u[52]=me>>>0&255,u[53]=me>>>8&255,u[54]=me>>>16&255,u[55]=me>>>24&255,u[56]=Ee>>>0&255,u[57]=Ee>>>8&255,u[58]=Ee>>>16&255,u[59]=Ee>>>24&255,u[60]=ye>>>0&255,u[61]=ye>>>8&255,u[62]=ye>>>16&255,u[63]=ye>>>24&255}function z(u,d,h,o){for(var g=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,E=h[0]&255|(h[1]&255)<<8|(h[2]&255)<<16|(h[3]&255)<<24,w=h[4]&255|(h[5]&255)<<8|(h[6]&255)<<16|(h[7]&255)<<24,P=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,F=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,Q=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,H=d[0]&255|(d[1]&255)<<8|(d[2]&255)<<16|(d[3]&255)<<24,Re=d[4]&255|(d[5]&255)<<8|(d[6]&255)<<16|(d[7]&255)<<24,G=d[8]&255|(d[9]&255)<<8|(d[10]&255)<<16|(d[11]&255)<<24,ae=d[12]&255|(d[13]&255)<<8|(d[14]&255)<<16|(d[15]&255)<<24,ce=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,ge=h[16]&255|(h[17]&255)<<8|(h[18]&255)<<16|(h[19]&255)<<24,de=h[20]&255|(h[21]&255)<<8|(h[22]&255)<<16|(h[23]&255)<<24,fe=h[24]&255|(h[25]&255)<<8|(h[26]&255)<<16|(h[27]&255)<<24,le=h[28]&255|(h[29]&255)<<8|(h[30]&255)<<16|(h[31]&255)<<24,ue=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,Y=g,J=E,$=w,X=P,Z=F,W=Q,v=H,S=Re,R=G,C=ae,k=ce,M=ge,ne=de,me=fe,Ee=le,ye=ue,y,Se=0;Se<20;Se+=2)y=Y+ne|0,Z^=y<<7|y>>>25,y=Z+Y|0,R^=y<<9|y>>>23,y=R+Z|0,ne^=y<<13|y>>>19,y=ne+R|0,Y^=y<<18|y>>>14,y=W+J|0,C^=y<<7|y>>>25,y=C+W|0,me^=y<<9|y>>>23,y=me+C|0,J^=y<<13|y>>>19,y=J+me|0,W^=y<<18|y>>>14,y=k+v|0,Ee^=y<<7|y>>>25,y=Ee+k|0,$^=y<<9|y>>>23,y=$+Ee|0,v^=y<<13|y>>>19,y=v+$|0,k^=y<<18|y>>>14,y=ye+M|0,X^=y<<7|y>>>25,y=X+ye|0,S^=y<<9|y>>>23,y=S+X|0,M^=y<<13|y>>>19,y=M+S|0,ye^=y<<18|y>>>14,y=Y+X|0,J^=y<<7|y>>>25,y=J+Y|0,$^=y<<9|y>>>23,y=$+J|0,X^=y<<13|y>>>19,y=X+$|0,Y^=y<<18|y>>>14,y=W+Z|0,v^=y<<7|y>>>25,y=v+W|0,S^=y<<9|y>>>23,y=S+v|0,Z^=y<<13|y>>>19,y=Z+S|0,W^=y<<18|y>>>14,y=k+C|0,M^=y<<7|y>>>25,y=M+k|0,R^=y<<9|y>>>23,y=R+M|0,C^=y<<13|y>>>19,y=C+R|0,k^=y<<18|y>>>14,y=ye+Ee|0,ne^=y<<7|y>>>25,y=ne+ye|0,me^=y<<9|y>>>23,y=me+ne|0,Ee^=y<<13|y>>>19,y=Ee+me|0,ye^=y<<18|y>>>14;u[0]=Y>>>0&255,u[1]=Y>>>8&255,u[2]=Y>>>16&255,u[3]=Y>>>24&255,u[4]=W>>>0&255,u[5]=W>>>8&255,u[6]=W>>>16&255,u[7]=W>>>24&255,u[8]=k>>>0&255,u[9]=k>>>8&255,u[10]=k>>>16&255,u[11]=k>>>24&255,u[12]=ye>>>0&255,u[13]=ye>>>8&255,u[14]=ye>>>16&255,u[15]=ye>>>24&255,u[16]=v>>>0&255,u[17]=v>>>8&255,u[18]=v>>>16&255,u[19]=v>>>24&255,u[20]=S>>>0&255,u[21]=S>>>8&255,u[22]=S>>>16&255,u[23]=S>>>24&255,u[24]=R>>>0&255,u[25]=R>>>8&255,u[26]=R>>>16&255,u[27]=R>>>24&255,u[28]=C>>>0&255,u[29]=C>>>8&255,u[30]=C>>>16&255,u[31]=C>>>24&255}function T(u,d,h,o){ie(u,d,h,o)}function D(u,d,h,o){z(u,d,h,o)}var te=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function q(u,d,h,o,g,E,w){var P=new Uint8Array(16),F=new Uint8Array(64),Q,H;for(H=0;H<16;H++)P[H]=0;for(H=0;H<8;H++)P[H]=E[H];for(;g>=64;){for(T(F,P,w,te),H=0;H<64;H++)u[d+H]=h[o+H]^F[H];for(Q=1,H=8;H<16;H++)Q=Q+(P[H]&255)|0,P[H]=Q&255,Q>>>=8;g-=64,d+=64,o+=64}if(g>0)for(T(F,P,w,te),H=0;H<g;H++)u[d+H]=h[o+H]^F[H];return 0}function ee(u,d,h,o,g){var E=new Uint8Array(16),w=new Uint8Array(64),P,F;for(F=0;F<16;F++)E[F]=0;for(F=0;F<8;F++)E[F]=o[F];for(;h>=64;){for(T(w,E,g,te),F=0;F<64;F++)u[d+F]=w[F];for(P=1,F=8;F<16;F++)P=P+(E[F]&255)|0,E[F]=P&255,P>>>=8;h-=64,d+=64}if(h>0)for(T(w,E,g,te),F=0;F<h;F++)u[d+F]=w[F];return 0}function pe(u,d,h,o,g){var E=new Uint8Array(32);D(E,o,g,te);for(var w=new Uint8Array(8),P=0;P<8;P++)w[P]=o[P+16];return ee(u,d,h,w,E)}function K(u,d,h,o,g,E,w){var P=new Uint8Array(32);D(P,E,w,te);for(var F=new Uint8Array(8),Q=0;Q<8;Q++)F[Q]=E[Q+16];return q(u,d,h,o,g,F,P)}var Me=function(u){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 d,h,o,g,E,w,P,F;d=u[0]&255|(u[1]&255)<<8,this.r[0]=d&8191,h=u[2]&255|(u[3]&255)<<8,this.r[1]=(d>>>13|h<<3)&8191,o=u[4]&255|(u[5]&255)<<8,this.r[2]=(h>>>10|o<<6)&7939,g=u[6]&255|(u[7]&255)<<8,this.r[3]=(o>>>7|g<<9)&8191,E=u[8]&255|(u[9]&255)<<8,this.r[4]=(g>>>4|E<<12)&255,this.r[5]=E>>>1&8190,w=u[10]&255|(u[11]&255)<<8,this.r[6]=(E>>>14|w<<2)&8191,P=u[12]&255|(u[13]&255)<<8,this.r[7]=(w>>>11|P<<5)&8065,F=u[14]&255|(u[15]&255)<<8,this.r[8]=(P>>>8|F<<8)&8191,this.r[9]=F>>>5&127,this.pad[0]=u[16]&255|(u[17]&255)<<8,this.pad[1]=u[18]&255|(u[19]&255)<<8,this.pad[2]=u[20]&255|(u[21]&255)<<8,this.pad[3]=u[22]&255|(u[23]&255)<<8,this.pad[4]=u[24]&255|(u[25]&255)<<8,this.pad[5]=u[26]&255|(u[27]&255)<<8,this.pad[6]=u[28]&255|(u[29]&255)<<8,this.pad[7]=u[30]&255|(u[31]&255)<<8};Me.prototype.blocks=function(u,d,h){for(var o=this.fin?0:2048,g,E,w,P,F,Q,H,Re,G,ae,ce,ge,de,fe,le,ue,Y,J,$,X=this.h[0],Z=this.h[1],W=this.h[2],v=this.h[3],S=this.h[4],R=this.h[5],C=this.h[6],k=this.h[7],M=this.h[8],ne=this.h[9],me=this.r[0],Ee=this.r[1],ye=this.r[2],y=this.r[3],Se=this.r[4],Ie=this.r[5],Le=this.r[6],be=this.r[7],Oe=this.r[8],Ce=this.r[9];h>=16;)g=u[d+0]&255|(u[d+1]&255)<<8,X+=g&8191,E=u[d+2]&255|(u[d+3]&255)<<8,Z+=(g>>>13|E<<3)&8191,w=u[d+4]&255|(u[d+5]&255)<<8,W+=(E>>>10|w<<6)&8191,P=u[d+6]&255|(u[d+7]&255)<<8,v+=(w>>>7|P<<9)&8191,F=u[d+8]&255|(u[d+9]&255)<<8,S+=(P>>>4|F<<12)&8191,R+=F>>>1&8191,Q=u[d+10]&255|(u[d+11]&255)<<8,C+=(F>>>14|Q<<2)&8191,H=u[d+12]&255|(u[d+13]&255)<<8,k+=(Q>>>11|H<<5)&8191,Re=u[d+14]&255|(u[d+15]&255)<<8,M+=(H>>>8|Re<<8)&8191,ne+=Re>>>5|o,G=0,ae=G,ae+=X*me,ae+=Z*(5*Ce),ae+=W*(5*Oe),ae+=v*(5*be),ae+=S*(5*Le),G=ae>>>13,ae&=8191,ae+=R*(5*Ie),ae+=C*(5*Se),ae+=k*(5*y),ae+=M*(5*ye),ae+=ne*(5*Ee),G+=ae>>>13,ae&=8191,ce=G,ce+=X*Ee,ce+=Z*me,ce+=W*(5*Ce),ce+=v*(5*Oe),ce+=S*(5*be),G=ce>>>13,ce&=8191,ce+=R*(5*Le),ce+=C*(5*Ie),ce+=k*(5*Se),ce+=M*(5*y),ce+=ne*(5*ye),G+=ce>>>13,ce&=8191,ge=G,ge+=X*ye,ge+=Z*Ee,ge+=W*me,ge+=v*(5*Ce),ge+=S*(5*Oe),G=ge>>>13,ge&=8191,ge+=R*(5*be),ge+=C*(5*Le),ge+=k*(5*Ie),ge+=M*(5*Se),ge+=ne*(5*y),G+=ge>>>13,ge&=8191,de=G,de+=X*y,de+=Z*ye,de+=W*Ee,de+=v*me,de+=S*(5*Ce),G=de>>>13,de&=8191,de+=R*(5*Oe),de+=C*(5*be),de+=k*(5*Le),de+=M*(5*Ie),de+=ne*(5*Se),G+=de>>>13,de&=8191,fe=G,fe+=X*Se,fe+=Z*y,fe+=W*ye,fe+=v*Ee,fe+=S*me,G=fe>>>13,fe&=8191,fe+=R*(5*Ce),fe+=C*(5*Oe),fe+=k*(5*be),fe+=M*(5*Le),fe+=ne*(5*Ie),G+=fe>>>13,fe&=8191,le=G,le+=X*Ie,le+=Z*Se,le+=W*y,le+=v*ye,le+=S*Ee,G=le>>>13,le&=8191,le+=R*me,le+=C*(5*Ce),le+=k*(5*Oe),le+=M*(5*be),le+=ne*(5*Le),G+=le>>>13,le&=8191,ue=G,ue+=X*Le,ue+=Z*Ie,ue+=W*Se,ue+=v*y,ue+=S*ye,G=ue>>>13,ue&=8191,ue+=R*Ee,ue+=C*me,ue+=k*(5*Ce),ue+=M*(5*Oe),ue+=ne*(5*be),G+=ue>>>13,ue&=8191,Y=G,Y+=X*be,Y+=Z*Le,Y+=W*Ie,Y+=v*Se,Y+=S*y,G=Y>>>13,Y&=8191,Y+=R*ye,Y+=C*Ee,Y+=k*me,Y+=M*(5*Ce),Y+=ne*(5*Oe),G+=Y>>>13,Y&=8191,J=G,J+=X*Oe,J+=Z*be,J+=W*Le,J+=v*Ie,J+=S*Se,G=J>>>13,J&=8191,J+=R*y,J+=C*ye,J+=k*Ee,J+=M*me,J+=ne*(5*Ce),G+=J>>>13,J&=8191,$=G,$+=X*Ce,$+=Z*Oe,$+=W*be,$+=v*Le,$+=S*Ie,G=$>>>13,$&=8191,$+=R*Se,$+=C*y,$+=k*ye,$+=M*Ee,$+=ne*me,G+=$>>>13,$&=8191,G=(G<<2)+G|0,G=G+ae|0,ae=G&8191,G=G>>>13,ce+=G,X=ae,Z=ce,W=ge,v=de,S=fe,R=le,C=ue,k=Y,M=J,ne=$,d+=16,h-=16;this.h[0]=X,this.h[1]=Z,this.h[2]=W,this.h[3]=v,this.h[4]=S,this.h[5]=R,this.h[6]=C,this.h[7]=k,this.h[8]=M,this.h[9]=ne},Me.prototype.finish=function(u,d){var h=new Uint16Array(10),o,g,E,w;if(this.leftover){for(w=this.leftover,this.buffer[w++]=1;w<16;w++)this.buffer[w]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(o=this.h[1]>>>13,this.h[1]&=8191,w=2;w<10;w++)this.h[w]+=o,o=this.h[w]>>>13,this.h[w]&=8191;for(this.h[0]+=o*5,o=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=o,o=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=o,h[0]=this.h[0]+5,o=h[0]>>>13,h[0]&=8191,w=1;w<10;w++)h[w]=this.h[w]+o,o=h[w]>>>13,h[w]&=8191;for(h[9]-=8192,g=(o^1)-1,w=0;w<10;w++)h[w]&=g;for(g=~g,w=0;w<10;w++)this.h[w]=this.h[w]&g|h[w];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,E=this.h[0]+this.pad[0],this.h[0]=E&65535,w=1;w<8;w++)E=(this.h[w]+this.pad[w]|0)+(E>>>16)|0,this.h[w]=E&65535;u[d+0]=this.h[0]>>>0&255,u[d+1]=this.h[0]>>>8&255,u[d+2]=this.h[1]>>>0&255,u[d+3]=this.h[1]>>>8&255,u[d+4]=this.h[2]>>>0&255,u[d+5]=this.h[2]>>>8&255,u[d+6]=this.h[3]>>>0&255,u[d+7]=this.h[3]>>>8&255,u[d+8]=this.h[4]>>>0&255,u[d+9]=this.h[4]>>>8&255,u[d+10]=this.h[5]>>>0&255,u[d+11]=this.h[5]>>>8&255,u[d+12]=this.h[6]>>>0&255,u[d+13]=this.h[6]>>>8&255,u[d+14]=this.h[7]>>>0&255,u[d+15]=this.h[7]>>>8&255},Me.prototype.update=function(u,d,h){var o,g;if(this.leftover){for(g=16-this.leftover,g>h&&(g=h),o=0;o<g;o++)this.buffer[this.leftover+o]=u[d+o];if(h-=g,d+=g,this.leftover+=g,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(h>=16&&(g=h-h%16,this.blocks(u,d,g),d+=g,h-=g),h){for(o=0;o<h;o++)this.buffer[this.leftover+o]=u[d+o];this.leftover+=h}};function tt(u,d,h,o,g,E){var w=new Me(E);return w.update(h,o,g),w.finish(u,d),0}function Te(u,d,h,o,g,E){var w=new Uint8Array(16);return tt(w,0,h,o,g,E),O(u,d,w,0)}function De(u,d,h,o,g){var E;if(h<32)return-1;for(K(u,0,d,0,h,o,g),tt(u,16,u,32,h-32,u),E=0;E<16;E++)u[E]=0;return 0}function ve(u,d,h,o,g){var E,w=new Uint8Array(32);if(h<32||(pe(w,0,32,o,g),Te(d,16,d,32,h-32,w)!==0))return-1;for(K(u,0,d,0,h,o,g),E=0;E<32;E++)u[E]=0;return 0}function We(u,d){var h;for(h=0;h<16;h++)u[h]=d[h]|0}function _e(u){var d,h,o=1;for(d=0;d<16;d++)h=u[d]+o+65535,o=Math.floor(h/65536),u[d]=h-o*65536;u[0]+=o-1+37*(o-1)}function rt(u,d,h){for(var o,g=~(h-1),E=0;E<16;E++)o=g&(u[E]^d[E]),u[E]^=o,d[E]^=o}function Fe(u,d){var h,o,g,E=e(),w=e();for(h=0;h<16;h++)w[h]=d[h];for(_e(w),_e(w),_e(w),o=0;o<2;o++){for(E[0]=w[0]-65517,h=1;h<15;h++)E[h]=w[h]-65535-(E[h-1]>>16&1),E[h-1]&=65535;E[15]=w[15]-32767-(E[14]>>16&1),g=E[15]>>16&1,E[14]&=65535,rt(w,E,1-g)}for(h=0;h<16;h++)u[2*h]=w[h]&255,u[2*h+1]=w[h]>>8}function Et(u,d){var h=new Uint8Array(32),o=new Uint8Array(32);return Fe(h,u),Fe(o,d),V(h,0,o,0)}function He(u){var d=new Uint8Array(32);return Fe(d,u),d[0]&1}function pt(u,d){var h;for(h=0;h<16;h++)u[h]=d[2*h]+(d[2*h+1]<<8);u[15]&=32767}function N(u,d,h){for(var o=0;o<16;o++)u[o]=d[o]+h[o]}function j(u,d,h){for(var o=0;o<16;o++)u[o]=d[o]-h[o]}function L(u,d,h){var o,g,E=0,w=0,P=0,F=0,Q=0,H=0,Re=0,G=0,ae=0,ce=0,ge=0,de=0,fe=0,le=0,ue=0,Y=0,J=0,$=0,X=0,Z=0,W=0,v=0,S=0,R=0,C=0,k=0,M=0,ne=0,me=0,Ee=0,ye=0,y=h[0],Se=h[1],Ie=h[2],Le=h[3],be=h[4],Oe=h[5],Ce=h[6],it=h[7],Be=h[8],Qe=h[9],Je=h[10],et=h[11],at=h[12],gt=h[13],mt=h[14],yt=h[15];o=d[0],E+=o*y,w+=o*Se,P+=o*Ie,F+=o*Le,Q+=o*be,H+=o*Oe,Re+=o*Ce,G+=o*it,ae+=o*Be,ce+=o*Qe,ge+=o*Je,de+=o*et,fe+=o*at,le+=o*gt,ue+=o*mt,Y+=o*yt,o=d[1],w+=o*y,P+=o*Se,F+=o*Ie,Q+=o*Le,H+=o*be,Re+=o*Oe,G+=o*Ce,ae+=o*it,ce+=o*Be,ge+=o*Qe,de+=o*Je,fe+=o*et,le+=o*at,ue+=o*gt,Y+=o*mt,J+=o*yt,o=d[2],P+=o*y,F+=o*Se,Q+=o*Ie,H+=o*Le,Re+=o*be,G+=o*Oe,ae+=o*Ce,ce+=o*it,ge+=o*Be,de+=o*Qe,fe+=o*Je,le+=o*et,ue+=o*at,Y+=o*gt,J+=o*mt,$+=o*yt,o=d[3],F+=o*y,Q+=o*Se,H+=o*Ie,Re+=o*Le,G+=o*be,ae+=o*Oe,ce+=o*Ce,ge+=o*it,de+=o*Be,fe+=o*Qe,le+=o*Je,ue+=o*et,Y+=o*at,J+=o*gt,$+=o*mt,X+=o*yt,o=d[4],Q+=o*y,H+=o*Se,Re+=o*Ie,G+=o*Le,ae+=o*be,ce+=o*Oe,ge+=o*Ce,de+=o*it,fe+=o*Be,le+=o*Qe,ue+=o*Je,Y+=o*et,J+=o*at,$+=o*gt,X+=o*mt,Z+=o*yt,o=d[5],H+=o*y,Re+=o*Se,G+=o*Ie,ae+=o*Le,ce+=o*be,ge+=o*Oe,de+=o*Ce,fe+=o*it,le+=o*Be,ue+=o*Qe,Y+=o*Je,J+=o*et,$+=o*at,X+=o*gt,Z+=o*mt,W+=o*yt,o=d[6],Re+=o*y,G+=o*Se,ae+=o*Ie,ce+=o*Le,ge+=o*be,de+=o*Oe,fe+=o*Ce,le+=o*it,ue+=o*Be,Y+=o*Qe,J+=o*Je,$+=o*et,X+=o*at,Z+=o*gt,W+=o*mt,v+=o*yt,o=d[7],G+=o*y,ae+=o*Se,ce+=o*Ie,ge+=o*Le,de+=o*be,fe+=o*Oe,le+=o*Ce,ue+=o*it,Y+=o*Be,J+=o*Qe,$+=o*Je,X+=o*et,Z+=o*at,W+=o*gt,v+=o*mt,S+=o*yt,o=d[8],ae+=o*y,ce+=o*Se,ge+=o*Ie,de+=o*Le,fe+=o*be,le+=o*Oe,ue+=o*Ce,Y+=o*it,J+=o*Be,$+=o*Qe,X+=o*Je,Z+=o*et,W+=o*at,v+=o*gt,S+=o*mt,R+=o*yt,o=d[9],ce+=o*y,ge+=o*Se,de+=o*Ie,fe+=o*Le,le+=o*be,ue+=o*Oe,Y+=o*Ce,J+=o*it,$+=o*Be,X+=o*Qe,Z+=o*Je,W+=o*et,v+=o*at,S+=o*gt,R+=o*mt,C+=o*yt,o=d[10],ge+=o*y,de+=o*Se,fe+=o*Ie,le+=o*Le,ue+=o*be,Y+=o*Oe,J+=o*Ce,$+=o*it,X+=o*Be,Z+=o*Qe,W+=o*Je,v+=o*et,S+=o*at,R+=o*gt,C+=o*mt,k+=o*yt,o=d[11],de+=o*y,fe+=o*Se,le+=o*Ie,ue+=o*Le,Y+=o*be,J+=o*Oe,$+=o*Ce,X+=o*it,Z+=o*Be,W+=o*Qe,v+=o*Je,S+=o*et,R+=o*at,C+=o*gt,k+=o*mt,M+=o*yt,o=d[12],fe+=o*y,le+=o*Se,ue+=o*Ie,Y+=o*Le,J+=o*be,$+=o*Oe,X+=o*Ce,Z+=o*it,W+=o*Be,v+=o*Qe,S+=o*Je,R+=o*et,C+=o*at,k+=o*gt,M+=o*mt,ne+=o*yt,o=d[13],le+=o*y,ue+=o*Se,Y+=o*Ie,J+=o*Le,$+=o*be,X+=o*Oe,Z+=o*Ce,W+=o*it,v+=o*Be,S+=o*Qe,R+=o*Je,C+=o*et,k+=o*at,M+=o*gt,ne+=o*mt,me+=o*yt,o=d[14],ue+=o*y,Y+=o*Se,J+=o*Ie,$+=o*Le,X+=o*be,Z+=o*Oe,W+=o*Ce,v+=o*it,S+=o*Be,R+=o*Qe,C+=o*Je,k+=o*et,M+=o*at,ne+=o*gt,me+=o*mt,Ee+=o*yt,o=d[15],Y+=o*y,J+=o*Se,$+=o*Ie,X+=o*Le,Z+=o*be,W+=o*Oe,v+=o*Ce,S+=o*it,R+=o*Be,C+=o*Qe,k+=o*Je,M+=o*et,ne+=o*at,me+=o*gt,Ee+=o*mt,ye+=o*yt,E+=38*J,w+=38*$,P+=38*X,F+=38*Z,Q+=38*W,H+=38*v,Re+=38*S,G+=38*R,ae+=38*C,ce+=38*k,ge+=38*M,de+=38*ne,fe+=38*me,le+=38*Ee,ue+=38*ye,g=1,o=E+g+65535,g=Math.floor(o/65536),E=o-g*65536,o=w+g+65535,g=Math.floor(o/65536),w=o-g*65536,o=P+g+65535,g=Math.floor(o/65536),P=o-g*65536,o=F+g+65535,g=Math.floor(o/65536),F=o-g*65536,o=Q+g+65535,g=Math.floor(o/65536),Q=o-g*65536,o=H+g+65535,g=Math.floor(o/65536),H=o-g*65536,o=Re+g+65535,g=Math.floor(o/65536),Re=o-g*65536,o=G+g+65535,g=Math.floor(o/65536),G=o-g*65536,o=ae+g+65535,g=Math.floor(o/65536),ae=o-g*65536,o=ce+g+65535,g=Math.floor(o/65536),ce=o-g*65536,o=ge+g+65535,g=Math.floor(o/65536),ge=o-g*65536,o=de+g+65535,g=Math.floor(o/65536),de=o-g*65536,o=fe+g+65535,g=Math.floor(o/65536),fe=o-g*65536,o=le+g+65535,g=Math.floor(o/65536),le=o-g*65536,o=ue+g+65535,g=Math.floor(o/65536),ue=o-g*65536,o=Y+g+65535,g=Math.floor(o/65536),Y=o-g*65536,E+=g-1+37*(g-1),g=1,o=E+g+65535,g=Math.floor(o/65536),E=o-g*65536,o=w+g+65535,g=Math.floor(o/65536),w=o-g*65536,o=P+g+65535,g=Math.floor(o/65536),P=o-g*65536,o=F+g+65535,g=Math.floor(o/65536),F=o-g*65536,o=Q+g+65535,g=Math.floor(o/65536),Q=o-g*65536,o=H+g+65535,g=Math.floor(o/65536),H=o-g*65536,o=Re+g+65535,g=Math.floor(o/65536),Re=o-g*65536,o=G+g+65535,g=Math.floor(o/65536),G=o-g*65536,o=ae+g+65535,g=Math.floor(o/65536),ae=o-g*65536,o=ce+g+65535,g=Math.floor(o/65536),ce=o-g*65536,o=ge+g+65535,g=Math.floor(o/65536),ge=o-g*65536,o=de+g+65535,g=Math.floor(o/65536),de=o-g*65536,o=fe+g+65535,g=Math.floor(o/65536),fe=o-g*65536,o=le+g+65535,g=Math.floor(o/65536),le=o-g*65536,o=ue+g+65535,g=Math.floor(o/65536),ue=o-g*65536,o=Y+g+65535,g=Math.floor(o/65536),Y=o-g*65536,E+=g-1+37*(g-1),u[0]=E,u[1]=w,u[2]=P,u[3]=F,u[4]=Q,u[5]=H,u[6]=Re,u[7]=G,u[8]=ae,u[9]=ce,u[10]=ge,u[11]=de,u[12]=fe,u[13]=le,u[14]=ue,u[15]=Y}function se(u,d){L(u,d,d)}function Ae(u,d){var h=e(),o;for(o=0;o<16;o++)h[o]=d[o];for(o=253;o>=0;o--)se(h,h),o!==2&&o!==4&&L(h,h,d);for(o=0;o<16;o++)u[o]=h[o]}function B(u,d){var h=e(),o;for(o=0;o<16;o++)h[o]=d[o];for(o=250;o>=0;o--)se(h,h),o!==1&&L(h,h,d);for(o=0;o<16;o++)u[o]=h[o]}function oe(u,d,h){var o=new Uint8Array(32),g=new Float64Array(80),E,w,P=e(),F=e(),Q=e(),H=e(),Re=e(),G=e();for(w=0;w<31;w++)o[w]=d[w];for(o[31]=d[31]&127|64,o[0]&=248,pt(g,h),w=0;w<16;w++)F[w]=g[w],H[w]=P[w]=Q[w]=0;for(P[0]=H[0]=1,w=254;w>=0;--w)E=o[w>>>3]>>>(w&7)&1,rt(P,F,E),rt(Q,H,E),N(Re,P,Q),j(P,P,Q),N(Q,F,H),j(F,F,H),se(H,Re),se(G,P),L(P,Q,P),L(Q,F,Re),N(Re,P,Q),j(P,P,Q),se(F,P),j(Q,H,G),L(P,Q,f),N(P,P,H),L(Q,Q,P),L(P,H,G),L(H,F,g),se(F,Re),rt(P,F,E),rt(Q,H,E);for(w=0;w<16;w++)g[w+16]=P[w],g[w+32]=Q[w],g[w+48]=F[w],g[w+64]=H[w];var ae=g.subarray(32),ce=g.subarray(16);return Ae(ae,ae),L(ce,ce,ae),Fe(u,ce),0}function Ue(u,d){return oe(u,d,i)}function nt(u,d){return t(d,32),Ue(u,d)}function bt(u,d,h){var o=new Uint8Array(32);return oe(o,h,d),D(u,n,o,te)}var zt=De,ln=ve;function Kr(u,d,h,o,g,E){var w=new Uint8Array(32);return bt(w,g,E),zt(u,d,h,o,w)}function Fn(u,d,h,o,g,E){var w=new Uint8Array(32);return bt(w,g,E),ln(u,d,h,o,w)}var ss=[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 Hf(u,d,h,o){for(var g=new Int32Array(16),E=new Int32Array(16),w,P,F,Q,H,Re,G,ae,ce,ge,de,fe,le,ue,Y,J,$,X,Z,W,v,S,R,C,k,M,ne=u[0],me=u[1],Ee=u[2],ye=u[3],y=u[4],Se=u[5],Ie=u[6],Le=u[7],be=d[0],Oe=d[1],Ce=d[2],it=d[3],Be=d[4],Qe=d[5],Je=d[6],et=d[7],at=0;o>=128;){for(Z=0;Z<16;Z++)W=8*Z+at,g[Z]=h[W+0]<<24|h[W+1]<<16|h[W+2]<<8|h[W+3],E[Z]=h[W+4]<<24|h[W+5]<<16|h[W+6]<<8|h[W+7];for(Z=0;Z<80;Z++)if(w=ne,P=me,F=Ee,Q=ye,H=y,Re=Se,G=Ie,ae=Le,ce=be,ge=Oe,de=Ce,fe=it,le=Be,ue=Qe,Y=Je,J=et,v=Le,S=et,R=S&65535,C=S>>>16,k=v&65535,M=v>>>16,v=(y>>>14|Be<<18)^(y>>>18|Be<<14)^(Be>>>9|y<<23),S=(Be>>>14|y<<18)^(Be>>>18|y<<14)^(y>>>9|Be<<23),R+=S&65535,C+=S>>>16,k+=v&65535,M+=v>>>16,v=y&Se^~y&Ie,S=Be&Qe^~Be&Je,R+=S&65535,C+=S>>>16,k+=v&65535,M+=v>>>16,v=ss[Z*2],S=ss[Z*2+1],R+=S&65535,C+=S>>>16,k+=v&65535,M+=v>>>16,v=g[Z%16],S=E[Z%16],R+=S&65535,C+=S>>>16,k+=v&65535,M+=v>>>16,C+=R>>>16,k+=C>>>16,M+=k>>>16,$=k&65535|M<<16,X=R&65535|C<<16,v=$,S=X,R=S&65535,C=S>>>16,k=v&65535,M=v>>>16,v=(ne>>>28|be<<4)^(be>>>2|ne<<30)^(be>>>7|ne<<25),S=(be>>>28|ne<<4)^(ne>>>2|be<<30)^(ne>>>7|be<<25),R+=S&65535,C+=S>>>16,k+=v&65535,M+=v>>>16,v=ne&me^ne&Ee^me&Ee,S=be&Oe^be&Ce^Oe&Ce,R+=S&65535,C+=S>>>16,k+=v&65535,M+=v>>>16,C+=R>>>16,k+=C>>>16,M+=k>>>16,ae=k&65535|M<<16,J=R&65535|C<<16,v=Q,S=fe,R=S&65535,C=S>>>16,k=v&65535,M=v>>>16,v=$,S=X,R+=S&65535,C+=S>>>16,k+=v&65535,M+=v>>>16,C+=R>>>16,k+=C>>>16,M+=k>>>16,Q=k&65535|M<<16,fe=R&65535|C<<16,me=w,Ee=P,ye=F,y=Q,Se=H,Ie=Re,Le=G,ne=ae,Oe=ce,Ce=ge,it=de,Be=fe,Qe=le,Je=ue,et=Y,be=J,Z%16===15)for(W=0;W<16;W++)v=g[W],S=E[W],R=S&65535,C=S>>>16,k=v&65535,M=v>>>16,v=g[(W+9)%16],S=E[(W+9)%16],R+=S&65535,C+=S>>>16,k+=v&65535,M+=v>>>16,$=g[(W+1)%16],X=E[(W+1)%16],v=($>>>1|X<<31)^($>>>8|X<<24)^$>>>7,S=(X>>>1|$<<31)^(X>>>8|$<<24)^(X>>>7|$<<25),R+=S&65535,C+=S>>>16,k+=v&65535,M+=v>>>16,$=g[(W+14)%16],X=E[(W+14)%16],v=($>>>19|X<<13)^(X>>>29|$<<3)^$>>>6,S=(X>>>19|$<<13)^($>>>29|X<<3)^(X>>>6|$<<26),R+=S&65535,C+=S>>>16,k+=v&65535,M+=v>>>16,C+=R>>>16,k+=C>>>16,M+=k>>>16,g[W]=k&65535|M<<16,E[W]=R&65535|C<<16;v=ne,S=be,R=S&65535,C=S>>>16,k=v&65535,M=v>>>16,v=u[0],S=d[0],R+=S&65535,C+=S>>>16,k+=v&65535,M+=v>>>16,C+=R>>>16,k+=C>>>16,M+=k>>>16,u[0]=ne=k&65535|M<<16,d[0]=be=R&65535|C<<16,v=me,S=Oe,R=S&65535,C=S>>>16,k=v&65535,M=v>>>16,v=u[1],S=d[1],R+=S&65535,C+=S>>>16,k+=v&65535,M+=v>>>16,C+=R>>>16,k+=C>>>16,M+=k>>>16,u[1]=me=k&65535|M<<16,d[1]=Oe=R&65535|C<<16,v=Ee,S=Ce,R=S&65535,C=S>>>16,k=v&65535,M=v>>>16,v=u[2],S=d[2],R+=S&65535,C+=S>>>16,k+=v&65535,M+=v>>>16,C+=R>>>16,k+=C>>>16,M+=k>>>16,u[2]=Ee=k&65535|M<<16,d[2]=Ce=R&65535|C<<16,v=ye,S=it,R=S&65535,C=S>>>16,k=v&65535,M=v>>>16,v=u[3],S=d[3],R+=S&65535,C+=S>>>16,k+=v&65535,M+=v>>>16,C+=R>>>16,k+=C>>>16,M+=k>>>16,u[3]=ye=k&65535|M<<16,d[3]=it=R&65535|C<<16,v=y,S=Be,R=S&65535,C=S>>>16,k=v&65535,M=v>>>16,v=u[4],S=d[4],R+=S&65535,C+=S>>>16,k+=v&65535,M+=v>>>16,C+=R>>>16,k+=C>>>16,M+=k>>>16,u[4]=y=k&65535|M<<16,d[4]=Be=R&65535|C<<16,v=Se,S=Qe,R=S&65535,C=S>>>16,k=v&65535,M=v>>>16,v=u[5],S=d[5],R+=S&65535,C+=S>>>16,k+=v&65535,M+=v>>>16,C+=R>>>16,k+=C>>>16,M+=k>>>16,u[5]=Se=k&65535|M<<16,d[5]=Qe=R&65535|C<<16,v=Ie,S=Je,R=S&65535,C=S>>>16,k=v&65535,M=v>>>16,v=u[6],S=d[6],R+=S&65535,C+=S>>>16,k+=v&65535,M+=v>>>16,C+=R>>>16,k+=C>>>16,M+=k>>>16,u[6]=Ie=k&65535|M<<16,d[6]=Je=R&65535|C<<16,v=Le,S=et,R=S&65535,C=S>>>16,k=v&65535,M=v>>>16,v=u[7],S=d[7],R+=S&65535,C+=S>>>16,k+=v&65535,M+=v>>>16,C+=R>>>16,k+=C>>>16,M+=k>>>16,u[7]=Le=k&65535|M<<16,d[7]=et=R&65535|C<<16,at+=128,o-=128}return o}function hn(u,d,h){var o=new Int32Array(8),g=new Int32Array(8),E=new Uint8Array(256),w,P=h;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,Hf(o,g,d,h),h%=128,w=0;w<h;w++)E[w]=d[P-h+w];for(E[h]=128,h=256-128*(h<112?1:0),E[h-9]=0,b(E,h-8,P/536870912|0,P<<3),Hf(o,g,E,h),w=0;w<8;w++)b(u,8*w,o[w],g[w]);return 0}function os(u,d){var h=e(),o=e(),g=e(),E=e(),w=e(),P=e(),F=e(),Q=e(),H=e();j(h,u[1],u[0]),j(H,d[1],d[0]),L(h,h,H),N(o,u[0],u[1]),N(H,d[0],d[1]),L(o,o,H),L(g,u[3],d[3]),L(g,g,l),L(E,u[2],d[2]),N(E,E,E),j(w,o,h),j(P,E,g),N(F,E,g),N(Q,o,h),L(u[0],w,P),L(u[1],Q,F),L(u[2],F,P),L(u[3],w,Q)}function Vf(u,d,h){var o;for(o=0;o<4;o++)rt(u[o],d[o],h)}function Xo(u,d){var h=e(),o=e(),g=e();Ae(g,d[2]),L(h,d[0],g),L(o,d[1],g),Fe(u,o),u[31]^=He(h)<<7}function Zo(u,d,h){var o,g;for(We(u[0],s),We(u[1],a),We(u[2],a),We(u[3],s),g=255;g>=0;--g)o=h[g/8|0]>>(g&7)&1,Vf(u,d,o),os(d,u),os(u,u),Vf(u,d,o)}function as(u,d){var h=[e(),e(),e(),e()];We(h[0],p),We(h[1],m),We(h[2],a),L(h[3],p,m),Zo(u,h,d)}function Qo(u,d,h){var o=new Uint8Array(64),g=[e(),e(),e(),e()],E;for(h||t(d,32),hn(o,d,32),o[0]&=248,o[31]&=127,o[31]|=64,as(g,o),Xo(u,g),E=0;E<32;E++)d[E+32]=u[E];return 0}var cs=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(u,d){var h,o,g,E;for(o=63;o>=32;--o){for(h=0,g=o-32,E=o-12;g<E;++g)d[g]+=h-16*d[o]*cs[g-(o-32)],h=Math.floor((d[g]+128)/256),d[g]-=h*256;d[g]+=h,d[o]=0}for(h=0,g=0;g<32;g++)d[g]+=h-(d[31]>>4)*cs[g],h=d[g]>>8,d[g]&=255;for(g=0;g<32;g++)d[g]-=h*cs[g];for(o=0;o<32;o++)d[o+1]+=d[o]>>8,u[o]=d[o]&255}function ea(u){var d=new Float64Array(64),h;for(h=0;h<64;h++)d[h]=u[h];for(h=0;h<64;h++)u[h]=0;Jo(u,d)}function $f(u,d,h,o){var g=new Uint8Array(64),E=new Uint8Array(64),w=new Uint8Array(64),P,F,Q=new Float64Array(64),H=[e(),e(),e(),e()];hn(g,o,32),g[0]&=248,g[31]&=127,g[31]|=64;var Re=h+64;for(P=0;P<h;P++)u[64+P]=d[P];for(P=0;P<32;P++)u[32+P]=g[32+P];for(hn(w,u.subarray(32),h+32),ea(w),as(H,w),Xo(u,H),P=32;P<64;P++)u[P]=o[P];for(hn(E,u,h+64),ea(E),P=0;P<64;P++)Q[P]=0;for(P=0;P<32;P++)Q[P]=w[P];for(P=0;P<32;P++)for(F=0;F<32;F++)Q[P+F]+=E[P]*g[F];return Jo(u.subarray(32),Q),Re}function eg(u,d){var h=e(),o=e(),g=e(),E=e(),w=e(),P=e(),F=e();return We(u[2],a),pt(u[1],d),se(g,u[1]),L(E,g,c),j(g,g,u[2]),N(E,u[2],E),se(w,E),se(P,w),L(F,P,w),L(h,F,g),L(h,h,E),B(h,h),L(h,h,g),L(h,h,E),L(h,h,E),L(u[0],h,E),se(o,u[0]),L(o,o,E),Et(o,g)&&L(u[0],u[0],_),se(o,u[0]),L(o,o,E),Et(o,g)?-1:(He(u[0])===d[31]>>7&&j(u[0],s,u[0]),L(u[3],u[0],u[1]),0)}function ta(u,d,h,o){var g,E=new Uint8Array(32),w=new Uint8Array(64),P=[e(),e(),e(),e()],F=[e(),e(),e(),e()];if(h<64||eg(F,o))return-1;for(g=0;g<h;g++)u[g]=d[g];for(g=0;g<32;g++)u[g+32]=o[g];if(hn(w,u,h),ea(w),Zo(P,F,w),as(F,d.subarray(32)),os(P,F),Xo(E,P),h-=64,V(d,0,E,0)){for(g=0;g<h;g++)u[g]=0;return-1}for(g=0;g<h;g++)u[g]=d[g+64];return h}var ra=32,fs=24,Ei=32,Bn=16,bi=32,us=32,wi=32,vi=32,na=32,Gf=fs,tg=Ei,rg=Bn,Sr=64,dn=32,jn=64,ia=32,sa=64;r.lowlevel={crypto_core_hsalsa20:D,crypto_stream_xor:K,crypto_stream:pe,crypto_stream_salsa20_xor:q,crypto_stream_salsa20:ee,crypto_onetimeauth:tt,crypto_onetimeauth_verify:Te,crypto_verify_16:O,crypto_verify_32:V,crypto_secretbox:De,crypto_secretbox_open:ve,crypto_scalarmult:oe,crypto_scalarmult_base:Ue,crypto_box_beforenm:bt,crypto_box_afternm:zt,crypto_box:Kr,crypto_box_open:Fn,crypto_box_keypair:nt,crypto_hash:hn,crypto_sign:$f,crypto_sign_keypair:Qo,crypto_sign_open:ta,crypto_secretbox_KEYBYTES:ra,crypto_secretbox_NONCEBYTES:fs,crypto_secretbox_ZEROBYTES:Ei,crypto_secretbox_BOXZEROBYTES:Bn,crypto_scalarmult_BYTES:bi,crypto_scalarmult_SCALARBYTES:us,crypto_box_PUBLICKEYBYTES:wi,crypto_box_SECRETKEYBYTES:vi,crypto_box_BEFORENMBYTES:na,crypto_box_NONCEBYTES:Gf,crypto_box_ZEROBYTES:tg,crypto_box_BOXZEROBYTES:rg,crypto_sign_BYTES:Sr,crypto_sign_PUBLICKEYBYTES:dn,crypto_sign_SECRETKEYBYTES:jn,crypto_sign_SEEDBYTES:ia,crypto_hash_BYTES:sa,gf:e,D:c,L:cs,pack25519:Fe,unpack25519:pt,M:L,A:N,S:se,Z:j,pow2523:B,add:os,set25519:We,modL:Jo,scalarmult:Zo,scalarbase:as};function zf(u,d){if(u.length!==ra)throw new Error("bad key size");if(d.length!==fs)throw new Error("bad nonce size")}function ng(u,d){if(u.length!==wi)throw new Error("bad public key size");if(d.length!==vi)throw new Error("bad secret key size")}function Ct(){for(var u=0;u<arguments.length;u++)if(!(arguments[u]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function Yf(u){for(var d=0;d<u.length;d++)u[d]=0}r.randomBytes=function(u){var d=new Uint8Array(u);return t(d,u),d},r.secretbox=function(u,d,h){Ct(u,d,h),zf(h,d);for(var o=new Uint8Array(Ei+u.length),g=new Uint8Array(o.length),E=0;E<u.length;E++)o[E+Ei]=u[E];return De(g,o,o.length,d,h),g.subarray(Bn)},r.secretbox.open=function(u,d,h){Ct(u,d,h),zf(h,d);for(var o=new Uint8Array(Bn+u.length),g=new Uint8Array(o.length),E=0;E<u.length;E++)o[E+Bn]=u[E];return o.length<32||ve(g,o,o.length,d,h)!==0?null:g.subarray(Ei)},r.secretbox.keyLength=ra,r.secretbox.nonceLength=fs,r.secretbox.overheadLength=Bn,r.scalarMult=function(u,d){if(Ct(u,d),u.length!==us)throw new Error("bad n size");if(d.length!==bi)throw new Error("bad p size");var h=new Uint8Array(bi);return oe(h,u,d),h},r.scalarMult.base=function(u){if(Ct(u),u.length!==us)throw new Error("bad n size");var d=new Uint8Array(bi);return Ue(d,u),d},r.scalarMult.scalarLength=us,r.scalarMult.groupElementLength=bi,r.box=function(u,d,h,o){var g=r.box.before(h,o);return r.secretbox(u,d,g)},r.box.before=function(u,d){Ct(u,d),ng(u,d);var h=new Uint8Array(na);return bt(h,u,d),h},r.box.after=r.secretbox,r.box.open=function(u,d,h,o){var g=r.box.before(h,o);return r.secretbox.open(u,d,g)},r.box.open.after=r.secretbox.open,r.box.keyPair=function(){var u=new Uint8Array(wi),d=new Uint8Array(vi);return nt(u,d),{publicKey:u,secretKey:d}},r.box.keyPair.fromSecretKey=function(u){if(Ct(u),u.length!==vi)throw new Error("bad secret key size");var d=new Uint8Array(wi);return Ue(d,u),{publicKey:d,secretKey:new Uint8Array(u)}},r.box.publicKeyLength=wi,r.box.secretKeyLength=vi,r.box.sharedKeyLength=na,r.box.nonceLength=Gf,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(u,d){if(Ct(u,d),d.length!==jn)throw new Error("bad secret key size");var h=new Uint8Array(Sr+u.length);return $f(h,u,u.length,d),h},r.sign.open=function(u,d){if(Ct(u,d),d.length!==dn)throw new Error("bad public key size");var h=new Uint8Array(u.length),o=ta(h,u,u.length,d);if(o<0)return null;for(var g=new Uint8Array(o),E=0;E<g.length;E++)g[E]=h[E];return g},r.sign.detached=function(u,d){for(var h=r.sign(u,d),o=new Uint8Array(Sr),g=0;g<o.length;g++)o[g]=h[g];return o},r.sign.detached.verify=function(u,d,h){if(Ct(u,d,h),d.length!==Sr)throw new Error("bad signature size");if(h.length!==dn)throw new Error("bad public key size");var o=new Uint8Array(Sr+u.length),g=new Uint8Array(Sr+u.length),E;for(E=0;E<Sr;E++)o[E]=d[E];for(E=0;E<u.length;E++)o[E+Sr]=u[E];return ta(g,o,o.length,h)>=0},r.sign.keyPair=function(){var u=new Uint8Array(dn),d=new Uint8Array(jn);return Qo(u,d),{publicKey:u,secretKey:d}},r.sign.keyPair.fromSecretKey=function(u){if(Ct(u),u.length!==jn)throw new Error("bad secret key size");for(var d=new Uint8Array(dn),h=0;h<d.length;h++)d[h]=u[32+h];return{publicKey:d,secretKey:new Uint8Array(u)}},r.sign.keyPair.fromSeed=function(u){if(Ct(u),u.length!==ia)throw new Error("bad seed size");for(var d=new Uint8Array(dn),h=new Uint8Array(jn),o=0;o<32;o++)h[o]=u[o];return Qo(d,h,!0),{publicKey:d,secretKey:h}},r.sign.publicKeyLength=dn,r.sign.secretKeyLength=jn,r.sign.seedLength=ia,r.sign.signatureLength=Sr,r.hash=function(u){Ct(u);var d=new Uint8Array(sa);return hn(d,u,u.length),d},r.hash.hashLength=sa,r.verify=function(u,d){return Ct(u,d),u.length===0||d.length===0||u.length!==d.length?!1:x(u,0,d,0,u.length)===0},r.setPRNG=function(u){t=u},(function(){var u=typeof self<"u"?self.crypto||self.msCrypto:null;if(u&&u.getRandomValues){var d=65536;r.setPRNG(function(h,o){var g,E=new Uint8Array(o);for(g=0;g<o;g+=d)u.getRandomValues(E.subarray(g,g+Math.min(o-g,d)));for(g=0;g<o;g++)h[g]=E[g];Yf(E)})}else typeof require<"u"&&(u=require("crypto"),u&&u.randomBytes&&r.setPRNG(function(h,o){var g,E=u.randomBytes(o);for(g=0;g<o;g++)h[g]=E[g];Yf(E)}))})()})(typeof vs<"u"&&vs.exports?vs.exports:self.nacl=self.nacl||{})});var Ci=I((gu,Ss)=>{(function(r,e){"use strict";typeof Ss<"u"&&Ss.exports?Ss.exports=e():(r.nacl||(r.nacl={}),r.nacl.util=e())})(gu,function(){"use strict";var r={};function e(t){if(!/^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(t))throw new TypeError("invalid encoding")}return r.decodeUTF8=function(t){if(typeof t!="string")throw new TypeError("expected string");var n,i=unescape(encodeURIComponent(t)),s=new Uint8Array(i.length);for(n=0;n<i.length;n++)s[n]=i.charCodeAt(n);return s},r.encodeUTF8=function(t){var n,i=[];for(n=0;n<t.length;n++)i.push(String.fromCharCode(t[n]));return decodeURIComponent(escape(i.join("")))},typeof atob>"u"?typeof Buffer.from<"u"?(r.encodeBase64=function(t){return Buffer.from(t).toString("base64")},r.decodeBase64=function(t){return e(t),new Uint8Array(Array.prototype.slice.call(Buffer.from(t,"base64"),0))}):(r.encodeBase64=function(t){return new Buffer(t).toString("base64")},r.decodeBase64=function(t){return e(t),new Uint8Array(Array.prototype.slice.call(new Buffer(t,"base64"),0))}):(r.encodeBase64=function(t){var n,i=[],s=t.length;for(n=0;n<s;n++)i.push(String.fromCharCode(t[n]));return btoa(i.join(""))},r.decodeBase64=function(t){e(t);var n,i=atob(t),s=new Uint8Array(i.length);for(n=0;n<i.length;n++)s[n]=i.charCodeAt(n);return s}),r})});var mu=I(kt=>{"use strict";var Tg=kt&&kt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(kt,"__esModule",{value:!0});kt.concatBytes=Pi;kt.generateIdentityKeyPair=Og;kt.identityPublicFromSecret=Cg;kt.signSessionKey=Pg;kt.verifySessionKey=kg;kt.buildKxCanonical=Ag;kt.buildKxAckCanonical=Rg;kt.fingerprintIdentityKey=Ig;kt.fingerprintShortHex=Lg;var cr=Tg(Oi()),Pt=Ci(),xs=ua();function Pi(...r){let e=0;for(let i of r)e+=i.length;let t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}function Og(){let r=cr.default.sign.keyPair();return{identityPublicKey:(0,Pt.encodeBase64)(r.publicKey),identitySecretKey:(0,Pt.encodeBase64)(r.secretKey)}}function Cg(r){let e=(0,Pt.decodeBase64)(r);if(e.length!==cr.default.sign.secretKeyLength)throw new Error("bad identity secret key length");let t=cr.default.sign.keyPair.fromSecretKey(e);return(0,Pt.encodeBase64)(t.publicKey)}function Pg(r,e){let t=(0,Pt.decodeBase64)(e);if(t.length!==cr.default.sign.secretKeyLength)throw new Error("bad identity secret key length");return(0,Pt.encodeBase64)(cr.default.sign.detached(r,t))}function kg(r,e,t){try{let n=(0,Pt.decodeBase64)(e),i=(0,Pt.decodeBase64)(t);return i.length!==cr.default.sign.publicKeyLength||n.length!==cr.default.sign.signatureLength?!1:cr.default.sign.detached.verify(r,n,i)}catch{return!1}}var pn=new Uint8Array([0]);function Ag(r){let e=new TextEncoder,t=e.encode(xs.KX_SIGN_LABEL),n=e.encode(r.agentId),i=e.encode(String(r.keyVersion)),s=(0,Pt.decodeBase64)(r.boxPublicKey);return Pi(t,pn,n,pn,i,pn,s)}function Rg(r){let e=new TextEncoder;return Pi(e.encode(xs.KX_ACK_LABEL),pn,e.encode(r.agentId),pn,e.encode(String(r.keyVersion)),pn,(0,Pt.decodeBase64)(r.boxPublicKey),pn,(0,Pt.decodeBase64)(r.boundClientKey))}function Ig(r){let e=(0,Pt.decodeBase64)(r),t=Pi(new TextEncoder().encode(xs.KX_FINGERPRINT_LABEL),e),n=cr.default.hash(t),i=[];for(let s=0;s<12;s++){let a=s*5,c=(((n[a]<<24>>>0)+(n[a+1]<<16)+(n[a+2]<<8)+n[a+3]^n[a+4])>>>0)%1e5;i.push(String(c).padStart(5,"0"))}return i.join(" ")}function Lg(r){let e=(0,Pt.decodeBase64)(r),t=Pi(new TextEncoder().encode(xs.KX_FINGERPRINT_LABEL),e),n=cr.default.hash(t).slice(0,8);return Array.from(n).map(i=>i.toString(16).padStart(2,"0")).join(":").toUpperCase()}});var yu=I(Vr=>{"use strict";var Ng=Vr&&Vr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Vr,"__esModule",{value:!0});Vr.encrypt=Mg;Vr.decrypt=Dg;Vr.encryptBinary=Fg;Vr.decryptBinary=Bg;var Or=Ng(Oi()),Hr=Ci();function Mg(r,e,t){let n=Or.default.randomBytes(Or.default.secretbox.nonceLength),i=new TextEncoder().encode(r),s=Or.default.secretbox(i,n,e);return{v:1,sid:t,n:(0,Hr.encodeBase64)(n),c:(0,Hr.encodeBase64)(s)}}function Dg(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Hr.decodeBase64)(r.n),n=(0,Hr.decodeBase64)(r.c);if(t.length!==Or.default.secretbox.nonceLength)throw new Error(`Invalid nonce length: ${t.length}`);let i=Or.default.secretbox.open(n,t,e);if(!i)throw new Error("Decryption failed: invalid ciphertext or wrong key");return new TextDecoder().decode(i)}function Fg(r,e,t){let n=Or.default.randomBytes(Or.default.secretbox.nonceLength),i=Or.default.secretbox(r,n,e);return{v:1,sid:t,n:(0,Hr.encodeBase64)(n),c:(0,Hr.encodeBase64)(i)}}function Bg(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Hr.decodeBase64)(r.n),n=(0,Hr.decodeBase64)(r.c),i=Or.default.secretbox.open(n,t,e);if(!i)throw new Error("Decryption failed: invalid ciphertext or wrong key");return i}});var _u=I(Xt=>{"use strict";var jg=Xt&&Xt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Xt,"__esModule",{value:!0});Xt.generateKeyPair=Ug;Xt.deriveSharedSecret=qg;Xt.deriveMetaSid=Kg;Xt.isValidPublicKey=Wg;Xt.clearKey=Hg;Xt.keyToBase64=Vg;Xt.base64ToKey=$g;var qn=jg(Oi()),fr=Ci();function Ug(){let r=qn.default.box.keyPair();return{publicKey:(0,fr.encodeBase64)(r.publicKey),secretKey:(0,fr.encodeBase64)(r.secretKey)}}function qg(r,e){let t=(0,fr.decodeBase64)(r),n=(0,fr.decodeBase64)(e);if(t.length!==qn.default.box.publicKeyLength)throw new Error(`Invalid public key length: ${t.length}`);if(n.length!==qn.default.box.secretKeyLength)throw new Error(`Invalid secret key length: ${n.length}`);return qn.default.box.before(t,n)}function Kg(r,e){let t=new TextEncoder().encode("termiq-meta-v1"),n=(0,fr.decodeBase64)(r),i=(0,fr.decodeBase64)(e),s=new Uint8Array(t.length+n.length+i.length);return s.set(t,0),s.set(n,t.length),s.set(i,t.length+n.length),(0,fr.encodeBase64)(qn.default.hash(s).slice(0,32))}function Wg(r){try{return(0,fr.decodeBase64)(r).length===qn.default.box.publicKeyLength}catch{return!1}}function Hg(r){r.fill(0)}function Vg(r){return(0,fr.encodeBase64)(r)}function $g(r){return(0,fr.decodeBase64)(r)}});var bu=I(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.base64ToKey=re.keyToBase64=re.clearKey=re.isValidPublicKey=re.deriveMetaSid=re.deriveSharedSecret=re.generateKeyPair=re.decryptBinary=re.encryptBinary=re.decrypt=re.encrypt=re.concatBytes=re.fingerprintShortHex=re.fingerprintIdentityKey=re.buildKxAckCanonical=re.buildKxCanonical=re.verifySessionKey=re.signSessionKey=re.identityPublicFromSecret=re.generateIdentityKeyPair=re.KX_SIG_VERSION=re.KX_FINGERPRINT_LABEL=re.KX_ACK_LABEL=re.KX_SIGN_LABEL=re.isMultiRecipientPayload=re.isEncryptedPayload=void 0;var Eu=pu();Object.defineProperty(re,"isEncryptedPayload",{enumerable:!0,get:function(){return Eu.isEncryptedPayload}});Object.defineProperty(re,"isMultiRecipientPayload",{enumerable:!0,get:function(){return Eu.isMultiRecipientPayload}});var Ts=ua();Object.defineProperty(re,"KX_SIGN_LABEL",{enumerable:!0,get:function(){return Ts.KX_SIGN_LABEL}});Object.defineProperty(re,"KX_ACK_LABEL",{enumerable:!0,get:function(){return Ts.KX_ACK_LABEL}});Object.defineProperty(re,"KX_FINGERPRINT_LABEL",{enumerable:!0,get:function(){return Ts.KX_FINGERPRINT_LABEL}});Object.defineProperty(re,"KX_SIG_VERSION",{enumerable:!0,get:function(){return Ts.KX_SIG_VERSION}});var Cr=mu();Object.defineProperty(re,"generateIdentityKeyPair",{enumerable:!0,get:function(){return Cr.generateIdentityKeyPair}});Object.defineProperty(re,"identityPublicFromSecret",{enumerable:!0,get:function(){return Cr.identityPublicFromSecret}});Object.defineProperty(re,"signSessionKey",{enumerable:!0,get:function(){return Cr.signSessionKey}});Object.defineProperty(re,"verifySessionKey",{enumerable:!0,get:function(){return Cr.verifySessionKey}});Object.defineProperty(re,"buildKxCanonical",{enumerable:!0,get:function(){return Cr.buildKxCanonical}});Object.defineProperty(re,"buildKxAckCanonical",{enumerable:!0,get:function(){return Cr.buildKxAckCanonical}});Object.defineProperty(re,"fingerprintIdentityKey",{enumerable:!0,get:function(){return Cr.fingerprintIdentityKey}});Object.defineProperty(re,"fingerprintShortHex",{enumerable:!0,get:function(){return Cr.fingerprintShortHex}});Object.defineProperty(re,"concatBytes",{enumerable:!0,get:function(){return Cr.concatBytes}});var Os=yu();Object.defineProperty(re,"encrypt",{enumerable:!0,get:function(){return Os.encrypt}});Object.defineProperty(re,"decrypt",{enumerable:!0,get:function(){return Os.decrypt}});Object.defineProperty(re,"encryptBinary",{enumerable:!0,get:function(){return Os.encryptBinary}});Object.defineProperty(re,"decryptBinary",{enumerable:!0,get:function(){return Os.decryptBinary}});var gn=_u();Object.defineProperty(re,"generateKeyPair",{enumerable:!0,get:function(){return gn.generateKeyPair}});Object.defineProperty(re,"deriveSharedSecret",{enumerable:!0,get:function(){return gn.deriveSharedSecret}});Object.defineProperty(re,"deriveMetaSid",{enumerable:!0,get:function(){return gn.deriveMetaSid}});Object.defineProperty(re,"isValidPublicKey",{enumerable:!0,get:function(){return gn.isValidPublicKey}});Object.defineProperty(re,"clearKey",{enumerable:!0,get:function(){return gn.clearKey}});Object.defineProperty(re,"keyToBase64",{enumerable:!0,get:function(){return gn.keyToBase64}});Object.defineProperty(re,"base64ToKey",{enumerable:!0,get:function(){return gn.base64ToKey}})});var wu=I(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.MIN_CLIENT_VERSION=At.PROTOCOL_VERSION_MINOR=At.PROTOCOL_VERSION_MAJOR=At.PROTOCOL_VERSION=void 0;At.isCompatibleVersion=Gg;At.compareVersions=zg;At.PROTOCOL_VERSION="2.1";At.PROTOCOL_VERSION_MAJOR=2;At.PROTOCOL_VERSION_MINOR=1;At.MIN_CLIENT_VERSION="2.0";function Gg(r){let[e]=r.split(".").map(Number);return e===At.PROTOCOL_VERSION_MAJOR}function zg(r,e){let[t,n]=r.split(".").map(Number),[i,s]=e.split(".").map(Number);return t!==i?t<i?-1:1:n!==s?n<s?-1:1:0}});var vu=I(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.SERVER_CAPABILITIES=ur.DEFAULT_CLIENT_CAPABILITIES=ur.Capability=void 0;ur.hasCapability=Yg;ur.negotiateCapabilities=Xg;var Kn;(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",r.SCREEN="screen"})(Kn||(ur.Capability=Kn={}));ur.DEFAULT_CLIENT_CAPABILITIES=[Kn.E2E_ENCRYPTION,Kn.TERMINAL_EVENTS,Kn.RELIABLE_INPUT];ur.SERVER_CAPABILITIES=Object.values(Kn);function Yg(r,e){return r.includes(e)}function Xg(r,e){return r.filter(t=>e.includes(t))}});var Su=I(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.DEFAULT_PRIORITY=Pr.PRIORITY_NAMES=Pr.Priority=void 0;Pr.comparePriority=Zg;var mn;(function(r){r[r.CRITICAL=0]="CRITICAL",r[r.HIGH=1]="HIGH",r[r.NORMAL=2]="NORMAL",r[r.LOW=3]="LOW"})(mn||(Pr.Priority=mn={}));Pr.PRIORITY_NAMES={[mn.CRITICAL]:"CRITICAL",[mn.HIGH]:"HIGH",[mn.NORMAL]:"NORMAL",[mn.LOW]:"LOW"};Pr.DEFAULT_PRIORITY=mn.NORMAL;function Zg(r,e){return r-e}});var xu=I(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.DEFAULT_RELIABILITY=lr.RELIABILITY_NAMES=lr.Reliability=void 0;lr.requiresAck=Qg;lr.requiresBuffer=Jg;var $r;(function(r){r[r.FIRE_FORGET=0]="FIRE_FORGET",r[r.BUFFERED=1]="BUFFERED",r[r.GUARANTEED=2]="GUARANTEED"})($r||(lr.Reliability=$r={}));lr.RELIABILITY_NAMES={[$r.FIRE_FORGET]:"FIRE_FORGET",[$r.BUFFERED]:"BUFFERED",[$r.GUARANTEED]:"GUARANTEED"};lr.DEFAULT_RELIABILITY=$r.FIRE_FORGET;function Qg(r){return r===$r.GUARANTEED}function Jg(r){return r>=$r.BUFFERED}});var Tu=I(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0});la.createMessage=em;function em(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 Ou=I(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.TerminalEventType=void 0;yn.deriveStatusFromEvent=tm;yn.shouldTriggerPushNotification=rm;yn.getPushNotificationMessage=nm;var wt;(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"})(wt||(yn.TerminalEventType=wt={}));function tm(r){switch(r.type){case wt.SESSION_START:case wt.TOOL_START:case wt.MESSAGE:return"working";case wt.WAITING_INPUT:return"waiting";case wt.SESSION_END:return r.status==="success"?"completed":"error";case wt.ERROR:return r.severity==="fatal"?"error":"working";case wt.TOOL_END:return r.status==="error"?"error":"working";default:return"idle"}}function rm(r){switch(r.type){case wt.WAITING_INPUT:return!0;case wt.SESSION_END:return!0;case wt.ERROR:return r.severity!=="warning";default:return!1}}function nm(r,e){switch(r.type){case wt.WAITING_INPUT:{let t=r.question;return{title:`${e}: Input Required`,body:t?t.slice(0,100):"Waiting for your input"}}case wt.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 wt.ERROR:{let t=r;return t.severity==="warning"?null:{title:`${e}: Error`,body:t.message.slice(0,100)}}default:return null}}});var ku=I(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.TransferDirection=Ge.TransferStatus=Ge.CHUNK_TTL_SECONDS=Ge.TRANSFER_TTL_SECONDS=Ge.MAX_RETRIES=Ge.ACK_TIMEOUT_MS=Ge.WINDOW_SIZE=Ge.DEFAULT_MAX_FILE_SIZE=Ge.CHUNK_SIZE=void 0;Ge.calculateTotalChunks=im;Ge.getMissingChunks=sm;Ge.isTransferComplete=om;Ge.CHUNK_SIZE=64*1024;Ge.DEFAULT_MAX_FILE_SIZE=100*1024*1024;Ge.WINDOW_SIZE=10;Ge.ACK_TIMEOUT_MS=3e4;Ge.MAX_RETRIES=3;Ge.TRANSFER_TTL_SECONDS=1440*60;Ge.CHUNK_TTL_SECONDS=1440*60;var Cu;(function(r){r.PENDING="pending",r.ACTIVE="active",r.PAUSED="paused",r.COMPLETED="completed",r.FAILED="failed",r.CANCELLED="cancelled",r.EXPIRED="expired"})(Cu||(Ge.TransferStatus=Cu={}));var Pu;(function(r){r.DOWNLOAD="download",r.UPLOAD="upload"})(Pu||(Ge.TransferDirection=Pu={}));function im(r,e=Ge.CHUNK_SIZE){return Math.ceil(r/e)}function sm(r,e){let t=new Set(e),n=[];for(let i=0;i<r;i++)t.has(i)||n.push(i);return n}function om(r,e){return e.length===r}});var Au=I(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.ERROR_MESSAGES=kr.ErrorCode=void 0;kr.createError=am;kr.isRetryableError=cm;var Pe;(function(r){r.AUTH_FAILED="E001",r.TOKEN_EXPIRED="E002",r.TOKEN_INVALID="E003",r.NOT_FOUND="E011",r.ALREADY_EXISTS="E012",r.ACCESS_DENIED="E021",r.FORBIDDEN="E022",r.RATE_LIMITED="E031",r.TOO_MANY_CONNECTIONS="E032",r.QUOTA_EXCEEDED="E041",r.FILE_TOO_LARGE="E042",r.QUEUE_FULL="E043",r.TRANSFERS_LIMIT="E044",r.TRANSFER_FAILED="E051",r.TRANSFER_EXPIRED="E052",r.TRANSFER_CANCELLED="E053",r.CHECKSUM_MISMATCH="E054",r.CHUNK_MISSING="E055",r.INVALID_MESSAGE="E061",r.UNSUPPORTED_VERSION="E062",r.CAPABILITY_REQUIRED="E063",r.INVALID_STATE="E071",r.TIMEOUT="E072",r.CONNECTION_LOST="E073",r.INTERNAL_ERROR="E091",r.SERVICE_UNAVAILABLE="E092",r.HANDSHAKE_UNAUTHORIZED="E401",r.HANDSHAKE_FORBIDDEN="E403"})(Pe||(kr.ErrorCode=Pe={}));kr.ERROR_MESSAGES={[Pe.AUTH_FAILED]:"Authentication failed",[Pe.TOKEN_EXPIRED]:"Token expired",[Pe.TOKEN_INVALID]:"Invalid token",[Pe.NOT_FOUND]:"Resource not found",[Pe.ALREADY_EXISTS]:"Resource already exists",[Pe.ACCESS_DENIED]:"Access denied",[Pe.FORBIDDEN]:"Operation forbidden",[Pe.RATE_LIMITED]:"Rate limit exceeded",[Pe.TOO_MANY_CONNECTIONS]:"Too many connections",[Pe.QUOTA_EXCEEDED]:"Plan quota exceeded",[Pe.FILE_TOO_LARGE]:"File size exceeds limit",[Pe.QUEUE_FULL]:"Message queue is full",[Pe.TRANSFERS_LIMIT]:"Daily transfers limit reached",[Pe.TRANSFER_FAILED]:"File transfer failed",[Pe.TRANSFER_EXPIRED]:"Transfer expired",[Pe.TRANSFER_CANCELLED]:"Transfer cancelled",[Pe.CHECKSUM_MISMATCH]:"File checksum mismatch",[Pe.CHUNK_MISSING]:"Chunk missing or corrupted",[Pe.INVALID_MESSAGE]:"Invalid message format",[Pe.UNSUPPORTED_VERSION]:"Unsupported protocol version",[Pe.CAPABILITY_REQUIRED]:"Required capability not supported",[Pe.INVALID_STATE]:"Invalid state for this operation",[Pe.TIMEOUT]:"Operation timed out",[Pe.CONNECTION_LOST]:"Connection lost",[Pe.INTERNAL_ERROR]:"Internal server error",[Pe.SERVICE_UNAVAILABLE]:"Service temporarily unavailable",[Pe.HANDSHAKE_UNAUTHORIZED]:"Authentication failed",[Pe.HANDSHAKE_FORBIDDEN]:"Connection not allowed by plan"};function am(r,e={}){return{code:r,message:e.message||kr.ERROR_MESSAGES[r],details:e.details,retryable:e.retryable??!1,retryAfter:e.retryAfter}}function cm(r){return[Pe.RATE_LIMITED,Pe.TIMEOUT,Pe.CONNECTION_LOST,Pe.SERVICE_UNAVAILABLE].includes(r)}});var Ru=I(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.SERVER_TO_AGENT_EVENT_NAMES=Wn.AGENT_EVENT_NAMES=void 0;Wn.AGENT_EVENT_NAMES=["ping","agent:rename","workspace:register","workspace:unregister","terminal:created","terminal:closed","terminal:notFound","terminal:output","terminal:status","terminal:event","agent:claimControl","agent:ptyResized","crypto:invalidSession","input:ack","input:resume","input:resend","agent:keyExchangeAck","file:changed","file:content","file:list:response","file:init","file:chunk","file:chunk:ack","file:end","file:complete","file:cancel","file:sync"];Wn.SERVER_TO_AGENT_EVENT_NAMES=["error","protocol:info","pong","agent:renamed","terminal:input","terminal:resize","terminal:createRequest","terminal:getBuffer","workspace:clientAttached","workspace:clientDetached","crypto:keyExchange","crypto:sessionCleanup","agent:keyExchangeRequest","meta:keyExchange","agent:sessionEnd","file:view","file:list","file:download:request","file:init","file:chunk","file:end","file:chunk:ack","file:cancel"]});var Iu=I(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.SCREEN_EVENTS=Ar.SCREEN_EVENT_PREFIX=void 0;Ar.isScreenEvent=fm;Ar.SCREEN_EVENT_PREFIX="screen:";Ar.SCREEN_EVENTS=["screen:request","screen:offer","screen:answer","screen:ice"];function fm(r){return typeof r=="string"&&r.length>Ar.SCREEN_EVENT_PREFIX.length&&r.startsWith(Ar.SCREEN_EVENT_PREFIX)}});var Du=I(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.FileEntryType=Rt.DiffBase=Rt.FileViewType=Rt.FileChangeType=void 0;Rt.getLanguageFromPath=um;Rt.parseUnifiedDiff=lm;Rt.createSimpleDiff=hm;var Gr;(function(r){r.CREATE="create",r.MODIFY="modify",r.DELETE="delete"})(Gr||(Rt.FileChangeType=Gr={}));var Lu;(function(r){r.CONTENT="content",r.DIFF="diff"})(Lu||(Rt.FileViewType=Lu={}));var Nu;(function(r){r.GIT="git",r.PREVIOUS="previous"})(Nu||(Rt.DiffBase=Nu={}));function um(r){let e=r.split(".").pop()?.toLowerCase(),t={js:"javascript",jsx:"javascript",ts:"typescript",tsx:"typescript",mjs:"javascript",cjs:"javascript",html:"html",htm:"html",css:"css",scss:"scss",sass:"scss",less:"less",json:"json",yaml:"yaml",yml:"yaml",xml:"xml",toml:"toml",md:"markdown",mdx:"markdown",env:"plaintext",gitignore:"plaintext",dockerignore:"plaintext",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",py:"python",pyw:"python",pyi:"python",go:"go",rs:"rust",java:"java",kt:"kotlin",kts:"kotlin",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp",hpp:"cpp",sql:"sql",graphql:"graphql",gql:"graphql",prisma:"prisma",dockerfile:"dockerfile"},n=r.split("/").pop()?.toLowerCase()||"";return{dockerfile:"dockerfile",makefile:"makefile",".gitignore":"plaintext",".env":"plaintext",".env.local":"plaintext",".env.development":"plaintext",".env.production":"plaintext"}[n]||t[e||""]||"plaintext"}function lm(r,e){let t=r.split(`
|
|
3
|
+
`),n=[],i=0,s=0,a=null,f=0,c=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&&n.push(a);let _=parseInt(m[1],10),b=parseInt(m[2]||"1",10),x=parseInt(m[3],10),O=parseInt(m[4]||"1",10);a={oldStart:_,oldLines:b,newStart:x,newLines:O,lines:[]},f=_,c=x;continue}a&&(p.startsWith("+")?(a.lines.push({type:"add",content:p.slice(1),oldLineNumber:null,newLineNumber:c++}),i++):p.startsWith("-")?(a.lines.push({type:"remove",content:p.slice(1),oldLineNumber:f++,newLineNumber:null}),s++):(p.startsWith(" ")||p==="")&&a.lines.push({type:"context",content:p.startsWith(" ")?p.slice(1):p,oldLineNumber:f++,newLineNumber:c++}))}a&&n.push(a);let l;return s===0&&i>0&&n.length===1&&n[0].oldLines===0?l=Gr.CREATE:i===0&&s>0&&n.length===1&&n[0].newLines===0?l=Gr.DELETE:l=Gr.MODIFY,{path:e,changeType:l,hunks:n,additions:i,deletions:s,isBinary:!1}}function hm(r,e,t){let n=r.split(`
|
|
4
4
|
`),i=e.split(`
|
|
5
|
-
`),s=[],a=0,f=0,c=Math.max(n.length,i.length);for(let p=0;p<c;p++){let m=n[p],_=i[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}),f++),_!==void 0&&(s.push({type:"add",content:_,oldLineNumber:null,newLineNumber:p+1}),a++))}let l;return r===""?l=Hr.CREATE:e===""?l=Hr.DELETE:l=Hr.MODIFY,{path:t,changeType:l,hunks:[{oldStart:1,oldLines:n.length,newStart:1,newLines:i.length,lines:s}],additions:a,deletions:f,isBinary:!1}}var Tu;(function(r){r.FILE="file",r.DIRECTORY="directory"})(Tu||(At.FileEntryType=Tu={}))});var Ou=L(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});A.FileEntryType=A.DiffBase=A.FileViewType=A.FileChangeType=A.isScreenEvent=A.SCREEN_EVENTS=A.SCREEN_EVENT_PREFIX=A.SERVER_TO_AGENT_EVENT_NAMES=A.AGENT_EVENT_NAMES=A.isRetryableError=A.createError=A.ERROR_MESSAGES=A.ErrorCode=A.isTransferComplete=A.getMissingChunks=A.calculateTotalChunks=A.TransferDirection=A.TransferStatus=A.CHUNK_TTL_SECONDS=A.TRANSFER_TTL_SECONDS=A.MAX_RETRIES=A.ACK_TIMEOUT_MS=A.WINDOW_SIZE=A.DEFAULT_MAX_FILE_SIZE=A.CHUNK_SIZE=A.getPushNotificationMessage=A.shouldTriggerPushNotification=A.deriveStatusFromEvent=A.TerminalEventType=A.createMessage=A.requiresBuffer=A.requiresAck=A.DEFAULT_RELIABILITY=A.RELIABILITY_NAMES=A.Reliability=A.comparePriority=A.DEFAULT_PRIORITY=A.PRIORITY_NAMES=A.Priority=A.negotiateCapabilities=A.hasCapability=A.SERVER_CAPABILITIES=A.DEFAULT_CLIENT_CAPABILITIES=A.Capability=A.compareVersions=A.isCompatibleVersion=A.MIN_CLIENT_VERSION=A.PROTOCOL_VERSION_MINOR=A.PROTOCOL_VERSION_MAJOR=A.PROTOCOL_VERSION=void 0;A.createSimpleDiff=A.parseUnifiedDiff=A.getLanguageFromPath=void 0;var Kn=lu();Object.defineProperty(A,"PROTOCOL_VERSION",{enumerable:!0,get:function(){return Kn.PROTOCOL_VERSION}});Object.defineProperty(A,"PROTOCOL_VERSION_MAJOR",{enumerable:!0,get:function(){return Kn.PROTOCOL_VERSION_MAJOR}});Object.defineProperty(A,"PROTOCOL_VERSION_MINOR",{enumerable:!0,get:function(){return Kn.PROTOCOL_VERSION_MINOR}});Object.defineProperty(A,"MIN_CLIENT_VERSION",{enumerable:!0,get:function(){return Kn.MIN_CLIENT_VERSION}});Object.defineProperty(A,"isCompatibleVersion",{enumerable:!0,get:function(){return Kn.isCompatibleVersion}});Object.defineProperty(A,"compareVersions",{enumerable:!0,get:function(){return Kn.compareVersions}});var ki=hu();Object.defineProperty(A,"Capability",{enumerable:!0,get:function(){return ki.Capability}});Object.defineProperty(A,"DEFAULT_CLIENT_CAPABILITIES",{enumerable:!0,get:function(){return ki.DEFAULT_CLIENT_CAPABILITIES}});Object.defineProperty(A,"SERVER_CAPABILITIES",{enumerable:!0,get:function(){return ki.SERVER_CAPABILITIES}});Object.defineProperty(A,"hasCapability",{enumerable:!0,get:function(){return ki.hasCapability}});Object.defineProperty(A,"negotiateCapabilities",{enumerable:!0,get:function(){return ki.negotiateCapabilities}});var xs=du();Object.defineProperty(A,"Priority",{enumerable:!0,get:function(){return xs.Priority}});Object.defineProperty(A,"PRIORITY_NAMES",{enumerable:!0,get:function(){return xs.PRIORITY_NAMES}});Object.defineProperty(A,"DEFAULT_PRIORITY",{enumerable:!0,get:function(){return xs.DEFAULT_PRIORITY}});Object.defineProperty(A,"comparePriority",{enumerable:!0,get:function(){return xs.comparePriority}});var Oi=pu();Object.defineProperty(A,"Reliability",{enumerable:!0,get:function(){return Oi.Reliability}});Object.defineProperty(A,"RELIABILITY_NAMES",{enumerable:!0,get:function(){return Oi.RELIABILITY_NAMES}});Object.defineProperty(A,"DEFAULT_RELIABILITY",{enumerable:!0,get:function(){return Oi.DEFAULT_RELIABILITY}});Object.defineProperty(A,"requiresAck",{enumerable:!0,get:function(){return Oi.requiresAck}});Object.defineProperty(A,"requiresBuffer",{enumerable:!0,get:function(){return Oi.requiresBuffer}});var Wg=gu();Object.defineProperty(A,"createMessage",{enumerable:!0,get:function(){return Wg.createMessage}});var Ts=mu();Object.defineProperty(A,"TerminalEventType",{enumerable:!0,get:function(){return Ts.TerminalEventType}});Object.defineProperty(A,"deriveStatusFromEvent",{enumerable:!0,get:function(){return Ts.deriveStatusFromEvent}});Object.defineProperty(A,"shouldTriggerPushNotification",{enumerable:!0,get:function(){return Ts.shouldTriggerPushNotification}});Object.defineProperty(A,"getPushNotificationMessage",{enumerable:!0,get:function(){return Ts.getPushNotificationMessage}});var Ft=Eu();Object.defineProperty(A,"CHUNK_SIZE",{enumerable:!0,get:function(){return Ft.CHUNK_SIZE}});Object.defineProperty(A,"DEFAULT_MAX_FILE_SIZE",{enumerable:!0,get:function(){return Ft.DEFAULT_MAX_FILE_SIZE}});Object.defineProperty(A,"WINDOW_SIZE",{enumerable:!0,get:function(){return Ft.WINDOW_SIZE}});Object.defineProperty(A,"ACK_TIMEOUT_MS",{enumerable:!0,get:function(){return Ft.ACK_TIMEOUT_MS}});Object.defineProperty(A,"MAX_RETRIES",{enumerable:!0,get:function(){return Ft.MAX_RETRIES}});Object.defineProperty(A,"TRANSFER_TTL_SECONDS",{enumerable:!0,get:function(){return Ft.TRANSFER_TTL_SECONDS}});Object.defineProperty(A,"CHUNK_TTL_SECONDS",{enumerable:!0,get:function(){return Ft.CHUNK_TTL_SECONDS}});Object.defineProperty(A,"TransferStatus",{enumerable:!0,get:function(){return Ft.TransferStatus}});Object.defineProperty(A,"TransferDirection",{enumerable:!0,get:function(){return Ft.TransferDirection}});Object.defineProperty(A,"calculateTotalChunks",{enumerable:!0,get:function(){return Ft.calculateTotalChunks}});Object.defineProperty(A,"getMissingChunks",{enumerable:!0,get:function(){return Ft.getMissingChunks}});Object.defineProperty(A,"isTransferComplete",{enumerable:!0,get:function(){return Ft.isTransferComplete}});var Cs=bu();Object.defineProperty(A,"ErrorCode",{enumerable:!0,get:function(){return Cs.ErrorCode}});Object.defineProperty(A,"ERROR_MESSAGES",{enumerable:!0,get:function(){return Cs.ERROR_MESSAGES}});Object.defineProperty(A,"createError",{enumerable:!0,get:function(){return Cs.createError}});Object.defineProperty(A,"isRetryableError",{enumerable:!0,get:function(){return Cs.isRetryableError}});var ku=vu();Object.defineProperty(A,"AGENT_EVENT_NAMES",{enumerable:!0,get:function(){return ku.AGENT_EVENT_NAMES}});Object.defineProperty(A,"SERVER_TO_AGENT_EVENT_NAMES",{enumerable:!0,get:function(){return ku.SERVER_TO_AGENT_EVENT_NAMES}});var oa=wu();Object.defineProperty(A,"SCREEN_EVENT_PREFIX",{enumerable:!0,get:function(){return oa.SCREEN_EVENT_PREFIX}});Object.defineProperty(A,"SCREEN_EVENTS",{enumerable:!0,get:function(){return oa.SCREEN_EVENTS}});Object.defineProperty(A,"isScreenEvent",{enumerable:!0,get:function(){return oa.isScreenEvent}});var gn=Cu();Object.defineProperty(A,"FileChangeType",{enumerable:!0,get:function(){return gn.FileChangeType}});Object.defineProperty(A,"FileViewType",{enumerable:!0,get:function(){return gn.FileViewType}});Object.defineProperty(A,"DiffBase",{enumerable:!0,get:function(){return gn.DiffBase}});Object.defineProperty(A,"FileEntryType",{enumerable:!0,get:function(){return gn.FileEntryType}});Object.defineProperty(A,"getLanguageFromPath",{enumerable:!0,get:function(){return gn.getLanguageFromPath}});Object.defineProperty(A,"parseUnifiedDiff",{enumerable:!0,get:function(){return gn.parseUnifiedDiff}});Object.defineProperty(A,"createSimpleDiff",{enumerable:!0,get:function(){return gn.createSimpleDiff}})});var Or=L(fr=>{"use strict";var Hg=fr&&fr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),ks=fr&&fr.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Hg(e,r,t)};Object.defineProperty(fr,"__esModule",{value:!0});ks(ru(),fr);ks(nu(),fr);ks(uu(),fr);ks(Ou(),fr)});var aa=L(Xe=>{"use strict";var Vg=Xe&&Xe.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Xe,"__esModule",{value:!0});Xe.FP_LABEL=Xe.KX_ACK_LABEL=Xe.KX_SIGN_LABEL=void 0;Xe.concatBytes=Pi;Xe.generateIdentityKeyPair=$g;Xe.identityPublicFromSecret=zg;Xe.signSessionKey=Gg;Xe.verifySessionKey=Yg;Xe.buildKxCanonical=Xg;Xe.buildKxAckCanonical=Jg;Xe.fingerprintIdentityKey=Zg;Xe.fingerprintShortHex=Qg;var ur=Vg(xi()),Rt=Ti();Xe.KX_SIGN_LABEL="termiq-kx-v1";Xe.KX_ACK_LABEL="termiq-kxack-v1";Xe.FP_LABEL="termiq-fp-v1";function Pi(...r){let e=0;for(let i of r)e+=i.length;let t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}function $g(){let r=ur.default.sign.keyPair();return{identityPublicKey:(0,Rt.encodeBase64)(r.publicKey),identitySecretKey:(0,Rt.encodeBase64)(r.secretKey)}}function zg(r){let e=(0,Rt.decodeBase64)(r);if(e.length!==ur.default.sign.secretKeyLength)throw new Error("bad identity secret key length");let t=ur.default.sign.keyPair.fromSecretKey(e);return(0,Rt.encodeBase64)(t.publicKey)}function Gg(r,e){let t=(0,Rt.decodeBase64)(e);if(t.length!==ur.default.sign.secretKeyLength)throw new Error("bad identity secret key length");return(0,Rt.encodeBase64)(ur.default.sign.detached(r,t))}function Yg(r,e,t){try{let n=(0,Rt.decodeBase64)(e),i=(0,Rt.decodeBase64)(t);return i.length!==ur.default.sign.publicKeyLength||n.length!==ur.default.sign.signatureLength?!1:ur.default.sign.detached.verify(r,n,i)}catch{return!1}}var mn=new Uint8Array([0]);function Xg(r){let e=new TextEncoder,t=e.encode(Xe.KX_SIGN_LABEL),n=e.encode(r.agentId),i=e.encode(String(r.keyVersion)),s=(0,Rt.decodeBase64)(r.boxPublicKey);return Pi(t,mn,n,mn,i,mn,s)}function Jg(r){let e=new TextEncoder;return Pi(e.encode(Xe.KX_ACK_LABEL),mn,e.encode(r.agentId),mn,e.encode(String(r.keyVersion)),mn,(0,Rt.decodeBase64)(r.boxPublicKey),mn,(0,Rt.decodeBase64)(r.boundClientKey))}function Zg(r){let e=(0,Rt.decodeBase64)(r),t=Pi(new TextEncoder().encode(Xe.FP_LABEL),e),n=ur.default.hash(t),i=[];for(let s=0;s<12;s++){let a=s*5,c=(((n[a]<<24>>>0)+(n[a+1]<<16)+(n[a+2]<<8)+n[a+3]^n[a+4])>>>0)%1e5;i.push(String(c).padStart(5,"0"))}return i.join(" ")}function Qg(r){let e=(0,Rt.decodeBase64)(r),t=Pi(new TextEncoder().encode(Xe.FP_LABEL),e),n=ur.default.hash(t).slice(0,8);return Array.from(n).map(i=>i.toString(16).padStart(2,"0")).join(":").toUpperCase()}});var Au=L(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});Os.CryptoService=void 0;var st=Or(),Vr=aa(),em=3600*1e3,Pu=10,ca=class{storage;logger;sessions=new Map;agentSessions=new Map;metaSessions=new Map;keyPair=null;identityKeyPair=null;publicKeyKey;secretKeyKey;keyVersionKey;identityPublicKeyKey;identitySecretKeyKey;constructor(e,t,n,i){this.storage=e,this.logger=t;let s=`termiq.${n}.${i}`;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",n,i)}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,st.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,Vr.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,Vr.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(),n=await this.getKeyVersion(),i=this.keyPair.publicKey,s=(0,Vr.buildKxCanonical)({agentId:e,keyVersion:n,boxPublicKey:i}),a=(0,Vr.signSessionKey)(s,t.identitySecretKey);return{boxPublicKey:i,identityPublicKey:t.identityPublicKey,keyVersion:n,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 n=await this.ensureIdentityKeyPair(),i=await this.getKeyVersion(),s=(0,Vr.buildKxAckCanonical)({agentId:e,keyVersion:i,boxPublicKey:this.keyPair.publicKey,boundClientKey:t});return(0,Vr.signSessionKey)(s,n.identitySecretKey)}async getSafetyNumber(){let e=await this.ensureIdentityKeyPair();return(0,Vr.fingerprintIdentityKey)(e.identityPublicKey)}async getShortFingerprint(){let e=await this.ensureIdentityKeyPair();return(0,Vr.fingerprintShortHex)(e.identityPublicKey)}async handleKeyExchange(e,t,n){if(!this.keyPair&&(this.logger.warn("Key pair missing, attempting re-initialization"),await this.initialize(),!this.keyPair))return this.logger.error("No identity key pair available after re-initialization"),!1;this.logger.info("Starting key exchange",e,n);try{let i=this.sessions.get(e);i||(i=new Map,this.sessions.set(e,i));let s=(0,st.deriveSharedSecret)(t,this.keyPair.secretKey),a={terminalId:e,clientPublicKey:t,sharedSecret:s,createdAt:Date.now(),sessionId:n};return i.set(n,a),this.logger.info("Key exchange completed",e,n,"total:",i.size),!0}catch(i){return this.logger.error("Key exchange failed",i),!1}}encryptOutput(e,t){let n=this.sessions.get(e);if(!n||n.size===0)return null;try{if(n.size===1){let s=n.values().next().value;return s?(0,st.encrypt)(t,s.sharedSecret,s.sessionId):null}let i=[];for(let s of n.values()){let a=(0,st.encrypt)(t,s.sharedSecret,s.sessionId);i.push({sid:a.sid,n:a.n,c:a.c})}return{v:2,recipients:i}}catch(i){return this.logger.error("Encryption failed",i),null}}decryptInput(e,t){let n=this.sessions.get(e);if(!n)return this.logger.error("No sessions for terminal",e),null;let i=n.get(t.sid);if(!i)return this.logger.error("No session for sessionId",t.sid),null;try{return(0,st.decrypt)(t,i.sharedSecret)}catch(s){return this.logger.error("Decryption failed",s),null}}encryptFileChunk(e,t){let n=this.sessions.get(e);if(!n||n.size===0)return null;let i=null;for(let s of n.values())(!i||s.createdAt>i.createdAt)&&(i=s);if(!i)return null;try{return(0,st.encryptBinary)(t,i.sharedSecret,i.sessionId)}catch(s){return this.logger.error("File chunk encryption failed",s),null}}decryptFileChunk(e,t){let n=this.sessions.get(e)?.get(t.sid);if(!n)return this.logger.error("No session for file chunk",e,t.sid),null;try{return(0,st.decryptBinary)(t,n.sharedSecret)}catch(i){return this.logger.error("File chunk decryption failed",i),null}}hasSession(e){let t=this.sessions.get(e);return t!==void 0&&t.size>0}removeSession(e,t){let n=this.sessions.get(e);if(n)if(t){let i=n.get(t);i&&((0,st.clearKey)(i.sharedSecret),n.delete(t),this.logger.info("Session removed",e,t)),n.size===0&&this.sessions.delete(e)}else{for(let i of n.values())(0,st.clearKey)(i.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,st.clearKey)(t.sharedSecret);this.sessions.clear(),this.logger.debug("All sessions cleared")}cleanupStaleSessions(e){let t=this.sessions.get(e);if(!t||t.size===0)return;let n=Date.now(),i=[];for(let[s,a]of t)n-a.createdAt>em&&i.push(s);for(let s of i){let a=t.get(s);a&&((0,st.clearKey)(a.sharedSecret),t.delete(s),this.logger.info("Session expired (TTL)",e,s,`age:${Math.round((n-a.createdAt)/1e3)}s`))}if(t.size>Pu){let a=Array.from(t.entries()).sort((f,c)=>f[1].createdAt-c[1].createdAt).slice(0,t.size-Pu);for(let[,f]of a)(0,st.clearKey)(f.sharedSecret),t.delete(f.sessionId)}t.size===0&&this.sessions.delete(e)}cleanupAllStaleSessions(){for(let e of this.sessions.keys())this.cleanupStaleSessions(e)}getSessionInfo(){let e=[];for(let[t,n]of this.sessions.entries())for(let i of n.values())e.push({terminalId:t,createdAt:i.createdAt,sessionId:i.sessionId});return e}async handleAgentKeyExchange(e,t){if(!this.keyPair&&(this.logger.warn("Key pair missing for agent key exchange"),await this.initialize(),!this.keyPair))return this.logger.error("No identity key pair available for agent key exchange"),!1;try{let n=this.agentSessions.get(t);n&&(this.logger.info("Rekeying existing agent session",t),(0,st.clearKey)(n.sharedSecret));let i=(0,st.deriveSharedSecret)(e,this.keyPair.secretKey),s={sessionId:t,clientPublicKey:e,sharedSecret:i,createdAt:Date.now()};return this.agentSessions.set(t,s),this.logger.info("Agent key exchange completed",t,"total:",this.agentSessions.size),!0}catch(n){return this.logger.error("Agent key exchange failed",n),!1}}removeAgentSession(e){let t=this.agentSessions.get(e);t&&((0,st.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),n=(0,st.deriveSharedSecret)(e,this.keyPair.secretKey),i=(0,st.deriveMetaSid)(this.keyPair.publicKey,e);return this.metaSessions.set(e,{clientIdentityPub:e,sharedSecret:n,sidMeta:i}),this.logger.info("Meta key exchange completed",i,"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 n=this.metaSessions.values().next().value;return n?(0,st.encrypt)(e,n.sharedSecret,n.sidMeta):null}let t=[];for(let n of this.metaSessions.values()){let i=(0,st.encrypt)(e,n.sharedSecret,n.sidMeta);t.push({sid:i.sid,n:i.n,c:i.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,st.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")}};Os.CryptoService=ca});var Ru=L(Ps=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});Ps.AuthService=void 0;var Ai=gs(),fa=class{storage;cryptoService;machineId;config;logger;notification;browser;pollingAbortController=null;tokenKey;refreshTokenKey;agentIdKey;constructor(e,t,n,i,s,a,f,c,l){this.storage=e,this.cryptoService=t,this.machineId=n,this.config=i,this.logger=s,this.notification=a,this.browser=f;let p=`termiq.${c}.${l}`;this.tokenKey=`${p}.accessToken`,this.refreshTokenKey=`${p}.refreshToken`,this.agentIdKey=`${p}.agentId`,this.logger.info("AuthService namespace",c,l)}cancelPolling(){this.pollingAbortController&&(this.logger.info("Cancelling active polling"),this.pollingAbortController.abort(),this.pollingAbortController=null)}async startDeviceCodeFlow(){this.cancelPolling();let e=(0,Ai.getApiUrl)(this.config),t=await this.machineId.getMachineId(),n=this.machineId.getMachineName(),i=await this.cryptoService.getPublicKey();i||(await this.cryptoService.generateIdentityKeyPair(),i=await this.cryptoService.getPublicKey()),this.logger.info("Starting device code flow",t,n);let s=await fetch(`${e}/auth/device/code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machineId:t,machineName:n,publicKey:i})});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,Ai.getApiUrl)(this.config),n=5e3,i=60;this.pollingAbortController=new AbortController;let s=this.pollingAbortController.signal;this.logger.info("Starting token polling");for(let a=0;a<i;a++){if(s.aborted)return this.logger.info("Polling was cancelled"),null;if(await this.sleep(n),s.aborted)return this.logger.info("Polling was cancelled"),null;try{let f=await fetch(`${t}/auth/device/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:e}),signal:s});if(!f.ok){if(f.status===403)try{let l=await f.json();if(l.error==="AGENT_LIMIT_EXCEEDED")return this.logger.warn("Agent limit exceeded",String(l.current),"/",String(l.max)),this.notification.warn(`Agent limit reached (${l.current}/${l.max}). Upgrade your plan to add more devices.`),null}catch{}this.logger.warn("Poll request failed",String(f.status));continue}let c=await f.json();if(c.status==="success"&&c.accessToken)return this.logger.info("Token received successfully"),this.pollingAbortController=null,await this.saveTokens(c),c;if(c.status==="expired")return this.logger.warn("Device code expired"),null;if(c.status==="limit_exceeded")return this.logger.warn("Agent limit exceeded",String(c.current),"/",String(c.max)),this.notification.warn(`Agent limit reached (${c.current}/${c.max}). Remove an old agent or upgrade your plan.`),null;this.logger.debug("Token pending, continuing poll",String(a))}catch(f){if(s.aborted)return this.logger.info("Polling was cancelled"),null;let c=f instanceof Error?f.message:String(f);this.logger.warn(`Poll error: ${c}`)}}return this.logger.warn("Polling timed out"),this.pollingAbortController=null,null}async loginWithApiKey(e){let t=(0,Ai.getApiUrl)(this.config),n=await this.machineId.getMachineId(),i=this.machineId.getMachineName(),s=await this.cryptoService.getPublicKey();s||(await this.cryptoService.generateIdentityKeyPair(),s=await this.cryptoService.getPublicKey()),this.logger.info("Logging in with API key");try{let a=await fetch(`${t}/auth/api-key/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e,machineId:n,machineName:i,publicKey:s})});if(!a.ok){let c=await a.text();return this.logger.error("API key login failed",c),!1}let f=await a.json();return f.accessToken?(await this.saveTokens(f),this.logger.info("API key login successful"),!0):!1}catch(a){return this.logger.error("API key login error",a),!1}}async hasValidToken(){let e=await this.storage.get(this.tokenKey);if(!e)return!1;try{let n=JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()).exp*1e3;return Date.now()<n}catch{return!1}}async getAccessToken(){return await this.storage.get(this.tokenKey)||null}async getAgentId(){return await this.storage.get(this.agentIdKey)||null}async refreshAccessToken(){let e=await this.storage.get(this.refreshTokenKey);if(!e)return this.logger.debug("No refresh token available"),null;let t=(0,Ai.getApiUrl)(this.config);try{this.logger.info("Refreshing access token");let n=await fetch(`${t}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!n.ok)return this.logger.warn("Token refresh failed",String(n.status)),n.status===401&&await this.storage.delete(this.refreshTokenKey),null;let i=await n.json();return await this.storage.set(this.tokenKey,i.accessToken),await this.storage.set(this.refreshTokenKey,i.refreshToken),this.logger.info("Access token refreshed successfully"),i.accessToken}catch(n){return this.logger.warn("Token refresh error",n),null}}async logout(){this.logger.info("Logging out"),this.cancelPolling(),await this.storage.delete(this.tokenKey),await this.storage.delete(this.refreshTokenKey),await this.storage.delete(this.agentIdKey),await this.cryptoService.deleteKeys()}async saveTokens(e){e.accessToken&&await this.storage.set(this.tokenKey,e.accessToken),e.refreshToken&&await this.storage.set(this.refreshTokenKey,e.refreshToken),e.agentId&&await this.storage.set(this.agentIdKey,e.agentId)}async getLimits(){let e=await this.getAccessToken();if(!e)return this.logger.warn("Cannot fetch limits: no access token"),null;let t=(0,Ai.getApiUrl)(this.config);try{let n=await fetch(`${t}/users/me/limits`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});return n.ok?await n.json():(this.logger.error("Failed to fetch limits",String(n.status)),null)}catch(n){let i=n instanceof Error?n.message:String(n);return this.logger.error(`Error fetching limits: ${i}`),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))}};Ps.AuthService=fa});var Iu=L(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});As.scanOsc=nm;As.classifyTitle=sm;var tm=4096,ua=/\x1b\]([^\x1b\x07]*)(?:\x07|\x1b\\)/g,rm="\x1B]";function nm(r,e=""){let t=e+r,n=[];ua.lastIndex=0;let i=0,s;for(;(s=ua.exec(t))!==null;)n.push(s[1]),i=ua.lastIndex;let a=t.slice(i),f=a.lastIndexOf(rm),c=f===-1?"":a.slice(f),l=c.indexOf("\x1B",1);return l!==-1&&l!==c.length-1&&(c=""),c.length>tm&&(c=""),{seqs:n,carry:c}}var im=/^([012]);([\s\S]*)$/;function sm(r){let e=r.match(im);if(!e)return null;let t=e[2].trim();return t?t.includes("Action Required")?{agent:t.startsWith("\u270B")?"gemini":/^\[\s*[!.]\s*\]/.test(t)?"codex":null,state:"waiting",title:t}:t.startsWith("\u2726")||t.startsWith("\u23F2")?{agent:"gemini",state:"working",title:t}:t.startsWith("\u25C7")?{agent:"gemini",state:"idle",title:t}:t.startsWith("\u25D0")||t.startsWith("\u25D1")?{agent:"claude",state:"working",title:t}:t.startsWith("\u2733")?{agent:"claude",state:"unknown",title:t}:{agent:null,state:"unknown",title:t}:{agent:null,state:"unknown",title:""}}});var Mu=L(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.MAX_TAIL_PLAIN=Ue.MAX_TAIL_WITH_SELECTOR=Ue.MAX_LABEL_LEN=Ue.MAX_QUESTION_LEN=Ue.classifyTitle=Ue.scanOsc=void 0;Ue.stripAnsi=ha;Ue.normalizeBuffer=Nu;Ue.clampQuestion=la;Ue.hasMenuSelector=am;Ue.hasBareComposer=fm;Ue.promptKey=um;Ue.extractQuestion=lm;Ue.extractNumberedChoices=hm;var Lu=Iu();Object.defineProperty(Ue,"scanOsc",{enumerable:!0,get:function(){return Lu.scanOsc}});Object.defineProperty(Ue,"classifyTitle",{enumerable:!0,get:function(){return Lu.classifyTitle}});Ue.MAX_QUESTION_LEN=160;Ue.MAX_LABEL_LEN=100;Ue.MAX_TAIL_WITH_SELECTOR=12;Ue.MAX_TAIL_PLAIN=2;function ha(r){return r.replace(/\x1b\[[0-9]*[GC]/g," ").replace(/\x1b\[[0-9;?]*[a-zA-Z]/g,"").replace(/\x1b\][^\x1b\x07]*(?:\x07|\x1b\\)/g,"").replace(/\x1b[()][AB012]/g,"").replace(/\x1b[=>]/g,"").replace(/\x1b[78DMEHc]/g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g,"")}function Nu(r){return r.replace(/\r\n/g,`
|
|
5
|
+
`),s=[],a=0,f=0,c=Math.max(n.length,i.length);for(let p=0;p<c;p++){let m=n[p],_=i[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}),f++),_!==void 0&&(s.push({type:"add",content:_,oldLineNumber:null,newLineNumber:p+1}),a++))}let l;return r===""?l=Gr.CREATE:e===""?l=Gr.DELETE:l=Gr.MODIFY,{path:t,changeType:l,hunks:[{oldStart:1,oldLines:n.length,newStart:1,newLines:i.length,lines:s}],additions:a,deletions:f,isBinary:!1}}var Mu;(function(r){r.FILE="file",r.DIRECTORY="directory"})(Mu||(Rt.FileEntryType=Mu={}))});var Bu=I(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});A.FileEntryType=A.DiffBase=A.FileViewType=A.FileChangeType=A.isScreenEvent=A.SCREEN_EVENTS=A.SCREEN_EVENT_PREFIX=A.SERVER_TO_AGENT_EVENT_NAMES=A.AGENT_EVENT_NAMES=A.isRetryableError=A.createError=A.ERROR_MESSAGES=A.ErrorCode=A.isTransferComplete=A.getMissingChunks=A.calculateTotalChunks=A.TransferDirection=A.TransferStatus=A.CHUNK_TTL_SECONDS=A.TRANSFER_TTL_SECONDS=A.MAX_RETRIES=A.ACK_TIMEOUT_MS=A.WINDOW_SIZE=A.DEFAULT_MAX_FILE_SIZE=A.CHUNK_SIZE=A.getPushNotificationMessage=A.shouldTriggerPushNotification=A.deriveStatusFromEvent=A.TerminalEventType=A.createMessage=A.requiresBuffer=A.requiresAck=A.DEFAULT_RELIABILITY=A.RELIABILITY_NAMES=A.Reliability=A.comparePriority=A.DEFAULT_PRIORITY=A.PRIORITY_NAMES=A.Priority=A.negotiateCapabilities=A.hasCapability=A.SERVER_CAPABILITIES=A.DEFAULT_CLIENT_CAPABILITIES=A.Capability=A.compareVersions=A.isCompatibleVersion=A.MIN_CLIENT_VERSION=A.PROTOCOL_VERSION_MINOR=A.PROTOCOL_VERSION_MAJOR=A.PROTOCOL_VERSION=void 0;A.createSimpleDiff=A.parseUnifiedDiff=A.getLanguageFromPath=void 0;var Hn=wu();Object.defineProperty(A,"PROTOCOL_VERSION",{enumerable:!0,get:function(){return Hn.PROTOCOL_VERSION}});Object.defineProperty(A,"PROTOCOL_VERSION_MAJOR",{enumerable:!0,get:function(){return Hn.PROTOCOL_VERSION_MAJOR}});Object.defineProperty(A,"PROTOCOL_VERSION_MINOR",{enumerable:!0,get:function(){return Hn.PROTOCOL_VERSION_MINOR}});Object.defineProperty(A,"MIN_CLIENT_VERSION",{enumerable:!0,get:function(){return Hn.MIN_CLIENT_VERSION}});Object.defineProperty(A,"isCompatibleVersion",{enumerable:!0,get:function(){return Hn.isCompatibleVersion}});Object.defineProperty(A,"compareVersions",{enumerable:!0,get:function(){return Hn.compareVersions}});var ki=vu();Object.defineProperty(A,"Capability",{enumerable:!0,get:function(){return ki.Capability}});Object.defineProperty(A,"DEFAULT_CLIENT_CAPABILITIES",{enumerable:!0,get:function(){return ki.DEFAULT_CLIENT_CAPABILITIES}});Object.defineProperty(A,"SERVER_CAPABILITIES",{enumerable:!0,get:function(){return ki.SERVER_CAPABILITIES}});Object.defineProperty(A,"hasCapability",{enumerable:!0,get:function(){return ki.hasCapability}});Object.defineProperty(A,"negotiateCapabilities",{enumerable:!0,get:function(){return ki.negotiateCapabilities}});var Cs=Su();Object.defineProperty(A,"Priority",{enumerable:!0,get:function(){return Cs.Priority}});Object.defineProperty(A,"PRIORITY_NAMES",{enumerable:!0,get:function(){return Cs.PRIORITY_NAMES}});Object.defineProperty(A,"DEFAULT_PRIORITY",{enumerable:!0,get:function(){return Cs.DEFAULT_PRIORITY}});Object.defineProperty(A,"comparePriority",{enumerable:!0,get:function(){return Cs.comparePriority}});var Ai=xu();Object.defineProperty(A,"Reliability",{enumerable:!0,get:function(){return Ai.Reliability}});Object.defineProperty(A,"RELIABILITY_NAMES",{enumerable:!0,get:function(){return Ai.RELIABILITY_NAMES}});Object.defineProperty(A,"DEFAULT_RELIABILITY",{enumerable:!0,get:function(){return Ai.DEFAULT_RELIABILITY}});Object.defineProperty(A,"requiresAck",{enumerable:!0,get:function(){return Ai.requiresAck}});Object.defineProperty(A,"requiresBuffer",{enumerable:!0,get:function(){return Ai.requiresBuffer}});var dm=Tu();Object.defineProperty(A,"createMessage",{enumerable:!0,get:function(){return dm.createMessage}});var Ps=Ou();Object.defineProperty(A,"TerminalEventType",{enumerable:!0,get:function(){return Ps.TerminalEventType}});Object.defineProperty(A,"deriveStatusFromEvent",{enumerable:!0,get:function(){return Ps.deriveStatusFromEvent}});Object.defineProperty(A,"shouldTriggerPushNotification",{enumerable:!0,get:function(){return Ps.shouldTriggerPushNotification}});Object.defineProperty(A,"getPushNotificationMessage",{enumerable:!0,get:function(){return Ps.getPushNotificationMessage}});var Bt=ku();Object.defineProperty(A,"CHUNK_SIZE",{enumerable:!0,get:function(){return Bt.CHUNK_SIZE}});Object.defineProperty(A,"DEFAULT_MAX_FILE_SIZE",{enumerable:!0,get:function(){return Bt.DEFAULT_MAX_FILE_SIZE}});Object.defineProperty(A,"WINDOW_SIZE",{enumerable:!0,get:function(){return Bt.WINDOW_SIZE}});Object.defineProperty(A,"ACK_TIMEOUT_MS",{enumerable:!0,get:function(){return Bt.ACK_TIMEOUT_MS}});Object.defineProperty(A,"MAX_RETRIES",{enumerable:!0,get:function(){return Bt.MAX_RETRIES}});Object.defineProperty(A,"TRANSFER_TTL_SECONDS",{enumerable:!0,get:function(){return Bt.TRANSFER_TTL_SECONDS}});Object.defineProperty(A,"CHUNK_TTL_SECONDS",{enumerable:!0,get:function(){return Bt.CHUNK_TTL_SECONDS}});Object.defineProperty(A,"TransferStatus",{enumerable:!0,get:function(){return Bt.TransferStatus}});Object.defineProperty(A,"TransferDirection",{enumerable:!0,get:function(){return Bt.TransferDirection}});Object.defineProperty(A,"calculateTotalChunks",{enumerable:!0,get:function(){return Bt.calculateTotalChunks}});Object.defineProperty(A,"getMissingChunks",{enumerable:!0,get:function(){return Bt.getMissingChunks}});Object.defineProperty(A,"isTransferComplete",{enumerable:!0,get:function(){return Bt.isTransferComplete}});var ks=Au();Object.defineProperty(A,"ErrorCode",{enumerable:!0,get:function(){return ks.ErrorCode}});Object.defineProperty(A,"ERROR_MESSAGES",{enumerable:!0,get:function(){return ks.ERROR_MESSAGES}});Object.defineProperty(A,"createError",{enumerable:!0,get:function(){return ks.createError}});Object.defineProperty(A,"isRetryableError",{enumerable:!0,get:function(){return ks.isRetryableError}});var Fu=Ru();Object.defineProperty(A,"AGENT_EVENT_NAMES",{enumerable:!0,get:function(){return Fu.AGENT_EVENT_NAMES}});Object.defineProperty(A,"SERVER_TO_AGENT_EVENT_NAMES",{enumerable:!0,get:function(){return Fu.SERVER_TO_AGENT_EVENT_NAMES}});var ha=Iu();Object.defineProperty(A,"SCREEN_EVENT_PREFIX",{enumerable:!0,get:function(){return ha.SCREEN_EVENT_PREFIX}});Object.defineProperty(A,"SCREEN_EVENTS",{enumerable:!0,get:function(){return ha.SCREEN_EVENTS}});Object.defineProperty(A,"isScreenEvent",{enumerable:!0,get:function(){return ha.isScreenEvent}});var _n=Du();Object.defineProperty(A,"FileChangeType",{enumerable:!0,get:function(){return _n.FileChangeType}});Object.defineProperty(A,"FileViewType",{enumerable:!0,get:function(){return _n.FileViewType}});Object.defineProperty(A,"DiffBase",{enumerable:!0,get:function(){return _n.DiffBase}});Object.defineProperty(A,"FileEntryType",{enumerable:!0,get:function(){return _n.FileEntryType}});Object.defineProperty(A,"getLanguageFromPath",{enumerable:!0,get:function(){return _n.getLanguageFromPath}});Object.defineProperty(A,"parseUnifiedDiff",{enumerable:!0,get:function(){return _n.parseUnifiedDiff}});Object.defineProperty(A,"createSimpleDiff",{enumerable:!0,get:function(){return _n.createSimpleDiff}})});var Rr=I(hr=>{"use strict";var pm=hr&&hr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),As=hr&&hr.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&pm(e,r,t)};Object.defineProperty(hr,"__esModule",{value:!0});As(hu(),hr);As(du(),hr);As(bu(),hr);As(Bu(),hr)});var da=I(Xe=>{"use strict";var gm=Xe&&Xe.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Xe,"__esModule",{value:!0});Xe.FP_LABEL=Xe.KX_ACK_LABEL=Xe.KX_SIGN_LABEL=void 0;Xe.concatBytes=Ri;Xe.generateIdentityKeyPair=mm;Xe.identityPublicFromSecret=ym;Xe.signSessionKey=_m;Xe.verifySessionKey=Em;Xe.buildKxCanonical=bm;Xe.buildKxAckCanonical=wm;Xe.fingerprintIdentityKey=vm;Xe.fingerprintShortHex=Sm;var dr=gm(Oi()),It=Ci();Xe.KX_SIGN_LABEL="termiq-kx-v1";Xe.KX_ACK_LABEL="termiq-kxack-v1";Xe.FP_LABEL="termiq-fp-v1";function Ri(...r){let e=0;for(let i of r)e+=i.length;let t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}function mm(){let r=dr.default.sign.keyPair();return{identityPublicKey:(0,It.encodeBase64)(r.publicKey),identitySecretKey:(0,It.encodeBase64)(r.secretKey)}}function ym(r){let e=(0,It.decodeBase64)(r);if(e.length!==dr.default.sign.secretKeyLength)throw new Error("bad identity secret key length");let t=dr.default.sign.keyPair.fromSecretKey(e);return(0,It.encodeBase64)(t.publicKey)}function _m(r,e){let t=(0,It.decodeBase64)(e);if(t.length!==dr.default.sign.secretKeyLength)throw new Error("bad identity secret key length");return(0,It.encodeBase64)(dr.default.sign.detached(r,t))}function Em(r,e,t){try{let n=(0,It.decodeBase64)(e),i=(0,It.decodeBase64)(t);return i.length!==dr.default.sign.publicKeyLength||n.length!==dr.default.sign.signatureLength?!1:dr.default.sign.detached.verify(r,n,i)}catch{return!1}}var En=new Uint8Array([0]);function bm(r){let e=new TextEncoder,t=e.encode(Xe.KX_SIGN_LABEL),n=e.encode(r.agentId),i=e.encode(String(r.keyVersion)),s=(0,It.decodeBase64)(r.boxPublicKey);return Ri(t,En,n,En,i,En,s)}function wm(r){let e=new TextEncoder;return Ri(e.encode(Xe.KX_ACK_LABEL),En,e.encode(r.agentId),En,e.encode(String(r.keyVersion)),En,(0,It.decodeBase64)(r.boxPublicKey),En,(0,It.decodeBase64)(r.boundClientKey))}function vm(r){let e=(0,It.decodeBase64)(r),t=Ri(new TextEncoder().encode(Xe.FP_LABEL),e),n=dr.default.hash(t),i=[];for(let s=0;s<12;s++){let a=s*5,c=(((n[a]<<24>>>0)+(n[a+1]<<16)+(n[a+2]<<8)+n[a+3]^n[a+4])>>>0)%1e5;i.push(String(c).padStart(5,"0"))}return i.join(" ")}function Sm(r){let e=(0,It.decodeBase64)(r),t=Ri(new TextEncoder().encode(Xe.FP_LABEL),e),n=dr.default.hash(t).slice(0,8);return Array.from(n).map(i=>i.toString(16).padStart(2,"0")).join(":").toUpperCase()}});var Uu=I(Rs=>{"use strict";Object.defineProperty(Rs,"__esModule",{value:!0});Rs.CryptoService=void 0;var st=Rr(),zr=da(),xm=3600*1e3,ju=10,pa=class{storage;logger;sessions=new Map;agentSessions=new Map;metaSessions=new Map;keyPair=null;identityKeyPair=null;publicKeyKey;secretKeyKey;keyVersionKey;identityPublicKeyKey;identitySecretKeyKey;constructor(e,t,n,i){this.storage=e,this.logger=t;let s=`termiq.${n}.${i}`;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",n,i)}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,st.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,zr.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,zr.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(),n=await this.getKeyVersion(),i=this.keyPair.publicKey,s=(0,zr.buildKxCanonical)({agentId:e,keyVersion:n,boxPublicKey:i}),a=(0,zr.signSessionKey)(s,t.identitySecretKey);return{boxPublicKey:i,identityPublicKey:t.identityPublicKey,keyVersion:n,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 n=await this.ensureIdentityKeyPair(),i=await this.getKeyVersion(),s=(0,zr.buildKxAckCanonical)({agentId:e,keyVersion:i,boxPublicKey:this.keyPair.publicKey,boundClientKey:t});return(0,zr.signSessionKey)(s,n.identitySecretKey)}async getSafetyNumber(){let e=await this.ensureIdentityKeyPair();return(0,zr.fingerprintIdentityKey)(e.identityPublicKey)}async getShortFingerprint(){let e=await this.ensureIdentityKeyPair();return(0,zr.fingerprintShortHex)(e.identityPublicKey)}async handleKeyExchange(e,t,n){if(!this.keyPair&&(this.logger.warn("Key pair missing, attempting re-initialization"),await this.initialize(),!this.keyPair))return this.logger.error("No identity key pair available after re-initialization"),!1;this.logger.info("Starting key exchange",e,n);try{let i=this.sessions.get(e);i||(i=new Map,this.sessions.set(e,i));let s=(0,st.deriveSharedSecret)(t,this.keyPair.secretKey),a={terminalId:e,clientPublicKey:t,sharedSecret:s,createdAt:Date.now(),sessionId:n};return i.set(n,a),this.logger.info("Key exchange completed",e,n,"total:",i.size),!0}catch(i){return this.logger.error("Key exchange failed",i),!1}}encryptOutput(e,t){let n=this.sessions.get(e);if(!n||n.size===0)return null;try{if(n.size===1){let s=n.values().next().value;return s?(0,st.encrypt)(t,s.sharedSecret,s.sessionId):null}let i=[];for(let s of n.values()){let a=(0,st.encrypt)(t,s.sharedSecret,s.sessionId);i.push({sid:a.sid,n:a.n,c:a.c})}return{v:2,recipients:i}}catch(i){return this.logger.error("Encryption failed",i),null}}decryptInput(e,t){let n=this.sessions.get(e);if(!n)return this.logger.error("No sessions for terminal",e),null;let i=n.get(t.sid);if(!i)return this.logger.error("No session for sessionId",t.sid),null;try{return(0,st.decrypt)(t,i.sharedSecret)}catch(s){return this.logger.error("Decryption failed",s),null}}encryptFileChunk(e,t){let n=this.sessions.get(e);if(!n||n.size===0)return null;let i=null;for(let s of n.values())(!i||s.createdAt>i.createdAt)&&(i=s);if(!i)return null;try{return(0,st.encryptBinary)(t,i.sharedSecret,i.sessionId)}catch(s){return this.logger.error("File chunk encryption failed",s),null}}decryptFileChunk(e,t){let n=this.sessions.get(e)?.get(t.sid);if(!n)return this.logger.error("No session for file chunk",e,t.sid),null;try{return(0,st.decryptBinary)(t,n.sharedSecret)}catch(i){return this.logger.error("File chunk decryption failed",i),null}}hasSession(e){let t=this.sessions.get(e);return t!==void 0&&t.size>0}removeSession(e,t){let n=this.sessions.get(e);if(n)if(t){let i=n.get(t);i&&((0,st.clearKey)(i.sharedSecret),n.delete(t),this.logger.info("Session removed",e,t)),n.size===0&&this.sessions.delete(e)}else{for(let i of n.values())(0,st.clearKey)(i.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,st.clearKey)(t.sharedSecret);this.sessions.clear(),this.logger.debug("All sessions cleared")}cleanupStaleSessions(e){let t=this.sessions.get(e);if(!t||t.size===0)return;let n=Date.now(),i=[];for(let[s,a]of t)n-a.createdAt>xm&&i.push(s);for(let s of i){let a=t.get(s);a&&((0,st.clearKey)(a.sharedSecret),t.delete(s),this.logger.info("Session expired (TTL)",e,s,`age:${Math.round((n-a.createdAt)/1e3)}s`))}if(t.size>ju){let a=Array.from(t.entries()).sort((f,c)=>f[1].createdAt-c[1].createdAt).slice(0,t.size-ju);for(let[,f]of a)(0,st.clearKey)(f.sharedSecret),t.delete(f.sessionId)}t.size===0&&this.sessions.delete(e)}cleanupAllStaleSessions(){for(let e of this.sessions.keys())this.cleanupStaleSessions(e)}getSessionInfo(){let e=[];for(let[t,n]of this.sessions.entries())for(let i of n.values())e.push({terminalId:t,createdAt:i.createdAt,sessionId:i.sessionId});return e}async handleAgentKeyExchange(e,t){if(!this.keyPair&&(this.logger.warn("Key pair missing for agent key exchange"),await this.initialize(),!this.keyPair))return this.logger.error("No identity key pair available for agent key exchange"),!1;try{let n=this.agentSessions.get(t);n&&(this.logger.info("Rekeying existing agent session",t),(0,st.clearKey)(n.sharedSecret));let i=(0,st.deriveSharedSecret)(e,this.keyPair.secretKey),s={sessionId:t,clientPublicKey:e,sharedSecret:i,createdAt:Date.now()};return this.agentSessions.set(t,s),this.logger.info("Agent key exchange completed",t,"total:",this.agentSessions.size),!0}catch(n){return this.logger.error("Agent key exchange failed",n),!1}}removeAgentSession(e){let t=this.agentSessions.get(e);t&&((0,st.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),n=(0,st.deriveSharedSecret)(e,this.keyPair.secretKey),i=(0,st.deriveMetaSid)(this.keyPair.publicKey,e);return this.metaSessions.set(e,{clientIdentityPub:e,sharedSecret:n,sidMeta:i}),this.logger.info("Meta key exchange completed",i,"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 n=this.metaSessions.values().next().value;return n?(0,st.encrypt)(e,n.sharedSecret,n.sidMeta):null}let t=[];for(let n of this.metaSessions.values()){let i=(0,st.encrypt)(e,n.sharedSecret,n.sidMeta);t.push({sid:i.sid,n:i.n,c:i.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,st.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")}};Rs.CryptoService=pa});var qu=I(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});Is.AuthService=void 0;var Ii=_s(),ga=class{storage;cryptoService;machineId;config;logger;notification;browser;pollingAbortController=null;tokenKey;refreshTokenKey;agentIdKey;constructor(e,t,n,i,s,a,f,c,l){this.storage=e,this.cryptoService=t,this.machineId=n,this.config=i,this.logger=s,this.notification=a,this.browser=f;let p=`termiq.${c}.${l}`;this.tokenKey=`${p}.accessToken`,this.refreshTokenKey=`${p}.refreshToken`,this.agentIdKey=`${p}.agentId`,this.logger.info("AuthService namespace",c,l)}cancelPolling(){this.pollingAbortController&&(this.logger.info("Cancelling active polling"),this.pollingAbortController.abort(),this.pollingAbortController=null)}async startDeviceCodeFlow(){this.cancelPolling();let e=(0,Ii.getApiUrl)(this.config),t=await this.machineId.getMachineId(),n=this.machineId.getMachineName(),i=await this.cryptoService.getPublicKey();i||(await this.cryptoService.generateIdentityKeyPair(),i=await this.cryptoService.getPublicKey()),this.logger.info("Starting device code flow",t,n);let s=await fetch(`${e}/auth/device/code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machineId:t,machineName:n,publicKey:i})});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,Ii.getApiUrl)(this.config),n=5e3,i=60;this.pollingAbortController=new AbortController;let s=this.pollingAbortController.signal;this.logger.info("Starting token polling");for(let a=0;a<i;a++){if(s.aborted)return this.logger.info("Polling was cancelled"),null;if(await this.sleep(n),s.aborted)return this.logger.info("Polling was cancelled"),null;try{let f=await fetch(`${t}/auth/device/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:e}),signal:s});if(!f.ok){if(f.status===403)try{let l=await f.json();if(l.error==="AGENT_LIMIT_EXCEEDED")return this.logger.warn("Agent limit exceeded",String(l.current),"/",String(l.max)),this.notification.warn(`Agent limit reached (${l.current}/${l.max}). Upgrade your plan to add more devices.`),null}catch{}this.logger.warn("Poll request failed",String(f.status));continue}let c=await f.json();if(c.status==="success"&&c.accessToken)return this.logger.info("Token received successfully"),this.pollingAbortController=null,await this.saveTokens(c),c;if(c.status==="expired")return this.logger.warn("Device code expired"),null;if(c.status==="limit_exceeded")return this.logger.warn("Agent limit exceeded",String(c.current),"/",String(c.max)),this.notification.warn(`Agent limit reached (${c.current}/${c.max}). Remove an old agent or upgrade your plan.`),null;this.logger.debug("Token pending, continuing poll",String(a))}catch(f){if(s.aborted)return this.logger.info("Polling was cancelled"),null;let c=f instanceof Error?f.message:String(f);this.logger.warn(`Poll error: ${c}`)}}return this.logger.warn("Polling timed out"),this.pollingAbortController=null,null}async loginWithApiKey(e){let t=(0,Ii.getApiUrl)(this.config),n=await this.machineId.getMachineId(),i=this.machineId.getMachineName(),s=await this.cryptoService.getPublicKey();s||(await this.cryptoService.generateIdentityKeyPair(),s=await this.cryptoService.getPublicKey()),this.logger.info("Logging in with API key");try{let a=await fetch(`${t}/auth/api-key/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e,machineId:n,machineName:i,publicKey:s})});if(!a.ok){let c=await a.text();return this.logger.error("API key login failed",c),!1}let f=await a.json();return f.accessToken?(await this.saveTokens(f),this.logger.info("API key login successful"),!0):!1}catch(a){return this.logger.error("API key login error",a),!1}}async hasValidToken(){let e=await this.storage.get(this.tokenKey);if(!e)return!1;try{let n=JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()).exp*1e3;return Date.now()<n}catch{return!1}}async getAccessToken(){return await this.storage.get(this.tokenKey)||null}async getAgentId(){return await this.storage.get(this.agentIdKey)||null}async refreshAccessToken(){let e=await this.storage.get(this.refreshTokenKey);if(!e)return this.logger.debug("No refresh token available"),null;let t=(0,Ii.getApiUrl)(this.config);try{this.logger.info("Refreshing access token");let n=await fetch(`${t}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!n.ok)return this.logger.warn("Token refresh failed",String(n.status)),n.status===401&&await this.storage.delete(this.refreshTokenKey),null;let i=await n.json();return await this.storage.set(this.tokenKey,i.accessToken),await this.storage.set(this.refreshTokenKey,i.refreshToken),this.logger.info("Access token refreshed successfully"),i.accessToken}catch(n){return this.logger.warn("Token refresh error",n),null}}async logout(){this.logger.info("Logging out"),this.cancelPolling(),await this.storage.delete(this.tokenKey),await this.storage.delete(this.refreshTokenKey),await this.storage.delete(this.agentIdKey),await this.cryptoService.deleteKeys()}async saveTokens(e){e.accessToken&&await this.storage.set(this.tokenKey,e.accessToken),e.refreshToken&&await this.storage.set(this.refreshTokenKey,e.refreshToken),e.agentId&&await this.storage.set(this.agentIdKey,e.agentId)}async getLimits(){let e=await this.getAccessToken();if(!e)return this.logger.warn("Cannot fetch limits: no access token"),null;let t=(0,Ii.getApiUrl)(this.config);try{let n=await fetch(`${t}/users/me/limits`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});return n.ok?await n.json():(this.logger.error("Failed to fetch limits",String(n.status)),null)}catch(n){let i=n instanceof Error?n.message:String(n);return this.logger.error(`Error fetching limits: ${i}`),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))}};Is.AuthService=ga});var Ku=I(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});Ls.scanOsc=Cm;Ls.classifyTitle=km;var Tm=4096,ma=/\x1b\]([^\x1b\x07]*)(?:\x07|\x1b\\)/g,Om="\x1B]";function Cm(r,e=""){let t=e+r,n=[];ma.lastIndex=0;let i=0,s;for(;(s=ma.exec(t))!==null;)n.push(s[1]),i=ma.lastIndex;let a=t.slice(i),f=a.lastIndexOf(Om),c=f===-1?"":a.slice(f),l=c.indexOf("\x1B",1);return l!==-1&&l!==c.length-1&&(c=""),c.length>Tm&&(c=""),{seqs:n,carry:c}}var Pm=/^([012]);([\s\S]*)$/;function km(r){let e=r.match(Pm);if(!e)return null;let t=e[2].trim();return t?t.includes("Action Required")?{agent:t.startsWith("\u270B")?"gemini":/^\[\s*[!.]\s*\]/.test(t)?"codex":null,state:"waiting",title:t}:t.startsWith("\u2726")||t.startsWith("\u23F2")?{agent:"gemini",state:"working",title:t}:t.startsWith("\u25C7")?{agent:"gemini",state:"idle",title:t}:t.startsWith("\u25D0")||t.startsWith("\u25D1")?{agent:"claude",state:"working",title:t}:t.startsWith("\u2733")?{agent:"claude",state:"unknown",title:t}:{agent:null,state:"unknown",title:t}:{agent:null,state:"unknown",title:""}}});var Ea=I(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.MAX_TAIL_PLAIN=qe.MAX_TAIL_WITH_SELECTOR=qe.MAX_LABEL_LEN=qe.MAX_QUESTION_LEN=qe.classifyTitle=qe.scanOsc=void 0;qe.stripAnsi=_a;qe.normalizeBuffer=Hu;qe.clampQuestion=ya;qe.hasMenuSelector=Rm;qe.hasBareComposer=Lm;qe.promptKey=Nm;qe.extractQuestion=Mm;qe.extractNumberedChoices=Dm;var Wu=Ku();Object.defineProperty(qe,"scanOsc",{enumerable:!0,get:function(){return Wu.scanOsc}});Object.defineProperty(qe,"classifyTitle",{enumerable:!0,get:function(){return Wu.classifyTitle}});qe.MAX_QUESTION_LEN=160;qe.MAX_LABEL_LEN=100;qe.MAX_TAIL_WITH_SELECTOR=12;qe.MAX_TAIL_PLAIN=2;function _a(r){return r.replace(/\x1b\[[0-9]*[GC]/g," ").replace(/\x1b\[[0-9;?]*[a-zA-Z]/g,"").replace(/\x1b\][^\x1b\x07]*(?:\x07|\x1b\\)/g,"").replace(/\x1b[()][AB012]/g,"").replace(/\x1b[=>]/g,"").replace(/\x1b[78DMEHc]/g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g,"")}function Hu(r){return r.replace(/\r\n/g,`
|
|
6
6
|
`).replace(/\r/g,`
|
|
7
7
|
`).replace(/\n{3,}/g,`
|
|
8
8
|
|
|
9
|
-
`)}function
|
|
10
|
-
`).some(e=>
|
|
11
|
-
`).some(e=>
|
|
12
|
-
`).filter(n=>n.trim());for(let n=t.length-1;n>=Math.max(0,t.length-8);n--){let i=t[n].trim();if(!i||/^[\s│┃]*(?:[❯▶▸›●>*]\s*)?\d+[.)]\s/.test(i)||/^[\s│┃]*\[/.test(i))continue;let s=
|
|
13
|
-
`),i=/^[\s│┃┊┋┆┇╎╏]*(?:[❯▶▸›●>*]\s*)?(?:(\d+)[.)]\s*|\[(\d+)\]\s*)(.+?)[\s│┃]*$/u,s=/^[\s│┃┊┋┆┇╎╏]*([❯▶▸›●])\s*(?:\d+[.)]|\[\d+\])/u,a=[],f=-1,c=-1,l=!1,p="",m=[],_=-1,b=!1,x="",
|
|
9
|
+
`)}function ya(r){let e=r.replace(/\s+/g," ").trim(),t=qe.MAX_QUESTION_LEN;return e.length<=t?e:e.slice(0,t-1).trimEnd()+"\u2026"}var Am=/^[\s\u2502\u2503\u250a\u250b\u2506\u2507\u254e\u254f]*[\u276f\u25b6\u25b8\u203a\u25cf]\s*(?:\d+[.)]|\[\d+\])/u;function Rm(r){return r.split(`
|
|
10
|
+
`).some(e=>Am.test(e))}var Im=/^[\s\u2502\u2503]*[\u276f>]\s*$/u;function Lm(r){return r.split(`
|
|
11
|
+
`).some(e=>Im.test(e))}function Nm(r){let e=(r.choices||[]).map(t=>`${t.key}=${t.label}`).join("\xA7");return`${r.type}|${r.question}|${e}`}function Mm(r,e){let t=r.split(`
|
|
12
|
+
`).filter(n=>n.trim());for(let n=t.length-1;n>=Math.max(0,t.length-8);n--){let i=t[n].trim();if(!i||/^[\s│┃]*(?:[❯▶▸›●>*]\s*)?\d+[.)]\s/.test(i)||/^[\s│┃]*\[/.test(i))continue;let s=_a(i).replace(/^[\s│┃┊┋┆┇╎╏]+/u,"").replace(/[\s│┃┊┋┆┇╎╏]+$/u,"").replace(/\s+/g," ");if(s.endsWith("?")||s.endsWith(":"))return ya(s.replace(/\s*\[Y\/n\]\s*$/i,"").replace(/\s*\(y\/n\)\s*$/i,"").replace(/\s*\(yes\/no\)\s*$/i,""));for(let a of e||[]){let f=s.match(a);if(f)return ya(f[1]||s)}}return null}function Dm(r){let e=[],n=Hu(_a(r)).split(`
|
|
13
|
+
`),i=/^[\s│┃┊┋┆┇╎╏]*(?:[❯▶▸›●>*]\s*)?(?:(\d+)[.)]\s*|\[(\d+)\]\s*)(.+?)[\s│┃]*$/u,s=/^[\s│┃┊┋┆┇╎╏]*([❯▶▸›●])\s*(?:\d+[.)]|\[\d+\])/u,a=[],f=-1,c=-1,l=!1,p="",m=[],_=-1,b=!1,x="",O=z=>z.length*1e3+z.reduce((T,D)=>T+D.label.length,0),V=()=>{m.length>=1&&O(m)>=f&&(a=m.slice(),f=O(m),c=_,l=b,p=x)};for(let z=0;z<n.length;z++){let T=n[z],D=T.match(i);if(!D)continue;let te=D[1]||D[2],q=D[3].replace(/\s+/g," ").trim();if(!te||!q)continue;let ee=q.length>qe.MAX_LABEL_LEN?q.slice(0,qe.MAX_LABEL_LEN-1)+"\u2026":q,pe=parseInt(te,10),K=T.match(s),Me=K!==null;pe===m.length+1?(m.push({key:te,label:ee}),_=z,b=b||Me,K&&(x=K[1])):pe===1?(V(),m=[{key:te,label:ee}],_=z,b=Me,x=K?K[1]:""):(V(),m=[],_=-1,b=!1,x="")}if(V(),c>=0){let z=n.slice(c+1).filter(D=>D.trim().length>0),T=l?qe.MAX_TAIL_WITH_SELECTOR:qe.MAX_TAIL_PLAIN;if(z.length>T)return{choices:e,digitSelect:"enter"}}return e.push(...a),{choices:e,digitSelect:p==="\u25CF"?"immediate":"enter"}}});var Vu=I(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.StatusDetector=void 0;bn.trackAltScreen=Fm;bn.isTerminalReplyOnly=Bm;bn.isAnswerKeystroke=jm;var Ir=Ea(),Ns={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]},Yr={IDLE_TIMEOUT_MS:5e3,DEBOUNCE_MS:500,BUFFER_SIZE:16e3,WORKING_TIMEOUT_MS:3e4,RESOLVE_GRACE_MS:1500,DRIFT_DWELL_MS:2500,PROMPT_REFRESH_MS:450},ba=class{onSignalDivergence;states=new Map;onStatusChange;signalWaitingEnabled;constructor(e,t,n){this.onSignalDivergence=t,this.onStatusChange=e,this.signalWaitingEnabled=n?.signalWaiting!==!1}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,typedSinceFailure:!1,workingTimeout:null,oscCarry:"",signalState:"none",signalAgent:null,agreeWaiting:0,signalOnlyWaiting:0,parserOnlyWaiting:0,lastSignalPair:"",driftTimer:null,signalConfirmedWaiting:!1,parserConfirmedWaiting:!1};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),t.driftTimer&&clearTimeout(t.driftTimer)),this.states.delete(e)}processOutput(e,t){let n=this.states.get(e);if(!n)return;n.lastOutput=Date.now(),this.readTitleSignal(n,t),n.outputBuffer+=t,n.outputBuffer.length>Yr.BUFFER_SIZE&&(n.outputBuffer=n.outputBuffer.slice(-Yr.BUFFER_SIZE));let i=Date.now()<n.resolveGraceUntil,s=!1;if(!i){let a=this.detectPrompt(n.outputBuffer);if(a&&a.type!=="free-input"&&this.isPromptActive(n.outputBuffer)&&(s=!0,n.parserConfirmedWaiting=!0,n.pendingPrompt=a,n.status==="waiting")){let f=this.promptKey(a);f!==n.lastSeenPromptKey&&(n.lastSeenPromptKey=f,this.schedulePromptRefresh(e))}}if(this.accountSignal(e,n,s),s)this.scheduleStatusUpdate(e,"waiting");else if(n.status==="waiting"&&!i){let a=this.analyzeOutput(n.outputBuffer);(a==="completed"||a==="error")&&this.scheduleStatusUpdate(e,a)}else{let a=this.analyzeOutput(n.outputBuffer),f=n.status==="error"&&(a==="idle"||a==="completed");a&&!f&&this.scheduleStatusUpdate(e,a)}this.resetWorkingTimeout(e,n)}agentEnded(e,t){let n=this.states.get(e);if(n){if(t)n.typedSinceFailure=!1;else if(n.status!=="error"||!n.typedSinceFailure)return;n.pendingUpdate&&(clearTimeout(n.pendingUpdate),n.pendingUpdate=null),n.pendingStatus=null,this.emitStatus(e,t?"error":"idle")}}isPromptActive(e){let n=this.normalizeBuffer(this.stripAnsi(e)).split(`
|
|
14
14
|
`).map(a=>a.trim()).filter(Boolean);if(n.length===0)return!1;let i=n[n.length-1],s=n.slice(-18).join(`
|
|
15
|
-
`);return(0,
|
|
15
|
+
`);return(0,Ir.hasBareComposer)(s)?!1:(0,Ir.hasMenuSelector)(s)||/\[y\/n\]|\(y\/n\)|\[y\/N\]|\(yes\/no\)/i.test(i)||/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 n=this.states.get(e);if(!n)return;n.workingTimeout&&(clearTimeout(n.workingTimeout),n.workingTimeout=null);let i;if(t!==void 0&&t!==0)i="error";else{let s=this.analyzeOutput(n.outputBuffer);s==="waiting"?i="waiting":s==="error"?i="error":s==="completed"?i="completed":i="idle"}this.scheduleStatusUpdate(e,i),(i==="completed"||i==="error")&&setTimeout(()=>{let s=this.states.get(e);s&&(s.status==="completed"||s.status==="error")&&this.scheduleStatusUpdate(e,"idle")},Yr.IDLE_TIMEOUT_MS)}analyzeOutput(e){let n=this.normalizeBuffer(this.stripAnsi(e)).split(`
|
|
16
16
|
`).slice(-10),i=n.join(`
|
|
17
|
-
`),s=(n[n.length-1]||"").trim();for(let a of
|
|
17
|
+
`),s=(n[n.length-1]||"").trim();for(let a of Ns.waiting)if(a.test(s))return"waiting";for(let a of Ns.working)if(a.test(s))return"working";for(let a of Ns.completed)if(a.test(i))return"completed";for(let a of Ns.idle)if(a.test(s))return"idle";return null}detectPrompt(e){let i=this.normalizeBuffer(this.stripAnsi(e)).split(`
|
|
18
18
|
`).slice(-20),s=i.join(`
|
|
19
|
-
`),a=i[i.length-1]||"",{choices:f,digitSelect:c}=this.extractNumberedChoices(e);if(f.length>=2)return{type:"numbered-choice",question:this.extractQuestion(s)||"Select an option:",choices:f,digitSelect:c};let l=[/\[Y\/n\]/i,/\[y\/N\]/i,/\(y\/n\)/i,/\(yes\/no\)/i];for(let _ of l)if(_.test(s))return{type:"yes-no",question:this.extractQuestion(s)||"Confirm?"};let p=[/Press Enter to continue/i,/Press Enter/i,/Hit Enter/i,/\[Enter\]/i,/press return/i];for(let _ of p)if(_.test(s))return{type:"enter",question:this.extractQuestion(s)||"Press Enter to continue"};let m=[/Press any key/i,/press a key/i];for(let _ of m)if(_.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){return(0,
|
|
20
|
-
`);return T.substr(0,T.length-2)},this.getRequestHeader=function(T){return typeof T=="string"&&l[T]?l[T]:""},this.send=function(T){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");if(_)throw new Error("INVALID_STATE_ERR: send has already been called");var F=!1,te=!1,U=Du.parse(a.url),ee;switch(U.protocol){case"https:":F=!0;case"http:":ee=U.hostname;break;case"file:":te=!0;break;case void 0:case"":ee="localhost";break;default:throw new Error("Protocol not supported.")}if(te){if(a.method!=="GET")throw new Error("XMLHttpRequest: Only GET method is supported");if(a.async)qn.readFile(unescape(U.pathname),function(I,se){I?e.handleError(I,I.errno||-1):(e.status=200,e.responseText=se.toString("utf8"),e.response=se,z(e.DONE))});else try{this.response=qn.readFileSync(unescape(U.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,z(e.DONE)}catch(I){this.handleError(I,I.errno||-1)}return}var pe=U.port||(F?443:80),K=U.pathname+(U.search?U.search:"");if(l.Host=ee,F&&pe===443||pe===80||(l.Host+=":"+U.port),a.user){typeof a.password>"u"&&(a.password="");var Ne=new Buffer(a.user+":"+a.password);l.Authorization="Basic "+Ne.toString("base64")}if(a.method==="GET"||a.method==="HEAD")T=null;else if(T){l["Content-Length"]=Buffer.isBuffer(T)?T.length:Buffer.byteLength(T);var tt=Object.keys(l);tt.some(function(I){return I.toLowerCase()==="content-type"})||(l["Content-Type"]="text/plain;charset=UTF-8")}else a.method==="POST"&&(l["Content-Length"]=0);var xe=r.agent||!1,Me={host:ee,port:pe,path:K,method:a.method,headers:l,agent:xe};if(F&&(Me.pfx=r.pfx,Me.key=r.key,Me.passphrase=r.passphrase,Me.cert=r.cert,Me.ca=r.ca,Me.ciphers=r.ciphers,Me.rejectUnauthorized=r.rejectUnauthorized!==!1),b=!1,a.async){var we=F?n.request:t.request;_=!0,e.dispatchEvent("readystatechange");var qe=function(I){if(s=I,s.statusCode===302||s.statusCode===303||s.statusCode===307){a.url=s.headers.location;var se=Du.parse(a.url);ee=se.hostname;var Pe={hostname:se.hostname,port:se.port,path:se.path,method:s.statusCode===303?"GET":a.method,headers:l};F&&(Pe.pfx=r.pfx,Pe.key=r.key,Pe.passphrase=r.passphrase,Pe.cert=r.cert,Pe.ca=r.ca,Pe.ciphers=r.ciphers,Pe.rejectUnauthorized=r.rejectUnauthorized!==!1),i=we(Pe,qe).on("error",be),i.end();return}z(e.HEADERS_RECEIVED),e.status=s.statusCode,s.on("data",function(j){if(j){var ue=Buffer.from(j);e.response=Buffer.concat([e.response,ue])}_&&z(e.LOADING)}),s.on("end",function(){_&&(_=!1,z(e.DONE),e.responseText=e.response.toString("utf8"))}),s.on("error",function(j){e.handleError(j)})},be=function(I){if(i.reusedSocket&&I.code==="ECONNRESET")return we(Me,qe).on("error",be);e.handleError(I)};i=we(Me,qe).on("error",be),r.autoUnref&&i.on("socket",I=>{I.unref()}),T&&i.write(T),i.end(),e.dispatchEvent("loadstart")}else{var rt=".node-xmlhttprequest-content-"+process.pid,Fe=".node-xmlhttprequest-sync-"+process.pid;qn.writeFileSync(Fe,"","utf8");for(var yt="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(F?"s":"")+".request;var options = "+JSON.stringify(Me)+";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('"+rt+"', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');fs.unlinkSync('"+Fe+"');});response.on('error', function(error) {fs.writeFileSync('"+rt+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Fe+"');});}).on('error', function(error) {fs.writeFileSync('"+rt+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Fe+"');});"+(T?"req.write('"+JSON.stringify(T).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",We=mm(process.argv[0],["-e",yt]),dt;qn.existsSync(Fe););if(e.responseText=qn.readFileSync(rt,"utf8"),We.stdin.end(),qn.unlinkSync(rt),e.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var N=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,""));e.handleError(N,503)}else{e.status=e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/,"$1");var B=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"));s={statusCode:e.status,headers:B.data.headers},e.responseText=B.data.text,e.response=Buffer.from(B.data.data,"base64"),z(e.DONE,!0)}}},this.handleError=function(T,F){this.status=F||0,this.statusText=T,this.responseText=T.stack,b=!0,z(this.DONE)},this.abort=function(){i&&(i.abort(),i=null),l=Object.assign({},c),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),b=x=!0,this.readyState!==this.UNSENT&&(this.readyState!==this.OPENED||_)&&this.readyState!==this.DONE&&(_=!1,z(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(T,F){T in C||(C[T]=[]),C[T].push(F)},this.removeEventListener=function(T,F){T in C&&(C[T]=C[T].filter(function(te){return te!==F}))},this.dispatchEvent=function(T){if(typeof e["on"+T]=="function"&&(this.readyState===this.DONE&&a.async?setTimeout(function(){e["on"+T]()},0):e["on"+T]()),T in C)for(let F=0,te=C[T].length;F<te;F++)this.readyState===this.DONE?setTimeout(function(){C[T][F].call(e)},0):C[T][F].call(e)};var z=function(T){if(!(e.readyState===T||e.readyState===e.UNSENT&&x)&&(e.readyState=T,(a.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let F;x?F="abort":b?F="error":F="load",e.dispatchEvent(F),e.dispatchEvent("loadend")}}}});var Is=L(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.ERROR_PACKET=zr.PACKET_TYPES_REVERSE=zr.PACKET_TYPES=void 0;var lr=Object.create(null);zr.PACKET_TYPES=lr;lr.open="0";lr.close="1";lr.ping="2";lr.pong="3";lr.message="4";lr.upgrade="5";lr.noop="6";var Uu=Object.create(null);zr.PACKET_TYPES_REVERSE=Uu;Object.keys(lr).forEach(r=>{Uu[lr[r]]=r});var ym={type:"error",data:"parser error"};zr.ERROR_PACKET=ym});var qu=L(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.encodePacket=void 0;Wn.encodePacketToBinary=bm;var _m=Is(),Em=({type:r,data:e},t,n)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?n(t?e:"b"+Ku(e,!0).toString("base64")):n(_m.PACKET_TYPES[r]+(e||""));Wn.encodePacket=Em;var Ku=(r,e)=>Buffer.isBuffer(r)||r instanceof Uint8Array&&!e?r:r instanceof ArrayBuffer?Buffer.from(r):Buffer.from(r.buffer,r.byteOffset,r.byteLength),ga;function bm(r,e){if(r.data instanceof ArrayBuffer||ArrayBuffer.isView(r.data))return e(Ku(r.data,!1));(0,Wn.encodePacket)(r,!0,t=>{ga||(ga=new TextEncoder),e(ga.encode(t))})}});var Hu=L(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});Ns.decodePacket=void 0;var Ls=Is(),vm=(r,e)=>{if(typeof r!="string")return{type:"message",data:Wu(r,e)};let t=r.charAt(0);if(t==="b"){let n=Buffer.from(r.substring(1),"base64");return{type:"message",data:Wu(n,e)}}return Ls.PACKET_TYPES_REVERSE[t]?r.length>1?{type:Ls.PACKET_TYPES_REVERSE[t],data:r.substring(1)}:{type:Ls.PACKET_TYPES_REVERSE[t]}:Ls.ERROR_PACKET};Ns.decodePacket=vm;var Wu=(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 Hn=L(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.decodePayload=St.decodePacket=St.encodePayload=St.encodePacket=St.protocol=void 0;St.createPacketEncoderStream=xm;St.createPacketDecoderStream=Tm;var ya=qu();Object.defineProperty(St,"encodePacket",{enumerable:!0,get:function(){return ya.encodePacket}});var _a=Hu();Object.defineProperty(St,"decodePacket",{enumerable:!0,get:function(){return _a.decodePacket}});var Vu=Is(),$u="",wm=(r,e)=>{let t=r.length,n=new Array(t),i=0;r.forEach((s,a)=>{(0,ya.encodePacket)(s,!1,f=>{n[a]=f,++i===t&&e(n.join($u))})})};St.encodePayload=wm;var Sm=(r,e)=>{let t=r.split($u),n=[];for(let i=0;i<t.length;i++){let s=(0,_a.decodePacket)(t[i],e);if(n.push(s),s.type==="error")break}return n};St.decodePayload=Sm;function xm(){return new TransformStream({transform(r,e){(0,ya.encodePacketToBinary)(r,t=>{let n=t.length,i;if(n<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,n);else if(n<65536){i=new Uint8Array(3);let s=new DataView(i.buffer);s.setUint8(0,126),s.setUint16(1,n)}else{i=new Uint8Array(9);let s=new DataView(i.buffer);s.setUint8(0,127),s.setBigUint64(1,BigInt(n))}r.data&&typeof r.data!="string"&&(i[0]|=128),e.enqueue(i),e.enqueue(t)})}})}var ma;function Ms(r){return r.reduce((e,t)=>e+t.length,0)}function Fs(r,e){if(r[0].length===e)return r.shift();let t=new Uint8Array(e),n=0;for(let i=0;i<e;i++)t[i]=r[0][n++],n===r[0].length&&(r.shift(),n=0);return r.length&&n<r[0].length&&(r[0]=r[0].slice(n)),t}function Tm(r,e){ma||(ma=new TextDecoder);let t=[],n=0,i=-1,s=!1;return new TransformStream({transform(a,f){for(t.push(a);;){if(n===0){if(Ms(t)<1)break;let c=Fs(t,1);s=(c[0]&128)===128,i=c[0]&127,i<126?n=3:i===126?n=1:n=2}else if(n===1){if(Ms(t)<2)break;let c=Fs(t,2);i=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),n=3}else if(n===2){if(Ms(t)<8)break;let c=Fs(t,8),l=new DataView(c.buffer,c.byteOffset,c.length),p=l.getUint32(0);if(p>Math.pow(2,21)-1){f.enqueue(Vu.ERROR_PACKET);break}i=p*Math.pow(2,32)+l.getUint32(4),n=3}else{if(Ms(t)<i)break;let c=Fs(t,i);f.enqueue((0,_a.decodePacket)(s?c:ma.decode(c),e)),n=0}if(i===0||i>r){f.enqueue(Vu.ERROR_PACKET);break}}}})}St.protocol=4});var _n=L(zu=>{zu.Emitter=bt;function bt(r){if(r)return Cm(r)}function Cm(r){for(var e in bt.prototype)r[e]=bt.prototype[e];return r}bt.prototype.on=bt.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this};bt.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this};bt.prototype.off=bt.prototype.removeListener=bt.prototype.removeAllListeners=bt.prototype.removeEventListener=function(r,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+r];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+r],this;for(var n,i=0;i<t.length;i++)if(n=t[i],n===e||n.fn===e){t.splice(i,1);break}return t.length===0&&delete this._callbacks["$"+r],this};bt.prototype.emit=function(r){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+r],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t){t=t.slice(0);for(var n=0,i=t.length;n<i;++n)t[n].apply(this,e)}return this};bt.prototype.emitReserved=bt.prototype.emit;bt.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};bt.prototype.hasListeners=function(r){return!!this.listeners(r).length}});var En=L(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.CookieJar=Dt.defaultBinaryType=Dt.globalThisShim=Dt.nextTick=void 0;Dt.createCookieJar=km;Dt.parse=Gu;Dt.nextTick=process.nextTick;Dt.globalThisShim=global;Dt.defaultBinaryType="nodebuffer";function km(){return new Ds}function Gu(r){let e=r.split("; "),t=e[0].indexOf("=");if(t===-1)return;let n=e[0].substring(0,t).trim();if(!n.length)return;let i=e[0].substring(t+1).trim();i.charCodeAt(0)===34&&(i=i.slice(1,-1));let s={name:n,value:i};for(let a=1;a<e.length;a++){let f=e[a].split("=");if(f.length!==2)continue;let c=f[0].trim(),l=f[1].trim();switch(c){case"Expires":s.expires=new Date(l);break;case"Max-Age":let p=new Date;p.setUTCSeconds(p.getUTCSeconds()+parseInt(l,10)),s.expires=p;break;default:}}return s}var Ds=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let n=Gu(t);n&&this._cookies.set(n.name,n)})}get cookies(){let e=Date.now();return this._cookies.forEach((t,n)=>{var i;((i=t.expires)===null||i===void 0?void 0:i.getTime())<e&&this._cookies.delete(n)}),this._cookies.entries()}addCookies(e){let t=[];for(let[n,i]of this.cookies)t.push(`${n}=${i.value}`);t.length&&(e.setDisableHeaderCheck(!0),e.setRequestHeader("cookie",t.join("; ")))}appendCookies(e){for(let[t,n]of this.cookies)e.append("cookie",`${t}=${n.value}`)}};Dt.CookieJar=Ds});var bn=L(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.pick=Om;Vn.installTimerFunctions=Rm;Vn.byteLength=Lm;Vn.randomString=Mm;var Gr=En();function Om(r,...e){return e.reduce((t,n)=>(r.hasOwnProperty(n)&&(t[n]=r[n]),t),{})}var Pm=Gr.globalThisShim.setTimeout,Am=Gr.globalThisShim.clearTimeout;function Rm(r,e){e.useNativeTimers?(r.setTimeoutFn=Pm.bind(Gr.globalThisShim),r.clearTimeoutFn=Am.bind(Gr.globalThisShim)):(r.setTimeoutFn=Gr.globalThisShim.setTimeout.bind(Gr.globalThisShim),r.clearTimeoutFn=Gr.globalThisShim.clearTimeout.bind(Gr.globalThisShim))}var Im=1.33;function Lm(r){return typeof r=="string"?Nm(r):Math.ceil((r.byteLength||r.size)*Im)}function Nm(r){let e=0,t=0;for(let n=0,i=r.length;n<i;n++)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(n++,t+=4);return t}function Mm(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}});var Ea=L(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});Bs.encode=Fm;Bs.decode=Dm;function Fm(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function Dm(r){let e={},t=r.split("&");for(let n=0,i=t.length;n<i;n++){let s=t[n].split("=");e[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return e}});var Xu=L((yw,Yu)=>{var $n=1e3,zn=$n*60,Gn=zn*60,vn=Gn*24,Bm=vn*7,jm=vn*365.25;Yu.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return Um(r);if(t==="number"&&isFinite(r))return e.long?qm(r):Km(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function Um(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*jm;case"weeks":case"week":case"w":return t*Bm;case"days":case"day":case"d":return t*vn;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Gn;case"minutes":case"minute":case"mins":case"min":case"m":return t*zn;case"seconds":case"second":case"secs":case"sec":case"s":return t*$n;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Km(r){var e=Math.abs(r);return e>=vn?Math.round(r/vn)+"d":e>=Gn?Math.round(r/Gn)+"h":e>=zn?Math.round(r/zn)+"m":e>=$n?Math.round(r/$n)+"s":r+"ms"}function qm(r){var e=Math.abs(r);return e>=vn?js(r,e,vn,"day"):e>=Gn?js(r,e,Gn,"hour"):e>=zn?js(r,e,zn,"minute"):e>=$n?js(r,e,$n,"second"):r+" ms"}function js(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var ba=L((_w,Ju)=>{function Wm(r){t.debug=t,t.default=t,t.coerce=c,t.disable=a,t.enable=i,t.enabled=f,t.humanize=Xu(),t.destroy=l,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,b,x;function C(...H){if(!C.enabled)return;let ie=C,z=Number(new Date),T=z-(m||z);ie.diff=T,ie.prev=m,ie.curr=z,m=z,H[0]=t.coerce(H[0]),typeof H[0]!="string"&&H.unshift("%O");let F=0;H[0]=H[0].replace(/%([a-zA-Z%])/g,(U,ee)=>{if(U==="%%")return"%";F++;let pe=t.formatters[ee];if(typeof pe=="function"){let K=H[F];U=pe.call(ie,K),H.splice(F,1),F--}return U}),t.formatArgs.call(ie,H),(ie.log||t.log).apply(ie,H)}return C.namespace=p,C.useColors=t.useColors(),C.color=t.selectColor(p),C.extend=n,C.destroy=t.destroy,Object.defineProperty(C,"enabled",{enumerable:!0,configurable:!1,get:()=>_!==null?_:(b!==t.namespaces&&(b=t.namespaces,x=t.enabled(p)),x),set:H=>{_=H}}),typeof t.init=="function"&&t.init(C),C}function n(p,m){let _=t(this.namespace+(typeof m>"u"?":":m)+p);return _.log=this.log,_}function i(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,b=0,x=-1,C=0;for(;_<p.length;)if(b<m.length&&(m[b]===p[_]||m[b]==="*"))m[b]==="*"?(x=b,C=_,b++):(_++,b++);else if(x!==-1)b=x+1,C++,_=C;else return!1;for(;b<m.length&&m[b]==="*";)b++;return b===m.length}function a(){let p=[...t.names,...t.skips.map(m=>"-"+m)].join(",");return t.enable(""),p}function f(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 c(p){return p instanceof Error?p.stack||p.message:p}function l(){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}Ju.exports=Wm});var Zu=L((xt,Us)=>{xt.formatArgs=Vm;xt.save=$m;xt.load=zm;xt.useColors=Hm;xt.storage=Gm();xt.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`."))}})();xt.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 Hm(){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 Vm(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Us.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(t++,i==="%c"&&(n=t))}),r.splice(n,0,e)}xt.log=console.debug||console.log||(()=>{});function $m(r){try{r?xt.storage.setItem("debug",r):xt.storage.removeItem("debug")}catch{}}function zm(){let r;try{r=xt.storage.getItem("debug")||xt.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Gm(){try{return localStorage}catch{}}Us.exports=ba()(xt);var{formatters:Ym}=Us.exports;Ym.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var el=L((Ew,Qu)=>{"use strict";Qu.exports=(r,e=process.argv)=>{let t=r.startsWith("-")?"":r.length===1?"-":"--",n=e.indexOf(t+r),i=e.indexOf("--");return n!==-1&&(i===-1||n<i)}});var nl=L((bw,rl)=>{"use strict";var Xm=require("os"),tl=require("tty"),Bt=el(),{env:ct}=process,Yr;Bt("no-color")||Bt("no-colors")||Bt("color=false")||Bt("color=never")?Yr=0:(Bt("color")||Bt("colors")||Bt("color=true")||Bt("color=always"))&&(Yr=1);"FORCE_COLOR"in ct&&(ct.FORCE_COLOR==="true"?Yr=1:ct.FORCE_COLOR==="false"?Yr=0:Yr=ct.FORCE_COLOR.length===0?1:Math.min(parseInt(ct.FORCE_COLOR,10),3));function va(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function wa(r,e){if(Yr===0)return 0;if(Bt("color=16m")||Bt("color=full")||Bt("color=truecolor"))return 3;if(Bt("color=256"))return 2;if(r&&!e&&Yr===void 0)return 0;let t=Yr||0;if(ct.TERM==="dumb")return t;if(process.platform==="win32"){let n=Xm.release().split(".");return Number(n[0])>=10&&Number(n[2])>=10586?Number(n[2])>=14931?3:2:1}if("CI"in ct)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(n=>n in ct)||ct.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in ct)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(ct.TEAMCITY_VERSION)?1:0;if(ct.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in ct){let n=parseInt((ct.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(ct.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(ct.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(ct.TERM)||"COLORTERM"in ct?1:t}function Jm(r){let e=wa(r,r&&r.isTTY);return va(e)}rl.exports={supportsColor:Jm,stdout:va(wa(!0,tl.isatty(1))),stderr:va(wa(!0,tl.isatty(2)))}});var sl=L((ft,qs)=>{var Zm=require("tty"),Ks=require("util");ft.init=sy;ft.log=ry;ft.formatArgs=ey;ft.save=ny;ft.load=iy;ft.useColors=Qm;ft.destroy=Ks.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");ft.colors=[6,2,3,4,5,1];try{let r=nl();r&&(r.stderr||r).level>=2&&(ft.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{}ft.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(i,s)=>s.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),r[t]=n,r},{});function Qm(){return"colors"in ft.inspectOpts?!!ft.inspectOpts.colors:Zm.isatty(process.stderr.fd)}function ey(r){let{namespace:e,useColors:t}=this;if(t){let n=this.color,i="\x1B[3"+(n<8?n:"8;5;"+n),s=` ${i};1m${e} \x1B[0m`;r[0]=s+r[0].split(`
|
|
19
|
+
`),a=i[i.length-1]||"",{choices:f,digitSelect:c}=this.extractNumberedChoices(e);if(f.length>=2)return{type:"numbered-choice",question:this.extractQuestion(s)||"Select an option:",choices:f,digitSelect:c};let l=[/\[Y\/n\]/i,/\[y\/N\]/i,/\(y\/n\)/i,/\(yes\/no\)/i];for(let _ of l)if(_.test(s))return{type:"yes-no",question:this.extractQuestion(s)||"Confirm?"};let p=[/Press Enter to continue/i,/Press Enter/i,/Hit Enter/i,/\[Enter\]/i,/press return/i];for(let _ of p)if(_.test(s))return{type:"enter",question:this.extractQuestion(s)||"Press Enter to continue"};let m=[/Press any key/i,/press a key/i];for(let _ of m)if(_.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){return(0,Ir.extractNumberedChoices)(e)}extractQuestion(e){return(0,Ir.extractQuestion)(e)}stripAnsi(e){return(0,Ir.stripAnsi)(e)}normalizeBuffer(e){return(0,Ir.normalizeBuffer)(e)}scheduleStatusUpdate(e,t){let n=this.states.get(e);n&&n.status!==t&&n.pendingStatus!==t&&(n.pendingUpdate&&clearTimeout(n.pendingUpdate),n.pendingStatus=t,n.pendingUpdate=setTimeout(()=>{n.pendingStatus=null,this.emitStatus(e,t),n.pendingUpdate=null},Yr.DEBOUNCE_MS))}emitStatus(e,t){let n=this.states.get(e);if(!n||n.status===t)return;n.status=t,n.lastUpdate=Date.now();let i;if(t==="waiting"){let s=this.detectPrompt(n.outputBuffer);i=s&&s.type!=="free-input"?s:n.pendingPrompt||s||void 0,n.emittedPromptKey=i?this.promptKey(i):null,n.lastSeenPromptKey=n.emittedPromptKey}else n.signalConfirmedWaiting=!1,n.parserConfirmedWaiting=!1,n.pendingPrompt=null,n.emittedPromptKey=null,n.lastSeenPromptKey=null,n.promptRefreshTimer&&(clearTimeout(n.promptRefreshTimer),n.promptRefreshTimer=null);this.onStatusChange(e,t,i)}getEmittedPromptKey(e){return this.states.get(e)?.emittedPromptKey??null}reEmitPrompt(e){let t=this.states.get(e);if(!t)return;let n=this.detectPrompt(t.outputBuffer),i=n&&n.type!=="free-input"?n:t.pendingPrompt||void 0;i&&(t.emittedPromptKey=this.promptKey(i),t.lastSeenPromptKey=t.emittedPromptKey,this.onStatusChange(e,"waiting",i))}promptKey(e){return(0,Ir.promptKey)(e)}schedulePromptRefresh(e){let t=this.states.get(e);t&&(t.promptRefreshTimer&&clearTimeout(t.promptRefreshTimer),t.promptRefreshTimer=setTimeout(()=>{let n=this.states.get(e);if(!n||(n.promptRefreshTimer=null,n.status!=="waiting"||Date.now()<n.resolveGraceUntil))return;let i=this.detectPrompt(n.outputBuffer),s=i&&i.type!=="free-input"?i:n.pendingPrompt;if(!s)return;let a=this.promptKey(s);a!==n.emittedPromptKey&&(n.emittedPromptKey=a,n.lastSeenPromptKey=a,this.onStatusChange(e,"waiting",s))},Yr.PROMPT_REFRESH_MS))}readTitleSignal(e,t){let{seqs:n,carry:i}=(0,Ir.scanOsc)(t,e.oscCarry);e.oscCarry=i;for(let s of n){let a=(0,Ir.classifyTitle)(s);!a||a.state==="unknown"||(e.signalState=a.state,e.signalAgent=a.agent)}}accountSignal(e,t,n){let i=t.signalState==="waiting",s=`${i?1:0}${n?1:0}`;s!==t.lastSignalPair&&(t.lastSignalPair=s,t.driftTimer&&(clearTimeout(t.driftTimer),t.driftTimer=null),i&&n?t.agreeWaiting++:i?t.driftTimer=setTimeout(()=>{t.driftTimer=null,t.signalOnlyWaiting++,this.onSignalDivergence?.(e,t.signalAgent),this.signalWaitingEnabled&&t.status!=="waiting"&&(Date.now()<t.resolveGraceUntil||(t.signalConfirmedWaiting=!0,t.pendingPrompt={type:"free-input",question:"Waiting for your input"},this.scheduleStatusUpdate(e,"waiting")))},Yr.DRIFT_DWELL_MS):n&&t.parserOnlyWaiting++)}getWaitingSource(e){let t=this.states.get(e);if(!t||t.status!=="waiting")return null;let n=t.signalConfirmedWaiting||t.signalState==="waiting";return t.parserConfirmedWaiting&&n?"both":t.parserConfirmedWaiting?"parser":"signal"}getSignalStats(e){let t=this.states.get(e);return t?{agent:t.signalAgent,state:t.signalState,agreeWaiting:t.agreeWaiting,signalOnlyWaiting:t.signalOnlyWaiting,parserOnlyWaiting:t.parserOnlyWaiting}:null}resetWorkingTimeout(e,t){t.workingTimeout&&clearTimeout(t.workingTimeout),t.status==="working"&&(t.workingTimeout=setTimeout(()=>{let n=this.states.get(e);n&&n.status==="working"&&(this.analyzeOutput(n.outputBuffer)==="waiting"?this.emitStatus(e,"waiting"):this.onStatusChange(e,"working",void 0))},Yr.WORKING_TIMEOUT_MS))}resolvePrompt(e){let t=this.states.get(e);if(t){if(t.typedSinceFailure=!0,t.status==="error"){this.scheduleStatusUpdate(e,"idle");return}t.status==="waiting"&&(t.resolveGraceUntil=Date.now()+Yr.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)}resendWaitingPrompts(){for(let[e,t]of this.states){if(t.status!=="waiting")continue;let n=this.detectPrompt(t.outputBuffer),i=n&&n.type!=="free-input"?n:t.pendingPrompt||void 0;i&&this.onStatusChange(e,"waiting",i)}}getStatus(e){return this.states.get(e)?.status??null}dispose(){for(let e of this.states.keys())this.stopTracking(e)}};bn.StatusDetector=ba;function Fm(r,e){let t=Math.max(r.lastIndexOf("\x1B[?1049h"),r.lastIndexOf("\x1B[?47h")),n=Math.max(r.lastIndexOf("\x1B[?1049l"),r.lastIndexOf("\x1B[?47l"));return t===-1&&n===-1?e:t>n}function Bm(r){return r?/^(?:\x1b\[[0-9]+;[0-9]+R|\x1b\[[?>][0-9;]*c|\x1b\[[0-9;]*n|\x1b\[\?[0-9;]*\$y|\x1b\[[IO]|\x1b\][^\x1b\x07]*(?:\x07|\x1b\\))+$/.test(r):!1}function jm(r){for(let e=0;e<r.length;e++){let t=r.charCodeAt(e);if(t===27){let n=r[e+1];if(n==="["||n==="O"){for(e+=2;e<r.length&&!/[A-Za-z~]/.test(r[e]);)e++;continue}if(n==="]"){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 Zu=I(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.AgentExitTracker=_t.LAUNCHER_PROGRAMS=_t.AGENT_PROGRAMS=_t.COMMAND_END_OSC=void 0;_t.agentForProgram=Yu;_t.isInterruptExit=Xu;_t.isSessionCrash=Wm;var Um=require("os"),$u=Ea();_t.COMMAND_END_OSC="6973";_t.AGENT_PROGRAMS=["claude","codex","gemini","copilot","kimi","opencode","pi","cursor-agent","aider","crush","goose"];_t.LAUNCHER_PROGRAMS=["npx","bunx","pnpx","pnpm","npm","yarn","node","bun","deno","uvx","pipx"];var qm=[3221225786,3221225786-4294967296],Km=["SIGKILL","SIGSEGV","SIGBUS","SIGABRT","SIGILL","SIGFPE","SIGSYS","SIGTRAP","SIGXCPU","SIGXFSZ"];function zu(r){return(r.split(/[\\/]/).pop()??"").replace(/\.(exe|cmd|bat|ps1)$/i,"").toLowerCase()}function Yu(r){let e=zu(r);return _t.AGENT_PROGRAMS.includes(e)?e:null}function Xu(r){return r===130||qm.includes(r)}function Wm(r){let e=r.signal;if(typeof e!="number"||e<=0)return!1;let t=Um.constants.signals;return Km.some(n=>t[n]===e)}function Gu(r){return r===void 0||!/^-?\d{1,10}$/.test(r)?null:Number(r)}var wa=class{nonce;carry="";titleAgent=null;ownMarks=!1;constructor(e={}){this.nonce=e.nonce||null}processOutput(e){let{seqs:t,carry:n}=(0,$u.scanOsc)(e,this.carry);this.carry=n;let i=[];for(let s of t){let a=this.readCommandEnd(s);if(a){let c=this.agentOf(a.program);this.titleAgent=null,c&&i.push({agent:c,exitCode:a.exitCode,failed:a.exitCode!==0&&!Xu(a.exitCode)});continue}let f=(0,$u.classifyTitle)(s);f?.agent&&(this.titleAgent=f.agent)}return i}readCommandEnd(e){let t=e.split(";");if(t[0]===_t.COMMAND_END_OSC){if(t.length!==5||t[1]!=="D"||this.nonce===null||t[4]!==this.nonce)return null;let n=Gu(t[2]);return n===null?null:(this.ownMarks=!0,{exitCode:n,program:t[3]?t[3]:null})}if((t[0]==="133"||t[0]==="633")&&t[1]==="D"&&!this.ownMarks){let n=Gu(t[2]);return n===null?null:{exitCode:n,program:null}}return null}agentOf(e){if(e===null)return this.titleAgent;let t=Yu(e);return t||(_t.LAUNCHER_PROGRAMS.includes(zu(e))?this.titleAgent:null)}};_t.AgentExitTracker=wa});var el=I(Lt=>{"use strict";var Hm=Lt&&Lt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Vm=Lt&&Lt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),va=Lt&&Lt.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),i=0;i<n.length;i++)n[i]!=="default"&&Hm(t,e,n[i]);return Vm(t,e),t}})();Object.defineProperty(Lt,"__esModule",{value:!0});Lt.SHELL_INTEGRATION_ENV=void 0;Lt.shellIntegrationKind=Ju;Lt.prepareShellLaunch=Xm;var $m=require("crypto"),Ms=va(require("fs")),Gm=va(require("os")),Ds=va(require("path"));Lt.SHELL_INTEGRATION_ENV="TERMIQ_SHELL_INTEGRATION";var Qu="TERMIQ_ZDOTDIR",Fs="@NONCE@",zm=`# TermIQ shell integration for bash.
|
|
20
|
+
#
|
|
21
|
+
# The TermIQ agent starts bash with --rcfile pointing to this file instead of ~/.bashrc. It
|
|
22
|
+
# loads ~/.bashrc first, as bash would have, and then prints at each prompt how the last
|
|
23
|
+
# command ended:
|
|
24
|
+
# ESC ] 6973 ; D ; <exit code> ; <program> ; <nonce> BEL
|
|
25
|
+
# <program> is the first word of the command, and only when the command is in the history:
|
|
26
|
+
# otherwise the history does not say which command it was. <nonce> is made for this shell
|
|
27
|
+
# alone: the agent counts only the marks that carry it, not the same sequence printed by a
|
|
28
|
+
# command. The agent reads the mark to tell that an AI agent failed; terminals ignore the
|
|
29
|
+
# unknown sequence. The prompt, the history and the exit status the other prompt hooks see
|
|
30
|
+
# stay as they were.
|
|
31
|
+
#
|
|
32
|
+
# Shells start without this file when TERMIQ_SHELL_INTEGRATION=0.
|
|
33
|
+
if [ -f ~/.bashrc ]; then . ~/.bashrc; fi
|
|
34
|
+
|
|
35
|
+
__termiq_precmd() {
|
|
36
|
+
local code=$? line= num= word=
|
|
37
|
+
# The last history entry, " 42 FOO=1 /usr/local/bin/claude -p x". A new number means
|
|
38
|
+
# that the command which has just ended is in the history. (HISTCMD would save the
|
|
39
|
+
# subshell, but before bash 5.1 it does not change inside PROMPT_COMMAND.)
|
|
40
|
+
line=$(HISTTIMEFORMAT= builtin history 1)
|
|
41
|
+
line=\${line#"\${line%%[![:space:]]*}"}
|
|
42
|
+
num=\${line%%[!0-9]*}
|
|
43
|
+
if [ -z "\${__termiq_hist+x}" ]; then
|
|
44
|
+
# The first prompt: no command has run yet.
|
|
45
|
+
__termiq_hist=$num
|
|
46
|
+
return "$code"
|
|
47
|
+
fi
|
|
48
|
+
if [ -n "$num" ] && [ "$num" != "$__termiq_hist" ]; then
|
|
49
|
+
__termiq_hist=$num
|
|
50
|
+
# "42 FOO=1 /usr/local/bin/claude -p x" -> "claude"; "42* ..." is an edited entry.
|
|
51
|
+
line=\${line#"$num"}
|
|
52
|
+
line=\${line#[*]}
|
|
53
|
+
while :; do
|
|
54
|
+
line=\${line#"\${line%%[![:space:]]*}"}
|
|
55
|
+
word=\${line%%[[:space:]]*}
|
|
56
|
+
case $word in
|
|
57
|
+
[A-Za-z_]*=*) line=\${line#"$word"} ;;
|
|
58
|
+
*) break ;;
|
|
59
|
+
esac
|
|
60
|
+
done
|
|
61
|
+
word=\${word##*/}
|
|
62
|
+
word=\${word//[!A-Za-z0-9._+-]/}
|
|
63
|
+
fi
|
|
64
|
+
builtin printf '\\033]6973;D;%s;%s;${Fs}\\007' "$code" "$word"
|
|
65
|
+
return "$code"
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
case ";\${PROMPT_COMMAND:-};" in
|
|
69
|
+
*";__termiq_precmd;"*) ;;
|
|
70
|
+
*) PROMPT_COMMAND="__termiq_precmd\${PROMPT_COMMAND:+;$PROMPT_COMMAND}" ;;
|
|
71
|
+
esac
|
|
72
|
+
`,Ym=`# TermIQ shell integration for zsh.
|
|
73
|
+
#
|
|
74
|
+
# The TermIQ agent starts zsh with ZDOTDIR pointing to the directory of this file, so zsh reads
|
|
75
|
+
# it as .zshenv. It first puts ZDOTDIR back to what it was, so that zsh reads the user's .zshrc
|
|
76
|
+
# and the other startup files as usual, and loads the user's .zshenv. An interactive shell
|
|
77
|
+
# then prints after each command how the command ended:
|
|
78
|
+
# ESC ] 6973 ; D ; <exit code> ; <program> ; <nonce> BEL
|
|
79
|
+
# <program> is the first word of the command line. <nonce> is made for this shell alone: the
|
|
80
|
+
# agent counts only the marks that carry it, not the same sequence printed by a command. The
|
|
81
|
+
# agent reads the mark to tell that an AI agent failed; terminals ignore the unknown sequence.
|
|
82
|
+
# The prompt and the exit status the other hooks see stay as they were.
|
|
83
|
+
#
|
|
84
|
+
# Shells start without this file when TERMIQ_SHELL_INTEGRATION=0.
|
|
85
|
+
if [[ -n "\${TERMIQ_ZDOTDIR+x}" ]]; then
|
|
86
|
+
ZDOTDIR=$TERMIQ_ZDOTDIR
|
|
87
|
+
unset TERMIQ_ZDOTDIR
|
|
88
|
+
else
|
|
89
|
+
unset ZDOTDIR
|
|
90
|
+
fi
|
|
91
|
+
if [[ -f "\${ZDOTDIR:-$HOME}/.zshenv" ]]; then
|
|
92
|
+
builtin source "\${ZDOTDIR:-$HOME}/.zshenv"
|
|
93
|
+
fi
|
|
94
|
+
|
|
95
|
+
if [[ -o interactive ]]; then
|
|
96
|
+
__termiq_preexec() {
|
|
97
|
+
__termiq_ran=1
|
|
98
|
+
__termiq_line=$1
|
|
99
|
+
}
|
|
100
|
+
__termiq_precmd() {
|
|
101
|
+
local code=$? line word
|
|
102
|
+
if [[ -n "\${__termiq_ran-}" ]]; then
|
|
103
|
+
unset __termiq_ran
|
|
104
|
+
# "FOO=1 /usr/local/bin/claude -p x" -> "claude"
|
|
105
|
+
line=$__termiq_line
|
|
106
|
+
while :; do
|
|
107
|
+
line=\${line#"\${line%%[![:space:]]*}"}
|
|
108
|
+
word=\${line%%[[:space:]]*}
|
|
109
|
+
case $word in
|
|
110
|
+
[A-Za-z_]*=*) line=\${line#"$word"} ;;
|
|
111
|
+
*) break ;;
|
|
112
|
+
esac
|
|
113
|
+
done
|
|
114
|
+
word=\${word##*/}
|
|
115
|
+
word=\${word//[!A-Za-z0-9._+-]/}
|
|
116
|
+
builtin printf '\\033]6973;D;%s;%s;${Fs}\\007' "$code" "$word"
|
|
117
|
+
fi
|
|
118
|
+
return $code
|
|
119
|
+
}
|
|
120
|
+
precmd_functions=(__termiq_precmd "\${precmd_functions[@]}")
|
|
121
|
+
preexec_functions+=(__termiq_preexec)
|
|
122
|
+
fi
|
|
123
|
+
`;function Ju(r){let e=Ds.basename(r);return e==="bash"||e==="zsh"?e:null}function Xm(r,e,t={}){let n={args:[],env:{...e},kind:null,nonce:null,dispose:()=>{}},i=t.enabled??e[Lt.SHELL_INTEGRATION_ENV]!=="0",s=t.platform??process.platform,a=Ju(r);if(!i||s==="win32"||!a)return n;let f=null,c=()=>{if(f){try{Ms.rmSync(f,{recursive:!0,force:!0})}catch{}f=null}};try{f=Ms.mkdtempSync(Ds.join(t.tmpDir??Gm.tmpdir(),"termiq-shell-"));let l=(0,$m.randomBytes)(16).toString("hex");if(a==="bash"){let m=Ds.join(f,"bashrc");return Ms.writeFileSync(m,zm.replace(Fs,l),{mode:384}),{args:["--rcfile",m],env:{...e},kind:a,nonce:l,dispose:c}}Ms.writeFileSync(Ds.join(f,".zshenv"),Ym.replace(Fs,l),{mode:384});let p={...e,ZDOTDIR:f};return e.ZDOTDIR!==void 0?p[Qu]=e.ZDOTDIR:delete p[Qu],{args:[],env:p,kind:a,nonce:l,dispose:c}}catch{return c(),n}}});var nl=I((Hv,rl)=>{var Vn=require("fs"),tl=require("url"),Zm=require("child_process").spawn;rl.exports=Sa;Sa.XMLHttpRequest=Sa;function Sa(r){"use strict";r=r||{};var e=this,t=require("http"),n=require("https"),i,s,a={},f=!1,c={"User-Agent":"node-XMLHttpRequest",Accept:"*/*"},l=Object.assign({},c),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,b=!1,x=!1,O={};this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.readyState=this.UNSENT,this.onreadystatechange=null,this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),this.status=null,this.statusText=null;var V=function(T){return f||T&&p.indexOf(T.toLowerCase())===-1},ie=function(T){return T&&m.indexOf(T)===-1};this.open=function(T,D,te,q,ee){if(this.abort(),b=!1,x=!1,!ie(T))throw new Error("SecurityError: Request method not allowed");a={method:T,url:D.toString(),async:typeof te!="boolean"?!0:te,user:q||null,password:ee||null},z(this.OPENED)},this.setDisableHeaderCheck=function(T){f=T},this.setRequestHeader=function(T,D){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");if(!V(T))return console.warn('Refused to set unsafe header "'+T+'"'),!1;if(_)throw new Error("INVALID_STATE_ERR: send flag is true");return l[T]=D,!0},this.getResponseHeader=function(T){return typeof T=="string"&&this.readyState>this.OPENED&&s.headers[T.toLowerCase()]&&!b?s.headers[T.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||b)return"";var T="";for(var D in s.headers)D!=="set-cookie"&&D!=="set-cookie2"&&(T+=D+": "+s.headers[D]+`\r
|
|
124
|
+
`);return T.substr(0,T.length-2)},this.getRequestHeader=function(T){return typeof T=="string"&&l[T]?l[T]:""},this.send=function(T){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");if(_)throw new Error("INVALID_STATE_ERR: send has already been called");var D=!1,te=!1,q=tl.parse(a.url),ee;switch(q.protocol){case"https:":D=!0;case"http:":ee=q.hostname;break;case"file:":te=!0;break;case void 0:case"":ee="localhost";break;default:throw new Error("Protocol not supported.")}if(te){if(a.method!=="GET")throw new Error("XMLHttpRequest: Only GET method is supported");if(a.async)Vn.readFile(unescape(q.pathname),function(L,se){L?e.handleError(L,L.errno||-1):(e.status=200,e.responseText=se.toString("utf8"),e.response=se,z(e.DONE))});else try{this.response=Vn.readFileSync(unescape(q.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,z(e.DONE)}catch(L){this.handleError(L,L.errno||-1)}return}var pe=q.port||(D?443:80),K=q.pathname+(q.search?q.search:"");if(l.Host=ee,D&&pe===443||pe===80||(l.Host+=":"+q.port),a.user){typeof a.password>"u"&&(a.password="");var Me=new Buffer(a.user+":"+a.password);l.Authorization="Basic "+Me.toString("base64")}if(a.method==="GET"||a.method==="HEAD")T=null;else if(T){l["Content-Length"]=Buffer.isBuffer(T)?T.length:Buffer.byteLength(T);var tt=Object.keys(l);tt.some(function(L){return L.toLowerCase()==="content-type"})||(l["Content-Type"]="text/plain;charset=UTF-8")}else a.method==="POST"&&(l["Content-Length"]=0);var Te=r.agent||!1,De={host:ee,port:pe,path:K,method:a.method,headers:l,agent:Te};if(D&&(De.pfx=r.pfx,De.key=r.key,De.passphrase=r.passphrase,De.cert=r.cert,De.ca=r.ca,De.ciphers=r.ciphers,De.rejectUnauthorized=r.rejectUnauthorized!==!1),b=!1,a.async){var ve=D?n.request:t.request;_=!0,e.dispatchEvent("readystatechange");var We=function(L){if(s=L,s.statusCode===302||s.statusCode===303||s.statusCode===307){a.url=s.headers.location;var se=tl.parse(a.url);ee=se.hostname;var Ae={hostname:se.hostname,port:se.port,path:se.path,method:s.statusCode===303?"GET":a.method,headers:l};D&&(Ae.pfx=r.pfx,Ae.key=r.key,Ae.passphrase=r.passphrase,Ae.cert=r.cert,Ae.ca=r.ca,Ae.ciphers=r.ciphers,Ae.rejectUnauthorized=r.rejectUnauthorized!==!1),i=ve(Ae,We).on("error",_e),i.end();return}z(e.HEADERS_RECEIVED),e.status=s.statusCode,s.on("data",function(B){if(B){var oe=Buffer.from(B);e.response=Buffer.concat([e.response,oe])}_&&z(e.LOADING)}),s.on("end",function(){_&&(_=!1,z(e.DONE),e.responseText=e.response.toString("utf8"))}),s.on("error",function(B){e.handleError(B)})},_e=function(L){if(i.reusedSocket&&L.code==="ECONNRESET")return ve(De,We).on("error",_e);e.handleError(L)};i=ve(De,We).on("error",_e),r.autoUnref&&i.on("socket",L=>{L.unref()}),T&&i.write(T),i.end(),e.dispatchEvent("loadstart")}else{var rt=".node-xmlhttprequest-content-"+process.pid,Fe=".node-xmlhttprequest-sync-"+process.pid;Vn.writeFileSync(Fe,"","utf8");for(var Et="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(D?"s":"")+".request;var options = "+JSON.stringify(De)+";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('"+rt+"', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');fs.unlinkSync('"+Fe+"');});response.on('error', function(error) {fs.writeFileSync('"+rt+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Fe+"');});}).on('error', function(error) {fs.writeFileSync('"+rt+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Fe+"');});"+(T?"req.write('"+JSON.stringify(T).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",He=Zm(process.argv[0],["-e",Et]),pt;Vn.existsSync(Fe););if(e.responseText=Vn.readFileSync(rt,"utf8"),He.stdin.end(),Vn.unlinkSync(rt),e.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var N=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,""));e.handleError(N,503)}else{e.status=e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/,"$1");var 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"),z(e.DONE,!0)}}},this.handleError=function(T,D){this.status=D||0,this.statusText=T,this.responseText=T.stack,b=!0,z(this.DONE)},this.abort=function(){i&&(i.abort(),i=null),l=Object.assign({},c),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),b=x=!0,this.readyState!==this.UNSENT&&(this.readyState!==this.OPENED||_)&&this.readyState!==this.DONE&&(_=!1,z(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(T,D){T in O||(O[T]=[]),O[T].push(D)},this.removeEventListener=function(T,D){T in O&&(O[T]=O[T].filter(function(te){return te!==D}))},this.dispatchEvent=function(T){if(typeof e["on"+T]=="function"&&(this.readyState===this.DONE&&a.async?setTimeout(function(){e["on"+T]()},0):e["on"+T]()),T in O)for(let D=0,te=O[T].length;D<te;D++)this.readyState===this.DONE?setTimeout(function(){O[T][D].call(e)},0):O[T][D].call(e)};var z=function(T){if(!(e.readyState===T||e.readyState===e.UNSENT&&x)&&(e.readyState=T,(a.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let D;x?D="abort":b?D="error":D="load",e.dispatchEvent(D),e.dispatchEvent("loadend")}}}});var Bs=I(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});Xr.ERROR_PACKET=Xr.PACKET_TYPES_REVERSE=Xr.PACKET_TYPES=void 0;var pr=Object.create(null);Xr.PACKET_TYPES=pr;pr.open="0";pr.close="1";pr.ping="2";pr.pong="3";pr.message="4";pr.upgrade="5";pr.noop="6";var il=Object.create(null);Xr.PACKET_TYPES_REVERSE=il;Object.keys(pr).forEach(r=>{il[pr[r]]=r});var Qm={type:"error",data:"parser error"};Xr.ERROR_PACKET=Qm});var ol=I($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.encodePacket=void 0;$n.encodePacketToBinary=ty;var Jm=Bs(),ey=({type:r,data:e},t,n)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?n(t?e:"b"+sl(e,!0).toString("base64")):n(Jm.PACKET_TYPES[r]+(e||""));$n.encodePacket=ey;var sl=(r,e)=>Buffer.isBuffer(r)||r instanceof Uint8Array&&!e?r:r instanceof ArrayBuffer?Buffer.from(r):Buffer.from(r.buffer,r.byteOffset,r.byteLength),xa;function ty(r,e){if(r.data instanceof ArrayBuffer||ArrayBuffer.isView(r.data))return e(sl(r.data,!1));(0,$n.encodePacket)(r,!0,t=>{xa||(xa=new TextEncoder),e(xa.encode(t))})}});var cl=I(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});Us.decodePacket=void 0;var js=Bs(),ry=(r,e)=>{if(typeof r!="string")return{type:"message",data:al(r,e)};let t=r.charAt(0);if(t==="b"){let n=Buffer.from(r.substring(1),"base64");return{type:"message",data:al(n,e)}}return js.PACKET_TYPES_REVERSE[t]?r.length>1?{type:js.PACKET_TYPES_REVERSE[t],data:r.substring(1)}:{type:js.PACKET_TYPES_REVERSE[t]}:js.ERROR_PACKET};Us.decodePacket=ry;var al=(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 Gn=I(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.decodePayload=Tt.decodePacket=Tt.encodePayload=Tt.encodePacket=Tt.protocol=void 0;Tt.createPacketEncoderStream=sy;Tt.createPacketDecoderStream=oy;var Oa=ol();Object.defineProperty(Tt,"encodePacket",{enumerable:!0,get:function(){return Oa.encodePacket}});var Ca=cl();Object.defineProperty(Tt,"decodePacket",{enumerable:!0,get:function(){return Ca.decodePacket}});var fl=Bs(),ul="",ny=(r,e)=>{let t=r.length,n=new Array(t),i=0;r.forEach((s,a)=>{(0,Oa.encodePacket)(s,!1,f=>{n[a]=f,++i===t&&e(n.join(ul))})})};Tt.encodePayload=ny;var iy=(r,e)=>{let t=r.split(ul),n=[];for(let i=0;i<t.length;i++){let s=(0,Ca.decodePacket)(t[i],e);if(n.push(s),s.type==="error")break}return n};Tt.decodePayload=iy;function sy(){return new TransformStream({transform(r,e){(0,Oa.encodePacketToBinary)(r,t=>{let n=t.length,i;if(n<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,n);else if(n<65536){i=new Uint8Array(3);let s=new DataView(i.buffer);s.setUint8(0,126),s.setUint16(1,n)}else{i=new Uint8Array(9);let s=new DataView(i.buffer);s.setUint8(0,127),s.setBigUint64(1,BigInt(n))}r.data&&typeof r.data!="string"&&(i[0]|=128),e.enqueue(i),e.enqueue(t)})}})}var Ta;function qs(r){return r.reduce((e,t)=>e+t.length,0)}function Ks(r,e){if(r[0].length===e)return r.shift();let t=new Uint8Array(e),n=0;for(let i=0;i<e;i++)t[i]=r[0][n++],n===r[0].length&&(r.shift(),n=0);return r.length&&n<r[0].length&&(r[0]=r[0].slice(n)),t}function oy(r,e){Ta||(Ta=new TextDecoder);let t=[],n=0,i=-1,s=!1;return new TransformStream({transform(a,f){for(t.push(a);;){if(n===0){if(qs(t)<1)break;let c=Ks(t,1);s=(c[0]&128)===128,i=c[0]&127,i<126?n=3:i===126?n=1:n=2}else if(n===1){if(qs(t)<2)break;let c=Ks(t,2);i=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),n=3}else if(n===2){if(qs(t)<8)break;let c=Ks(t,8),l=new DataView(c.buffer,c.byteOffset,c.length),p=l.getUint32(0);if(p>Math.pow(2,21)-1){f.enqueue(fl.ERROR_PACKET);break}i=p*Math.pow(2,32)+l.getUint32(4),n=3}else{if(qs(t)<i)break;let c=Ks(t,i);f.enqueue((0,Ca.decodePacket)(s?c:Ta.decode(c),e)),n=0}if(i===0||i>r){f.enqueue(fl.ERROR_PACKET);break}}}})}Tt.protocol=4});var wn=I(ll=>{ll.Emitter=vt;function vt(r){if(r)return ay(r)}function ay(r){for(var e in vt.prototype)r[e]=vt.prototype[e];return r}vt.prototype.on=vt.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this};vt.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this};vt.prototype.off=vt.prototype.removeListener=vt.prototype.removeAllListeners=vt.prototype.removeEventListener=function(r,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+r];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+r],this;for(var n,i=0;i<t.length;i++)if(n=t[i],n===e||n.fn===e){t.splice(i,1);break}return t.length===0&&delete this._callbacks["$"+r],this};vt.prototype.emit=function(r){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+r],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t){t=t.slice(0);for(var n=0,i=t.length;n<i;++n)t[n].apply(this,e)}return this};vt.prototype.emitReserved=vt.prototype.emit;vt.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};vt.prototype.hasListeners=function(r){return!!this.listeners(r).length}});var vn=I(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.CookieJar=jt.defaultBinaryType=jt.globalThisShim=jt.nextTick=void 0;jt.createCookieJar=cy;jt.parse=hl;jt.nextTick=process.nextTick;jt.globalThisShim=global;jt.defaultBinaryType="nodebuffer";function cy(){return new Ws}function hl(r){let e=r.split("; "),t=e[0].indexOf("=");if(t===-1)return;let n=e[0].substring(0,t).trim();if(!n.length)return;let i=e[0].substring(t+1).trim();i.charCodeAt(0)===34&&(i=i.slice(1,-1));let s={name:n,value:i};for(let a=1;a<e.length;a++){let f=e[a].split("=");if(f.length!==2)continue;let c=f[0].trim(),l=f[1].trim();switch(c){case"Expires":s.expires=new Date(l);break;case"Max-Age":let p=new Date;p.setUTCSeconds(p.getUTCSeconds()+parseInt(l,10)),s.expires=p;break;default:}}return s}var Ws=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let n=hl(t);n&&this._cookies.set(n.name,n)})}get cookies(){let e=Date.now();return this._cookies.forEach((t,n)=>{var i;((i=t.expires)===null||i===void 0?void 0:i.getTime())<e&&this._cookies.delete(n)}),this._cookies.entries()}addCookies(e){let t=[];for(let[n,i]of this.cookies)t.push(`${n}=${i.value}`);t.length&&(e.setDisableHeaderCheck(!0),e.setRequestHeader("cookie",t.join("; ")))}appendCookies(e){for(let[t,n]of this.cookies)e.append("cookie",`${t}=${n.value}`)}};jt.CookieJar=Ws});var Sn=I(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.pick=fy;zn.installTimerFunctions=hy;zn.byteLength=py;zn.randomString=my;var Zr=vn();function fy(r,...e){return e.reduce((t,n)=>(r.hasOwnProperty(n)&&(t[n]=r[n]),t),{})}var uy=Zr.globalThisShim.setTimeout,ly=Zr.globalThisShim.clearTimeout;function hy(r,e){e.useNativeTimers?(r.setTimeoutFn=uy.bind(Zr.globalThisShim),r.clearTimeoutFn=ly.bind(Zr.globalThisShim)):(r.setTimeoutFn=Zr.globalThisShim.setTimeout.bind(Zr.globalThisShim),r.clearTimeoutFn=Zr.globalThisShim.clearTimeout.bind(Zr.globalThisShim))}var dy=1.33;function py(r){return typeof r=="string"?gy(r):Math.ceil((r.byteLength||r.size)*dy)}function gy(r){let e=0,t=0;for(let n=0,i=r.length;n<i;n++)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(n++,t+=4);return t}function my(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}});var Pa=I(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});Hs.encode=yy;Hs.decode=_y;function yy(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function _y(r){let e={},t=r.split("&");for(let n=0,i=t.length;n<i;n++){let s=t[n].split("=");e[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return e}});var pl=I((Jv,dl)=>{var Yn=1e3,Xn=Yn*60,Zn=Xn*60,xn=Zn*24,Ey=xn*7,by=xn*365.25;dl.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return wy(r);if(t==="number"&&isFinite(r))return e.long?Sy(r):vy(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function wy(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*by;case"weeks":case"week":case"w":return t*Ey;case"days":case"day":case"d":return t*xn;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Zn;case"minutes":case"minute":case"mins":case"min":case"m":return t*Xn;case"seconds":case"second":case"secs":case"sec":case"s":return t*Yn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function vy(r){var e=Math.abs(r);return e>=xn?Math.round(r/xn)+"d":e>=Zn?Math.round(r/Zn)+"h":e>=Xn?Math.round(r/Xn)+"m":e>=Yn?Math.round(r/Yn)+"s":r+"ms"}function Sy(r){var e=Math.abs(r);return e>=xn?Vs(r,e,xn,"day"):e>=Zn?Vs(r,e,Zn,"hour"):e>=Xn?Vs(r,e,Xn,"minute"):e>=Yn?Vs(r,e,Yn,"second"):r+" ms"}function Vs(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var ka=I((eS,gl)=>{function xy(r){t.debug=t,t.default=t,t.coerce=c,t.disable=a,t.enable=i,t.enabled=f,t.humanize=pl(),t.destroy=l,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,b,x;function O(...V){if(!O.enabled)return;let ie=O,z=Number(new Date),T=z-(m||z);ie.diff=T,ie.prev=m,ie.curr=z,m=z,V[0]=t.coerce(V[0]),typeof V[0]!="string"&&V.unshift("%O");let D=0;V[0]=V[0].replace(/%([a-zA-Z%])/g,(q,ee)=>{if(q==="%%")return"%";D++;let pe=t.formatters[ee];if(typeof pe=="function"){let K=V[D];q=pe.call(ie,K),V.splice(D,1),D--}return q}),t.formatArgs.call(ie,V),(ie.log||t.log).apply(ie,V)}return O.namespace=p,O.useColors=t.useColors(),O.color=t.selectColor(p),O.extend=n,O.destroy=t.destroy,Object.defineProperty(O,"enabled",{enumerable:!0,configurable:!1,get:()=>_!==null?_:(b!==t.namespaces&&(b=t.namespaces,x=t.enabled(p)),x),set:V=>{_=V}}),typeof t.init=="function"&&t.init(O),O}function n(p,m){let _=t(this.namespace+(typeof m>"u"?":":m)+p);return _.log=this.log,_}function i(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,b=0,x=-1,O=0;for(;_<p.length;)if(b<m.length&&(m[b]===p[_]||m[b]==="*"))m[b]==="*"?(x=b,O=_,b++):(_++,b++);else if(x!==-1)b=x+1,O++,_=O;else return!1;for(;b<m.length&&m[b]==="*";)b++;return b===m.length}function a(){let p=[...t.names,...t.skips.map(m=>"-"+m)].join(",");return t.enable(""),p}function f(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 c(p){return p instanceof Error?p.stack||p.message:p}function l(){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}gl.exports=xy});var ml=I((Ot,$s)=>{Ot.formatArgs=Oy;Ot.save=Cy;Ot.load=Py;Ot.useColors=Ty;Ot.storage=ky();Ot.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`."))}})();Ot.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 Ty(){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 Oy(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+$s.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(t++,i==="%c"&&(n=t))}),r.splice(n,0,e)}Ot.log=console.debug||console.log||(()=>{});function Cy(r){try{r?Ot.storage.setItem("debug",r):Ot.storage.removeItem("debug")}catch{}}function Py(){let r;try{r=Ot.storage.getItem("debug")||Ot.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function ky(){try{return localStorage}catch{}}$s.exports=ka()(Ot);var{formatters:Ay}=$s.exports;Ay.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var _l=I((tS,yl)=>{"use strict";yl.exports=(r,e=process.argv)=>{let t=r.startsWith("-")?"":r.length===1?"-":"--",n=e.indexOf(t+r),i=e.indexOf("--");return n!==-1&&(i===-1||n<i)}});var wl=I((rS,bl)=>{"use strict";var Ry=require("os"),El=require("tty"),Ut=_l(),{env:ft}=process,Qr;Ut("no-color")||Ut("no-colors")||Ut("color=false")||Ut("color=never")?Qr=0:(Ut("color")||Ut("colors")||Ut("color=true")||Ut("color=always"))&&(Qr=1);"FORCE_COLOR"in ft&&(ft.FORCE_COLOR==="true"?Qr=1:ft.FORCE_COLOR==="false"?Qr=0:Qr=ft.FORCE_COLOR.length===0?1:Math.min(parseInt(ft.FORCE_COLOR,10),3));function Aa(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function Ra(r,e){if(Qr===0)return 0;if(Ut("color=16m")||Ut("color=full")||Ut("color=truecolor"))return 3;if(Ut("color=256"))return 2;if(r&&!e&&Qr===void 0)return 0;let t=Qr||0;if(ft.TERM==="dumb")return t;if(process.platform==="win32"){let n=Ry.release().split(".");return Number(n[0])>=10&&Number(n[2])>=10586?Number(n[2])>=14931?3:2:1}if("CI"in ft)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(n=>n in ft)||ft.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in ft)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(ft.TEAMCITY_VERSION)?1:0;if(ft.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in ft){let n=parseInt((ft.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(ft.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(ft.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(ft.TERM)||"COLORTERM"in ft?1:t}function Iy(r){let e=Ra(r,r&&r.isTTY);return Aa(e)}bl.exports={supportsColor:Iy,stdout:Aa(Ra(!0,El.isatty(1))),stderr:Aa(Ra(!0,El.isatty(2)))}});var Sl=I((ut,zs)=>{var Ly=require("tty"),Gs=require("util");ut.init=Uy;ut.log=Fy;ut.formatArgs=My;ut.save=By;ut.load=jy;ut.useColors=Ny;ut.destroy=Gs.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");ut.colors=[6,2,3,4,5,1];try{let r=wl();r&&(r.stderr||r).level>=2&&(ut.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{}ut.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(i,s)=>s.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),r[t]=n,r},{});function Ny(){return"colors"in ut.inspectOpts?!!ut.inspectOpts.colors:Ly.isatty(process.stderr.fd)}function My(r){let{namespace:e,useColors:t}=this;if(t){let n=this.color,i="\x1B[3"+(n<8?n:"8;5;"+n),s=` ${i};1m${e} \x1B[0m`;r[0]=s+r[0].split(`
|
|
21
125
|
`).join(`
|
|
22
|
-
`+s),r.push(i+"m+"+
|
|
23
|
-
`)}function
|
|
24
|
-
`).map(e=>e.trim()).join(" ")};il.O=function(r){return this.inspectOpts.colors=this.useColors,Ks.inspect(r,this.inspectOpts)}});var jt=L((vw,Sa)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Sa.exports=Zu():Sa.exports=sl()});var Ri=L(Xr=>{"use strict";var oy=Xr&&Xr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Xr,"__esModule",{value:!0});Xr.Transport=Xr.TransportError=void 0;var ay=Hn(),cy=_n(),fy=bn(),uy=Ea(),ly=oy(jt()),hy=(0,ly.default)("engine.io-client:transport"),Ws=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}};Xr.TransportError=Ws;var xa=class extends cy.Emitter{constructor(e){super(),this.writable=!1,(0,fy.installTimerFunctions)(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new Ws(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"?this.write(e):hy("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=(0,ay.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,uy.encode)(e);return t.length?"?"+t:""}};Xr.Transport=xa});var Ca=L(Yn=>{"use strict";var dy=Yn&&Yn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Yn,"__esModule",{value:!0});Yn.Polling=void 0;var py=Ri(),gy=bn(),ol=Hn(),my=dy(jt()),Gt=(0,my.default)("engine.io-client:polling"),Ta=class extends py.Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{Gt("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let n=0;this._polling&&(Gt("we are currently polling - waiting to pause"),n++,this.once("pollComplete",function(){Gt("pre-pause polling complete"),--n||t()})),this.writable||(Gt("we are currently writing - waiting to pause"),n++,this.once("drain",function(){Gt("pre-pause writing complete"),--n||t()}))}else t()}_poll(){Gt("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){Gt("polling got data %s",e);let t=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};(0,ol.decodePayload)(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Gt('ignoring poll - transport state "%s"',this.readyState))}doClose(){let e=()=>{Gt("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Gt("transport open - closing"),e()):(Gt("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,(0,ol.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,gy.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}};Yn.Polling=Ta});var cl=L(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});Hs.hasCORS=void 0;var al=!1;try{al=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}Hs.hasCORS=al});var Pa=L(hr=>{"use strict";var yy=hr&&hr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(hr,"__esModule",{value:!0});hr.XHR=hr.Request=hr.BaseXHR=void 0;var _y=Ca(),Ey=_n(),fl=bn(),ll=En(),by=cl(),vy=yy(jt()),ka=(0,vy.default)("engine.io-client:polling");function wy(){}var Vs=class extends _y.Polling{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",n=location.port;n||(n=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){let n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(i,s)=>{this.onError("xhr post error",i,s)})}doPoll(){ka("xhr poll");let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=e}};hr.BaseXHR=Vs;var Ar=class r extends Ey.Emitter{constructor(e,t,n){super(),this.createRequest=e,(0,fl.installTimerFunctions)(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var e;let t=(0,fl.pick)(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let n=this._xhr=this.createRequest(t);try{ka("xhr open %s: %s",this._method,this._uri),n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&n.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var i;n.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},ka("xhr data %s",this._data),n.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},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=wy,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()}};hr.Request=Ar;Ar.requestsCount=0;Ar.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",ul);else if(typeof addEventListener=="function"){let r="onpagehide"in ll.globalThisShim?"pagehide":"unload";addEventListener(r,ul,!1)}}function ul(){for(let r in Ar.requests)Ar.requests.hasOwnProperty(r)&&Ar.requests[r].abort()}var Sy=(function(){let r=hl({xdomain:!1});return r&&r.responseType!==null})(),Oa=class extends Vs{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=Sy&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Ar(hl,this.uri(),e)}};hr.XHR=Oa;function hl(r){let e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||by.hasCORS))return new XMLHttpRequest}catch{}if(!e)try{return new ll.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}});var Ra=L(dr=>{"use strict";var xy=dr&&dr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Ty=dr&&dr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Cy=dr&&dr.__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)&&xy(e,r,t);return Ty(e,r),e};Object.defineProperty(dr,"__esModule",{value:!0});dr.XHR=void 0;var dl=Cy(ju()),pl=Pa(),ky=dl.default||dl,Aa=class extends pl.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 pl.Request(n=>new ky(n),this.uri(),e)}};dr.XHR=Aa});var Rr=L((kw,yl)=>{"use strict";var gl=["nodebuffer","arraybuffer","fragments"],ml=typeof Blob<"u";ml&&gl.push("blob");yl.exports={BINARY_TYPES:gl,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:ml,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ii=L((Ow,$s)=>{"use strict";var{EMPTY_BUFFER:Oy}=Rr(),Ia=Buffer[Symbol.species];function Py(r,e){if(r.length===0)return Oy;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let i=0;i<r.length;i++){let s=r[i];t.set(s,n),n+=s.length}return n<e?new Ia(t.buffer,t.byteOffset,n):t}function _l(r,e,t,n,i){for(let s=0;s<i;s++)t[n+s]=r[s]^e[s&3]}function El(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function Ay(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function La(r){if(La.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new Ia(r):ArrayBuffer.isView(r)?e=new Ia(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),La.readOnly=!1),e}$s.exports={concat:Py,mask:_l,toArrayBuffer:Ay,toBuffer:La,unmask:El};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");$s.exports.mask=function(e,t,n,i,s){s<48?_l(e,t,n,i,s):r.mask(e,t,n,i,s)},$s.exports.unmask=function(e,t){e.length<32?El(e,t):r.unmask(e,t)}}catch{}});var wl=L((Pw,vl)=>{"use strict";var bl=Symbol("kDone"),Na=Symbol("kRun"),Ma=class{constructor(e){this[bl]=()=>{this.pending--,this[Na]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Na]()}[Na](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[bl])}}};vl.exports=Ma});var Ni=L((Aw,Cl)=>{"use strict";var Li=require("zlib"),Sl=Ii(),Ry=wl(),{kStatusCode:xl}=Rr(),Iy=Buffer[Symbol.species],Ly=Buffer.from([0,0,255,255]),Gs=Symbol("permessage-deflate"),Ir=Symbol("total-length"),Xn=Symbol("callback"),Jr=Symbol("buffers"),Jn=Symbol("error"),zs,Fa=class{constructor(e,t,n){if(this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!zs){let i=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;zs=new Ry(i)}}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[Xn];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,n=e.find(i=>!(t.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>i.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(n=>{let i=t[n];if(i.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(i=i[0],n==="client_max_window_bits"){if(i!==!0){let s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else if(n==="server_max_window_bits"){let s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=s}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=i})}),e}decompress(e,t,n){zs.add(i=>{this._decompress(e,t,(s,a)=>{i(),n(s,a)})})}compress(e,t,n){zs.add(i=>{this._compress(e,t,(s,a)=>{i(),n(s,a)})})}_decompress(e,t,n){let i=this._isServer?"client":"server";if(!this._inflate){let s=`${i}_max_window_bits`,a=typeof this.params[s]!="number"?Li.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=Li.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[Gs]=this,this._inflate[Ir]=0,this._inflate[Jr]=[],this._inflate.on("error",My),this._inflate.on("data",Tl)}this._inflate[Xn]=n,this._inflate.write(e),t&&this._inflate.write(Ly),this._inflate.flush(()=>{let s=this._inflate[Jn];if(s){this._inflate.close(),this._inflate=null,n(s);return}let a=Sl.concat(this._inflate[Jr],this._inflate[Ir]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Ir]=0,this._inflate[Jr]=[],t&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),n(null,a)})}_compress(e,t,n){let i=this._isServer?"server":"client";if(!this._deflate){let s=`${i}_max_window_bits`,a=typeof this.params[s]!="number"?Li.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=Li.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[Ir]=0,this._deflate[Jr]=[],this._deflate.on("data",Ny)}this._deflate[Xn]=n,this._deflate.write(e),this._deflate.flush(Li.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=Sl.concat(this._deflate[Jr],this._deflate[Ir]);t&&(s=new Iy(s.buffer,s.byteOffset,s.length-4)),this._deflate[Xn]=null,this._deflate[Ir]=0,this._deflate[Jr]=[],t&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),n(null,s)})}};Cl.exports=Fa;function Ny(r){this[Jr].push(r),this[Ir]+=r.length}function Tl(r){if(this[Ir]+=r.length,this[Gs]._maxPayload<1||this[Ir]<=this[Gs]._maxPayload){this[Jr].push(r);return}this[Jn]=new RangeError("Max payload size exceeded"),this[Jn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Jn][xl]=1009,this.removeListener("data",Tl),this.reset()}function My(r){if(this[Gs]._inflate=null,this[Jn]){this[Xn](this[Jn]);return}r[xl]=1007,this[Xn](r)}});var Zn=L((Rw,Ys)=>{"use strict";var{isUtf8:kl}=require("buffer"),{hasBlob:Fy}=Rr(),Dy=[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 By(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Da(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 jy(r){return Fy&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}Ys.exports={isBlob:jy,isValidStatusCode:By,isValidUTF8:Da,tokenChars:Dy};if(kl)Ys.exports.isValidUTF8=function(r){return r.length<24?Da(r):kl(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");Ys.exports.isValidUTF8=function(e){return e.length<32?Da(e):r(e)}}catch{}});var qa=L((Iw,Nl)=>{"use strict";var{Writable:Uy}=require("stream"),Ol=Ni(),{BINARY_TYPES:Ky,EMPTY_BUFFER:Pl,kStatusCode:qy,kWebSocket:Wy}=Rr(),{concat:Ba,toArrayBuffer:Hy,unmask:Vy}=Ii(),{isValidStatusCode:$y,isValidUTF8:Al}=Zn(),Xs=Buffer[Symbol.species],Ut=0,Rl=1,Il=2,Ll=3,ja=4,Ua=5,Js=6,Ka=class extends Uy{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Ky[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Wy]=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=Ut}_write(e,t,n){if(this._opcode===8&&this._state==Ut)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new Xs(n.buffer,n.byteOffset+e,n.length-e),new Xs(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],i=t.length-e;e>=n.length?t.set(this._buffers.shift(),i):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),i),this._buffers[0]=new Xs(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case Ut:this.getInfo(e);break;case Rl:this.getPayloadLength16(e);break;case Il:this.getPayloadLength64(e);break;case Ll:this.getMask();break;case ja:this.getData(e);break;case Ua:case Js: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 i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let n=(t[0]&64)===64;if(n&&!this._extensions[Ol.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=Rl:this._payloadLength===127?this._state=Il:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=Ll:this._state=ja}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ja}getData(e){let t=Pl;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&&Vy(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Ua,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Ol.extensionName].decompress(e,this._fin,(i,s)=>{if(i)return t(i);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===Ut&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Ut;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=Ba(n,t):this._binaryType==="arraybuffer"?i=Hy(Ba(n,t)):this._binaryType==="blob"?i=new Blob(n):i=n,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=Ut):(this._state=Js,setImmediate(()=>{this.emit("message",i,!0),this._state=Ut,this.startLoop(e)}))}else{let i=Ba(n,t);if(!this._skipUTF8Validation&&!Al(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===Ua||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=Ut):(this._state=Js,setImmediate(()=>{this.emit("message",i,!1),this._state=Ut,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Pl),this.end();else{let n=e.readUInt16BE(0);if(!$y(n)){let s=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(s);return}let i=new Xs(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Al(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(s);return}this._loop=!1,this.emit("conclude",n,i),this.end()}this._state=Ut;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Ut):(this._state=Js,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Ut,this.startLoop(t)}))}createError(e,t,n,i,s){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=s,a[qy]=i,a}};Nl.exports=Ka});var Va=L((Nw,Dl)=>{"use strict";var{Duplex:Lw}=require("stream"),{randomFillSync:zy}=require("crypto"),Ml=Ni(),{EMPTY_BUFFER:Gy,kWebSocket:Yy,NOOP:Xy}=Rr(),{isBlob:Qn,isValidStatusCode:Jy}=Zn(),{mask:Fl,toBuffer:wn}=Ii(),Kt=Symbol("kByteLength"),Zy=Buffer.alloc(4),Zs=8*1024,Sn,ei=Zs,Yt=0,Qy=1,e_=2,Wa=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Yt,this.onerror=Xy,this[Yy]=void 0}static frame(e,t){let n,i=!1,s=2,a=!1;t.mask&&(n=t.maskBuffer||Zy,t.generateMask?t.generateMask(n):(ei===Zs&&(Sn===void 0&&(Sn=Buffer.alloc(Zs)),zy(Sn,0,Zs),ei=0),n[0]=Sn[ei++],n[1]=Sn[ei++],n[2]=Sn[ei++],n[3]=Sn[ei++]),a=(n[0]|n[1]|n[2]|n[3])===0,s=6);let f;typeof e=="string"?(!t.mask||a)&&t[Kt]!==void 0?f=t[Kt]:(e=Buffer.from(e),f=e.length):(f=e.length,i=t.mask&&t.readOnly&&!a);let c=f;f>=65536?(s+=8,c=127):f>125&&(s+=2,c=126);let l=Buffer.allocUnsafe(i?f+s:s);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(f,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(f,4,6)),t.mask?(l[1]|=128,l[s-4]=n[0],l[s-3]=n[1],l[s-2]=n[2],l[s-1]=n[3],a?[l,e]:i?(Fl(e,n,l,s,f),[l]):(Fl(e,n,e,0,f),[l,e])):[l,e]}close(e,t,n,i){let s;if(e===void 0)s=Gy;else{if(typeof e!="number"||!Jy(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 f=Buffer.byteLength(t);if(f>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+f),s.writeUInt16BE(e,0),typeof t=="string"?s.write(t,2):s.set(t,2)}}let a={[Kt]:s.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Yt?this.enqueue([this.dispatch,s,!1,a,i]):this.sendFrame(r.frame(s,a),i)}ping(e,t,n){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):Qn(e)?(i=e.size,s=!1):(e=wn(e),i=e.length,s=wn.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Kt]:i,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};Qn(e)?this._state!==Yt?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==Yt?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(r.frame(e,a),n)}pong(e,t,n){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):Qn(e)?(i=e.size,s=!1):(e=wn(e),i=e.length,s=wn.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Kt]:i,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};Qn(e)?this._state!==Yt?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==Yt?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(r.frame(e,a),n)}send(e,t,n){let i=this._extensions[Ml.extensionName],s=t.binary?2:1,a=t.compress,f,c;typeof e=="string"?(f=Buffer.byteLength(e),c=!1):Qn(e)?(f=e.size,c=!1):(e=wn(e),f=e.length,c=wn.readOnly),this._firstFragment?(this._firstFragment=!1,a&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=f>=i._threshold),this._compress=a):(a=!1,s=0),t.fin&&(this._firstFragment=!0);let l={[Kt]:f,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:c,rsv1:a};Qn(e)?this._state!==Yt?this.enqueue([this.getBlobData,e,this._compress,l,n]):this.getBlobData(e,this._compress,l,n):this._state!==Yt?this.enqueue([this.dispatch,e,this._compress,l,n]):this.dispatch(e,this._compress,l,n)}getBlobData(e,t,n,i){this._bufferedBytes+=n[Kt],this._state=e_,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let f=new Error("The socket was closed while the blob was being read");process.nextTick(Ha,this,f,i);return}this._bufferedBytes-=n[Kt];let a=wn(s);t?this.dispatch(a,t,n,i):(this._state=Yt,this.sendFrame(r.frame(a,n),i),this.dequeue())}).catch(s=>{process.nextTick(t_,this,s,i)})}dispatch(e,t,n,i){if(!t){this.sendFrame(r.frame(e,n),i);return}let s=this._extensions[Ml.extensionName];this._bufferedBytes+=n[Kt],this._state=Qy,s.compress(e,n.fin,(a,f)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Ha(this,c,i);return}this._bufferedBytes-=n[Kt],this._state=Yt,n.readOnly=!1,this.sendFrame(r.frame(f,n),i),this.dequeue()})}dequeue(){for(;this._state===Yt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Kt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Kt],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)}};Dl.exports=Wa;function Ha(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let i=r._queue[n],s=i[i.length-1];typeof s=="function"&&s(e)}}function t_(r,e,t){Ha(r,e,t),r.onerror(e)}});var $l=L((Mw,Vl)=>{"use strict";var{kForOnEventAttribute:Mi,kListener:$a}=Rr(),Bl=Symbol("kCode"),jl=Symbol("kData"),Ul=Symbol("kError"),Kl=Symbol("kMessage"),ql=Symbol("kReason"),ti=Symbol("kTarget"),Wl=Symbol("kType"),Hl=Symbol("kWasClean"),Lr=class{constructor(e){this[ti]=null,this[Wl]=e}get target(){return this[ti]}get type(){return this[Wl]}};Object.defineProperty(Lr.prototype,"target",{enumerable:!0});Object.defineProperty(Lr.prototype,"type",{enumerable:!0});var xn=class extends Lr{constructor(e,t={}){super(e),this[Bl]=t.code===void 0?0:t.code,this[ql]=t.reason===void 0?"":t.reason,this[Hl]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Bl]}get reason(){return this[ql]}get wasClean(){return this[Hl]}};Object.defineProperty(xn.prototype,"code",{enumerable:!0});Object.defineProperty(xn.prototype,"reason",{enumerable:!0});Object.defineProperty(xn.prototype,"wasClean",{enumerable:!0});var ri=class extends Lr{constructor(e,t={}){super(e),this[Ul]=t.error===void 0?null:t.error,this[Kl]=t.message===void 0?"":t.message}get error(){return this[Ul]}get message(){return this[Kl]}};Object.defineProperty(ri.prototype,"error",{enumerable:!0});Object.defineProperty(ri.prototype,"message",{enumerable:!0});var Fi=class extends Lr{constructor(e,t={}){super(e),this[jl]=t.data===void 0?null:t.data}get data(){return this[jl]}};Object.defineProperty(Fi.prototype,"data",{enumerable:!0});var r_={addEventListener(r,e,t={}){for(let i of this.listeners(r))if(!t[Mi]&&i[$a]===e&&!i[Mi])return;let n;if(r==="message")n=function(s,a){let f=new Fi("message",{data:a?s:s.toString()});f[ti]=this,Qs(e,this,f)};else if(r==="close")n=function(s,a){let f=new xn("close",{code:s,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});f[ti]=this,Qs(e,this,f)};else if(r==="error")n=function(s){let a=new ri("error",{error:s,message:s.message});a[ti]=this,Qs(e,this,a)};else if(r==="open")n=function(){let s=new Lr("open");s[ti]=this,Qs(e,this,s)};else return;n[Mi]=!!t[Mi],n[$a]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[$a]===e&&!t[Mi]){this.removeListener(r,t);break}}};Vl.exports={CloseEvent:xn,ErrorEvent:ri,Event:Lr,EventTarget:r_,MessageEvent:Fi};function Qs(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var za=L((Fw,zl)=>{"use strict";var{tokenChars:Di}=Zn();function pr(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function n_(r){let e=Object.create(null),t=Object.create(null),n=!1,i=!1,s=!1,a,f,c=-1,l=-1,p=-1,m=0;for(;m<r.length;m++)if(l=r.charCodeAt(m),a===void 0)if(p===-1&&Di[l]===1)c===-1&&(c=m);else if(m!==0&&(l===32||l===9))p===-1&&c!==-1&&(p=m);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m);let b=r.slice(c,p);l===44?(pr(e,b,t),t=Object.create(null)):a=b,c=p=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);else if(f===void 0)if(p===-1&&Di[l]===1)c===-1&&(c=m);else if(l===32||l===9)p===-1&&c!==-1&&(p=m);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m),pr(t,r.slice(c,p),!0),l===44&&(pr(e,a,t),t=Object.create(null),a=void 0),c=p=-1}else if(l===61&&c!==-1&&p===-1)f=r.slice(c,m),c=p=-1;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(i){if(Di[l]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);c===-1?c=m:n||(n=!0),i=!1}else if(s)if(Di[l]===1)c===-1&&(c=m);else if(l===34&&c!==-1)s=!1,p=m;else if(l===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(l===34&&r.charCodeAt(m-1)===61)s=!0;else if(p===-1&&Di[l]===1)c===-1&&(c=m);else if(c!==-1&&(l===32||l===9))p===-1&&(p=m);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m);let b=r.slice(c,p);n&&(b=b.replace(/\\/g,""),n=!1),pr(t,f,b),l===44&&(pr(e,a,t),t=Object.create(null),a=void 0),f=void 0,c=p=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);if(c===-1||s||l===32||l===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=m);let _=r.slice(c,p);return a===void 0?pr(e,_,t):(f===void 0?pr(t,_,!0):n?pr(t,f,_.replace(/\\/g,"")):pr(t,f,_),pr(e,a,t)),e}function i_(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(i=>{let s=n[i];return Array.isArray(s)||(s=[s]),s.map(a=>a===!0?i:`${i}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}zl.exports={format:i_,parse:n_}});var no=L((jw,sh)=>{"use strict";var s_=require("events"),o_=require("https"),a_=require("http"),Xl=require("net"),c_=require("tls"),{randomBytes:f_,createHash:u_}=require("crypto"),{Duplex:Dw,Readable:Bw}=require("stream"),{URL:Ga}=require("url"),Zr=Ni(),l_=qa(),h_=Va(),{isBlob:d_}=Zn(),{BINARY_TYPES:Gl,EMPTY_BUFFER:eo,GUID:p_,kForOnEventAttribute:Ya,kListener:g_,kStatusCode:m_,kWebSocket:ut,NOOP:Jl}=Rr(),{EventTarget:{addEventListener:y_,removeEventListener:__}}=$l(),{format:E_,parse:b_}=za(),{toBuffer:v_}=Ii(),w_=30*1e3,Zl=Symbol("kAborted"),Xa=[8,13],Nr=["CONNECTING","OPEN","CLOSING","CLOSED"],S_=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ze=class r extends s_{constructor(e,t,n){super(),this._binaryType=Gl[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=eo,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(n=t,t=[]):t=[t]),Ql(this,e,t,n)):(this._autoPong=n.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Gl.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,n){let i=new l_({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),s=new h_(e,this._extensions,n.generateMask);this._receiver=i,this._sender=s,this._socket=e,i[ut]=this,s[ut]=this,e[ut]=this,i.on("conclude",C_),i.on("drain",k_),i.on("error",O_),i.on("message",P_),i.on("ping",A_),i.on("pong",R_),s.onerror=I_,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",rh),e.on("data",ro),e.on("end",nh),e.on("error",ih),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[Zr.extensionName]&&this._extensions[Zr.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){It(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),th(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ja(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||eo,t,n)}pong(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ja(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||eo,t,n)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(n=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ja(this,e,n);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Zr.extensionName]||(i.compress=!1),this._sender.send(e||eo,i,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){It(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(ze,"CONNECTING",{enumerable:!0,value:Nr.indexOf("CONNECTING")});Object.defineProperty(ze.prototype,"CONNECTING",{enumerable:!0,value:Nr.indexOf("CONNECTING")});Object.defineProperty(ze,"OPEN",{enumerable:!0,value:Nr.indexOf("OPEN")});Object.defineProperty(ze.prototype,"OPEN",{enumerable:!0,value:Nr.indexOf("OPEN")});Object.defineProperty(ze,"CLOSING",{enumerable:!0,value:Nr.indexOf("CLOSING")});Object.defineProperty(ze.prototype,"CLOSING",{enumerable:!0,value:Nr.indexOf("CLOSING")});Object.defineProperty(ze,"CLOSED",{enumerable:!0,value:Nr.indexOf("CLOSED")});Object.defineProperty(ze.prototype,"CLOSED",{enumerable:!0,value:Nr.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(ze.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(ze.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[Ya])return e[g_];return null},set(e){for(let t of this.listeners(r))if(t[Ya]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[Ya]:!0})}})});ze.prototype.addEventListener=y_;ze.prototype.removeEventListener=__;sh.exports=ze;function Ql(r,e,t,n){let i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:Xa[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=i.autoPong,!Xa.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${Xa.join(", ")})`);let s;if(e instanceof Ga)s=e;else try{s=new Ga(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:",f=s.protocol==="ws+unix:",c;if(s.protocol!=="ws:"&&!a&&!f?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:f&&!s.pathname?c="The URL's pathname is empty":s.hash&&(c="The URL contains a fragment identifier"),c){let C=new SyntaxError(c);if(r._redirects===0)throw C;to(r,C);return}let l=a?443:80,p=f_(16).toString("base64"),m=a?o_.request:a_.request,_=new Set,b;if(i.createConnection=i.createConnection||(a?T_:x_),i.defaultPort=i.defaultPort||l,i.port=s.port||l,i.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(b=new Zr(i.perMessageDeflate!==!0?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=E_({[Zr.extensionName]:b.offer()})),t.length){for(let C of t){if(typeof C!="string"||!S_.test(C)||_.has(C))throw new SyntaxError("An invalid or duplicated subprotocol was specified");_.add(C)}i.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(s.username||s.password)&&(i.auth=`${s.username}:${s.password}`),f){let C=i.path.split(":");i.socketPath=C[0],i.path=C[1]}let x;if(i.followRedirects){if(r._redirects===0){r._originalIpc=f,r._originalSecure=a,r._originalHostOrSocketPath=f?i.socketPath:s.host;let C=n&&n.headers;if(n={...n,headers:{}},C)for(let[H,ie]of Object.entries(C))n.headers[H.toLowerCase()]=ie}else if(r.listenerCount("redirect")===0){let C=f?r._originalIpc?i.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:s.host===r._originalHostOrSocketPath;(!C||r._originalSecure&&!a)&&(delete i.headers.authorization,delete i.headers.cookie,C||delete i.headers.host,i.auth=void 0)}i.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),x=r._req=m(i),r._redirects&&r.emit("redirect",r.url,x)}else x=r._req=m(i);i.timeout&&x.on("timeout",()=>{It(r,x,"Opening handshake has timed out")}),x.on("error",C=>{x===null||x[Zl]||(x=r._req=null,to(r,C))}),x.on("response",C=>{let H=C.headers.location,ie=C.statusCode;if(H&&i.followRedirects&&ie>=300&&ie<400){if(++r._redirects>i.maxRedirects){It(r,x,"Maximum redirects exceeded");return}x.abort();let z;try{z=new Ga(H,e)}catch{let F=new SyntaxError(`Invalid URL: ${H}`);to(r,F);return}Ql(r,z,t,n)}else r.emit("unexpected-response",x,C)||It(r,x,`Unexpected server response: ${C.statusCode}`)}),x.on("upgrade",(C,H,ie)=>{if(r.emit("upgrade",C),r.readyState!==ze.CONNECTING)return;x=r._req=null;let z=C.headers.upgrade;if(z===void 0||z.toLowerCase()!=="websocket"){It(r,H,"Invalid Upgrade header");return}let T=u_("sha1").update(p+p_).digest("base64");if(C.headers["sec-websocket-accept"]!==T){It(r,H,"Invalid Sec-WebSocket-Accept header");return}let F=C.headers["sec-websocket-protocol"],te;if(F!==void 0?_.size?_.has(F)||(te="Server sent an invalid subprotocol"):te="Server sent a subprotocol but none was requested":_.size&&(te="Server sent no subprotocol"),te){It(r,H,te);return}F&&(r._protocol=F);let U=C.headers["sec-websocket-extensions"];if(U!==void 0){if(!b){It(r,H,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ee;try{ee=b_(U)}catch{It(r,H,"Invalid Sec-WebSocket-Extensions header");return}let pe=Object.keys(ee);if(pe.length!==1||pe[0]!==Zr.extensionName){It(r,H,"Server indicated an extension that was not requested");return}try{b.accept(ee[Zr.extensionName])}catch{It(r,H,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Zr.extensionName]=b}r.setSocket(H,ie,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(x,r):x.end()}function to(r,e){r._readyState=ze.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function x_(r){return r.path=r.socketPath,Xl.connect(r)}function T_(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=Xl.isIP(r.host)?"":r.host),c_.connect(r)}function It(r,e,t){r._readyState=ze.CLOSING;let n=new Error(t);Error.captureStackTrace(n,It),e.setHeader?(e[Zl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(to,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function Ja(r,e,t){if(e){let n=d_(e)?e.size:v_(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${Nr[r.readyState]})`);process.nextTick(t,n)}}function C_(r,e){let t=this[ut];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[ut]!==void 0&&(t._socket.removeListener("data",ro),process.nextTick(eh,t._socket),r===1005?t.close():t.close(r,e))}function k_(){let r=this[ut];r.isPaused||r._socket.resume()}function O_(r){let e=this[ut];e._socket[ut]!==void 0&&(e._socket.removeListener("data",ro),process.nextTick(eh,e._socket),e.close(r[m_])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Yl(){this[ut].emitClose()}function P_(r,e){this[ut].emit("message",r,e)}function A_(r){let e=this[ut];e._autoPong&&e.pong(r,!this._isServer,Jl),e.emit("ping",r)}function R_(r){this[ut].emit("pong",r)}function eh(r){r.resume()}function I_(r){let e=this[ut];e.readyState!==ze.CLOSED&&(e.readyState===ze.OPEN&&(e._readyState=ze.CLOSING,th(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function th(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),w_)}function rh(){let r=this[ut];this.removeListener("close",rh),this.removeListener("data",ro),this.removeListener("end",nh),r._readyState=ze.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[ut]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Yl),r._receiver.on("finish",Yl))}function ro(r){this[ut]._receiver.write(r)||this.pause()}function nh(){let r=this[ut];r._readyState=ze.CLOSING,r._receiver.end(),this.end()}function ih(){let r=this[ut];this.removeListener("error",ih),this.on("error",Jl),r&&(r._readyState=ze.CLOSING,this.destroy())}});var fh=L((Kw,ch)=>{"use strict";var Uw=no(),{Duplex:L_}=require("stream");function oh(r){r.emit("close")}function N_(){!this.destroyed&&this._writableState.finished&&this.destroy()}function ah(r){this.removeListener("error",ah),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function M_(r,e){let t=!0,n=new L_({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(s,a){let f=!a&&n._readableState.objectMode?s.toString():s;n.push(f)||r.pause()}),r.once("error",function(s){n.destroyed||(t=!1,n.destroy(s))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(i,s){if(r.readyState===r.CLOSED){s(i),process.nextTick(oh,n);return}let a=!1;r.once("error",function(c){a=!0,s(c)}),r.once("close",function(){a||s(i),process.nextTick(oh,n)}),t&&r.terminate()},n._final=function(i){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(i)});return}r._socket!==null&&(r._socket._writableState.finished?(i(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){i()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(i,s,a){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(i,s,a)});return}r.send(i,a)},n.on("end",N_),n.on("error",ah),n}ch.exports=M_});var lh=L((qw,uh)=>{"use strict";var{tokenChars:F_}=Zn();function D_(r){let e=new Set,t=-1,n=-1,i=0;for(i;i<r.length;i++){let a=r.charCodeAt(i);if(n===-1&&F_[a]===1)t===-1&&(t=i);else if(i!==0&&(a===32||a===9))n===-1&&t!==-1&&(n=i);else if(a===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${i}`);n===-1&&(n=i);let f=r.slice(t,n);if(e.has(f))throw new SyntaxError(`The "${f}" subprotocol is duplicated`);e.add(f),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let s=r.slice(t,i);if(e.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return e.add(s),e}uh.exports={parse:D_}});var _h=L((Hw,yh)=>{"use strict";var B_=require("events"),io=require("http"),{Duplex:Ww}=require("stream"),{createHash:j_}=require("crypto"),hh=za(),Tn=Ni(),U_=lh(),K_=no(),{GUID:q_,kWebSocket:W_}=Rr(),H_=/^[+/0-9A-Za-z]{22}==$/,dh=0,ph=1,mh=2,Za=class extends B_{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:K_,...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=io.createServer((n,i)=>{let s=io.STATUS_CODES[426];i.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),i.end(s)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=V_(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,s,a)=>{this.handleUpgrade(i,s,a,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=dh}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===mh){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Bi,this);return}if(e&&this.once("close",e),this._state!==ph)if(this._state=ph,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(Bi,this):process.nextTick(Bi,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Bi(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,i){t.on("error",gh);let s=e.headers["sec-websocket-key"],a=e.headers.upgrade,f=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Cn(this,e,t,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){Cn(this,e,t,400,"Invalid Upgrade header");return}if(s===void 0||!H_.test(s)){Cn(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(f!==13&&f!==8){Cn(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ji(t,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=U_.parse(c)}catch{Cn(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 Tn(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let b=hh.parse(p);b[Tn.extensionName]&&(_.accept(b[Tn.extensionName]),m[Tn.extensionName]=_)}catch{Cn(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let _={origin:e.headers[`${f===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(_,(b,x,C,H)=>{if(!b)return ji(t,x||401,C,H);this.completeUpgrade(m,s,l,e,t,n,i)});return}if(!this.options.verifyClient(_))return ji(t,401)}this.completeUpgrade(m,s,l,e,t,n,i)}completeUpgrade(e,t,n,i,s,a,f){if(!s.readable||!s.writable)return s.destroy();if(s[W_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>dh)return ji(s,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${j_("sha1").update(t+q_).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let m=this.options.handleProtocols?this.options.handleProtocols(n,i):n.values().next().value;m&&(l.push(`Sec-WebSocket-Protocol: ${m}`),p._protocol=m)}if(e[Tn.extensionName]){let m=e[Tn.extensionName].params,_=hh.format({[Tn.extensionName]:[m]});l.push(`Sec-WebSocket-Extensions: ${_}`),p._extensions=e}this.emit("headers",l,i),s.write(l.concat(`\r
|
|
126
|
+
`+s),r.push(i+"m+"+zs.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=Dy()+e+" "+r[0]}function Dy(){return ut.inspectOpts.hideDate?"":new Date().toISOString()+" "}function Fy(...r){return process.stderr.write(Gs.formatWithOptions(ut.inspectOpts,...r)+`
|
|
127
|
+
`)}function By(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function jy(){return process.env.DEBUG}function Uy(r){r.inspectOpts={};let e=Object.keys(ut.inspectOpts);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=ut.inspectOpts[e[t]]}zs.exports=ka()(ut);var{formatters:vl}=zs.exports;vl.o=function(r){return this.inspectOpts.colors=this.useColors,Gs.inspect(r,this.inspectOpts).split(`
|
|
128
|
+
`).map(e=>e.trim()).join(" ")};vl.O=function(r){return this.inspectOpts.colors=this.useColors,Gs.inspect(r,this.inspectOpts)}});var qt=I((nS,Ia)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Ia.exports=ml():Ia.exports=Sl()});var Li=I(Jr=>{"use strict";var qy=Jr&&Jr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Jr,"__esModule",{value:!0});Jr.Transport=Jr.TransportError=void 0;var Ky=Gn(),Wy=wn(),Hy=Sn(),Vy=Pa(),$y=qy(qt()),Gy=(0,$y.default)("engine.io-client:transport"),Ys=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}};Jr.TransportError=Ys;var La=class extends Wy.Emitter{constructor(e){super(),this.writable=!1,(0,Hy.installTimerFunctions)(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new Ys(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"?this.write(e):Gy("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=(0,Ky.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,Vy.encode)(e);return t.length?"?"+t:""}};Jr.Transport=La});var Ma=I(Qn=>{"use strict";var zy=Qn&&Qn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Qn,"__esModule",{value:!0});Qn.Polling=void 0;var Yy=Li(),Xy=Sn(),xl=Gn(),Zy=zy(qt()),Zt=(0,Zy.default)("engine.io-client:polling"),Na=class extends Yy.Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{Zt("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let n=0;this._polling&&(Zt("we are currently polling - waiting to pause"),n++,this.once("pollComplete",function(){Zt("pre-pause polling complete"),--n||t()})),this.writable||(Zt("we are currently writing - waiting to pause"),n++,this.once("drain",function(){Zt("pre-pause writing complete"),--n||t()}))}else t()}_poll(){Zt("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){Zt("polling got data %s",e);let t=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};(0,xl.decodePayload)(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Zt('ignoring poll - transport state "%s"',this.readyState))}doClose(){let e=()=>{Zt("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Zt("transport open - closing"),e()):(Zt("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,(0,xl.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,Xy.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}};Qn.Polling=Na});var Ol=I(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});Xs.hasCORS=void 0;var Tl=!1;try{Tl=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}Xs.hasCORS=Tl});var Ba=I(gr=>{"use strict";var Qy=gr&&gr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(gr,"__esModule",{value:!0});gr.XHR=gr.Request=gr.BaseXHR=void 0;var Jy=Ma(),e_=wn(),Cl=Sn(),kl=vn(),t_=Ol(),r_=Qy(qt()),Da=(0,r_.default)("engine.io-client:polling");function n_(){}var Zs=class extends Jy.Polling{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",n=location.port;n||(n=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){let n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(i,s)=>{this.onError("xhr post error",i,s)})}doPoll(){Da("xhr poll");let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=e}};gr.BaseXHR=Zs;var Lr=class r extends e_.Emitter{constructor(e,t,n){super(),this.createRequest=e,(0,Cl.installTimerFunctions)(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var e;let t=(0,Cl.pick)(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let n=this._xhr=this.createRequest(t);try{Da("xhr open %s: %s",this._method,this._uri),n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&n.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var i;n.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},Da("xhr data %s",this._data),n.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},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=n_,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()}};gr.Request=Lr;Lr.requestsCount=0;Lr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Pl);else if(typeof addEventListener=="function"){let r="onpagehide"in kl.globalThisShim?"pagehide":"unload";addEventListener(r,Pl,!1)}}function Pl(){for(let r in Lr.requests)Lr.requests.hasOwnProperty(r)&&Lr.requests[r].abort()}var i_=(function(){let r=Al({xdomain:!1});return r&&r.responseType!==null})(),Fa=class extends Zs{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=i_&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Lr(Al,this.uri(),e)}};gr.XHR=Fa;function Al(r){let e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||t_.hasCORS))return new XMLHttpRequest}catch{}if(!e)try{return new kl.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}});var Ua=I(mr=>{"use strict";var s_=mr&&mr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),o_=mr&&mr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),a_=mr&&mr.__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)&&s_(e,r,t);return o_(e,r),e};Object.defineProperty(mr,"__esModule",{value:!0});mr.XHR=void 0;var Rl=a_(nl()),Il=Ba(),c_=Rl.default||Rl,ja=class extends Il.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 Il.Request(n=>new c_(n),this.uri(),e)}};mr.XHR=ja});var Nr=I((fS,Ml)=>{"use strict";var Ll=["nodebuffer","arraybuffer","fragments"],Nl=typeof Blob<"u";Nl&&Ll.push("blob");Ml.exports={BINARY_TYPES:Ll,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Nl,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ni=I((uS,Qs)=>{"use strict";var{EMPTY_BUFFER:f_}=Nr(),qa=Buffer[Symbol.species];function u_(r,e){if(r.length===0)return f_;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let i=0;i<r.length;i++){let s=r[i];t.set(s,n),n+=s.length}return n<e?new qa(t.buffer,t.byteOffset,n):t}function Dl(r,e,t,n,i){for(let s=0;s<i;s++)t[n+s]=r[s]^e[s&3]}function Fl(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function l_(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function Ka(r){if(Ka.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new qa(r):ArrayBuffer.isView(r)?e=new qa(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),Ka.readOnly=!1),e}Qs.exports={concat:u_,mask:Dl,toArrayBuffer:l_,toBuffer:Ka,unmask:Fl};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");Qs.exports.mask=function(e,t,n,i,s){s<48?Dl(e,t,n,i,s):r.mask(e,t,n,i,s)},Qs.exports.unmask=function(e,t){e.length<32?Fl(e,t):r.unmask(e,t)}}catch{}});var Ul=I((lS,jl)=>{"use strict";var Bl=Symbol("kDone"),Wa=Symbol("kRun"),Ha=class{constructor(e){this[Bl]=()=>{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[Bl])}}};jl.exports=Ha});var Di=I((hS,Hl)=>{"use strict";var Mi=require("zlib"),ql=Ni(),h_=Ul(),{kStatusCode:Kl}=Nr(),d_=Buffer[Symbol.species],p_=Buffer.from([0,0,255,255]),eo=Symbol("permessage-deflate"),Mr=Symbol("total-length"),Jn=Symbol("callback"),en=Symbol("buffers"),ei=Symbol("error"),Js,Va=class{constructor(e,t,n){if(this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!Js){let i=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Js=new h_(i)}}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[Jn];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,n=e.find(i=>!(t.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>i.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(n=>{let i=t[n];if(i.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(i=i[0],n==="client_max_window_bits"){if(i!==!0){let s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else if(n==="server_max_window_bits"){let s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=s}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=i})}),e}decompress(e,t,n){Js.add(i=>{this._decompress(e,t,(s,a)=>{i(),n(s,a)})})}compress(e,t,n){Js.add(i=>{this._compress(e,t,(s,a)=>{i(),n(s,a)})})}_decompress(e,t,n){let i=this._isServer?"client":"server";if(!this._inflate){let s=`${i}_max_window_bits`,a=typeof this.params[s]!="number"?Mi.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=Mi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[eo]=this,this._inflate[Mr]=0,this._inflate[en]=[],this._inflate.on("error",m_),this._inflate.on("data",Wl)}this._inflate[Jn]=n,this._inflate.write(e),t&&this._inflate.write(p_),this._inflate.flush(()=>{let s=this._inflate[ei];if(s){this._inflate.close(),this._inflate=null,n(s);return}let a=ql.concat(this._inflate[en],this._inflate[Mr]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Mr]=0,this._inflate[en]=[],t&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),n(null,a)})}_compress(e,t,n){let i=this._isServer?"server":"client";if(!this._deflate){let s=`${i}_max_window_bits`,a=typeof this.params[s]!="number"?Mi.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=Mi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[Mr]=0,this._deflate[en]=[],this._deflate.on("data",g_)}this._deflate[Jn]=n,this._deflate.write(e),this._deflate.flush(Mi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=ql.concat(this._deflate[en],this._deflate[Mr]);t&&(s=new d_(s.buffer,s.byteOffset,s.length-4)),this._deflate[Jn]=null,this._deflate[Mr]=0,this._deflate[en]=[],t&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),n(null,s)})}};Hl.exports=Va;function g_(r){this[en].push(r),this[Mr]+=r.length}function Wl(r){if(this[Mr]+=r.length,this[eo]._maxPayload<1||this[Mr]<=this[eo]._maxPayload){this[en].push(r);return}this[ei]=new RangeError("Max payload size exceeded"),this[ei].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ei][Kl]=1009,this.removeListener("data",Wl),this.reset()}function m_(r){if(this[eo]._inflate=null,this[ei]){this[Jn](this[ei]);return}r[Kl]=1007,this[Jn](r)}});var ti=I((dS,to)=>{"use strict";var{isUtf8:Vl}=require("buffer"),{hasBlob:y_}=Nr(),__=[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 E_(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function $a(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 b_(r){return y_&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}to.exports={isBlob:b_,isValidStatusCode:E_,isValidUTF8:$a,tokenChars:__};if(Vl)to.exports.isValidUTF8=function(r){return r.length<24?$a(r):Vl(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");to.exports.isValidUTF8=function(e){return e.length<32?$a(e):r(e)}}catch{}});var Za=I((pS,Ql)=>{"use strict";var{Writable:w_}=require("stream"),$l=Di(),{BINARY_TYPES:v_,EMPTY_BUFFER:Gl,kStatusCode:S_,kWebSocket:x_}=Nr(),{concat:Ga,toArrayBuffer:T_,unmask:O_}=Ni(),{isValidStatusCode:C_,isValidUTF8:zl}=ti(),ro=Buffer[Symbol.species],Kt=0,Yl=1,Xl=2,Zl=3,za=4,Ya=5,no=6,Xa=class extends w_{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||v_[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[x_]=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=Kt}_write(e,t,n){if(this._opcode===8&&this._state==Kt)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new ro(n.buffer,n.byteOffset+e,n.length-e),new ro(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],i=t.length-e;e>=n.length?t.set(this._buffers.shift(),i):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),i),this._buffers[0]=new ro(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case Kt:this.getInfo(e);break;case Yl:this.getPayloadLength16(e);break;case Xl:this.getPayloadLength64(e);break;case Zl:this.getMask();break;case za:this.getData(e);break;case Ya:case no: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 i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let n=(t[0]&64)===64;if(n&&!this._extensions[$l.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=Yl:this._payloadLength===127?this._state=Xl:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=Zl:this._state=za}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=za}getData(e){let t=Gl;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&&O_(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Ya,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[$l.extensionName].decompress(e,this._fin,(i,s)=>{if(i)return t(i);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===Kt&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Kt;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=Ga(n,t):this._binaryType==="arraybuffer"?i=T_(Ga(n,t)):this._binaryType==="blob"?i=new Blob(n):i=n,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=Kt):(this._state=no,setImmediate(()=>{this.emit("message",i,!0),this._state=Kt,this.startLoop(e)}))}else{let i=Ga(n,t);if(!this._skipUTF8Validation&&!zl(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===Ya||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=Kt):(this._state=no,setImmediate(()=>{this.emit("message",i,!1),this._state=Kt,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Gl),this.end();else{let n=e.readUInt16BE(0);if(!C_(n)){let s=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(s);return}let i=new ro(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!zl(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(s);return}this._loop=!1,this.emit("conclude",n,i),this.end()}this._state=Kt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Kt):(this._state=no,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Kt,this.startLoop(t)}))}createError(e,t,n,i,s){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=s,a[S_]=i,a}};Ql.exports=Xa});var ec=I((mS,th)=>{"use strict";var{Duplex:gS}=require("stream"),{randomFillSync:P_}=require("crypto"),Jl=Di(),{EMPTY_BUFFER:k_,kWebSocket:A_,NOOP:R_}=Nr(),{isBlob:ri,isValidStatusCode:I_}=ti(),{mask:eh,toBuffer:Tn}=Ni(),Wt=Symbol("kByteLength"),L_=Buffer.alloc(4),io=8*1024,On,ni=io,Qt=0,N_=1,M_=2,Qa=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Qt,this.onerror=R_,this[A_]=void 0}static frame(e,t){let n,i=!1,s=2,a=!1;t.mask&&(n=t.maskBuffer||L_,t.generateMask?t.generateMask(n):(ni===io&&(On===void 0&&(On=Buffer.alloc(io)),P_(On,0,io),ni=0),n[0]=On[ni++],n[1]=On[ni++],n[2]=On[ni++],n[3]=On[ni++]),a=(n[0]|n[1]|n[2]|n[3])===0,s=6);let f;typeof e=="string"?(!t.mask||a)&&t[Wt]!==void 0?f=t[Wt]:(e=Buffer.from(e),f=e.length):(f=e.length,i=t.mask&&t.readOnly&&!a);let c=f;f>=65536?(s+=8,c=127):f>125&&(s+=2,c=126);let l=Buffer.allocUnsafe(i?f+s:s);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(f,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(f,4,6)),t.mask?(l[1]|=128,l[s-4]=n[0],l[s-3]=n[1],l[s-2]=n[2],l[s-1]=n[3],a?[l,e]:i?(eh(e,n,l,s,f),[l]):(eh(e,n,e,0,f),[l,e])):[l,e]}close(e,t,n,i){let s;if(e===void 0)s=k_;else{if(typeof e!="number"||!I_(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 f=Buffer.byteLength(t);if(f>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+f),s.writeUInt16BE(e,0),typeof t=="string"?s.write(t,2):s.set(t,2)}}let a={[Wt]:s.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Qt?this.enqueue([this.dispatch,s,!1,a,i]):this.sendFrame(r.frame(s,a),i)}ping(e,t,n){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):ri(e)?(i=e.size,s=!1):(e=Tn(e),i=e.length,s=Tn.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Wt]:i,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};ri(e)?this._state!==Qt?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==Qt?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(r.frame(e,a),n)}pong(e,t,n){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):ri(e)?(i=e.size,s=!1):(e=Tn(e),i=e.length,s=Tn.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Wt]:i,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};ri(e)?this._state!==Qt?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==Qt?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(r.frame(e,a),n)}send(e,t,n){let i=this._extensions[Jl.extensionName],s=t.binary?2:1,a=t.compress,f,c;typeof e=="string"?(f=Buffer.byteLength(e),c=!1):ri(e)?(f=e.size,c=!1):(e=Tn(e),f=e.length,c=Tn.readOnly),this._firstFragment?(this._firstFragment=!1,a&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=f>=i._threshold),this._compress=a):(a=!1,s=0),t.fin&&(this._firstFragment=!0);let l={[Wt]:f,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:c,rsv1:a};ri(e)?this._state!==Qt?this.enqueue([this.getBlobData,e,this._compress,l,n]):this.getBlobData(e,this._compress,l,n):this._state!==Qt?this.enqueue([this.dispatch,e,this._compress,l,n]):this.dispatch(e,this._compress,l,n)}getBlobData(e,t,n,i){this._bufferedBytes+=n[Wt],this._state=M_,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let f=new Error("The socket was closed while the blob was being read");process.nextTick(Ja,this,f,i);return}this._bufferedBytes-=n[Wt];let a=Tn(s);t?this.dispatch(a,t,n,i):(this._state=Qt,this.sendFrame(r.frame(a,n),i),this.dequeue())}).catch(s=>{process.nextTick(D_,this,s,i)})}dispatch(e,t,n,i){if(!t){this.sendFrame(r.frame(e,n),i);return}let s=this._extensions[Jl.extensionName];this._bufferedBytes+=n[Wt],this._state=N_,s.compress(e,n.fin,(a,f)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Ja(this,c,i);return}this._bufferedBytes-=n[Wt],this._state=Qt,n.readOnly=!1,this.sendFrame(r.frame(f,n),i),this.dequeue()})}dequeue(){for(;this._state===Qt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Wt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Wt],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)}};th.exports=Qa;function Ja(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let i=r._queue[n],s=i[i.length-1];typeof s=="function"&&s(e)}}function D_(r,e,t){Ja(r,e,t),r.onerror(e)}});var uh=I((yS,fh)=>{"use strict";var{kForOnEventAttribute:Fi,kListener:tc}=Nr(),rh=Symbol("kCode"),nh=Symbol("kData"),ih=Symbol("kError"),sh=Symbol("kMessage"),oh=Symbol("kReason"),ii=Symbol("kTarget"),ah=Symbol("kType"),ch=Symbol("kWasClean"),Dr=class{constructor(e){this[ii]=null,this[ah]=e}get target(){return this[ii]}get type(){return this[ah]}};Object.defineProperty(Dr.prototype,"target",{enumerable:!0});Object.defineProperty(Dr.prototype,"type",{enumerable:!0});var Cn=class extends Dr{constructor(e,t={}){super(e),this[rh]=t.code===void 0?0:t.code,this[oh]=t.reason===void 0?"":t.reason,this[ch]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[rh]}get reason(){return this[oh]}get wasClean(){return this[ch]}};Object.defineProperty(Cn.prototype,"code",{enumerable:!0});Object.defineProperty(Cn.prototype,"reason",{enumerable:!0});Object.defineProperty(Cn.prototype,"wasClean",{enumerable:!0});var si=class extends Dr{constructor(e,t={}){super(e),this[ih]=t.error===void 0?null:t.error,this[sh]=t.message===void 0?"":t.message}get error(){return this[ih]}get message(){return this[sh]}};Object.defineProperty(si.prototype,"error",{enumerable:!0});Object.defineProperty(si.prototype,"message",{enumerable:!0});var Bi=class extends Dr{constructor(e,t={}){super(e),this[nh]=t.data===void 0?null:t.data}get data(){return this[nh]}};Object.defineProperty(Bi.prototype,"data",{enumerable:!0});var F_={addEventListener(r,e,t={}){for(let i of this.listeners(r))if(!t[Fi]&&i[tc]===e&&!i[Fi])return;let n;if(r==="message")n=function(s,a){let f=new Bi("message",{data:a?s:s.toString()});f[ii]=this,so(e,this,f)};else if(r==="close")n=function(s,a){let f=new Cn("close",{code:s,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});f[ii]=this,so(e,this,f)};else if(r==="error")n=function(s){let a=new si("error",{error:s,message:s.message});a[ii]=this,so(e,this,a)};else if(r==="open")n=function(){let s=new Dr("open");s[ii]=this,so(e,this,s)};else return;n[Fi]=!!t[Fi],n[tc]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[tc]===e&&!t[Fi]){this.removeListener(r,t);break}}};fh.exports={CloseEvent:Cn,ErrorEvent:si,Event:Dr,EventTarget:F_,MessageEvent:Bi};function so(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var rc=I((_S,lh)=>{"use strict";var{tokenChars:ji}=ti();function yr(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function B_(r){let e=Object.create(null),t=Object.create(null),n=!1,i=!1,s=!1,a,f,c=-1,l=-1,p=-1,m=0;for(;m<r.length;m++)if(l=r.charCodeAt(m),a===void 0)if(p===-1&&ji[l]===1)c===-1&&(c=m);else if(m!==0&&(l===32||l===9))p===-1&&c!==-1&&(p=m);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m);let b=r.slice(c,p);l===44?(yr(e,b,t),t=Object.create(null)):a=b,c=p=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);else if(f===void 0)if(p===-1&&ji[l]===1)c===-1&&(c=m);else if(l===32||l===9)p===-1&&c!==-1&&(p=m);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m),yr(t,r.slice(c,p),!0),l===44&&(yr(e,a,t),t=Object.create(null),a=void 0),c=p=-1}else if(l===61&&c!==-1&&p===-1)f=r.slice(c,m),c=p=-1;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(i){if(ji[l]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);c===-1?c=m:n||(n=!0),i=!1}else if(s)if(ji[l]===1)c===-1&&(c=m);else if(l===34&&c!==-1)s=!1,p=m;else if(l===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(l===34&&r.charCodeAt(m-1)===61)s=!0;else if(p===-1&&ji[l]===1)c===-1&&(c=m);else if(c!==-1&&(l===32||l===9))p===-1&&(p=m);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m);let b=r.slice(c,p);n&&(b=b.replace(/\\/g,""),n=!1),yr(t,f,b),l===44&&(yr(e,a,t),t=Object.create(null),a=void 0),f=void 0,c=p=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);if(c===-1||s||l===32||l===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=m);let _=r.slice(c,p);return a===void 0?yr(e,_,t):(f===void 0?yr(t,_,!0):n?yr(t,f,_.replace(/\\/g,"")):yr(t,f,_),yr(e,a,t)),e}function j_(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(i=>{let s=n[i];return Array.isArray(s)||(s=[s]),s.map(a=>a===!0?i:`${i}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}lh.exports={format:j_,parse:B_}});var fo=I((wS,Sh)=>{"use strict";var U_=require("events"),q_=require("https"),K_=require("http"),ph=require("net"),W_=require("tls"),{randomBytes:H_,createHash:V_}=require("crypto"),{Duplex:ES,Readable:bS}=require("stream"),{URL:nc}=require("url"),tn=Di(),$_=Za(),G_=ec(),{isBlob:z_}=ti(),{BINARY_TYPES:hh,EMPTY_BUFFER:oo,GUID:Y_,kForOnEventAttribute:ic,kListener:X_,kStatusCode:Z_,kWebSocket:lt,NOOP:gh}=Nr(),{EventTarget:{addEventListener:Q_,removeEventListener:J_}}=uh(),{format:e0,parse:t0}=rc(),{toBuffer:r0}=Ni(),n0=30*1e3,mh=Symbol("kAborted"),sc=[8,13],Fr=["CONNECTING","OPEN","CLOSING","CLOSED"],i0=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ze=class r extends U_{constructor(e,t,n){super(),this._binaryType=hh[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=oo,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(n=t,t=[]):t=[t]),yh(this,e,t,n)):(this._autoPong=n.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){hh.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,n){let i=new $_({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),s=new G_(e,this._extensions,n.generateMask);this._receiver=i,this._sender=s,this._socket=e,i[lt]=this,s[lt]=this,e[lt]=this,i.on("conclude",a0),i.on("drain",c0),i.on("error",f0),i.on("message",u0),i.on("ping",l0),i.on("pong",h0),s.onerror=d0,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",bh),e.on("data",co),e.on("end",wh),e.on("error",vh),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[tn.extensionName]&&this._extensions[tn.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){Nt(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Eh(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){oc(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||oo,t,n)}pong(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){oc(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||oo,t,n)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(n=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){oc(this,e,n);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[tn.extensionName]||(i.compress=!1),this._sender.send(e||oo,i,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Nt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(ze,"CONNECTING",{enumerable:!0,value:Fr.indexOf("CONNECTING")});Object.defineProperty(ze.prototype,"CONNECTING",{enumerable:!0,value:Fr.indexOf("CONNECTING")});Object.defineProperty(ze,"OPEN",{enumerable:!0,value:Fr.indexOf("OPEN")});Object.defineProperty(ze.prototype,"OPEN",{enumerable:!0,value:Fr.indexOf("OPEN")});Object.defineProperty(ze,"CLOSING",{enumerable:!0,value:Fr.indexOf("CLOSING")});Object.defineProperty(ze.prototype,"CLOSING",{enumerable:!0,value:Fr.indexOf("CLOSING")});Object.defineProperty(ze,"CLOSED",{enumerable:!0,value:Fr.indexOf("CLOSED")});Object.defineProperty(ze.prototype,"CLOSED",{enumerable:!0,value:Fr.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(ze.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(ze.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[ic])return e[X_];return null},set(e){for(let t of this.listeners(r))if(t[ic]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[ic]:!0})}})});ze.prototype.addEventListener=Q_;ze.prototype.removeEventListener=J_;Sh.exports=ze;function yh(r,e,t,n){let i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:sc[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=i.autoPong,!sc.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${sc.join(", ")})`);let s;if(e instanceof nc)s=e;else try{s=new nc(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:",f=s.protocol==="ws+unix:",c;if(s.protocol!=="ws:"&&!a&&!f?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:f&&!s.pathname?c="The URL's pathname is empty":s.hash&&(c="The URL contains a fragment identifier"),c){let O=new SyntaxError(c);if(r._redirects===0)throw O;ao(r,O);return}let l=a?443:80,p=H_(16).toString("base64"),m=a?q_.request:K_.request,_=new Set,b;if(i.createConnection=i.createConnection||(a?o0:s0),i.defaultPort=i.defaultPort||l,i.port=s.port||l,i.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(b=new tn(i.perMessageDeflate!==!0?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=e0({[tn.extensionName]:b.offer()})),t.length){for(let O of t){if(typeof O!="string"||!i0.test(O)||_.has(O))throw new SyntaxError("An invalid or duplicated subprotocol was specified");_.add(O)}i.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(s.username||s.password)&&(i.auth=`${s.username}:${s.password}`),f){let O=i.path.split(":");i.socketPath=O[0],i.path=O[1]}let x;if(i.followRedirects){if(r._redirects===0){r._originalIpc=f,r._originalSecure=a,r._originalHostOrSocketPath=f?i.socketPath:s.host;let O=n&&n.headers;if(n={...n,headers:{}},O)for(let[V,ie]of Object.entries(O))n.headers[V.toLowerCase()]=ie}else if(r.listenerCount("redirect")===0){let O=f?r._originalIpc?i.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:s.host===r._originalHostOrSocketPath;(!O||r._originalSecure&&!a)&&(delete i.headers.authorization,delete i.headers.cookie,O||delete i.headers.host,i.auth=void 0)}i.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),x=r._req=m(i),r._redirects&&r.emit("redirect",r.url,x)}else x=r._req=m(i);i.timeout&&x.on("timeout",()=>{Nt(r,x,"Opening handshake has timed out")}),x.on("error",O=>{x===null||x[mh]||(x=r._req=null,ao(r,O))}),x.on("response",O=>{let V=O.headers.location,ie=O.statusCode;if(V&&i.followRedirects&&ie>=300&&ie<400){if(++r._redirects>i.maxRedirects){Nt(r,x,"Maximum redirects exceeded");return}x.abort();let z;try{z=new nc(V,e)}catch{let D=new SyntaxError(`Invalid URL: ${V}`);ao(r,D);return}yh(r,z,t,n)}else r.emit("unexpected-response",x,O)||Nt(r,x,`Unexpected server response: ${O.statusCode}`)}),x.on("upgrade",(O,V,ie)=>{if(r.emit("upgrade",O),r.readyState!==ze.CONNECTING)return;x=r._req=null;let z=O.headers.upgrade;if(z===void 0||z.toLowerCase()!=="websocket"){Nt(r,V,"Invalid Upgrade header");return}let T=V_("sha1").update(p+Y_).digest("base64");if(O.headers["sec-websocket-accept"]!==T){Nt(r,V,"Invalid Sec-WebSocket-Accept header");return}let D=O.headers["sec-websocket-protocol"],te;if(D!==void 0?_.size?_.has(D)||(te="Server sent an invalid subprotocol"):te="Server sent a subprotocol but none was requested":_.size&&(te="Server sent no subprotocol"),te){Nt(r,V,te);return}D&&(r._protocol=D);let q=O.headers["sec-websocket-extensions"];if(q!==void 0){if(!b){Nt(r,V,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ee;try{ee=t0(q)}catch{Nt(r,V,"Invalid Sec-WebSocket-Extensions header");return}let pe=Object.keys(ee);if(pe.length!==1||pe[0]!==tn.extensionName){Nt(r,V,"Server indicated an extension that was not requested");return}try{b.accept(ee[tn.extensionName])}catch{Nt(r,V,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[tn.extensionName]=b}r.setSocket(V,ie,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(x,r):x.end()}function ao(r,e){r._readyState=ze.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function s0(r){return r.path=r.socketPath,ph.connect(r)}function o0(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=ph.isIP(r.host)?"":r.host),W_.connect(r)}function Nt(r,e,t){r._readyState=ze.CLOSING;let n=new Error(t);Error.captureStackTrace(n,Nt),e.setHeader?(e[mh]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ao,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function oc(r,e,t){if(e){let n=z_(e)?e.size:r0(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${Fr[r.readyState]})`);process.nextTick(t,n)}}function a0(r,e){let t=this[lt];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[lt]!==void 0&&(t._socket.removeListener("data",co),process.nextTick(_h,t._socket),r===1005?t.close():t.close(r,e))}function c0(){let r=this[lt];r.isPaused||r._socket.resume()}function f0(r){let e=this[lt];e._socket[lt]!==void 0&&(e._socket.removeListener("data",co),process.nextTick(_h,e._socket),e.close(r[Z_])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function dh(){this[lt].emitClose()}function u0(r,e){this[lt].emit("message",r,e)}function l0(r){let e=this[lt];e._autoPong&&e.pong(r,!this._isServer,gh),e.emit("ping",r)}function h0(r){this[lt].emit("pong",r)}function _h(r){r.resume()}function d0(r){let e=this[lt];e.readyState!==ze.CLOSED&&(e.readyState===ze.OPEN&&(e._readyState=ze.CLOSING,Eh(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Eh(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),n0)}function bh(){let r=this[lt];this.removeListener("close",bh),this.removeListener("data",co),this.removeListener("end",wh),r._readyState=ze.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[lt]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",dh),r._receiver.on("finish",dh))}function co(r){this[lt]._receiver.write(r)||this.pause()}function wh(){let r=this[lt];r._readyState=ze.CLOSING,r._receiver.end(),this.end()}function vh(){let r=this[lt];this.removeListener("error",vh),this.on("error",gh),r&&(r._readyState=ze.CLOSING,this.destroy())}});var Ch=I((SS,Oh)=>{"use strict";var vS=fo(),{Duplex:p0}=require("stream");function xh(r){r.emit("close")}function g0(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Th(r){this.removeListener("error",Th),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function m0(r,e){let t=!0,n=new p0({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(s,a){let f=!a&&n._readableState.objectMode?s.toString():s;n.push(f)||r.pause()}),r.once("error",function(s){n.destroyed||(t=!1,n.destroy(s))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(i,s){if(r.readyState===r.CLOSED){s(i),process.nextTick(xh,n);return}let a=!1;r.once("error",function(c){a=!0,s(c)}),r.once("close",function(){a||s(i),process.nextTick(xh,n)}),t&&r.terminate()},n._final=function(i){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(i)});return}r._socket!==null&&(r._socket._writableState.finished?(i(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){i()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(i,s,a){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(i,s,a)});return}r.send(i,a)},n.on("end",g0),n.on("error",Th),n}Oh.exports=m0});var kh=I((xS,Ph)=>{"use strict";var{tokenChars:y0}=ti();function _0(r){let e=new Set,t=-1,n=-1,i=0;for(i;i<r.length;i++){let a=r.charCodeAt(i);if(n===-1&&y0[a]===1)t===-1&&(t=i);else if(i!==0&&(a===32||a===9))n===-1&&t!==-1&&(n=i);else if(a===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${i}`);n===-1&&(n=i);let f=r.slice(t,n);if(e.has(f))throw new SyntaxError(`The "${f}" subprotocol is duplicated`);e.add(f),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let s=r.slice(t,i);if(e.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return e.add(s),e}Ph.exports={parse:_0}});var Dh=I((OS,Mh)=>{"use strict";var E0=require("events"),uo=require("http"),{Duplex:TS}=require("stream"),{createHash:b0}=require("crypto"),Ah=rc(),Pn=Di(),w0=kh(),v0=fo(),{GUID:S0,kWebSocket:x0}=Nr(),T0=/^[+/0-9A-Za-z]{22}==$/,Rh=0,Ih=1,Nh=2,ac=class extends E0{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:v0,...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=uo.createServer((n,i)=>{let s=uo.STATUS_CODES[426];i.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),i.end(s)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=O0(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,s,a)=>{this.handleUpgrade(i,s,a,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Rh}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===Nh){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Ui,this);return}if(e&&this.once("close",e),this._state!==Ih)if(this._state=Ih,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(Ui,this):process.nextTick(Ui,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Ui(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,i){t.on("error",Lh);let s=e.headers["sec-websocket-key"],a=e.headers.upgrade,f=+e.headers["sec-websocket-version"];if(e.method!=="GET"){kn(this,e,t,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){kn(this,e,t,400,"Invalid Upgrade header");return}if(s===void 0||!T0.test(s)){kn(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(f!==13&&f!==8){kn(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){qi(t,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=w0.parse(c)}catch{kn(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 Pn(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let b=Ah.parse(p);b[Pn.extensionName]&&(_.accept(b[Pn.extensionName]),m[Pn.extensionName]=_)}catch{kn(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let _={origin:e.headers[`${f===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(_,(b,x,O,V)=>{if(!b)return qi(t,x||401,O,V);this.completeUpgrade(m,s,l,e,t,n,i)});return}if(!this.options.verifyClient(_))return qi(t,401)}this.completeUpgrade(m,s,l,e,t,n,i)}completeUpgrade(e,t,n,i,s,a,f){if(!s.readable||!s.writable)return s.destroy();if(s[x0])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Rh)return qi(s,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${b0("sha1").update(t+S0).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let m=this.options.handleProtocols?this.options.handleProtocols(n,i):n.values().next().value;m&&(l.push(`Sec-WebSocket-Protocol: ${m}`),p._protocol=m)}if(e[Pn.extensionName]){let m=e[Pn.extensionName].params,_=Ah.format({[Pn.extensionName]:[m]});l.push(`Sec-WebSocket-Extensions: ${_}`),p._extensions=e}this.emit("headers",l,i),s.write(l.concat(`\r
|
|
25
129
|
`).join(`\r
|
|
26
|
-
`)),s.removeListener("error",
|
|
130
|
+
`)),s.removeListener("error",Lh),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(Ui,this)})),f(p,i)}};Mh.exports=ac;function O0(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let n of Object.keys(e))r.removeListener(n,e[n])}}function Ui(r){r._state=Nh,r.emit("close")}function Lh(){this.destroy()}function qi(r,e,t,n){t=t||uo.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...n},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${uo.STATUS_CODES[e]}\r
|
|
27
131
|
`+Object.keys(n).map(i=>`${i}: ${n[i]}`).join(`\r
|
|
28
132
|
`)+`\r
|
|
29
133
|
\r
|
|
30
|
-
`+t)}function Cn(r,e,t,n,i,s){if(r.listenerCount("wsClientError")){let a=new Error(i);Error.captureStackTrace(a,Cn),r.emit("wsClientError",a,t,e)}else ji(t,n,i,s)}});var bh=L((Vw,Eh)=>{"use strict";var Mr=no();Mr.createWebSocketStream=fh();Mr.Server=_h();Mr.Receiver=qa();Mr.Sender=Va();Mr.WebSocket=Mr;Mr.WebSocketServer=Mr.Server;Eh.exports=Mr});var rc=L(Qr=>{"use strict";var $_=Qr&&Qr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Qr,"__esModule",{value:!0});Qr.WS=Qr.BaseWS=void 0;var z_=Ri(),vh=bn(),G_=Hn(),ec=En(),Y_=$_(jt()),X_=(0,Y_.default)("engine.io-client:websocket"),wh=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",so=class extends z_.Transport{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,n=wh?{}:(0,vh.pick)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],i=t===e.length-1;(0,G_.encodePacket)(n,this.supportsBinary,s=>{try{this.doWrite(n,s)}catch{X_("websocket closed before onclose event")}i&&(0,ec.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,vh.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}};Qr.BaseWS=so;var Qa=ec.globalThisShim.WebSocket||ec.globalThisShim.MozWebSocket,tc=class extends so{createSocket(e,t,n){return wh?new Qa(e,t,n):t?new Qa(e,t):new Qa(e)}doWrite(e,t){this.ws.send(t)}};Qr.WS=tc});var ic=L(gr=>{"use strict";var J_=gr&&gr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Z_=gr&&gr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Q_=gr&&gr.__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)&&J_(e,r,t);return Z_(e,r),e};Object.defineProperty(gr,"__esModule",{value:!0});gr.WS=void 0;var e0=Q_(bh()),t0=rc(),nc=class extends t0.BaseWS{createSocket(e,t,n){var i;if(!((i=this.socket)===null||i===void 0)&&i._cookieJar){n.headers=n.headers||{},n.headers.cookie=typeof n.headers.cookie=="string"?[n.headers.cookie]:n.headers.cookie||[];for(let[s,a]of this.socket._cookieJar.cookies)n.headers.cookie.push(`${s}=${a.value}`)}return new e0.WebSocket(e,t,n)}doWrite(e,t){let n={};e.options&&(n.compress=e.options.compress),this.opts.perMessageDeflate&&(typeof t=="string"?Buffer.byteLength(t):t.length)<this.opts.perMessageDeflate.threshold&&(n.compress=!1),this.ws.send(t,n)}};gr.WS=nc});var oc=L(ni=>{"use strict";var r0=ni&&ni.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ni,"__esModule",{value:!0});ni.WT=void 0;var n0=Ri(),i0=En(),Sh=Hn(),s0=r0(jt()),Ui=(0,s0.default)("engine.io-client:webtransport"),sc=class extends n0.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(()=>{Ui("transport closed gracefully"),this.onClose()}).catch(e=>{Ui("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=(0,Sh.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),i=(0,Sh.createPacketEncoderStream)();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();let s=()=>{n.read().then(({done:f,value:c})=>{if(f){Ui("session is closed");return}Ui("received chunk: %o",c),this.onPacket(c),s()}).catch(f=>{Ui("an error occurred while reading: %s",f)})};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 n=e[t],i=t===e.length-1;this._writer.write(n).then(()=>{i&&(0,i0.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};ni.WT=sc});var ac=L(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.transports=void 0;var o0=Ra(),a0=ic(),c0=oc();oo.transports={websocket:a0.WS,webtransport:c0.WT,polling:o0.XHR}});var fc=L(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});cc.parse=l0;var f0=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,u0=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function l0(r){if(r.length>8e3)throw"URI too long";let e=r,t=r.indexOf("["),n=r.indexOf("]");t!=-1&&n!=-1&&(r=r.substring(0,t)+r.substring(t,n).replace(/:/g,";")+r.substring(n,r.length));let i=f0.exec(r||""),s={},a=14;for(;a--;)s[u0[a]]=i[a]||"";return t!=-1&&n!=-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=h0(s,s.path),s.queryKey=d0(s,s.query),s}function h0(r,e){let t=/\/{2,9}/g,n=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&n.splice(0,1),e.slice(-1)=="/"&&n.splice(n.length-1,1),n}function d0(r,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,s){i&&(t[i]=s)}),t}});var dc=L(mr=>{"use strict";var p0=mr&&mr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(mr,"__esModule",{value:!0});mr.Socket=mr.SocketWithUpgrade=mr.SocketWithoutUpgrade=void 0;var g0=ac(),xh=bn(),m0=Ea(),Th=fc(),y0=_n(),Ch=Hn(),uc=En(),_0=p0(jt()),Ke=(0,_0.default)("engine.io-client:socket"),lc=typeof addEventListener=="function"&&typeof removeEventListener=="function",Ki=[];lc&&addEventListener("offline",()=>{Ke("closing %d connection(s) because the network was lost",Ki.length),Ki.forEach(r=>r())},!1);var kn=class r extends y0.Emitter{constructor(e,t){if(super(),this.binaryType=uc.defaultBinaryType,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){let n=(0,Th.parse)(e);t.hostname=n.host,t.secure=n.protocol==="https"||n.protocol==="wss",t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=(0,Th.parse)(t.host).host);(0,xh.installTimerFunctions)(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(n=>{let i=n.prototype.name;this.transports.push(i),this._transportsByName[i]=n}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=(0,m0.decode)(this.opts.query)),lc&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(Ke("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Ki.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,uc.createCookieJar)()),this._open()}createTransport(e){Ke('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=Ch.protocol,t.transport=e,this.id&&(t.sid=this.id);let n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return Ke("options: %j",n),new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let e=this.opts.rememberUpgrade&&r.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){Ke("setting transport %s",e.name),this.transport&&(Ke("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(){Ke("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(Ke('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 Ke('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();Ke("flushing %d packets in socket",e.length),this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let n=0;n<this.writeBuffer.length;n++){let i=this.writeBuffer[n].data;if(i&&(t+=(0,xh.byteLength)(i)),n>0&&t>this._maxPayload)return Ke("only send %d out of %d packets",n,this.writeBuffer.length),this.writeBuffer.slice(0,n);t+=2}return Ke("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&&(Ke("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,uc.nextTick)(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,i){if(typeof t=="function"&&(i=t,t=void 0),typeof n=="function"&&(i=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;let s={type:e,data:t,options:n};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),i&&this.once("flush",i),this.flush()}close(){let e=()=>{this._onClose("forced close"),Ke("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(Ke("socket error %j",e),r.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return Ke("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(Ke('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),lc&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let n=Ki.indexOf(this._offlineEventListener);n!==-1&&(Ke("removing listener for the 'offline' event"),Ki.splice(n,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};mr.SocketWithoutUpgrade=kn;kn.protocol=Ch.protocol;var ao=class extends kn{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){Ke("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){Ke('probing transport "%s"',e);let t=this.createTransport(e),n=!1;kn.priorWebsocketSuccess=!1;let i=()=>{n||(Ke('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",m=>{if(!n)if(m.type==="pong"&&m.data==="probe"){if(Ke('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;kn.priorWebsocketSuccess=t.name==="websocket",Ke('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{n||this.readyState!=="closed"&&(Ke("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{Ke('probe transport "%s" failed',e);let _=new Error("probe error");_.transport=t.name,this.emitReserved("upgradeError",_)}}))};function s(){n||(n=!0,p(),t.close(),t=null)}let a=m=>{let _=new Error("probe error: "+m);_.transport=t.name,s(),Ke('probe transport "%s" failed because of error: %s',e,m),this.emitReserved("upgradeError",_)};function f(){a("transport closed")}function c(){a("socket closed")}function l(m){t&&m.name!==t.name&&(Ke('"%s" works - aborting "%s"',m.name,t.name),s())}let p=()=>{t.removeListener("open",i),t.removeListener("error",a),t.removeListener("close",f),this.off("close",c),this.off("upgrading",l)};t.once("open",i),t.once("error",a),t.once("close",f),this.once("close",c),this.once("upgrading",l),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}};mr.SocketWithUpgrade=ao;var hc=class extends ao{constructor(e,t={}){let n=typeof e=="object"?e:t;(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(i=>g0.transports[i]).filter(i=>!!i)),super(e,n)}};mr.Socket=hc});var kh=L(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});co.Fetch=void 0;var E0=Ca(),pc=class extends E0.Polling{doPoll(){this._fetch().then(e=>{if(!e.ok)return this.onError("fetch read error",e.status,e);e.text().then(t=>this.onData(t))}).catch(e=>{this.onError("fetch read error",e)})}doWrite(e,t){this._fetch(e).then(n=>{if(!n.ok)return this.onError("fetch write error",n.status,n);t()}).catch(n=>{this.onError("fetch write error",n)})}_fetch(e){var t;let n=e!==void 0,i=new Headers(this.opts.extraHeaders);return n&&i.set("content-type","text/plain;charset=UTF-8"),(t=this.socket._cookieJar)===null||t===void 0||t.appendCookies(i),fetch(this.uri(),{method:n?"POST":"GET",body:n?e:null,headers:i,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})}};co.Fetch=pc});var fo=L(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 Oh=dc();Object.defineProperty(Oe,"Socket",{enumerable:!0,get:function(){return Oh.Socket}});var Ph=dc();Object.defineProperty(Oe,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return Ph.SocketWithoutUpgrade}});Object.defineProperty(Oe,"SocketWithUpgrade",{enumerable:!0,get:function(){return Ph.SocketWithUpgrade}});Oe.protocol=Oh.Socket.protocol;var Ah=Ri();Object.defineProperty(Oe,"Transport",{enumerable:!0,get:function(){return Ah.Transport}});Object.defineProperty(Oe,"TransportError",{enumerable:!0,get:function(){return Ah.TransportError}});var b0=ac();Object.defineProperty(Oe,"transports",{enumerable:!0,get:function(){return b0.transports}});var v0=bn();Object.defineProperty(Oe,"installTimerFunctions",{enumerable:!0,get:function(){return v0.installTimerFunctions}});var w0=fc();Object.defineProperty(Oe,"parse",{enumerable:!0,get:function(){return w0.parse}});var S0=En();Object.defineProperty(Oe,"nextTick",{enumerable:!0,get:function(){return S0.nextTick}});var x0=kh();Object.defineProperty(Oe,"Fetch",{enumerable:!0,get:function(){return x0.Fetch}});var T0=Ra();Object.defineProperty(Oe,"NodeXHR",{enumerable:!0,get:function(){return T0.XHR}});var C0=Pa();Object.defineProperty(Oe,"XHR",{enumerable:!0,get:function(){return C0.XHR}});var k0=ic();Object.defineProperty(Oe,"NodeWebSocket",{enumerable:!0,get:function(){return k0.WS}});var O0=rc();Object.defineProperty(Oe,"WebSocket",{enumerable:!0,get:function(){return O0.WS}});var P0=oc();Object.defineProperty(Oe,"WebTransport",{enumerable:!0,get:function(){return P0.WT}})});var Ih=L(qi=>{"use strict";var A0=qi&&qi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(qi,"__esModule",{value:!0});qi.url=L0;var R0=fo(),I0=A0(jt()),Rh=(0,I0.default)("socket.io-client:url");function L0(r,e="",t){let n=r;t=t||typeof location<"u"&&location,r==null&&(r=t.protocol+"//"+t.host),typeof r=="string"&&(r.charAt(0)==="/"&&(r.charAt(1)==="/"?r=t.protocol+r:r=t.host+r),/^(https?|wss?):\/\//.test(r)||(Rh("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),Rh("parse %s",r),n=(0,R0.parse)(r)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";let s=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+s+":"+n.port+e,n.href=n.protocol+"://"+s+(t&&t.port===n.port?"":":"+n.port),n}});var gc=L(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.isBinary=Nh;lo.hasBinary=uo;var N0=typeof ArrayBuffer=="function",M0=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,Lh=Object.prototype.toString,F0=typeof Blob=="function"||typeof Blob<"u"&&Lh.call(Blob)==="[object BlobConstructor]",D0=typeof File=="function"||typeof File<"u"&&Lh.call(File)==="[object FileConstructor]";function Nh(r){return N0&&(r instanceof ArrayBuffer||M0(r))||F0&&r instanceof Blob||D0&&r instanceof File}function uo(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,n=r.length;t<n;t++)if(uo(r[t]))return!0;return!1}if(Nh(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return uo(r.toJSON(),!0);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&uo(r[t]))return!0;return!1}});var Mh=L(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});ho.deconstructPacket=j0;ho.reconstructPacket=U0;var B0=gc();function j0(r){let e=[],t=r.data,n=r;return n.data=mc(t,e),n.attachments=e.length,{packet:n,buffers:e}}function mc(r,e){if(!r)return r;if((0,B0.isBinary)(r)){let t={_placeholder:!0,num:e.length};return e.push(r),t}else if(Array.isArray(r)){let t=new Array(r.length);for(let n=0;n<r.length;n++)t[n]=mc(r[n],e);return t}else if(typeof r=="object"&&!(r instanceof Date)){let t={};for(let n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=mc(r[n],e));return t}return r}function U0(r,e){return r.data=yc(r.data,e),delete r.attachments,r}function yc(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]=yc(r[t],e);else if(typeof r=="object")for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=yc(r[t],e));return r}});var go=L(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.Decoder=Xt.Encoder=Xt.PacketType=Xt.protocol=void 0;Xt.isPacketValid=z0;var K0=_n(),Fh=Mh(),Dh=gc(),q0=jt(),_c=(0,q0.default)("socket.io-parser"),Bh=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];Xt.protocol=5;var Be;(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"})(Be||(Xt.PacketType=Be={}));var Ec=class{constructor(e){this.replacer=e}encode(e){return _c("encoding packet %j",e),(e.type===Be.EVENT||e.type===Be.ACK)&&(0,Dh.hasBinary)(e)?this.encodeAsBinary({type:e.type===Be.EVENT?Be.BINARY_EVENT:Be.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===Be.BINARY_EVENT||e.type===Be.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)),_c("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=(0,Fh.deconstructPacket)(e),n=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(n),i}};Xt.Encoder=Ec;var bc=class r extends K0.Emitter{constructor(e){super(),this.reviver=e}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);let n=t.type===Be.BINARY_EVENT;n||t.type===Be.BINARY_ACK?(t.type=n?Be.EVENT:Be.ACK,this.reconstructor=new vc(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,Dh.isBinary)(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0,n={type:Number(e.charAt(0))};if(Be[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===Be.BINARY_EVENT||n.type===Be.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");n.attachments=Number(a)}if(e.charAt(t+1)==="/"){let s=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););n.nsp=e.substring(s,t)}else n.nsp="/";let i=e.charAt(t+1);if(i!==""&&Number(i)==i){let s=t+1;for(;++t;){let a=e.charAt(t);if(a==null||Number(a)!=a){--t;break}if(t===e.length)break}n.id=Number(e.substring(s,t+1))}if(e.charAt(++t)){let s=this.tryParse(e.substr(t));if(r.isPayloadValid(n.type,s))n.data=s;else throw new Error("invalid payload")}return _c("decoded %s as %j",e,n),n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case Be.CONNECT:return po(t);case Be.DISCONNECT:return t===void 0;case Be.CONNECT_ERROR:return typeof t=="string"||po(t);case Be.EVENT:case Be.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Bh.indexOf(t[0])===-1);case Be.ACK:case Be.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};Xt.Decoder=bc;var vc=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,Fh.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function W0(r){return typeof r=="string"}var H0=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function V0(r){return r===void 0||H0(r)}function po(r){return Object.prototype.toString.call(r)==="[object Object]"}function $0(r,e){switch(r){case Be.CONNECT:return e===void 0||po(e);case Be.DISCONNECT:return e===void 0;case Be.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Bh.indexOf(e[0])===-1);case Be.ACK:return Array.isArray(e);case Be.CONNECT_ERROR:return typeof e=="string"||po(e);default:return!1}}function z0(r){return W0(r.nsp)&&V0(r.id)&&$0(r.type,r.data)}});var Sc=L(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});wc.on=G0;function G0(r,e,t){return r.on(e,t),function(){r.off(e,t)}}});var Tc=L(ii=>{"use strict";var Y0=ii&&ii.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ii,"__esModule",{value:!0});ii.Socket=void 0;var Jt=go(),mo=Sc(),X0=_n(),J0=Y0(jt()),ot=(0,J0.default)("socket.io-client:socket"),Z0=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),xc=class extends X0.Emitter{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[(0,mo.on)(e,"open",this.onopen.bind(this)),(0,mo.on)(e,"packet",this.onpacket.bind(this)),(0,mo.on)(e,"error",this.onerror.bind(this)),(0,mo.on)(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,i,s;if(Z0.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:Jt.PacketType.EVENT,data:t};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let p=this.ids++;ot("emitting packet with ack id %d",p);let m=t.pop();this._registerAckCallback(p,m),a.id=p}let f=(i=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||i===void 0?void 0:i.writable,c=this.connected&&!(!((s=this.io.engine)===null||s===void 0)&&s._hasPingExpired());return this.flags.volatile&&!f?ot("discard packet as the transport is not currently writable"):c?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a),this.flags={},this}_registerAckCallback(e,t){var n;let i=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(i===void 0){this.acks[e]=t;return}let s=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let f=0;f<this.sendBuffer.length;f++)this.sendBuffer[f].id===e&&(ot("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(f,1));ot("event with ack id %d has timed out after %d ms",e,i),t.call(this,new Error("operation has timed out"))},i),a=(...f)=>{this.io.clearTimeoutFn(s),t.apply(this,f)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((n,i)=>{let s=(a,f)=>a?i(a):n(f);s.withError=!0,t.push(s),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...s)=>n!==this._queue[0]?ot("packet [%d] already acknowledged",n.id):(i!==null?n.tryCount>this._opts.retries&&(ot("packet [%d] is discarded after %d tries",n.id,n.tryCount),this._queue.shift(),t&&t(i)):(ot("packet [%d] was successfully sent",n.id),this._queue.shift(),t&&t(null,...s)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(ot("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){ot("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,ot("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(){ot("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Jt.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){ot("close (%s)",e),this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(n=>String(n.id)===e)){let n=this.acks[e];delete this.acks[e],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Jt.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 Jt.PacketType.EVENT:case Jt.PacketType.BINARY_EVENT:this.onevent(e);break;case Jt.PacketType.ACK:case Jt.PacketType.BINARY_ACK:this.onack(e);break;case Jt.PacketType.DISCONNECT:this.ondisconnect();break;case Jt.PacketType.CONNECT_ERROR:this.destroy();let n=new Error(e.data.message);n.data=e.data.data,this.emitReserved("connect_error",n);break}}onevent(e){let t=e.data||[];ot("emitting event %j",t),e.id!=null&&(ot("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,n=!1;return function(...i){n||(n=!0,ot("sending ack %j",i),t.packet({type:Jt.PacketType.ACK,id:e,data:i}))}}onack(e){let t=this.acks[e.id];if(typeof t!="function"){ot("bad ack %s",e.id);return}delete this.acks[e.id],ot("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){ot("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(){ot("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&&(ot("performing disconnect (%s)",this.nsp),this.packet({type:Jt.PacketType.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let n of t)n.apply(this,e.data)}}};ii.Socket=xc});var jh=L(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});Cc.Backoff=si;function si(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}si.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};si.prototype.reset=function(){this.attempts=0};si.prototype.setMin=function(r){this.ms=r};si.prototype.setMax=function(r){this.max=r};si.prototype.setJitter=function(r){this.jitter=r}});var Uh=L(qt=>{"use strict";var Q0=qt&&qt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),eE=qt&&qt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),tE=qt&&qt.__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)&&Q0(e,r,t);return eE(e,r),e},rE=qt&&qt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(qt,"__esModule",{value:!0});qt.Manager=void 0;var kc=fo(),nE=Tc(),iE=tE(go()),On=Sc(),sE=jh(),oE=_n(),aE=rE(jt()),lt=(0,aE.default)("socket.io-client:manager"),Oc=class extends oE.Emitter{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,(0,kc.installTimerFunctions)(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((n=t.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new sE.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 i=t.parser||iE;this.encoder=new i.Encoder,this.decoder=new i.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(lt("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;lt("opening %s",this.uri),this.engine=new kc.Socket(this.uri,this.opts);let t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;let i=(0,On.on)(t,"open",function(){n.onopen(),e&&e()}),s=f=>{lt("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",f),e?e(f):this.maybeReconnectOnOpen()},a=(0,On.on)(t,"error",s);if(this._timeout!==!1){let f=this._timeout;lt("connect attempt will timeout after %d",f);let c=this.setTimeoutFn(()=>{lt("connect attempt timed out after %d",f),i(),s(new Error("timeout")),t.close()},f);this.opts.autoUnref&&c.unref(),this.subs.push(()=>{this.clearTimeoutFn(c)})}return this.subs.push(i),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){lt("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push((0,On.on)(e,"ping",this.onping.bind(this)),(0,On.on)(e,"data",this.ondata.bind(this)),(0,On.on)(e,"error",this.onerror.bind(this)),(0,On.on)(e,"close",this.onclose.bind(this)),(0,On.on)(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){(0,kc.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){lt("error",e),this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new nE.Socket(this,e,t),this.nsps[e]=n),n}_destroy(e){let t=Object.keys(this.nsps);for(let n of t)if(this.nsps[n].active){lt("socket %s is still active, skipping close",n);return}this._close()}_packet(e){lt("writing packet %j",e);let t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){lt("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){lt("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;lt("closed due to %s",e),this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)lt("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();lt("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(lt("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(lt("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):(lt("reconnect success"),e.onreconnect())}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}};qt.Manager=Oc});var Hh=L((He,Wh)=>{"use strict";var cE=He&&He.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(He,"__esModule",{value:!0});He.WebTransport=He.WebSocket=He.NodeWebSocket=He.XHR=He.NodeXHR=He.Fetch=He.Socket=He.Manager=He.protocol=void 0;He.io=Pn;He.connect=Pn;He.default=Pn;var fE=Ih(),yo=Uh();Object.defineProperty(He,"Manager",{enumerable:!0,get:function(){return yo.Manager}});var qh=Tc();Object.defineProperty(He,"Socket",{enumerable:!0,get:function(){return qh.Socket}});var uE=cE(jt()),Kh=(0,uE.default)("socket.io-client"),Wi={};function Pn(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};let t=(0,fE.url)(r,e.path||"/socket.io"),n=t.source,i=t.id,s=t.path,a=Wi[i]&&s in Wi[i].nsps,f=e.forceNew||e["force new connection"]||e.multiplex===!1||a,c;return f?(Kh("ignoring socket cache for %s",n),c=new yo.Manager(n,e)):(Wi[i]||(Kh("new io instance for %s",n),Wi[i]=new yo.Manager(n,e)),c=Wi[i]),t.query&&!e.query&&(e.query=t.queryKey),c.socket(t.path,e)}Object.assign(Pn,{Manager:yo.Manager,Socket:qh.Socket,io:Pn,connect:Pn});var lE=go();Object.defineProperty(He,"protocol",{enumerable:!0,get:function(){return lE.protocol}});var oi=fo();Object.defineProperty(He,"Fetch",{enumerable:!0,get:function(){return oi.Fetch}});Object.defineProperty(He,"NodeXHR",{enumerable:!0,get:function(){return oi.NodeXHR}});Object.defineProperty(He,"XHR",{enumerable:!0,get:function(){return oi.XHR}});Object.defineProperty(He,"NodeWebSocket",{enumerable:!0,get:function(){return oi.NodeWebSocket}});Object.defineProperty(He,"WebSocket",{enumerable:!0,get:function(){return oi.WebSocket}});Object.defineProperty(He,"WebTransport",{enumerable:!0,get:function(){return oi.WebTransport}});Wh.exports=Pn});var Ac=L(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});_o.InputStreamReceiver=void 0;var hE=64,dE=30,pE=4,gE=256,mE=16,Pc=class{streamId;lastAppliedSeq=0;cb;windowSize;ackThrottleMs;ackTimer=null;framesSinceAck=0;lastResendFrom=0;resendSuppressed=0;constructor(e,t,n={}){this.streamId=e,this.cb=t,this.windowSize=Math.max(1,n.windowSize??hE),this.ackThrottleMs=Math.max(0,n.ackThrottleMs??dE)}get appliedSeq(){return this.lastAppliedSeq}receive(e,t,n,i){if(e<=this.lastAppliedSeq){this.flushAck();return}if(e===this.lastAppliedSeq+1){try{this.cb.onApply(t,n,i)}catch{}this.lastAppliedSeq=e,this.scheduleAck();return}this.flushAck();let s=Math.max(this.windowSize*pE,gE);e-this.lastAppliedSeq>s||this.maybeResend(this.lastAppliedSeq+1)}maybeResend(e){if(e===this.lastResendFrom){if(++this.resendSuppressed<mE)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)}};_o.InputStreamReceiver=Pc});var Gh=L(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});Eo.WebSocketService=void 0;var yE=Hh(),Vh=Or(),$h=gs(),zh=hs(),_E=Ac(),Rc=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,n,i,s,a,f="vscode",c=[]){this.authService=e,this.cryptoService=t,this.config=n,this.logger=i,this.notification=s,this.deviceId=a,this.platform=f,this.extraCapabilities=c}async connect(){let e=await this.authService.getAccessToken();if(!e)throw new Error("No access token available");this.isManualDisconnect=!1,this.stopReconnect(),this.reconnectAttempts=0,this.agentId=await this.authService.getAgentId();let t=(0,$h.getWsUrl)(this.config);this.logger.info("Connecting to WebSocket",t),this.statusChangeHandler?.("connecting");let n=await this.cryptoService.getPublicKey(),i=this.agentId?await this.cryptoService.getSignedAgentKey(this.agentId):null;return i||this.logger.warn(this.agentId?"No signed agent key available, connecting unsigned (legacy)":"No agentId in storage, connecting unsigned (legacy)"),new Promise((s,a)=>{let f=Array.from(new Set([...Vh.DEFAULT_CLIENT_CAPABILITIES,...this.extraCapabilities]));this.socket=(0,yE.io)(`${t}/agent`,{auth:{token:e,protocolVersion:Vh.PROTOCOL_VERSION,deviceId:this.deviceId,platform:this.platform,capabilities:f,publicKey:n,identityPublicKey:i?.identityPublicKey,identitySignature:i?.signature,keyVersion:i?.keyVersion},transports:["websocket"],reconnection:!1}),this.socket.on("connect",()=>{if(this.logger.info("WebSocket connected"),this.reconnectAttempts=0,this.statusChangeHandler?.("connected",this.agentId??void 0),this.startHeartbeat(),this.cryptoService.cleanupAllStaleSessions(),this.hasConnectedOnce){this.logger.info("Reconnected - triggering workspace re-registration");for(let c of this.reconnectHandlers)c()}else this.hasConnectedOnce=!0,s()}),this.socket.on("error",c=>{this.logger.error(`Server error [${c.code}]: ${c.message}`),c.code==="E401"&&(this.logger.warn("Auth failure (E401)"),this.authFailureHandler?.())}),this.socket.on("disconnect",c=>{this.logger.warn("WebSocket disconnected",c),this.stopHeartbeat(),this.statusChangeHandler?.("disconnected"),this.isManualDisconnect||(c==="transport close"?(this.logger.info("Transport close - attempting immediate reconnect"),this.attemptReconnect(!0)):this.scheduleReconnect())}),this.socket.on("protocol:info",c=>{this.logger.info("Protocol info received",c.protocolVersion),this.negotiatedCapabilities=c.negotiatedCapabilities,c.agentName&&this.config.getAgentName()!==c.agentName&&(this.isRemoteRename=!0,this.config.setAgentName(c.agentName).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(c.agentName),this.logger.info("Agent name synced from server",c.agentName))}),this.socket.on("pong",()=>{this.lastPongTime=Date.now(),this.clearPongTimeout(),this.logger.debug("Heartbeat pong received")}),this.socket.on("connect_error",c=>{this.logger.error("WebSocket connection error",c),this.statusChangeHandler?.("error"),this.hasConnectedOnce||a(c),this.scheduleReconnect()}),this.socket.on("terminal:input",c=>{this.handleTerminalInput(c)}),this.socket.on("crypto:keyExchange",async(c,l)=>{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 m=await this.cryptoService.getPublicKey(),_=this.agentId?await this.cryptoService.getSignedAgentKey(this.agentId):null,b=this.agentId?await this.cryptoService.signKeyExchangeAck(this.agentId,c.clientPublicKey):null;l?.({success:!0,agentPublicKey:m||void 0,..._&&b?{signedKey:{..._,ackSignature:b},boundClientKey:c.clientPublicKey}:{}}),this.flushOutputBuffer(c.terminalId)}else l?.({success:!1,error:"Key exchange failed"})}catch(p){this.logger.error("Key exchange error",p),l?.({success:!1,error:String(p)})}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 l=await this.cryptoService.handleAgentKeyExchange(c.clientPublicKey,c.sessionId),p={agentId:c.agentId,sessionId:c.sessionId,ok:l,error:l?void 0:"Key exchange failed"};this.socket?.emit("agent:keyExchangeAck",p)}catch(l){this.logger.error("Agent key exchange error",l);let p={agentId:c.agentId,sessionId:c.sessionId,ok:!1,error:String(l)};this.socket?.emit("agent:keyExchangeAck",p)}}),this.socket.on("meta:keyExchange",async(c,l)=>{let{ok:p,isNew:m}=await this.cryptoService.handleMetaKeyExchange(c.clientIdentityPub),_=await this.cryptoService.getPublicKey()||void 0;l?.({ok:p,agentPublicKey:_}),p&&this.metaSessionEstablishedHandler?.(m)}),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,l)=>{if(!this.getBufferHandler){l?.({success:!1,error:"Buffer handler not set"});return}let p=this.getBufferHandler(c.terminalId);if(p===null){l?.({success:!1,error:"Terminal not found"});return}let m=this.cryptoService.encryptOutput(c.terminalId,p);if(!m){this.signalInvalidSession(void 0,c.terminalId),l?.({success:!1,error:"No E2E session"});return}l?.({success:!0,encrypted:m}),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,n,i){this.socket?.connected&&this.socket.emit("agent:ptyResized",{instanceId:e,terminalId:t,cols:n,rows:i})}sendClaimControl(e,t,n,i){this.socket?.connected&&this.socket.emit("agent:claimControl",{instanceId:e,terminalId:t,cols:n,rows:i})}sendOutput(e,t,n){if(!this.socket?.connected)return;if(this.rekeyingTerminals.has(t)){let a=this.outputBuffer.get(t);a&&a.length<this.OUTPUT_BUFFER_MAX_SIZE&&a.push({instanceId:e,data:n});return}let i=this.cryptoService.encryptOutput(t,n);if(!i){this.attachedClientCount>0&&this.signalInvalidSession(e,t);return}let s={instanceId:e,terminalId:t,encrypted:i};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:n,data:i}of t){let s=this.cryptoService.encryptOutput(e,i);if(!s){this.signalInvalidSession(n,e);continue}let a={instanceId:n,terminalId:e,encrypted:s};this.socket?.emit("terminal:output",a)}}}signalInvalidSession(e,t){let n=Date.now(),i=this.invalidSessionSignalAt.get(t)??0;n-i<this.INVALID_SESSION_SIGNAL_THROTTLE_MS||(this.invalidSessionSignalAt.set(t,n),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,n){let i={instanceId:e,terminalId:t,event:n};this.socket?.emit("terminal:event",i)}hasCapability(e){return this.negotiatedCapabilities.includes(e)}sendFileChangedEvent(e,t,n){let i={instanceId:e,terminalId:t,event:n};this.socket?.emit("file:changed",i)}sendFileListResponse(e,t){let n={instanceId:e,response:t};this.socket?.emit("file:list:response",n)}sendAgentRename(e){this.socket?.emit("agent:rename",{name:e})}isRemoteRenameInProgress(){return this.isRemoteRename}getSocket(){return this.socket}emit(e,t){let n=(0,zh.generateCorrelationId)(),i=t&&typeof t=="object"&&!Array.isArray(t)?{...t,_cid:n}:t;return(0,zh.runWithCorrelation)(n,()=>new Promise((s,a)=>{if(!this.socket?.connected){a(new Error("WebSocket not connected"));return}this.socket.emit(e,i,f=>{f.success?s(f):a(new Error(f.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 n=this.cryptoService.decryptInput(e.terminalId,e.encrypted);if(!n){this.logger.error("Failed to decrypt terminal input",e.terminalId),this.signalInvalidSession(e.instanceId,e.terminalId);return}t=n}else if(e.data)t=Buffer.from(e.data,"base64").toString("utf8");else{this.logger.error("Invalid terminal input payload");return}if(e.streamId&&typeof e.seq=="number"){let n=this.getOrCreateInputReceiver(e.terminalId,e.streamId,e.instanceId,e.dbTerminalId);if(!n)return;n.receive(e.seq,t,e.paste,e.answerFor);return}this.inputHandler?.(e.terminalId,t,e.dbTerminalId,void 0,e.answerFor)}getOrCreateInputReceiver(e,t,n,i){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 i&&(s.routeId=i),n&&(s.instanceId=n),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 _E.InputStreamReceiver(t,{onApply:(f,c,l)=>this.inputHandler?.(e,f,this.routeIdFor(e),c,l),onAck:f=>this.sendInputAck(e,t,f),onResend:f=>this.sendInputResend(e,t,f)});return this.inputReceivers.set(e,{receiver:a,routeId:i??e,instanceId:n??""}),a}setTerminalActiveCheck(e){this.terminalActiveCheck=e}routeIdFor(e){return this.inputReceivers.get(e)?.routeId??e}sendInputAck(e,t,n){let i=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:ack",{instanceId:i,terminalId:e,streamId:t,ackSeq:n})}sendInputResend(e,t,n){let i=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:resend",{instanceId:i,terminalId:e,streamId:t,fromSeq:n})}sendInputResume(e){let t=this.inputReceivers.get(e);if(!t)return;let{streamId:n,lastAckSeq:i}=t.receiver.resumeState();this.socket?.emit("input:resume",{instanceId:t.instanceId,terminalId:e,streamId:n,lastAckSeq:i})}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(n){this.logger.warn("Reconnect failed",n),this.statusChangeHandler?.("error"),this.scheduleReconnect()}}stopReconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stopNetworkCheck()}async checkNetwork(){let e=Date.now();if(e-this.lastNetworkCheck<1e3)return this.isOnline;this.lastNetworkCheck=e;try{let t=`${(0,$h.getApiUrl)(this.config)}/health`,n=new AbortController,i=setTimeout(()=>n.abort(),5e3),s=await fetch(t,{method:"GET",signal:n.signal});return clearTimeout(i),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)}};Eo.WebSocketService=Rc});var Jh=L(Zt=>{"use strict";var EE=Zt&&Zt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),bE=Zt&&Zt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Lc=Zt&&Zt.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),i=0;i<n.length;i++)n[i]!=="default"&&EE(t,e,n[i]);return bE(t,e),t}})();Object.defineProperty(Zt,"__esModule",{value:!0});Zt.FileTransferService=void 0;Zt.resolveUploadPath=Xh;var bo=Lc(require("fs")),An=Lc(require("path")),Yh=Lc(require("crypto")),Ve=Or();function Xh(r,e,t){let n=An.basename(t),i=(e??"").trim()||".";if(An.isAbsolute(i))return An.resolve(i,n);let s=An.resolve(r,i),a=s===r||s.startsWith(r+An.sep)?s:r;return An.resolve(a,n)}var Ic=class{socket=null;activeTransfers=new Map;instanceId="";logger;fallbackDir;workspaceRoot=null;cryptoService=null;constructor(e,t="/tmp",n=null){this.logger=e,this.fallbackDir=t,this.workspaceRoot=n}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,n,i,s){let a=bo.readFileSync(t),f=t.split("/").pop()||"file";return this.initAndSendChunks(e,a,f,{mimeType:this.getMimeType(f),requestId:s,onProgress:n,onComplete:i})}async sendBuffer(e,t,n,i,s){return this.initAndSendChunks(e,t,n,{mimeType:i,purpose:s?.purpose,viewMetadata:s?.viewMetadata,requestId:s?.requestId,onProgress:s?.onProgress,onComplete:s?.onComplete})}async initAndSendChunks(e,t,n,i){if(!this.socket)throw new Error("Socket not connected");let s=t.length,a=(0,Ve.calculateTotalChunks)(s),f=this.calculateChecksum(t),c=Yh.randomUUID(),l={id:c,terminalId:e,filename:n,size:s,totalChunks:a,direction:Ve.TransferDirection.DOWNLOAD,status:Ve.TransferStatus.PENDING,deliveredChunks:new Set,pendingChunks:new Map,checksum:f,checksumAlgorithm:"sha256",onProgress:i.onProgress?(m,_)=>i.onProgress(c,m,_):void 0,onComplete:i.onComplete?(m,_)=>i.onComplete(c,m,_):void 0,ackTimeouts:new Map};l.chunks=[];for(let m=0;m<a;m++){let _=m*Ve.CHUNK_SIZE,b=Math.min(_+Ve.CHUNK_SIZE,s);l.chunks.push(t.subarray(_,b))}this.activeTransfers.set(c,l);let p={transferId:c,terminalId:e,filename:n,size:s,totalChunks:a,mimeType:i.mimeType||"application/octet-stream",checksum:f,direction:Ve.TransferDirection.DOWNLOAD,instanceId:this.instanceId};return i.requestId&&(p.requestId=i.requestId),i.purpose&&(p.purpose=i.purpose),i.viewMetadata&&(p.viewMetadata=i.viewMetadata),new Promise((m,_)=>{this.socket.emit("file:init",p,b=>{b.accepted?(l.status=Ve.TransferStatus.ACTIVE,this.startSendingChunks(c),m(c)):(this.activeTransfers.delete(c),_(new Error(b.error||"Transfer rejected")))})})}async receiveFile(e,t,n,i,s,a,f,c="sha256",l,p){let m={id:e,terminalId:t,filename:n,filePath:f,size:i,totalChunks:s,direction:Ve.TransferDirection.UPLOAD,status:Ve.TransferStatus.ACTIVE,deliveredChunks:new Set,pendingChunks:new Map,chunks:new Array(s).fill(null),checksum:a,checksumAlgorithm:c,onProgress:l?(_,b)=>l(e,_,b):void 0,onComplete:p?(_,b)=>p(e,_,b):void 0,ackTimeouts:new Map};this.activeTransfers.set(e,m)}cancelTransfer(e,t){let n=this.activeTransfers.get(e);if(n){for(let i of n.ackTimeouts.values())clearTimeout(i);if(n.status=Ve.TransferStatus.CANCELLED,n.onComplete?.(!1,t),this.socket){let i={transferId:e,reason:t};this.socket.emit("file:cancel",i)}this.activeTransfers.delete(e)}}async resumeTransfer(e){let t=this.activeTransfers.get(e);!t||!this.socket||this.socket.emit("file:sync",{transferId:e},n=>{if(n.status===Ve.TransferStatus.EXPIRED){t.onComplete?.(!1,"Transfer expired"),this.activeTransfers.delete(e);return}if(n.deliveredChunks)for(let i of n.deliveredChunks)t.deliveredChunks.add(i);if(t.direction===Ve.TransferDirection.DOWNLOAD&&n.missingChunks){t.status=Ve.TransferStatus.ACTIVE;for(let i of n.missingChunks)this.sendChunk(t,i)}})}getTransferStatus(e){return this.activeTransfers.get(e)?.status??null}getTransferProgress(e){let t=this.activeTransfers.get(e);return t?{delivered:t.deliveredChunks.size,total:t.totalChunks}:null}setupEventHandlers(){this.socket&&(this.socket.on("file:chunk",e=>{this.handleIncomingChunk(e)}),this.socket.on("file:chunk:ack",e=>{this.handleChunkAck(e)}),this.socket.on("file:complete",e=>{this.handleComplete(e)}),this.socket.on("file:progress",e=>{this.handleProgress(e)}),this.socket.on("file:init",(e,t)=>{this.handleIncomingFileInit(e,t)}),this.socket.on("file:cancel",e=>{let t=this.activeTransfers.get(e.transferId);if(t){for(let n of t.ackTimeouts.values())clearTimeout(n);t.status=Ve.TransferStatus.CANCELLED,t.onComplete?.(!1,e.reason||"Cancelled by remote"),this.activeTransfers.delete(e.transferId)}}))}startSendingChunks(e){let t=this.activeTransfers.get(e);if(!(!t||!t.chunks))for(let n=0;n<Math.min(Ve.WINDOW_SIZE,t.totalChunks);n++)t.deliveredChunks.has(n)||this.sendChunk(t,n)}sendChunk(e,t){if(!this.socket||!e.chunks)return;let n=e.chunks[t];if(!n)return;let i=e.pendingChunks.get(t),s={seq:t,data:n,retries:i?i.retries:0,sentAt:Date.now()};e.pendingChunks.set(t,s);let a=this.cryptoService?.encryptFileChunk(e.terminalId,new Uint8Array(n.buffer,n.byteOffset,n.byteLength));if(!a){this.cancelTransfer(e.id,"No E2E session for file transfer");return}let f={transferId:e.id,seq:t,encrypted:a};this.socket.emit("file:chunk",f,l=>{l&&!l.success&&this.cancelTransfer(e.id,l.error||"Server rejected chunk")});let c=setTimeout(()=>{this.handleAckTimeout(e.id,t)},Ve.ACK_TIMEOUT_MS);e.ackTimeouts.set(t,c)}handleChunkAck(e){let t=this.activeTransfers.get(e.transferId);if(!t||t.status===Ve.TransferStatus.COMPLETED)return;let n=t.ackTimeouts.get(e.seq);n&&(clearTimeout(n),t.ackTimeouts.delete(e.seq)),t.deliveredChunks.add(e.seq),t.pendingChunks.delete(e.seq),t.onProgress?.(t.deliveredChunks.size,t.totalChunks);let i=e.seq+Ve.WINDOW_SIZE;i<t.totalChunks&&!t.deliveredChunks.has(i)&&this.sendChunk(t,i),t.deliveredChunks.size===t.totalChunks&&this.finishSending(t)}handleAckTimeout(e,t){let n=this.activeTransfers.get(e);if(!n)return;let i=n.pendingChunks.get(t);i&&(i.retries<Ve.MAX_RETRIES?(i.retries++,this.sendChunk(n,t)):this.cancelTransfer(e,"Max retries exceeded"))}finishSending(e){if(!this.socket)return;e.status=Ve.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 n=e.encrypted?this.cryptoService?.decryptFileChunk(t.terminalId,e.encrypted):null;if(!n){this.cancelTransfer(e.transferId,"Chunk decryption failed (no E2E session?)");return}if(t.chunks[e.seq]=Buffer.from(n),t.deliveredChunks.add(e.seq),this.socket){let i={transferId:e.transferId,seq:e.seq};this.socket.emit("file:chunk:ack",i)}t.onProgress?.(t.deliveredChunks.size,t.totalChunks),t.deliveredChunks.size===t.totalChunks&&this.finishReceiving(t)}finishReceiving(e){if(!e.chunks||!e.filePath)return;let t=Buffer.concat(e.chunks);if(this.calculateChecksum(t,e.checksumAlgorithm)!==e.checksum){e.status=Ve.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 i=An.dirname(e.filePath);bo.existsSync(i)||bo.mkdirSync(i,{recursive:!0}),bo.writeFileSync(e.filePath,t),e.status=Ve.TransferStatus.COMPLETED,e.onComplete?.(!0),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!0})}catch(i){let s=i instanceof Error?i.message:String(i);e.status=Ve.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=Ve.TransferStatus.COMPLETED,t.onComplete?.(!0)):(t.status=Ve.TransferStatus.FAILED,t.onComplete?.(!1,e.error));for(let n of t.ackTimeouts.values())clearTimeout(n);this.activeTransfers.delete(e.transferId)}}handleProgress(e){let t=this.activeTransfers.get(e.transferId);t&&t.onProgress?.(e.deliveredChunks,e.totalChunks)}handleIncomingFileInit(e,t){let n=Xh(this.workspaceRoot??this.fallbackDir,e.targetPath,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(i=>t({accepted:!1,error:i.message}))}calculateChecksum(e,t="sha256"){return t==="fnv1a"?this.fnv1aHash(e):Yh.createHash("sha256").update(e).digest("hex")}fnv1aHash(e){let t=2166136261;for(let i=0;i<e.length;i++)t^=e[i],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"}};Zt.FileTransferService=Ic});var Uc=L((lS,So)=>{function ed(r){return Array.isArray(r)?r:[r]}var vE=void 0,Mc="",Zh=" ",Nc="\\",wE=/^\s+$/,SE=/(?:[^\\]|^)\\$/,xE=/^\\!/,TE=/^\\#/,CE=/\r?\n/g,kE=/^\.{0,2}\/|^\.{1,2}$/,OE=/\/$/,ai="/",td="node-ignore";typeof Symbol<"u"&&(td=Symbol.for("node-ignore"));var rd=td,ci=(r,e,t)=>(Object.defineProperty(r,e,{value:t}),t),PE=/([0-z])-([0-z])/g,nd=()=>!1,AE=r=>r.replace(PE,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:Mc),RE=r=>{let{length:e}=r;return r.slice(0,e-e%2)},IE=[[/^\uFEFF/,()=>Mc],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?Zh:Mc)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+Zh}],[/[\\$.|*+(){^]/g,r=>`\\${r}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(r,e,t)=>e+6<t.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(r,e,t)=>{let n=t.replace(/\\\*/g,"[^\\/]*");return e+n}],[/\\\\\\(?=[$.|*+(){^])/g,()=>Nc],[/\\\\/g,()=>Nc],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,n,i)=>e===Nc?`\\[${t}${RE(n)}${i}`:i==="]"&&n.length%2===0?`[${AE(t)}${n}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`]],LE=/(^|\\\/)?\\\*$/,Hi="regex",vo="checkRegex",Qh="_",NE={[Hi](r,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[vo](r,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},ME=r=>IE.reduce((e,[t,n])=>e.replace(t,n.bind(r)),r),wo=r=>typeof r=="string",FE=r=>r&&wo(r)&&!wE.test(r)&&!SE.test(r)&&r.indexOf("#")!==0,DE=r=>r.split(CE).filter(Boolean),Fc=class{constructor(e,t,n,i,s,a){this.pattern=e,this.mark=t,this.negative=s,ci(this,"body",n),ci(this,"ignoreCase",i),ci(this,"regexPrefix",a)}get regex(){let e=Qh+Hi;return this[e]?this[e]:this._make(Hi,e)}get checkRegex(){let e=Qh+vo;return this[e]?this[e]:this._make(vo,e)}_make(e,t){let n=this.regexPrefix.replace(LE,NE[e]),i=this.ignoreCase?new RegExp(n,"i"):new RegExp(n);return ci(this,t,i)}},BE=({pattern:r,mark:e},t)=>{let n=!1,i=r;i.indexOf("!")===0&&(n=!0,i=i.substr(1)),i=i.replace(xE,"!").replace(TE,"#");let s=ME(i);return new Fc(r,e,i,t,n,s)},Dc=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[rd]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(wo(e)&&(e={pattern:e}),FE(e.pattern)){let t=BE(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,ed(wo(e)?DE(e):e).forEach(this._add,this),this._added}test(e,t,n){let i=!1,s=!1,a;this._rules.forEach(c=>{let{negative:l}=c;s===l&&i!==s||l&&!i&&!s&&!t||!c[n].test(e)||(i=!l,s=l,a=l?vE:c)});let f={ignored:i,unignored:s};return a&&(f.rule=a),f}},jE=(r,e)=>{throw new e(r)},Fr=(r,e,t)=>wo(r)?r?Fr.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),id=r=>kE.test(r);Fr.isNotRelative=id;Fr.convert=r=>r;var Bc=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){ci(this,rd,!0),this._rules=new Dc(t),this._strictPathCheck=!n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(e){return this._rules.add(e)&&this._initCache(),this}addPattern(e){return this.add(e)}_test(e,t,n,i){let s=e&&Fr.convert(e);return Fr(s,e,this._strictPathCheck?jE:nd),this._t(s,t,n,i)}checkIgnore(e){if(!OE.test(e))return this.test(e);let t=e.split(ai).filter(Boolean);if(t.pop(),t.length){let n=this._t(t.join(ai)+ai,this._testCache,!0,t);if(n.ignored)return n}return this._rules.test(e,!1,vo)}_t(e,t,n,i){if(e in t)return t[e];if(i||(i=e.split(ai).filter(Boolean)),i.pop(),!i.length)return t[e]=this._rules.test(e,n,Hi);let s=this._t(i.join(ai)+ai,t,n,i);return t[e]=s.ignored?s:this._rules.test(e,n,Hi)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return ed(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},jc=r=>new Bc(r),UE=r=>Fr(r&&Fr.convert(r),r,nd),sd=()=>{let r=t=>/^\\\\\?\\/.test(t)||/["<>|\u0000-\u001F]+/u.test(t)?t:t.replace(/\\/g,"/");Fr.convert=r;let e=/^[a-z]:\//i;Fr.isNotRelative=t=>e.test(t)||id(t)};typeof process<"u"&&process.platform==="win32"&&sd();So.exports=jc;jc.default=jc;So.exports.isPathValid=UE;ci(So.exports,Symbol.for("setupWindows"),sd)});var ad=L(Wt=>{"use strict";var KE=Wt&&Wt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),qE=Wt&&Wt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),od=Wt&&Wt.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),i=0;i<n.length;i++)n[i]!=="default"&&KE(t,e,n[i]);return qE(t,e),t}})(),WE=Wt&&Wt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Wt,"__esModule",{value:!0});Wt.FileListService=void 0;var fi=od(require("path")),Kc=od(require("fs/promises")),HE=WE(Uc()),qc=Or(),VE=["node_modules",".pnpm","vendor",".git","dist","build","out",".next",".nuxt",".output",".cache",".turbo",".idea",".vscode",".DS_Store","Thumbs.db"],Wc=class{ignoreFilter;workspaceRoot;onResponseCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,HE.default)(),this.ignoreFilter.add(VE),this.workspaceRoot&&this.loadGitignore(),this.logger.info("FileListService initialized",t||"null")}async loadGitignore(){if(!this.workspaceRoot)return;let e=fi.join(this.workspaceRoot,".gitignore");try{let t=await Kc.readFile(e,"utf-8");this.ignoreFilter.add(t)}catch{}}onResponse(e){this.onResponseCallback=e}async handleListRequest(e){if(!this.workspaceRoot){this.sendResponse({requestId:e.requestId,path:e.path,entries:[],error:"No workspace root"});return}try{let t=this.resolvePath(e.path),n=await this.listDirectory(t,e.path);this.sendResponse({requestId:e.requestId,path:e.path,entries:n})}catch(t){this.logger.error("Failed to list directory",String(t)),this.sendResponse({requestId:e.requestId,path:e.path,entries:[],error:t instanceof Error?t.message:"Unknown error"})}}async listDirectory(e,t){let n=await Kc.readdir(e,{withFileTypes:!0}),i=[];for(let s of n){let a=t==="."||t===""?s.name:fi.join(t,s.name);if(this.shouldHide(a,s.isDirectory()))continue;let f=fi.join(e,s.name),c={name:s.name,path:a,type:s.isDirectory()?qc.FileEntryType.DIRECTORY:qc.FileEntryType.FILE};if(!s.isDirectory())try{let l=await Kc.stat(f);c.size=l.size,c.modified=l.mtime.toISOString()}catch{}i.push(c)}return i.sort((s,a)=>s.type!==a.type?s.type===qc.FileEntryType.DIRECTORY?-1:1:s.name.localeCompare(a.name))}shouldHide(e,t){let n=e.split(fi.sep).join("/"),i=t?`${n}/`:n;return this.ignoreFilter.ignores(i)}resolvePath(e){if(!this.workspaceRoot)throw new Error("No workspace root");if(e==="."||e==="")return this.workspaceRoot;let t=fi.resolve(this.workspaceRoot,e);if(t!==this.workspaceRoot&&!t.startsWith(this.workspaceRoot+fi.sep))throw new Error("Path outside workspace");return t}sendResponse(e){this.onResponseCallback?.(e)}dispose(){this.onResponseCallback=null}};Wt.FileListService=Wc});var fd=L(yr=>{"use strict";var $E=yr&&yr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),zE=yr&&yr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),cd=yr&&yr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),i=0;i<n.length;i++)n[i]!=="default"&&$E(t,e,n[i]);return zE(t,e),t}})();Object.defineProperty(yr,"__esModule",{value:!0});yr.FileTrackerService=void 0;var Hc=cd(require("path")),Rn=cd(require("fs/promises")),GE=require("child_process"),YE=require("util"),Qt=Or(),Vc=(0,YE.promisify)(GE.execFile),$c={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},zc=class{trackedFiles=new Map;pendingToolCalls=new Map;outputBuffers=new Map;workspaceRoot;onFileChangedCallback=null;onFileViewTransferCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t}onFileChanged(e){this.onFileChangedCallback=e}onFileViewTransfer(e){this.onFileViewTransferCallback=e}async processOutput(e,t){let n=this.outputBuffers.get(e)||"";n+=t,n.length>10240&&(n=n.slice(-10240)),this.outputBuffers.set(e,n);try{await this.parseToolCalls(e,n)}catch(i){this.logger.error("Error parsing tool calls",i)}}async parseToolCalls(e,t){let n=this.stripAnsi(t),i=n.match($c.toolStart);if(i){let a=i[1],f=i[2],c=`${a}_${Date.now()}_${f}`;this.pendingToolCalls.has(c)||await this.handleToolStart(e,c,a,{file_path:f})}let s=n.match($c.toolSuccess);if(s){let a=s[1];for(let[f,c]of this.pendingToolCalls)if(c.filePath===a||a.endsWith(c.filePath)||c.filePath.endsWith(a)){await this.handleToolEnd(e,f,c.toolName,"success");break}}if($c.toolError.test(n))for(let[a,f]of this.pendingToolCalls)await this.handleToolEnd(e,a,f.toolName,"error")}stripAnsi(e){return e.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g,"").replace(/\x1b\][^\x07]*\x07/g,"").replace(/\x1b[()][AB012]/g,"").replace(/\x1b[=>]/g,"").replace(/\x1b[78DMEHc]/g,"")}async handleToolStart(e,t,n,i){if(!this.isFileModifyingTool(n))return;let s=this.extractFilePath(n,i);if(!s)return;let a=this.resolveFilePath(s),f={toolId:t,toolName:n,filePath:s,timestamp:new Date().toISOString()};this.pendingToolCalls.set(t,f);let c;try{c=await Rn.readFile(a,"utf-8")}catch{c=void 0}let l={path:s,changeType:c===void 0?Qt.FileChangeType.CREATE:Qt.FileChangeType.MODIFY,toolName:n,toolId:t,timestamp:f.timestamp,previousContent:c},p=this.trackedFiles.get(e)||[];p.push(l),this.trackedFiles.set(e,p)}async handleToolEnd(e,t,n,i){if(!this.isFileModifyingTool(n)||!this.pendingToolCalls.get(t))return;if(this.pendingToolCalls.delete(t),i==="error"){let p=this.trackedFiles.get(e)||[],m=p.findIndex(_=>_.toolId===t);m!==-1&&p.splice(m,1);return}let f=(this.trackedFiles.get(e)||[]).find(p=>p.toolId===t);if(!f)return;let c=this.resolveFilePath(f.path);try{let p=await Rn.stat(c);f.size=p.size}catch{f.changeType=Qt.FileChangeType.DELETE,f.size=void 0}let l={path:f.path,changeType:f.changeType,timestamp:new Date().toISOString(),source:"tool-call",toolName:f.toolName,toolId:f.toolId,size:f.size};this.onFileChangedCallback?.(e,l)}async handleViewRequest(e,t){let n=this.resolveFilePath(t.path),i=this.getViewableMimeType(t.path);if(i&&this.onFileViewTransferCallback){try{let a=await Rn.readFile(n),f={requestId:t.requestId,path:t.path,viewType:"content",mimeType:i};this.onFileViewTransferCallback(e,Buffer.from(a),f)}catch(a){let f={requestId:t.requestId,path:t.path,viewType:"content",mimeType:i,error:a instanceof Error?a.message:"Unknown error"};this.onFileViewTransferCallback(e,Buffer.alloc(0),f)}return}let s;try{t.type===Qt.FileViewType.CONTENT?s=await this.getFileContent(t,n):s=await this.getFileDiff(e,t,n)}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===Qt.FileViewType.CONTENT?"content":"diff",language:s.language,truncated:s.truncated,error:s.error},f=Buffer.from(s.content||"","utf-8");this.onFileViewTransferCallback(e,f,a)}}getViewableMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf"}[t||""]||null}async getFileContent(e,t){let n=e.maxSize||1048576,i=await Rn.stat(t),s=await Rn.readFile(t,"utf-8"),a=!1,f=s;return s.length>n&&(f=s.slice(0,n),a=!0),{requestId:e.requestId,path:e.path,type:Qt.FileViewType.CONTENT,content:f,language:(0,Qt.getLanguageFromPath)(e.path),size:i.size,truncated:a}}async getFileDiff(e,t,n){let i=t.diffBase||Qt.DiffBase.GIT,s;return i===Qt.DiffBase.GIT?s=await this.getGitDiff(n):s=await this.getPreviousDiff(e,t.path,n),{requestId:t.requestId,path:t.path,type:Qt.FileViewType.DIFF,content:s,language:"diff"}}async getGitDiff(e){if(!this.workspaceRoot)throw new Error("No workspace root");try{let{stdout:t}=await Vc("git",["diff","--cached","--",e],{cwd:this.workspaceRoot});if(t.trim())return t;let{stdout:n}=await Vc("git",["diff","--",e],{cwd:this.workspaceRoot});if(n.trim())return n;let{stdout:i}=await Vc("git",["status","--porcelain","--",e],{cwd:this.workspaceRoot});if(i.startsWith("??")||i.startsWith("A ")){let a=(await Rn.readFile(e,"utf-8")).split(`
|
|
31
|
-
`),f=
|
|
32
|
-
`)}return"(no changes)"}catch{throw new Error("Git not available")}}async getPreviousDiff(e,t,n){let a=(this.trackedFiles.get(e)||[]).find(l=>l.path===t&&l.previousContent!==void 0)?.previousContent||"",f;try{f=await
|
|
33
|
-
`)}clearTerminal(e){this.trackedFiles.delete(e),this.outputBuffers.delete(e)}getChangedFiles(e){return(this.trackedFiles.get(e)||[]).map(n=>({path:n.path,changeType:n.changeType,timestamp:n.timestamp,source:"tool-call",toolName:n.toolName,toolId:n.toolId,size:n.size}))}isFileModifyingTool(e){return["Write","Edit","NotebookEdit"].includes(e)}extractFilePath(e,t){return t?e==="Write"||e==="Edit"?t.file_path||null:e==="NotebookEdit"&&t.notebook_path||null:null}resolveFilePath(e){let t=this.workspaceRoot;if(!t)throw new Error("No workspace root configured");let n=Hc.resolve(t,e);if(n!==t&&!n.startsWith(t+Hc.sep))throw new Error("Path escapes workspace root");return n}dispose(){this.trackedFiles.clear(),this.pendingToolCalls.clear(),this.onFileChangedCallback=null,this.onFileViewTransferCallback=null}};yr.FileTrackerService=zc});var ud=L(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.InputStreamReceiver=Ge.FileTrackerService=Ge.FileListService=Ge.FileTransferService=Ge.WebSocketService=Ge.trackAltScreen=Ge.isTerminalReplyOnly=Ge.isAnswerKeystroke=Ge.StatusDetector=Ge.AuthService=Ge.CryptoService=void 0;var XE=Au();Object.defineProperty(Ge,"CryptoService",{enumerable:!0,get:function(){return XE.CryptoService}});var JE=Ru();Object.defineProperty(Ge,"AuthService",{enumerable:!0,get:function(){return JE.AuthService}});var xo=Fu();Object.defineProperty(Ge,"StatusDetector",{enumerable:!0,get:function(){return xo.StatusDetector}});Object.defineProperty(Ge,"isAnswerKeystroke",{enumerable:!0,get:function(){return xo.isAnswerKeystroke}});Object.defineProperty(Ge,"isTerminalReplyOnly",{enumerable:!0,get:function(){return xo.isTerminalReplyOnly}});Object.defineProperty(Ge,"trackAltScreen",{enumerable:!0,get:function(){return xo.trackAltScreen}});var ZE=Gh();Object.defineProperty(Ge,"WebSocketService",{enumerable:!0,get:function(){return ZE.WebSocketService}});var QE=Jh();Object.defineProperty(Ge,"FileTransferService",{enumerable:!0,get:function(){return QE.FileTransferService}});var eb=ad();Object.defineProperty(Ge,"FileListService",{enumerable:!0,get:function(){return eb.FileListService}});var tb=fd();Object.defineProperty(Ge,"FileTrackerService",{enumerable:!0,get:function(){return tb.FileTrackerService}});var rb=Ac();Object.defineProperty(Ge,"InputStreamReceiver",{enumerable:!0,get:function(){return rb.InputStreamReceiver}})});var Vi=L(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.FP_LABEL=G.KX_ACK_LABEL=G.KX_SIGN_LABEL=G.concatBytes=G.fingerprintShortHex=G.fingerprintIdentityKey=G.buildKxAckCanonical=G.buildKxCanonical=G.verifySessionKey=G.signSessionKey=G.identityPublicFromSecret=G.generateIdentityKeyPair=G.InputStreamReceiver=G.FileTrackerService=G.FileListService=G.FileTransferService=G.WebSocketService=G.trackAltScreen=G.isTerminalReplyOnly=G.isAnswerKeystroke=G.StatusDetector=G.AuthService=G.CryptoService=G.getCurrentCorrelationId=G.runWithCorrelation=G.generateCorrelationId=G.getWsUrl=G.getApiUrl=G.CircularBuffer=G.formatLogLine=G.shouldLog=G.LOG_LEVELS=void 0;var Gc=Vf();Object.defineProperty(G,"LOG_LEVELS",{enumerable:!0,get:function(){return Gc.LOG_LEVELS}});Object.defineProperty(G,"shouldLog",{enumerable:!0,get:function(){return Gc.shouldLog}});Object.defineProperty(G,"formatLogLine",{enumerable:!0,get:function(){return Gc.formatLogLine}});var ui=Gf();Object.defineProperty(G,"CircularBuffer",{enumerable:!0,get:function(){return ui.CircularBuffer}});Object.defineProperty(G,"getApiUrl",{enumerable:!0,get:function(){return ui.getApiUrl}});Object.defineProperty(G,"getWsUrl",{enumerable:!0,get:function(){return ui.getWsUrl}});Object.defineProperty(G,"generateCorrelationId",{enumerable:!0,get:function(){return ui.generateCorrelationId}});Object.defineProperty(G,"runWithCorrelation",{enumerable:!0,get:function(){return ui.runWithCorrelation}});Object.defineProperty(G,"getCurrentCorrelationId",{enumerable:!0,get:function(){return ui.getCurrentCorrelationId}});var er=ud();Object.defineProperty(G,"CryptoService",{enumerable:!0,get:function(){return er.CryptoService}});Object.defineProperty(G,"AuthService",{enumerable:!0,get:function(){return er.AuthService}});Object.defineProperty(G,"StatusDetector",{enumerable:!0,get:function(){return er.StatusDetector}});Object.defineProperty(G,"isAnswerKeystroke",{enumerable:!0,get:function(){return er.isAnswerKeystroke}});Object.defineProperty(G,"isTerminalReplyOnly",{enumerable:!0,get:function(){return er.isTerminalReplyOnly}});Object.defineProperty(G,"trackAltScreen",{enumerable:!0,get:function(){return er.trackAltScreen}});Object.defineProperty(G,"WebSocketService",{enumerable:!0,get:function(){return er.WebSocketService}});Object.defineProperty(G,"FileTransferService",{enumerable:!0,get:function(){return er.FileTransferService}});Object.defineProperty(G,"FileListService",{enumerable:!0,get:function(){return er.FileListService}});Object.defineProperty(G,"FileTrackerService",{enumerable:!0,get:function(){return er.FileTrackerService}});Object.defineProperty(G,"InputStreamReceiver",{enumerable:!0,get:function(){return er.InputStreamReceiver}});var Ht=aa();Object.defineProperty(G,"generateIdentityKeyPair",{enumerable:!0,get:function(){return Ht.generateIdentityKeyPair}});Object.defineProperty(G,"identityPublicFromSecret",{enumerable:!0,get:function(){return Ht.identityPublicFromSecret}});Object.defineProperty(G,"signSessionKey",{enumerable:!0,get:function(){return Ht.signSessionKey}});Object.defineProperty(G,"verifySessionKey",{enumerable:!0,get:function(){return Ht.verifySessionKey}});Object.defineProperty(G,"buildKxCanonical",{enumerable:!0,get:function(){return Ht.buildKxCanonical}});Object.defineProperty(G,"buildKxAckCanonical",{enumerable:!0,get:function(){return Ht.buildKxAckCanonical}});Object.defineProperty(G,"fingerprintIdentityKey",{enumerable:!0,get:function(){return Ht.fingerprintIdentityKey}});Object.defineProperty(G,"fingerprintShortHex",{enumerable:!0,get:function(){return Ht.fingerprintShortHex}});Object.defineProperty(G,"concatBytes",{enumerable:!0,get:function(){return Ht.concatBytes}});Object.defineProperty(G,"KX_SIGN_LABEL",{enumerable:!0,get:function(){return Ht.KX_SIGN_LABEL}});Object.defineProperty(G,"KX_ACK_LABEL",{enumerable:!0,get:function(){return Ht.KX_ACK_LABEL}});Object.defineProperty(G,"FP_LABEL",{enumerable:!0,get:function(){return Ht.FP_LABEL}})});var Zc=L((zi,Jc)=>{(function(r,e){typeof zi=="object"&&typeof Jc=="object"?Jc.exports=e(require("child_process"),require("crypto")):typeof define=="function"&&define.amd?define(["child_process","crypto"],e):typeof zi=="object"?zi["electron-machine-id"]=e(require("child_process"),require("crypto")):r["electron-machine-id"]=e(r.child_process,r.crypto)})(zi,function(r,e){return(function(t){function n(s){if(i[s])return i[s].exports;var a=i[s]={exports:{},id:s,loaded:!1};return t[s].call(a.exports,a,a.exports,n),a.loaded=!0,a.exports}var i={};return n.m=t,n.c=i,n.p="",n(0)})([function(t,n,i){t.exports=i(34)},function(t,n,i){var s=i(29)("wks"),a=i(33),f=i(2).Symbol,c=typeof f=="function",l=t.exports=function(p){return s[p]||(s[p]=c&&f[p]||(c?f:a)("Symbol."+p))};l.store=s},function(t,n){var i=t.exports=typeof window<"u"&&window.Math==Math?window:typeof self<"u"&&self.Math==Math?self:Function("return this")();typeof __g=="number"&&(__g=i)},function(t,n,i){var s=i(9);t.exports=function(a){if(!s(a))throw TypeError(a+" is not an object!");return a}},function(t,n,i){t.exports=!i(24)(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7})},function(t,n,i){var s=i(12),a=i(17);t.exports=i(4)?function(f,c,l){return s.f(f,c,a(1,l))}:function(f,c,l){return f[c]=l,f}},function(t,n){var i=t.exports={version:"2.4.0"};typeof __e=="number"&&(__e=i)},function(t,n,i){var s=i(14);t.exports=function(a,f,c){if(s(a),f===void 0)return a;switch(c){case 1:return function(l){return a.call(f,l)};case 2:return function(l,p){return a.call(f,l,p)};case 3:return function(l,p,m){return a.call(f,l,p,m)}}return function(){return a.apply(f,arguments)}}},function(t,n){var i={}.hasOwnProperty;t.exports=function(s,a){return i.call(s,a)}},function(t,n){t.exports=function(i){return typeof i=="object"?i!==null:typeof i=="function"}},function(t,n){t.exports={}},function(t,n){var i={}.toString;t.exports=function(s){return i.call(s).slice(8,-1)}},function(t,n,i){var s=i(3),a=i(26),f=i(32),c=Object.defineProperty;n.f=i(4)?Object.defineProperty:function(l,p,m){if(s(l),p=f(p,!0),s(m),a)try{return c(l,p,m)}catch{}if("get"in m||"set"in m)throw TypeError("Accessors not supported!");return"value"in m&&(l[p]=m.value),l}},function(t,n,i){var s=i(42),a=i(15);t.exports=function(f){return s(a(f))}},function(t,n){t.exports=function(i){if(typeof i!="function")throw TypeError(i+" is not a function!");return i}},function(t,n){t.exports=function(i){if(i==null)throw TypeError("Can't call method on "+i);return i}},function(t,n,i){var s=i(9),a=i(2).document,f=s(a)&&s(a.createElement);t.exports=function(c){return f?a.createElement(c):{}}},function(t,n){t.exports=function(i,s){return{enumerable:!(1&i),configurable:!(2&i),writable:!(4&i),value:s}}},function(t,n,i){var s=i(12).f,a=i(8),f=i(1)("toStringTag");t.exports=function(c,l,p){c&&!a(c=p?c:c.prototype,f)&&s(c,f,{configurable:!0,value:l})}},function(t,n,i){var s=i(29)("keys"),a=i(33);t.exports=function(f){return s[f]||(s[f]=a(f))}},function(t,n){var i=Math.ceil,s=Math.floor;t.exports=function(a){return isNaN(a=+a)?0:(a>0?s:i)(a)}},function(t,n,i){var s=i(11),a=i(1)("toStringTag"),f=s((function(){return arguments})())=="Arguments",c=function(l,p){try{return l[p]}catch{}};t.exports=function(l){var p,m,_;return l===void 0?"Undefined":l===null?"Null":typeof(m=c(p=Object(l),a))=="string"?m:f?s(p):(_=s(p))=="Object"&&typeof p.callee=="function"?"Arguments":_}},function(t,n){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,n,i){var s=i(2),a=i(6),f=i(7),c=i(5),l="prototype",p=function(m,_,b){var x,C,H,ie=m&p.F,z=m&p.G,T=m&p.S,F=m&p.P,te=m&p.B,U=m&p.W,ee=z?a:a[_]||(a[_]={}),pe=ee[l],K=z?s:T?s[_]:(s[_]||{})[l];z&&(b=_);for(x in b)C=!ie&&K&&K[x]!==void 0,C&&x in ee||(H=C?K[x]:b[x],ee[x]=z&&typeof K[x]!="function"?b[x]:te&&C?f(H,s):U&&K[x]==H?(function(Ne){var tt=function(xe,Me,we){if(this instanceof Ne){switch(arguments.length){case 0:return new Ne;case 1:return new Ne(xe);case 2:return new Ne(xe,Me)}return new Ne(xe,Me,we)}return Ne.apply(this,arguments)};return tt[l]=Ne[l],tt})(H):F&&typeof H=="function"?f(Function.call,H):H,F&&((ee.virtual||(ee.virtual={}))[x]=H,m&p.R&&pe&&!pe[x]&&c(pe,x,H)))};p.F=1,p.G=2,p.S=4,p.P=8,p.B=16,p.W=32,p.U=64,p.R=128,t.exports=p},function(t,n){t.exports=function(i){try{return!!i()}catch{return!0}}},function(t,n,i){t.exports=i(2).document&&document.documentElement},function(t,n,i){t.exports=!i(4)&&!i(24)(function(){return Object.defineProperty(i(16)("div"),"a",{get:function(){return 7}}).a!=7})},function(t,n,i){"use strict";var s=i(28),a=i(23),f=i(57),c=i(5),l=i(8),p=i(10),m=i(45),_=i(18),b=i(52),x=i(1)("iterator"),C=!([].keys&&"next"in[].keys()),H="@@iterator",ie="keys",z="values",T=function(){return this};t.exports=function(F,te,U,ee,pe,K,Ne){m(U,te,ee);var tt,xe,Me,we=function(B){if(!C&&B in Fe)return Fe[B];switch(B){case ie:return function(){return new U(this,B)};case z:return function(){return new U(this,B)}}return function(){return new U(this,B)}},qe=te+" Iterator",be=pe==z,rt=!1,Fe=F.prototype,yt=Fe[x]||Fe[H]||pe&&Fe[pe],We=yt||we(pe),dt=pe?be?we("entries"):We:void 0,N=te=="Array"&&Fe.entries||yt;if(N&&(Me=b(N.call(new F)),Me!==Object.prototype&&(_(Me,qe,!0),s||l(Me,x)||c(Me,x,T))),be&&yt&&yt.name!==z&&(rt=!0,We=function(){return yt.call(this)}),s&&!Ne||!C&&!rt&&Fe[x]||c(Fe,x,We),p[te]=We,p[qe]=T,pe)if(tt={values:be?We:we(z),keys:K?We:we(ie),entries:dt},Ne)for(xe in tt)xe in Fe||f(Fe,xe,tt[xe]);else a(a.P+a.F*(C||rt),te,tt);return tt}},function(t,n){t.exports=!0},function(t,n,i){var s=i(2),a="__core-js_shared__",f=s[a]||(s[a]={});t.exports=function(c){return f[c]||(f[c]={})}},function(t,n,i){var s,a,f,c=i(7),l=i(41),p=i(25),m=i(16),_=i(2),b=_.process,x=_.setImmediate,C=_.clearImmediate,H=_.MessageChannel,ie=0,z={},T="onreadystatechange",F=function(){var U=+this;if(z.hasOwnProperty(U)){var ee=z[U];delete z[U],ee()}},te=function(U){F.call(U.data)};x&&C||(x=function(U){for(var ee=[],pe=1;arguments.length>pe;)ee.push(arguments[pe++]);return z[++ie]=function(){l(typeof U=="function"?U:Function(U),ee)},s(ie),ie},C=function(U){delete z[U]},i(11)(b)=="process"?s=function(U){b.nextTick(c(F,U,1))}:H?(a=new H,f=a.port2,a.port1.onmessage=te,s=c(f.postMessage,f,1)):_.addEventListener&&typeof postMessage=="function"&&!_.importScripts?(s=function(U){_.postMessage(U+"","*")},_.addEventListener("message",te,!1)):s=T in m("script")?function(U){p.appendChild(m("script"))[T]=function(){p.removeChild(this),F.call(U)}}:function(U){setTimeout(c(F,U,1),0)}),t.exports={set:x,clear:C}},function(t,n,i){var s=i(20),a=Math.min;t.exports=function(f){return f>0?a(s(f),9007199254740991):0}},function(t,n,i){var s=i(9);t.exports=function(a,f){if(!s(a))return a;var c,l;if(f&&typeof(c=a.toString)=="function"&&!s(l=c.call(a))||typeof(c=a.valueOf)=="function"&&!s(l=c.call(a))||!f&&typeof(c=a.toString)=="function"&&!s(l=c.call(a)))return l;throw TypeError("Can't convert object to primitive value")}},function(t,n){var i=0,s=Math.random();t.exports=function(a){return"Symbol(".concat(a===void 0?"":a,")_",(++i+s).toString(36))}},function(t,n,i){"use strict";function s(T){return T&&T.__esModule?T:{default:T}}function a(){return process.platform!=="win32"?"":process.arch==="ia32"&&process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432")?"mixed":"native"}function f(T){return(0,x.createHash)("sha256").update(T).digest("hex")}function c(T){switch(H){case"darwin":return T.split("IOPlatformUUID")[1].split(`
|
|
34
|
-
`)[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return T.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return T.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"freebsd":return T.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error("Unsupported platform: "+process.platform)}}function l(T){var F=c((0,b.execSync)(z[H]).toString());return T?F:f(F)}function p(T){return new _.default(function(F,te){return(0,b.exec)(z[H],{},function(U,ee,pe){if(U)return te(new Error("Error while obtaining machine id: "+U.stack));var K=c(ee.toString());return F(T?K:f(K))})})}Object.defineProperty(n,"__esModule",{value:!0});var m=i(35),_=s(m);n.machineIdSync=l,n.machineId=p;var b=i(70),x=i(71),C=process,H=C.platform,ie={native:"%windir%\\System32",mixed:"%windir%\\sysnative\\cmd.exe /c %windir%\\System32"},z={darwin:"ioreg -rd1 -c IOPlatformExpertDevice",win32:ie[a()]+"\\REG.exe QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",linux:"( cat /var/lib/dbus/machine-id /etc/machine-id 2> /dev/null || hostname ) | head -n 1 || :",freebsd:"kenv -q smbios.system.uuid || sysctl -n kern.hostuuid"}},function(t,n,i){t.exports={default:i(36),__esModule:!0}},function(t,n,i){i(66),i(68),i(69),i(67),t.exports=i(6).Promise},function(t,n){t.exports=function(){}},function(t,n){t.exports=function(i,s,a,f){if(!(i instanceof s)||f!==void 0&&f in i)throw TypeError(a+": incorrect invocation!");return i}},function(t,n,i){var s=i(13),a=i(31),f=i(62);t.exports=function(c){return function(l,p,m){var _,b=s(l),x=a(b.length),C=f(m,x);if(c&&p!=p){for(;x>C;)if(_=b[C++],_!=_)return!0}else for(;x>C;C++)if((c||C in b)&&b[C]===p)return c||C||0;return!c&&-1}}},function(t,b,i){var s=i(7),a=i(44),f=i(43),c=i(3),l=i(31),p=i(64),m={},_={},b=t.exports=function(x,C,H,ie,z){var T,F,te,U,ee=z?function(){return x}:p(x),pe=s(H,ie,C?2:1),K=0;if(typeof ee!="function")throw TypeError(x+" is not iterable!");if(f(ee)){for(T=l(x.length);T>K;K++)if(U=C?pe(c(F=x[K])[0],F[1]):pe(x[K]),U===m||U===_)return U}else for(te=ee.call(x);!(F=te.next()).done;)if(U=a(te,pe,F.value,C),U===m||U===_)return U};b.BREAK=m,b.RETURN=_},function(t,n){t.exports=function(i,s,a){var f=a===void 0;switch(s.length){case 0:return f?i():i.call(a);case 1:return f?i(s[0]):i.call(a,s[0]);case 2:return f?i(s[0],s[1]):i.call(a,s[0],s[1]);case 3:return f?i(s[0],s[1],s[2]):i.call(a,s[0],s[1],s[2]);case 4:return f?i(s[0],s[1],s[2],s[3]):i.call(a,s[0],s[1],s[2],s[3])}return i.apply(a,s)}},function(t,n,i){var s=i(11);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(a){return s(a)=="String"?a.split(""):Object(a)}},function(t,n,i){var s=i(10),a=i(1)("iterator"),f=Array.prototype;t.exports=function(c){return c!==void 0&&(s.Array===c||f[a]===c)}},function(t,n,i){var s=i(3);t.exports=function(a,f,c,l){try{return l?f(s(c)[0],c[1]):f(c)}catch(m){var p=a.return;throw p!==void 0&&s(p.call(a)),m}}},function(t,n,i){"use strict";var s=i(49),a=i(17),f=i(18),c={};i(5)(c,i(1)("iterator"),function(){return this}),t.exports=function(l,p,m){l.prototype=s(c,{next:a(1,m)}),f(l,p+" Iterator")}},function(t,n,i){var s=i(1)("iterator"),a=!1;try{var f=[7][s]();f.return=function(){a=!0},Array.from(f,function(){throw 2})}catch{}t.exports=function(c,l){if(!l&&!a)return!1;var p=!1;try{var m=[7],_=m[s]();_.next=function(){return{done:p=!0}},m[s]=function(){return _},c(m)}catch{}return p}},function(t,n){t.exports=function(i,s){return{value:s,done:!!i}}},function(t,n,i){var s=i(2),a=i(30).set,f=s.MutationObserver||s.WebKitMutationObserver,c=s.process,l=s.Promise,p=i(11)(c)=="process";t.exports=function(){var m,_,b,x=function(){var z,T;for(p&&(z=c.domain)&&z.exit();m;){T=m.fn,m=m.next;try{T()}catch(F){throw m?b():_=void 0,F}}_=void 0,z&&z.enter()};if(p)b=function(){c.nextTick(x)};else if(f){var C=!0,H=document.createTextNode("");new f(x).observe(H,{characterData:!0}),b=function(){H.data=C=!C}}else if(l&&l.resolve){var ie=l.resolve();b=function(){ie.then(x)}}else b=function(){a.call(s,x)};return function(z){var T={fn:z,next:void 0};_&&(_.next=T),m||(m=T,b()),_=T}}},function(t,n,i){var s=i(3),a=i(50),f=i(22),c=i(19)("IE_PROTO"),l=function(){},p="prototype",m=function(){var _,b=i(16)("iframe"),x=f.length,C=">";for(b.style.display="none",i(25).appendChild(b),b.src="javascript:",_=b.contentWindow.document,_.open(),_.write("<script>document.F=Object</script"+C),_.close(),m=_.F;x--;)delete m[p][f[x]];return m()};t.exports=Object.create||function(_,b){var x;return _!==null?(l[p]=s(_),x=new l,l[p]=null,x[c]=_):x=m(),b===void 0?x:a(x,b)}},function(t,n,i){var s=i(12),a=i(3),f=i(54);t.exports=i(4)?Object.defineProperties:function(c,l){a(c);for(var p,m=f(l),_=m.length,b=0;_>b;)s.f(c,p=m[b++],l[p]);return c}},function(t,n,i){var s=i(55),a=i(17),f=i(13),c=i(32),l=i(8),p=i(26),m=Object.getOwnPropertyDescriptor;n.f=i(4)?m:function(_,b){if(_=f(_),b=c(b,!0),p)try{return m(_,b)}catch{}if(l(_,b))return a(!s.f.call(_,b),_[b])}},function(t,n,i){var s=i(8),a=i(63),f=i(19)("IE_PROTO"),c=Object.prototype;t.exports=Object.getPrototypeOf||function(l){return l=a(l),s(l,f)?l[f]:typeof l.constructor=="function"&&l instanceof l.constructor?l.constructor.prototype:l instanceof Object?c:null}},function(t,n,i){var s=i(8),a=i(13),f=i(39)(!1),c=i(19)("IE_PROTO");t.exports=function(l,p){var m,_=a(l),b=0,x=[];for(m in _)m!=c&&s(_,m)&&x.push(m);for(;p.length>b;)s(_,m=p[b++])&&(~f(x,m)||x.push(m));return x}},function(t,n,i){var s=i(53),a=i(22);t.exports=Object.keys||function(f){return s(f,a)}},function(t,n){n.f={}.propertyIsEnumerable},function(t,n,i){var s=i(5);t.exports=function(a,f,c){for(var l in f)c&&a[l]?a[l]=f[l]:s(a,l,f[l]);return a}},function(t,n,i){t.exports=i(5)},function(t,n,i){var s=i(9),a=i(3),f=function(c,l){if(a(c),!s(l)&&l!==null)throw TypeError(l+": can't set as prototype!")};t.exports={set:Object.setPrototypeOf||("__proto__"in{}?(function(c,l,p){try{p=i(7)(Function.call,i(51).f(Object.prototype,"__proto__").set,2),p(c,[]),l=!(c instanceof Array)}catch{l=!0}return function(m,_){return f(m,_),l?m.__proto__=_:p(m,_),m}})({},!1):void 0),check:f}},function(t,n,i){"use strict";var s=i(2),a=i(6),f=i(12),c=i(4),l=i(1)("species");t.exports=function(p){var m=typeof a[p]=="function"?a[p]:s[p];c&&m&&!m[l]&&f.f(m,l,{configurable:!0,get:function(){return this}})}},function(t,n,i){var s=i(3),a=i(14),f=i(1)("species");t.exports=function(c,l){var p,m=s(c).constructor;return m===void 0||(p=s(m)[f])==null?l:a(p)}},function(t,n,i){var s=i(20),a=i(15);t.exports=function(f){return function(c,l){var p,m,_=String(a(c)),b=s(l),x=_.length;return b<0||b>=x?f?"":void 0:(p=_.charCodeAt(b),p<55296||p>56319||b+1===x||(m=_.charCodeAt(b+1))<56320||m>57343?f?_.charAt(b):p:f?_.slice(b,b+2):(p-55296<<10)+(m-56320)+65536)}}},function(t,n,i){var s=i(20),a=Math.max,f=Math.min;t.exports=function(c,l){return c=s(c),c<0?a(c+l,0):f(c,l)}},function(t,n,i){var s=i(15);t.exports=function(a){return Object(s(a))}},function(t,n,i){var s=i(21),a=i(1)("iterator"),f=i(10);t.exports=i(6).getIteratorMethod=function(c){if(c!=null)return c[a]||c["@@iterator"]||f[s(c)]}},function(t,n,i){"use strict";var s=i(37),a=i(47),f=i(10),c=i(13);t.exports=i(27)(Array,"Array",function(l,p){this._t=c(l),this._i=0,this._k=p},function(){var l=this._t,p=this._k,m=this._i++;return!l||m>=l.length?(this._t=void 0,a(1)):p=="keys"?a(0,m):p=="values"?a(0,l[m]):a(0,[m,l[m]])},"values"),f.Arguments=f.Array,s("keys"),s("values"),s("entries")},function(t,n){},function(t,n,i){"use strict";var s,a,f,c=i(28),l=i(2),p=i(7),m=i(21),_=i(23),b=i(9),x=(i(3),i(14)),C=i(38),H=i(40),ie=(i(58).set,i(60)),z=i(30).set,T=i(48)(),F="Promise",te=l.TypeError,ee=l.process,U=l[F],ee=l.process,pe=m(ee)=="process",K=function(){},Ne=!!(function(){try{var N=U.resolve(1),B=(N.constructor={})[i(1)("species")]=function(I){I(K,K)};return(pe||typeof PromiseRejectionEvent=="function")&&N.then(K)instanceof B}catch{}})(),tt=function(N,B){return N===B||N===U&&B===f},xe=function(N){var B;return!(!b(N)||typeof(B=N.then)!="function")&&B},Me=function(N){return tt(U,N)?new we(N):new a(N)},we=a=function(N){var B,I;this.promise=new N(function(se,Pe){if(B!==void 0||I!==void 0)throw te("Bad Promise constructor");B=se,I=Pe}),this.resolve=x(B),this.reject=x(I)},qe=function(N){try{N()}catch(B){return{error:B}}},be=function(N,B){if(!N._n){N._n=!0;var I=N._c;T(function(){for(var se=N._v,Pe=N._s==1,j=0,ue=function(je){var nt,_t,Vt=Pe?je.ok:je.fail,cn=je.resolve,jr=je.reject,Nn=je.domain;try{Vt?(Pe||(N._h==2&&yt(N),N._h=1),Vt===!0?nt=se:(Nn&&Nn.enter(),nt=Vt(se),Nn&&Nn.exit()),nt===je.promise?jr(te("Promise-chain cycle")):(_t=xe(nt))?_t.call(nt,cn,jr):cn(nt)):jr(se)}catch(rs){jr(rs)}};I.length>j;)ue(I[j++]);N._c=[],N._n=!1,B&&!N._h&&rt(N)})}},rt=function(N){z.call(l,function(){var B,I,se,Pe=N._v;if(Fe(N)&&(B=qe(function(){pe?ee.emit("unhandledRejection",Pe,N):(I=l.onunhandledrejection)?I({promise:N,reason:Pe}):(se=l.console)&&se.error&&se.error("Unhandled promise rejection",Pe)}),N._h=pe||Fe(N)?2:1),N._a=void 0,B)throw B.error})},Fe=function(N){if(N._h==1)return!1;for(var B,I=N._a||N._c,se=0;I.length>se;)if(B=I[se++],B.fail||!Fe(B.promise))return!1;return!0},yt=function(N){z.call(l,function(){var B;pe?ee.emit("rejectionHandled",N):(B=l.onrejectionhandled)&&B({promise:N,reason:N._v})})},We=function(N){var B=this;B._d||(B._d=!0,B=B._w||B,B._v=N,B._s=2,B._a||(B._a=B._c.slice()),be(B,!0))},dt=function(N){var B,I=this;if(!I._d){I._d=!0,I=I._w||I;try{if(I===N)throw te("Promise can't be resolved itself");(B=xe(N))?T(function(){var se={_w:I,_d:!1};try{B.call(N,p(dt,se,1),p(We,se,1))}catch(Pe){We.call(se,Pe)}}):(I._v=N,I._s=1,be(I,!1))}catch(se){We.call({_w:I,_d:!1},se)}}};Ne||(U=function(N){C(this,U,F,"_h"),x(N),s.call(this);try{N(p(dt,this,1),p(We,this,1))}catch(B){We.call(this,B)}},s=function(N){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},s.prototype=i(56)(U.prototype,{then:function(N,B){var I=Me(ie(this,U));return I.ok=typeof N!="function"||N,I.fail=typeof B=="function"&&B,I.domain=pe?ee.domain:void 0,this._c.push(I),this._a&&this._a.push(I),this._s&&be(this,!1),I.promise},catch:function(N){return this.then(void 0,N)}}),we=function(){var N=new s;this.promise=N,this.resolve=p(dt,N,1),this.reject=p(We,N,1)}),_(_.G+_.W+_.F*!Ne,{Promise:U}),i(18)(U,F),i(59)(F),f=i(6)[F],_(_.S+_.F*!Ne,F,{reject:function(N){var B=Me(this),I=B.reject;return I(N),B.promise}}),_(_.S+_.F*(c||!Ne),F,{resolve:function(N){if(N instanceof U&&tt(N.constructor,this))return N;var B=Me(this),I=B.resolve;return I(N),B.promise}}),_(_.S+_.F*!(Ne&&i(46)(function(N){U.all(N).catch(K)})),F,{all:function(N){var B=this,I=Me(B),se=I.resolve,Pe=I.reject,j=qe(function(){var ue=[],je=0,nt=1;H(N,!1,function(_t){var Vt=je++,cn=!1;ue.push(void 0),nt++,B.resolve(_t).then(function(jr){cn||(cn=!0,ue[Vt]=jr,--nt||se(ue))},Pe)}),--nt||se(ue)});return j&&Pe(j.error),I.promise},race:function(N){var B=this,I=Me(B),se=I.reject,Pe=qe(function(){H(N,!1,function(j){B.resolve(j).then(I.resolve,se)})});return Pe&&se(Pe.error),I.promise}})},function(t,n,i){"use strict";var s=i(61)(!0);i(27)(String,"String",function(a){this._t=String(a),this._i=0},function(){var a,f=this._t,c=this._i;return c>=f.length?{value:void 0,done:!0}:(a=s(f,c),this._i+=a.length,{value:a,done:!1})})},function(t,n,i){i(65);for(var s=i(2),a=i(5),f=i(10),c=i(1)("toStringTag"),l=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],p=0;p<5;p++){var m=l[p],_=s[m],b=_&&_.prototype;b&&!b[c]&&a(b,c,m),f[m]=f.Array}},function(t,n){t.exports=require("child_process")},function(t,n){t.exports=require("crypto")}])})});function ab(){try{return ef.default.statSync("/.dockerenv"),!0}catch{return!1}}function cb(){try{return ef.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function tf(){return Qc===void 0&&(Qc=ab()||cb()),Qc}var ef,Qc,gd=$t(()=>{ef=he(require("node:fs"),1)});function li(){return rf===void 0&&(rf=fb()||tf()),rf}var md,rf,fb,nf=$t(()=>{md=he(require("node:fs"),1);gd();fb=()=>{try{return md.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var sf,_d,Ed,yd,tn,of=$t(()=>{sf=he(require("node:process"),1),_d=he(require("node:os"),1),Ed=he(require("node:fs"),1);nf();yd=()=>{if(sf.default.platform!=="linux")return!1;if(_d.default.release().toLowerCase().includes("microsoft"))return!li();try{return Ed.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!li():!1}catch{return!1}},tn=sf.default.env.__IS_WSL_TEST__?yd:yd()});var af,Xi,ub,lb,cf,bd=$t(()=>{af=he(require("node:process"),1),Xi=he(require("node:fs/promises"),1);of();of();ub=(()=>{let r="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",n=!1;try{await Xi.default.access(t,Xi.constants.F_OK),n=!0}catch{}if(!n)return r;let i=await Xi.default.readFile(t,{encoding:"utf8"}),s=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(i);return s?(e=s.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):r}})(),lb=async()=>`${await ub()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,cf=async()=>tn?lb():`${af.default.env.SYSTEMROOT||af.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function rn(r,e,t){let n=i=>Object.defineProperty(r,e,{value:i,enumerable:!0,writable:!0});return Object.defineProperty(r,e,{configurable:!0,enumerable:!0,get(){let i=t();return n(i),i},set(i){n(i)}}),r}var vd=$t(()=>{});async function ff(){if(Sd.default.platform!=="darwin")throw new Error("macOS only");let{stdout:r}=await hb("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 wd,Sd,xd,hb,Td=$t(()=>{wd=require("node:util"),Sd=he(require("node:process"),1),xd=require("node:child_process"),hb=(0,wd.promisify)(xd.execFile)});async function Od(r,{humanReadableOutput:e=!0,signal:t}={}){if(Cd.default.platform!=="darwin")throw new Error("macOS only");let n=e?[]:["-ss"],i={};t&&(i.signal=t);let{stdout:s}=await db("osascript",["-e",r,n],i);return s.trim()}var Cd,kd,uf,db,Pd=$t(()=>{Cd=he(require("node:process"),1),kd=require("node:util"),uf=require("node:child_process"),db=(0,kd.promisify)(uf.execFile)});async function lf(r){return Od(`tell application "Finder" to set app_path to application file id "${r}" as string
|
|
35
|
-
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var
|
|
36
|
-
`,{encoding:"utf8"})}catch{}}var
|
|
37
|
-
`)}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 dd=he(require("os")),pd=he(Zc()),Gi=class{cachedId=null;name;constructor(e){this.name=e||dd.hostname()||"CLI"}async getMachineId(){if(this.cachedId)return this.cachedId;try{this.cachedId=(0,pd.machineIdSync)()}catch{this.cachedId=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}return this.cachedId}getMachineName(){return this.name}};var Yi=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 Zi=class{async openUrl(e){let{default:t}=await Promise.resolve().then(()=>(Hd(),Wd));await t(e)}};var Vd=he(require("fs")),bf=he(require("path"));function Ao(r){let e=r?[r]:[bf.join(__dirname,"..","package.json"),bf.join(__dirname,"..","..","package.json")];for(let t of e)try{let n=JSON.parse(Vd.readFileSync(t,"utf8"));if(typeof n.version=="string"&&n.version.length>0)return n.version}catch{}return"unknown"}function $d(r,e){for(let t=0;t<r.length;t++){let n=r[t];if(n.startsWith("-")){e.has(n)&&t++;continue}return n}}var vf=new Set(["--cid","--token","--server","--log-level"]),zd=new Set(["--help","-h","--version","-V","--verbose","-v","--watch","-w","--log-to-file","--statusline","--multi-viewer","--force"]);function Gd(r,e,t){for(let n=0;n<r.length;n++){let i=r[n];if(!i.startsWith("-"))continue;let s=i.includes("=")?i.slice(0,i.indexOf("=")):i;if(e.has(s)||t.has(s)){e.has(s)&&!i.includes("=")&&n++;continue}return i}}var vp=he(require("path")),ht=he(Vi()),wp=he(Or());var Yd=he(require("os")),Xd=require("crypto"),Jd=he(require("node-pty")),di=he(Vi()),Ro=class r{ptyProcess=null;outputBuffer=new di.CircularBuffer(100);altScreenActive=!1;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 n=process.env.SHELL||(Yd.platform()==="win32"?"powershell.exe":"/bin/bash"),i=process.stdout.columns||80,s=process.stdout.rows||24,a=Math.max(1,s-t);this.reservedBottomRows=t,this.ptyProcess=Jd.spawn(n,[],{name:"xterm-256color",cols:i,rows:a,cwd:e,env:{...process.env,TERMIQ_SESSION_ACTIVE:"1"}}),this.onResize?.(i,a),this.streamId=(0,Xd.randomUUID)();let f=`cli_${this.ptyProcess.pid}`;return this.ptyProcess.onData(c=>{this.altScreenActive=(0,di.trackAltScreen)(c,this.altScreenActive),this.preWriteHook?.(c),process.stdout.write(c),this.outputBuffer.append(c),this.onOutput?.(c)}),this.ptyProcess.onExit(({exitCode:c})=>{this.logger.info("Shell exited",String(c)),this.onExit?.(c)}),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",c=>{let l=c.toString();this.multiViewerMode&&!(0,di.isTerminalReplyOnly)(l)&&this.maybeClaimLocalControl(),this.onLocalInput?.(l),this.ptyProcess?.write(l)}),this.sigwinchListener=()=>{let c=process.stdout.columns||80,l=Math.max(1,(process.stdout.rows||24)-this.reservedBottomRows);if(this.multiViewerMode){this.logger.info("Local resize claims control",{cols:c,rows:l}),this.resize(c,l),this.onLocalClaim?.(c,l);return}if(this.desiredCols!==null&&this.desiredRows!==null){this.logger.info("Local resize ignored (PWA desired-size set)",{host:{cols:c,rows:l},desired:{cols:this.desiredCols,rows:this.desiredRows}});return}if(!this.sigwinchEnabled){this.logger.info("Local resize ignored (PWA viewers attached)",{cols:c,rows:l});return}this.logger.info("Local resize applied",{cols:c,rows:l}),this.ptyProcess?.resize(c,l),this.onResize?.(c,l)},process.platform==="win32"?process.stdout.on("resize",this.sigwinchListener):process.on("SIGWINCH",this.sigwinchListener),this.logger.info("Shell spawned",n,f),f}write(e,t=!1){if(this.ptyProcess){if(!t&&!this.draining){this.ptyProcess.write(e);return}for(let n of e)this.writeQueue.push(n);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){if(this.desiredCols=e,this.desiredRows=t,this.ptyProcess&&this.ptyProcess.cols===e&&this.ptyProcess.rows===t){this.cancelRebroadcast();return}this.ptyProcess?.resize(e,t),this.onResize?.(e,t),this.cancelRebroadcast();for(let n of r.REBROADCAST_DELAYS_MS)this.rebroadcastTimers.push(setTimeout(()=>{this.ptyProcess&&(this.desiredCols!==e||this.desiredRows!==t||this.ptyProcess.cols===e&&this.ptyProcess.rows===t||this.ptyProcess.resize(e,t))},n))}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(){let e=this.outputBuffer.getContent();return this.altScreenActive?`\x1B[?1049h${e}`:e}isAltScreen(){return this.altScreenActive}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 sn=he(require("path")),gi=he(require("fs"));var dp=require("node:events"),pp=require("node:fs"),jo=require("node:fs/promises"),Se=he(require("node:path"),1);var Dr=require("node:fs/promises"),Br=require("node:path"),tp=require("node:stream"),Lt={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},wf={root:".",fileFilter:r=>!0,directoryFilter:r=>!0,type:Lt.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(wf);var rp="READDIRP_RECURSIVE_ERROR",Sb=new Set(["ENOENT","EPERM","EACCES","ELOOP",rp]),Zd=[Lt.DIR_TYPE,Lt.EVERYTHING_TYPE,Lt.FILE_DIR_TYPE,Lt.FILE_TYPE],xb=new Set([Lt.DIR_TYPE,Lt.EVERYTHING_TYPE,Lt.FILE_DIR_TYPE]),Tb=new Set([Lt.EVERYTHING_TYPE,Lt.FILE_DIR_TYPE,Lt.FILE_TYPE]),Cb=r=>Sb.has(r.code),kb=process.platform==="win32",Qd=r=>!0,ep=r=>{if(r===void 0)return Qd;if(typeof r=="function")return r;if(typeof r=="string"){let e=r.trim();return t=>t.basename===e}if(Array.isArray(r)){let e=r.map(t=>t.trim());return t=>e.some(n=>t.basename===n)}return Qd},Sf=class extends tp.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={...wf,...e},{root:n,type:i}=t;this._fileFilter=ep(t.fileFilter),this._directoryFilter=ep(t.directoryFilter);let s=t.lstat?Dr.lstat:Dr.stat;kb?this._stat=a=>s(a,{bigint:!0}):this._stat=s,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:wf.depth,this._wantsDir=i?xb.has(i):!1,this._wantsFile=i?Tb.has(i):!1,this._wantsEverything=i===Lt.EVERYTHING_TYPE,this._root=(0,Br.resolve)(n),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:i,depth:s}=t,a=n.splice(0,e).map(c=>this._formatEntry(c,i)),f=await Promise.all(a);for(let c of f){if(!c)continue;if(this.destroyed)return;let l=await this._getEntryType(c);l==="directory"&&this._directoryFilter(c)?(s<=this._maxDepth&&this.parents.push(this._exploreDir(c.fullPath,s+1)),this._wantsDir&&(this.push(c),e--)):(l==="file"||this._includeAsFile(c))&&this._fileFilter(c)&&this._wantsFile&&(this.push(c),e--)}}else{let i=this.parents.pop();if(!i){this.push(null);break}if(this.parent=await i,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await(0,Dr.readdir)(e,this._rdOptions)}catch(i){this._onError(i)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n,i=this._isDirent?e.name:e;try{let s=(0,Br.resolve)((0,Br.join)(t,i));n={path:(0,Br.relative)(this._root,s),fullPath:s,basename:i},n[this._statsProp]=this._isDirent?e:await this._stat(s)}catch(s){this._onError(s);return}return n}_onError(e){Cb(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return"";let t=e[this._statsProp];if(t.isFile())return"file";if(t.isDirectory())return"directory";if(t&&t.isSymbolicLink()){let n=e.fullPath;try{let i=await(0,Dr.realpath)(n),s=await(0,Dr.lstat)(i);if(s.isFile())return"file";if(s.isDirectory()){let a=i.length;if(n.startsWith(i)&&n.substr(a,1)===Br.sep){let f=new Error(`Circular symlink detected: "${n}" points to "${i}"`);return f.code=rp,this._onError(f)}return"directory"}}catch(i){return this._onError(i),""}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function np(r,e={}){let t=e.entryType||e.type;if(t==="both"&&(t=Lt.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&&!Zd.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${Zd.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=r,new Sf(e)}var Ln=require("node:fs"),rr=require("node:fs/promises"),sp=require("node:os"),Ye=he(require("node:path"),1),Ob="data",Cf="end",op="close",Fo=()=>{};var Do=process.platform,kf=Do==="win32",Pb=Do==="darwin",Ab=Do==="linux",Rb=Do==="freebsd",ap=(0,sp.type)()==="OS400",Je={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},tr=Je,Ib="watch",Lb={lstat:rr.lstat,stat:rr.stat},In="listeners",Io="errHandlers",pi="rawEmitters",Nb=[In,Io,pi],Mb=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"]),Fb=r=>Mb.has(Ye.extname(r).slice(1).toLowerCase()),Tf=(r,e)=>{r instanceof Set?r.forEach(e):e(r)},Qi=(r,e,t)=>{let n=r[e];n instanceof Set||(r[e]=n=new Set([n])),n.add(t)},Db=r=>e=>{let t=r[e];t instanceof Set?t.clear():delete r[e]},es=(r,e,t)=>{let n=r[e];n instanceof Set?n.delete(t):n===t&&delete r[e]},cp=r=>r instanceof Set?r.size===0:!r,Lo=new Map;function ip(r,e,t,n,i){let s=(a,f)=>{t(r),i(a,f,{watchedPath:r}),f&&r!==f&&No(Ye.resolve(r,f),In,Ye.join(r,f))};try{return(0,Ln.watch)(r,{persistent:e.persistent},s)}catch(a){n(a);return}}var No=(r,e,t,n,i)=>{let s=Lo.get(r);s&&Tf(s[e],a=>{a(t,n,i)})},Bb=(r,e,t,n)=>{let{listener:i,errHandler:s,rawEmitter:a}=n,f=Lo.get(e),c;if(!t.persistent)return c=ip(r,t,i,s,a),c?c.close.bind(c):void 0;if(f)Qi(f,In,i),Qi(f,Io,s),Qi(f,pi,a);else{if(c=ip(r,t,No.bind(null,e,In),s,No.bind(null,e,pi)),!c)return;c.on(tr.ERROR,async l=>{let p=No.bind(null,e,Io);if(f&&(f.watcherUnusable=!0),kf&&l.code==="EPERM")try{await(await(0,rr.open)(r,"r")).close(),p(l)}catch{}else p(l)}),f={listeners:i,errHandlers:s,rawEmitters:a,watcher:c},Lo.set(e,f)}return()=>{es(f,In,i),es(f,Io,s),es(f,pi,a),cp(f.listeners)&&(f.watcher.close(),Lo.delete(e),Nb.forEach(Db(f)),f.watcher=void 0,Object.freeze(f))}},xf=new Map,jb=(r,e,t,n)=>{let{listener:i,rawEmitter:s}=n,a=xf.get(e),f=a&&a.options;return f&&(f.persistent<t.persistent||f.interval>t.interval)&&((0,Ln.unwatchFile)(e),a=void 0),a?(Qi(a,In,i),Qi(a,pi,s)):(a={listeners:i,rawEmitters:s,options:t,watcher:(0,Ln.watchFile)(e,t,(c,l)=>{Tf(a.rawEmitters,m=>{m(tr.CHANGE,e,{curr:c,prev:l})});let p=c.mtimeMs;(c.size!==l.size||p>l.mtimeMs||p===0)&&Tf(a.listeners,m=>m(r,c))})},xf.set(e,a)),()=>{es(a,In,i),es(a,pi,s),cp(a.listeners)&&(xf.delete(e),(0,Ln.unwatchFile)(e),a.options=a.watcher=void 0,Object.freeze(a))}},Mo=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,i=Ye.dirname(e),s=Ye.basename(e);this.fsw._getWatchedDir(i).add(s);let f=Ye.resolve(e),c={persistent:n.persistent};t||(t=Fo);let l;if(n.usePolling){let p=n.interval!==n.binaryInterval;c.interval=p&&Fb(s)?n.binaryInterval:n.interval,l=jb(e,f,c,{listener:t,rawEmitter:this.fsw._emitRaw})}else l=Bb(e,f,c,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return l}_handleFile(e,t,n){if(this.fsw.closed)return;let i=Ye.dirname(e),s=Ye.basename(e),a=this.fsw._getWatchedDir(i),f=t;if(a.has(s))return;let c=async(p,m)=>{if(this.fsw._throttle(Ib,e,5)){if(!m||m.mtimeMs===0)try{let _=await(0,rr.stat)(e);if(this.fsw.closed)return;let b=_.atimeMs,x=_.mtimeMs;if((!b||b<=x||x!==f.mtimeMs)&&this.fsw._emit(tr.CHANGE,e,_),(Pb||Ab||Rb)&&f.ino!==_.ino){this.fsw._closeFile(p),f=_;let C=this._watchWithNodeFs(e,c);C&&this.fsw._addPathCloser(p,C)}else f=_}catch{this.fsw._remove(i,s)}else if(a.has(s)){let _=m.atimeMs,b=m.mtimeMs;(!_||_<=b||b!==f.mtimeMs)&&this.fsw._emit(tr.CHANGE,e,m),f=m}}},l=this._watchWithNodeFs(e,c);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(tr.ADD,e,0))return;this.fsw._emit(tr.ADD,e,t)}return l}async _handleSymlink(e,t,n,i){if(this.fsw.closed)return;let s=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let f;try{f=await(0,rr.realpath)(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(i)?this.fsw._symlinkPaths.get(s)!==f&&(this.fsw._symlinkPaths.set(s,f),this.fsw._emit(tr.CHANGE,n,e.stats)):(a.add(i),this.fsw._symlinkPaths.set(s,f),this.fsw._emit(tr.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(s))return!0;this.fsw._symlinkPaths.set(s,!0)}_handleRead(e,t,n,i,s,a,f){e=Ye.join(e,"");let c=i?`${e}:${i}`:e;if(f=this.fsw._throttle("readdir",c,1e3),!f)return;let l=this.fsw._getWatchedDir(n.path),p=new Set,m=this.fsw._readdirp(e,{fileFilter:_=>n.filterPath(_),directoryFilter:_=>n.filterDir(_)});if(m)return m.on(Ob,async _=>{if(this.fsw.closed){m=void 0;return}let b=_.path,x=Ye.join(e,b);if(p.add(b),!(_.stats.isSymbolicLink()&&await this._handleSymlink(_,e,x,b))){if(this.fsw.closed){m=void 0;return}(b===i||!i&&!l.has(b))&&(this.fsw._incrReadyCount(),x=Ye.join(s,Ye.relative(s,x)),this._addToNodeFs(x,t,n,a+1))}}).on(tr.ERROR,this._boundHandleError),new Promise((_,b)=>{if(!m)return b();m.once(Cf,()=>{if(this.fsw.closed){m=void 0;return}let x=f?f.clear():!1;_(void 0),l.getChildren().filter(C=>C!==e&&!p.has(C)).forEach(C=>{this.fsw._remove(e,C)}),m=void 0,x&&this._handleRead(e,!1,n,i,s,a,f)})})}async _handleDir(e,t,n,i,s,a,f){let c=this.fsw._getWatchedDir(Ye.dirname(e)),l=c.has(Ye.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!s&&!l&&this.fsw._emit(tr.ADD_DIR,e,t),c.add(Ye.basename(e)),this.fsw._getWatchedDir(e);let p,m,_=this.fsw.options.depth;if((_==null||i<=_)&&!this.fsw._symlinkPaths.has(f)){if(!s&&(await this._handleRead(e,n,a,s,e,i,p),this.fsw.closed))return;m=this._watchWithNodeFs(e,(b,x)=>{x&&x.mtimeMs===0||this._handleRead(b,!1,a,s,e,i,p)})}return m}async _addToNodeFs(e,t,n,i,s){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let f=this.fsw._getWatchHelpers(e);n&&(f.filterPath=c=>n.filterPath(c),f.filterDir=c=>n.filterDir(c));try{let c=await Lb[f.statMethod](f.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(f.watchPath,c))return a(),!1;let l=this.fsw.options.followSymlinks,p;if(c.isDirectory()){let m=Ye.resolve(e),_=l?await(0,rr.realpath)(e):e;if(this.fsw.closed||(p=await this._handleDir(f.watchPath,c,t,i,s,f,_),this.fsw.closed))return;m!==_&&_!==void 0&&this.fsw._symlinkPaths.set(m,_)}else if(c.isSymbolicLink()){let m=l?await(0,rr.realpath)(e):e;if(this.fsw.closed)return;let _=Ye.dirname(f.watchPath);if(this.fsw._getWatchedDir(_).add(f.watchPath),this.fsw._emit(tr.ADD,f.watchPath,c),p=await this._handleDir(_,c,t,i,e,f,m),this.fsw.closed)return;m!==void 0&&this.fsw._symlinkPaths.set(Ye.resolve(e),m)}else p=this._handleFile(f.watchPath,c,t);return a(),p&&this.fsw._addPathCloser(e,p),!1}catch(c){if(this.fsw._handleError(c))return a(),e}}};var Of="/",Ub="//",gp=".",Kb="..",qb="string",Wb=/\\/g,mp=/\/\//g,Hb=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Vb=/^\.[/\\]/;function Bo(r){return Array.isArray(r)?r:[r]}var Pf=r=>typeof r=="object"&&r!==null&&!(r instanceof RegExp);function $b(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=Se.relative(r.path,e);return t?!t.startsWith("..")&&!Se.isAbsolute(t):!1}return!1}:()=>!1}function zb(r){if(typeof r!="string")throw new Error("string expected");r=Se.normalize(r),r=r.replace(/\\/g,"/");let e=!1;return r.startsWith("//")&&(e=!0),r=r.replace(mp,"/"),e&&(r="/"+r),r}function fp(r,e,t){let n=zb(e);for(let i=0;i<r.length;i++){let s=r[i];if(s(n,t))return!0}return!1}function Gb(r,e){if(r==null)throw new TypeError("anymatch: specify first argument");let n=Bo(r).map(i=>$b(i));return e==null?(i,s)=>fp(n,i,s):fp(n,e)}var up=r=>{let e=Bo(r).flat();if(!e.every(t=>typeof t===qb))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(yp)},lp=r=>{let e=r.replace(Wb,Of),t=!1;return e.startsWith(Ub)&&(t=!0),e=e.replace(mp,Of),t&&(e=Of+e),e},yp=r=>lp(Se.normalize(lp(r))),hp=(r="")=>e=>typeof e=="string"?yp(Se.isAbsolute(e)?e:Se.join(r,e)):e,Yb=(r,e)=>Se.isAbsolute(r)?r:Se.join(e,r),Xb=Object.freeze(new Set),Af=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!==gp&&e!==Kb&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await(0,jo.readdir)(n)}catch{this._removeWatcher&&this._removeWatcher(Se.dirname(n),Se.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=Fo,this.items=Xb,Object.freeze(this)}},Jb="stat",Zb="lstat",Rf=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,t,n){this.fsw=n;let i=e;this.path=e=e.replace(Vb,""),this.watchPath=i,this.fullWatchPath=Se.resolve(i),this.dirParts=[],this.dirParts.forEach(s=>{s.length>1&&s.pop()}),this.followSymlinks=t,this.statMethod=t?Jb:Zb}entryPath(e){return Se.join(this.watchPath,Se.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},If=class extends dp.EventEmitter{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},i={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?Bo(e.ignored):Bo([]),awaitWriteFinish:t===!0?n:typeof t=="object"?{...n,...t}:!1};ap&&(i.usePolling=!0),i.atomic===void 0&&(i.atomic=!i.usePolling);let s=process.env.CHOKIDAR_USEPOLLING;if(s!==void 0){let c=s.toLowerCase();c==="false"||c==="0"?i.usePolling=!1:c==="true"||c==="1"?i.usePolling=!0:i.usePolling=!!c}let a=process.env.CHOKIDAR_INTERVAL;a&&(i.interval=Number.parseInt(a,10));let f=0;this._emitReady=()=>{f++,f>=this._readyCount&&(this._emitReady=Fo,this._readyEmitted=!0,process.nextTick(()=>this.emit(Je.READY)))},this._emitRaw=(...c)=>this.emit(Je.RAW,...c),this._boundRemove=this._remove.bind(this),this.options=i,this._nodeFsHandler=new Mo(this),Object.freeze(i)}_addIgnoredPath(e){if(Pf(e)){for(let t of this._ignoredPaths)if(Pf(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)Pf(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:i}=this.options;this.closed=!1,this._closePromise=void 0;let s=up(e);return i&&(s=s.map(a=>Yb(a,i))),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 f=await this._nodeFsHandler._addToNodeFs(a,!n,void 0,0,t);return f&&this._emitReady(),f})).then(a=>{this.closed||a.forEach(f=>{f&&this.add(Se.dirname(f),Se.basename(t||f))})}),this}unwatch(e){if(this.closed)return this;let t=up(e),{cwd:n}=this.options;return t.forEach(i=>{!Se.isAbsolute(i)&&!this._closers.has(i)&&(n&&(i=Se.join(n,i)),i=Se.resolve(i)),this._closePath(i),this._addIgnoredPath(i),this._watched.has(i)&&this._addIgnoredPath({path:i,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(n=>{let i=n();i instanceof Promise&&e.push(i)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let s=(this.options.cwd?Se.relative(this.options.cwd,n):n)||gp;e[s]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==Je.ERROR&&this.emit(Je.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let i=this.options;kf&&(t=Se.normalize(t)),i.cwd&&(t=Se.relative(i.cwd,t));let s=[t];n!=null&&s.push(n);let a=i.awaitWriteFinish,f;if(a&&(f=this._pendingWrites.get(t)))return f.lastChange=new Date,this;if(i.atomic){if(e===Je.UNLINK)return this._pendingUnlinks.set(t,[e,...s]),setTimeout(()=>{this._pendingUnlinks.forEach((c,l)=>{this.emit(...c),this.emit(Je.ALL,...c),this._pendingUnlinks.delete(l)})},typeof i.atomic=="number"?i.atomic:100),this;e===Je.ADD&&this._pendingUnlinks.has(t)&&(e=Je.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===Je.ADD||e===Je.CHANGE)&&this._readyEmitted){let c=(l,p)=>{l?(e=Je.ERROR,s[0]=l,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,c),this}if(e===Je.CHANGE&&!this._throttle(Je.CHANGE,t,50))return this;if(i.alwaysStat&&n===void 0&&(e===Je.ADD||e===Je.ADD_DIR||e===Je.CHANGE)){let c=i.cwd?Se.join(i.cwd,t):t,l;try{l=await(0,jo.stat)(c)}catch{}if(!l||this.closed)return;s.push(l)}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(Je.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let i=this._throttled.get(e);if(!i)throw new Error("invalid throttle");let s=i.get(t);if(s)return s.count++,!1;let a,f=()=>{let l=i.get(t),p=l?l.count:0;return i.delete(t),clearTimeout(a),l&&clearTimeout(l.timeoutObject),p};a=setTimeout(f,n);let c={timeoutObject:a,clear:f,count:0};return i.set(t,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,i){let s=this.options.awaitWriteFinish;if(typeof s!="object")return;let a=s.pollInterval,f,c=e;this.options.cwd&&!Se.isAbsolute(e)&&(c=Se.join(this.options.cwd,e));let l=new Date,p=this._pendingWrites;function m(_){(0,pp.stat)(c,(b,x)=>{if(b||!p.has(e)){b&&b.code!=="ENOENT"&&i(b);return}let C=Number(new Date);_&&x.size!==_.size&&(p.get(e).lastChange=C);let H=p.get(e);C-H.lastChange>=t?(p.delete(e),i(void 0,x)):f=setTimeout(m,a,x)})}p.has(e)||(p.set(e,{lastChange:l,cancelWait:()=>(p.delete(e),clearTimeout(f),n)}),f=setTimeout(m,a))}_isIgnored(e,t){if(this.options.atomic&&Hb.test(e))return!0;if(!this._userIgnored){let{cwd:n}=this.options,s=(this.options.ignored||[]).map(hp(n)),f=[...[...this._ignoredPaths].map(hp(n)),...s];this._userIgnored=Gb(f,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new Rf(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=Se.resolve(e);return this._watched.has(t)||this._watched.set(t,new Af(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let i=Se.join(e,t),s=Se.resolve(i);if(n=n??(this._watched.has(i)||this._watched.has(s)),!this._throttle("remove",i,100))return;!n&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(i).getChildren().forEach(_=>this._remove(i,_));let c=this._getWatchedDir(e),l=c.has(t);c.remove(t),this._symlinkPaths.has(s)&&this._symlinkPaths.delete(s);let p=i;if(this.options.cwd&&(p=Se.relative(this.options.cwd,i)),this.options.awaitWriteFinish&&this._pendingWrites.has(p)&&this._pendingWrites.get(p).cancelWait()===Je.ADD)return;this._watched.delete(i),this._watched.delete(s);let m=n?Je.UNLINK_DIR:Je.UNLINK;l&&!this._isIgnored(i)&&this._emit(m,i),this._closePath(i)}_closePath(e){this._closeFile(e);let t=Se.dirname(e);this._getWatchedDir(t).remove(Se.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(n=>n()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n={type:Je.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},i=np(e,n);return this._streams.add(i),i.once(op,()=>{i=void 0}),i.once(Cf,()=>{i&&(this._streams.delete(i),i=void 0)}),i}};function _p(r,e={}){let t=new If(e);return t.add(r),t}var Ep=he(Uc()),_r=he(Or()),Qb=["**/node_modules/**","**/.git/**","**/dist/**","**/.next/**","**/.turbo/**","**/.cache/**","**/coverage/**","**/*.log"],ev=300,Uo=class{watcher=null;ignoreFilter;workspaceRoot;logger;onFileChangedCallback=null;pendingEvents=new Map;pendingTypes=new Map;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,Ep.default)(),this.initializeIgnoreFilter()}initializeIgnoreFilter(){this.ignoreFilter.add(Qb);let e=sn.join(this.workspaceRoot,".gitignore");try{if(gi.existsSync(e)){let t=gi.readFileSync(e,"utf-8");this.ignoreFilter.add(t)}}catch{}}onFileChanged(e){this.onFileChangedCallback=e}start(){this.watcher||(this.watcher=_p(this.workspaceRoot,{ignored:e=>{let t=sn.relative(this.workspaceRoot,e);if(!t||t===".")return!1;let n=t.split(sn.sep).join("/");return this.ignoreFilter.ignores(n)},persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:200,pollInterval:50}}),this.watcher.on("add",e=>this.handleEvent(e,_r.FileChangeType.CREATE)),this.watcher.on("change",e=>this.handleEvent(e,_r.FileChangeType.MODIFY)),this.watcher.on("unlink",e=>this.handleEvent(e,_r.FileChangeType.DELETE)),this.watcher.on("error",e=>this.logger.error("File watcher error",e)),this.logger.info("File watcher started"))}stop(){this.watcher?.close(),this.watcher=null;for(let e of this.pendingEvents.values())clearTimeout(e);this.pendingEvents.clear(),this.pendingTypes.clear()}handleEvent(e,t){let n=sn.relative(this.workspaceRoot,e);if(!n)return;let i=this.pendingEvents.get(n);i&&clearTimeout(i);let s=this.pendingTypes.get(n);this.pendingTypes.set(n,this.mergeTypes(s,t));let a=setTimeout(()=>{this.emit(n,this.pendingTypes.get(n)||t),this.pendingEvents.delete(n),this.pendingTypes.delete(n)},ev);this.pendingEvents.set(n,a)}mergeTypes(e,t){return e?t===_r.FileChangeType.DELETE||e===_r.FileChangeType.DELETE?_r.FileChangeType.DELETE:e===_r.FileChangeType.CREATE?_r.FileChangeType.CREATE:t:t}emit(e,t){let n={path:e,changeType:t,timestamp:new Date().toISOString(),source:"watcher"};if(t!==_r.FileChangeType.DELETE)try{let i=sn.join(this.workspaceRoot,e),s=gi.statSync(i);n.size=s.size}catch{}this.onFileChangedCallback?.(n)}dispose(){this.stop(),this.onFileChangedCallback=null}};var tv={online:!1,viewerCount:0},Ko=class r{enabled=!1;state={...tv};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(),n=`\x1B[1;${e-1}r\x1B7\x1B[${e};1H\x1B[2K${t}\x1B8`;process.stdout.write(n)}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 qo(r,e,t,n){if(n)return process.stderr.write(`Logging in with API key...
|
|
134
|
+
`+t)}function kn(r,e,t,n,i,s){if(r.listenerCount("wsClientError")){let a=new Error(i);Error.captureStackTrace(a,kn),r.emit("wsClientError",a,t,e)}else qi(t,n,i,s)}});var Bh=I((CS,Fh)=>{"use strict";var Br=fo();Br.createWebSocketStream=Ch();Br.Server=Dh();Br.Receiver=Za();Br.Sender=ec();Br.WebSocket=Br;Br.WebSocketServer=Br.Server;Fh.exports=Br});var lc=I(rn=>{"use strict";var C0=rn&&rn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(rn,"__esModule",{value:!0});rn.WS=rn.BaseWS=void 0;var P0=Li(),jh=Sn(),k0=Gn(),fc=vn(),A0=C0(qt()),R0=(0,A0.default)("engine.io-client:websocket"),Uh=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",lo=class extends P0.Transport{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,n=Uh?{}:(0,jh.pick)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],i=t===e.length-1;(0,k0.encodePacket)(n,this.supportsBinary,s=>{try{this.doWrite(n,s)}catch{R0("websocket closed before onclose event")}i&&(0,fc.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,jh.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}};rn.BaseWS=lo;var cc=fc.globalThisShim.WebSocket||fc.globalThisShim.MozWebSocket,uc=class extends lo{createSocket(e,t,n){return Uh?new cc(e,t,n):t?new cc(e,t):new cc(e)}doWrite(e,t){this.ws.send(t)}};rn.WS=uc});var dc=I(_r=>{"use strict";var I0=_r&&_r.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),L0=_r&&_r.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),N0=_r&&_r.__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)&&I0(e,r,t);return L0(e,r),e};Object.defineProperty(_r,"__esModule",{value:!0});_r.WS=void 0;var M0=N0(Bh()),D0=lc(),hc=class extends D0.BaseWS{createSocket(e,t,n){var i;if(!((i=this.socket)===null||i===void 0)&&i._cookieJar){n.headers=n.headers||{},n.headers.cookie=typeof n.headers.cookie=="string"?[n.headers.cookie]:n.headers.cookie||[];for(let[s,a]of this.socket._cookieJar.cookies)n.headers.cookie.push(`${s}=${a.value}`)}return new M0.WebSocket(e,t,n)}doWrite(e,t){let n={};e.options&&(n.compress=e.options.compress),this.opts.perMessageDeflate&&(typeof t=="string"?Buffer.byteLength(t):t.length)<this.opts.perMessageDeflate.threshold&&(n.compress=!1),this.ws.send(t,n)}};_r.WS=hc});var gc=I(oi=>{"use strict";var F0=oi&&oi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(oi,"__esModule",{value:!0});oi.WT=void 0;var B0=Li(),j0=vn(),qh=Gn(),U0=F0(qt()),Ki=(0,U0.default)("engine.io-client:webtransport"),pc=class extends B0.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(()=>{Ki("transport closed gracefully"),this.onClose()}).catch(e=>{Ki("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=(0,qh.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),i=(0,qh.createPacketEncoderStream)();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();let s=()=>{n.read().then(({done:f,value:c})=>{if(f){Ki("session is closed");return}Ki("received chunk: %o",c),this.onPacket(c),s()}).catch(f=>{Ki("an error occurred while reading: %s",f)})};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 n=e[t],i=t===e.length-1;this._writer.write(n).then(()=>{i&&(0,j0.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};oi.WT=pc});var mc=I(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});ho.transports=void 0;var q0=Ua(),K0=dc(),W0=gc();ho.transports={websocket:K0.WS,webtransport:W0.WT,polling:q0.XHR}});var _c=I(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});yc.parse=$0;var H0=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,V0=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function $0(r){if(r.length>8e3)throw"URI too long";let e=r,t=r.indexOf("["),n=r.indexOf("]");t!=-1&&n!=-1&&(r=r.substring(0,t)+r.substring(t,n).replace(/:/g,";")+r.substring(n,r.length));let i=H0.exec(r||""),s={},a=14;for(;a--;)s[V0[a]]=i[a]||"";return t!=-1&&n!=-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=G0(s,s.path),s.queryKey=z0(s,s.query),s}function G0(r,e){let t=/\/{2,9}/g,n=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&n.splice(0,1),e.slice(-1)=="/"&&n.splice(n.length-1,1),n}function z0(r,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,s){i&&(t[i]=s)}),t}});var vc=I(Er=>{"use strict";var Y0=Er&&Er.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Er,"__esModule",{value:!0});Er.Socket=Er.SocketWithUpgrade=Er.SocketWithoutUpgrade=void 0;var X0=mc(),Kh=Sn(),Z0=Pa(),Wh=_c(),Q0=wn(),Hh=Gn(),Ec=vn(),J0=Y0(qt()),Ke=(0,J0.default)("engine.io-client:socket"),bc=typeof addEventListener=="function"&&typeof removeEventListener=="function",Wi=[];bc&&addEventListener("offline",()=>{Ke("closing %d connection(s) because the network was lost",Wi.length),Wi.forEach(r=>r())},!1);var An=class r extends Q0.Emitter{constructor(e,t){if(super(),this.binaryType=Ec.defaultBinaryType,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){let n=(0,Wh.parse)(e);t.hostname=n.host,t.secure=n.protocol==="https"||n.protocol==="wss",t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=(0,Wh.parse)(t.host).host);(0,Kh.installTimerFunctions)(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(n=>{let i=n.prototype.name;this.transports.push(i),this._transportsByName[i]=n}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=(0,Z0.decode)(this.opts.query)),bc&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(Ke("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Wi.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,Ec.createCookieJar)()),this._open()}createTransport(e){Ke('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=Hh.protocol,t.transport=e,this.id&&(t.sid=this.id);let n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return Ke("options: %j",n),new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let e=this.opts.rememberUpgrade&&r.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){Ke("setting transport %s",e.name),this.transport&&(Ke("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(){Ke("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(Ke('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 Ke('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();Ke("flushing %d packets in socket",e.length),this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let n=0;n<this.writeBuffer.length;n++){let i=this.writeBuffer[n].data;if(i&&(t+=(0,Kh.byteLength)(i)),n>0&&t>this._maxPayload)return Ke("only send %d out of %d packets",n,this.writeBuffer.length),this.writeBuffer.slice(0,n);t+=2}return Ke("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&&(Ke("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,Ec.nextTick)(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,i){if(typeof t=="function"&&(i=t,t=void 0),typeof n=="function"&&(i=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;let s={type:e,data:t,options:n};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),i&&this.once("flush",i),this.flush()}close(){let e=()=>{this._onClose("forced close"),Ke("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(Ke("socket error %j",e),r.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return Ke("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(Ke('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),bc&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let n=Wi.indexOf(this._offlineEventListener);n!==-1&&(Ke("removing listener for the 'offline' event"),Wi.splice(n,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};Er.SocketWithoutUpgrade=An;An.protocol=Hh.protocol;var po=class extends An{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){Ke("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){Ke('probing transport "%s"',e);let t=this.createTransport(e),n=!1;An.priorWebsocketSuccess=!1;let i=()=>{n||(Ke('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",m=>{if(!n)if(m.type==="pong"&&m.data==="probe"){if(Ke('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;An.priorWebsocketSuccess=t.name==="websocket",Ke('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{n||this.readyState!=="closed"&&(Ke("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{Ke('probe transport "%s" failed',e);let _=new Error("probe error");_.transport=t.name,this.emitReserved("upgradeError",_)}}))};function s(){n||(n=!0,p(),t.close(),t=null)}let a=m=>{let _=new Error("probe error: "+m);_.transport=t.name,s(),Ke('probe transport "%s" failed because of error: %s',e,m),this.emitReserved("upgradeError",_)};function f(){a("transport closed")}function c(){a("socket closed")}function l(m){t&&m.name!==t.name&&(Ke('"%s" works - aborting "%s"',m.name,t.name),s())}let p=()=>{t.removeListener("open",i),t.removeListener("error",a),t.removeListener("close",f),this.off("close",c),this.off("upgrading",l)};t.once("open",i),t.once("error",a),t.once("close",f),this.once("close",c),this.once("upgrading",l),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}};Er.SocketWithUpgrade=po;var wc=class extends po{constructor(e,t={}){let n=typeof e=="object"?e:t;(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(i=>X0.transports[i]).filter(i=>!!i)),super(e,n)}};Er.Socket=wc});var Vh=I(go=>{"use strict";Object.defineProperty(go,"__esModule",{value:!0});go.Fetch=void 0;var eE=Ma(),Sc=class extends eE.Polling{doPoll(){this._fetch().then(e=>{if(!e.ok)return this.onError("fetch read error",e.status,e);e.text().then(t=>this.onData(t))}).catch(e=>{this.onError("fetch read error",e)})}doWrite(e,t){this._fetch(e).then(n=>{if(!n.ok)return this.onError("fetch write error",n.status,n);t()}).catch(n=>{this.onError("fetch write error",n)})}_fetch(e){var t;let n=e!==void 0,i=new Headers(this.opts.extraHeaders);return n&&i.set("content-type","text/plain;charset=UTF-8"),(t=this.socket._cookieJar)===null||t===void 0||t.appendCookies(i),fetch(this.uri(),{method:n?"POST":"GET",body:n?e:null,headers:i,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})}};go.Fetch=Sc});var mo=I(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.WebTransport=ke.WebSocket=ke.NodeWebSocket=ke.XHR=ke.NodeXHR=ke.Fetch=ke.nextTick=ke.parse=ke.installTimerFunctions=ke.transports=ke.TransportError=ke.Transport=ke.protocol=ke.SocketWithUpgrade=ke.SocketWithoutUpgrade=ke.Socket=void 0;var $h=vc();Object.defineProperty(ke,"Socket",{enumerable:!0,get:function(){return $h.Socket}});var Gh=vc();Object.defineProperty(ke,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return Gh.SocketWithoutUpgrade}});Object.defineProperty(ke,"SocketWithUpgrade",{enumerable:!0,get:function(){return Gh.SocketWithUpgrade}});ke.protocol=$h.Socket.protocol;var zh=Li();Object.defineProperty(ke,"Transport",{enumerable:!0,get:function(){return zh.Transport}});Object.defineProperty(ke,"TransportError",{enumerable:!0,get:function(){return zh.TransportError}});var tE=mc();Object.defineProperty(ke,"transports",{enumerable:!0,get:function(){return tE.transports}});var rE=Sn();Object.defineProperty(ke,"installTimerFunctions",{enumerable:!0,get:function(){return rE.installTimerFunctions}});var nE=_c();Object.defineProperty(ke,"parse",{enumerable:!0,get:function(){return nE.parse}});var iE=vn();Object.defineProperty(ke,"nextTick",{enumerable:!0,get:function(){return iE.nextTick}});var sE=Vh();Object.defineProperty(ke,"Fetch",{enumerable:!0,get:function(){return sE.Fetch}});var oE=Ua();Object.defineProperty(ke,"NodeXHR",{enumerable:!0,get:function(){return oE.XHR}});var aE=Ba();Object.defineProperty(ke,"XHR",{enumerable:!0,get:function(){return aE.XHR}});var cE=dc();Object.defineProperty(ke,"NodeWebSocket",{enumerable:!0,get:function(){return cE.WS}});var fE=lc();Object.defineProperty(ke,"WebSocket",{enumerable:!0,get:function(){return fE.WS}});var uE=gc();Object.defineProperty(ke,"WebTransport",{enumerable:!0,get:function(){return uE.WT}})});var Xh=I(Hi=>{"use strict";var lE=Hi&&Hi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Hi,"__esModule",{value:!0});Hi.url=pE;var hE=mo(),dE=lE(qt()),Yh=(0,dE.default)("socket.io-client:url");function pE(r,e="",t){let n=r;t=t||typeof location<"u"&&location,r==null&&(r=t.protocol+"//"+t.host),typeof r=="string"&&(r.charAt(0)==="/"&&(r.charAt(1)==="/"?r=t.protocol+r:r=t.host+r),/^(https?|wss?):\/\//.test(r)||(Yh("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),Yh("parse %s",r),n=(0,hE.parse)(r)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";let s=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+s+":"+n.port+e,n.href=n.protocol+"://"+s+(t&&t.port===n.port?"":":"+n.port),n}});var xc=I(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});_o.isBinary=Qh;_o.hasBinary=yo;var gE=typeof ArrayBuffer=="function",mE=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,Zh=Object.prototype.toString,yE=typeof Blob=="function"||typeof Blob<"u"&&Zh.call(Blob)==="[object BlobConstructor]",_E=typeof File=="function"||typeof File<"u"&&Zh.call(File)==="[object FileConstructor]";function Qh(r){return gE&&(r instanceof ArrayBuffer||mE(r))||yE&&r instanceof Blob||_E&&r instanceof File}function yo(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,n=r.length;t<n;t++)if(yo(r[t]))return!0;return!1}if(Qh(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return yo(r.toJSON(),!0);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&yo(r[t]))return!0;return!1}});var Jh=I(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});Eo.deconstructPacket=bE;Eo.reconstructPacket=wE;var EE=xc();function bE(r){let e=[],t=r.data,n=r;return n.data=Tc(t,e),n.attachments=e.length,{packet:n,buffers:e}}function Tc(r,e){if(!r)return r;if((0,EE.isBinary)(r)){let t={_placeholder:!0,num:e.length};return e.push(r),t}else if(Array.isArray(r)){let t=new Array(r.length);for(let n=0;n<r.length;n++)t[n]=Tc(r[n],e);return t}else if(typeof r=="object"&&!(r instanceof Date)){let t={};for(let n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=Tc(r[n],e));return t}return r}function wE(r,e){return r.data=Oc(r.data,e),delete r.attachments,r}function Oc(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]=Oc(r[t],e);else if(typeof r=="object")for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=Oc(r[t],e));return r}});var wo=I(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.Decoder=Jt.Encoder=Jt.PacketType=Jt.protocol=void 0;Jt.isPacketValid=PE;var vE=wn(),ed=Jh(),td=xc(),SE=qt(),Cc=(0,SE.default)("socket.io-parser"),rd=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];Jt.protocol=5;var je;(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"})(je||(Jt.PacketType=je={}));var Pc=class{constructor(e){this.replacer=e}encode(e){return Cc("encoding packet %j",e),(e.type===je.EVENT||e.type===je.ACK)&&(0,td.hasBinary)(e)?this.encodeAsBinary({type:e.type===je.EVENT?je.BINARY_EVENT:je.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===je.BINARY_EVENT||e.type===je.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)),Cc("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=(0,ed.deconstructPacket)(e),n=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(n),i}};Jt.Encoder=Pc;var kc=class r extends vE.Emitter{constructor(e){super(),this.reviver=e}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);let n=t.type===je.BINARY_EVENT;n||t.type===je.BINARY_ACK?(t.type=n?je.EVENT:je.ACK,this.reconstructor=new Ac(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,td.isBinary)(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0,n={type:Number(e.charAt(0))};if(je[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===je.BINARY_EVENT||n.type===je.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");n.attachments=Number(a)}if(e.charAt(t+1)==="/"){let s=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););n.nsp=e.substring(s,t)}else n.nsp="/";let i=e.charAt(t+1);if(i!==""&&Number(i)==i){let s=t+1;for(;++t;){let a=e.charAt(t);if(a==null||Number(a)!=a){--t;break}if(t===e.length)break}n.id=Number(e.substring(s,t+1))}if(e.charAt(++t)){let s=this.tryParse(e.substr(t));if(r.isPayloadValid(n.type,s))n.data=s;else throw new Error("invalid payload")}return Cc("decoded %s as %j",e,n),n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case je.CONNECT:return bo(t);case je.DISCONNECT:return t===void 0;case je.CONNECT_ERROR:return typeof t=="string"||bo(t);case je.EVENT:case je.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&rd.indexOf(t[0])===-1);case je.ACK:case je.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};Jt.Decoder=kc;var Ac=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,ed.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function xE(r){return typeof r=="string"}var TE=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function OE(r){return r===void 0||TE(r)}function bo(r){return Object.prototype.toString.call(r)==="[object Object]"}function CE(r,e){switch(r){case je.CONNECT:return e===void 0||bo(e);case je.DISCONNECT:return e===void 0;case je.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&rd.indexOf(e[0])===-1);case je.ACK:return Array.isArray(e);case je.CONNECT_ERROR:return typeof e=="string"||bo(e);default:return!1}}function PE(r){return xE(r.nsp)&&OE(r.id)&&CE(r.type,r.data)}});var Ic=I(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});Rc.on=kE;function kE(r,e,t){return r.on(e,t),function(){r.off(e,t)}}});var Nc=I(ai=>{"use strict";var AE=ai&&ai.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ai,"__esModule",{value:!0});ai.Socket=void 0;var er=wo(),vo=Ic(),RE=wn(),IE=AE(qt()),ot=(0,IE.default)("socket.io-client:socket"),LE=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Lc=class extends RE.Emitter{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[(0,vo.on)(e,"open",this.onopen.bind(this)),(0,vo.on)(e,"packet",this.onpacket.bind(this)),(0,vo.on)(e,"error",this.onerror.bind(this)),(0,vo.on)(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,i,s;if(LE.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:er.PacketType.EVENT,data:t};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let p=this.ids++;ot("emitting packet with ack id %d",p);let m=t.pop();this._registerAckCallback(p,m),a.id=p}let f=(i=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||i===void 0?void 0:i.writable,c=this.connected&&!(!((s=this.io.engine)===null||s===void 0)&&s._hasPingExpired());return this.flags.volatile&&!f?ot("discard packet as the transport is not currently writable"):c?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a),this.flags={},this}_registerAckCallback(e,t){var n;let i=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(i===void 0){this.acks[e]=t;return}let s=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let f=0;f<this.sendBuffer.length;f++)this.sendBuffer[f].id===e&&(ot("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(f,1));ot("event with ack id %d has timed out after %d ms",e,i),t.call(this,new Error("operation has timed out"))},i),a=(...f)=>{this.io.clearTimeoutFn(s),t.apply(this,f)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((n,i)=>{let s=(a,f)=>a?i(a):n(f);s.withError=!0,t.push(s),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...s)=>n!==this._queue[0]?ot("packet [%d] already acknowledged",n.id):(i!==null?n.tryCount>this._opts.retries&&(ot("packet [%d] is discarded after %d tries",n.id,n.tryCount),this._queue.shift(),t&&t(i)):(ot("packet [%d] was successfully sent",n.id),this._queue.shift(),t&&t(null,...s)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(ot("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){ot("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,ot("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(){ot("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:er.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){ot("close (%s)",e),this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(n=>String(n.id)===e)){let n=this.acks[e];delete this.acks[e],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case er.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 er.PacketType.EVENT:case er.PacketType.BINARY_EVENT:this.onevent(e);break;case er.PacketType.ACK:case er.PacketType.BINARY_ACK:this.onack(e);break;case er.PacketType.DISCONNECT:this.ondisconnect();break;case er.PacketType.CONNECT_ERROR:this.destroy();let n=new Error(e.data.message);n.data=e.data.data,this.emitReserved("connect_error",n);break}}onevent(e){let t=e.data||[];ot("emitting event %j",t),e.id!=null&&(ot("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,n=!1;return function(...i){n||(n=!0,ot("sending ack %j",i),t.packet({type:er.PacketType.ACK,id:e,data:i}))}}onack(e){let t=this.acks[e.id];if(typeof t!="function"){ot("bad ack %s",e.id);return}delete this.acks[e.id],ot("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){ot("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(){ot("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&&(ot("performing disconnect (%s)",this.nsp),this.packet({type:er.PacketType.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let n of t)n.apply(this,e.data)}}};ai.Socket=Lc});var nd=I(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});Mc.Backoff=ci;function ci(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}ci.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};ci.prototype.reset=function(){this.attempts=0};ci.prototype.setMin=function(r){this.ms=r};ci.prototype.setMax=function(r){this.max=r};ci.prototype.setJitter=function(r){this.jitter=r}});var id=I(Ht=>{"use strict";var NE=Ht&&Ht.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),ME=Ht&&Ht.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),DE=Ht&&Ht.__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)&&NE(e,r,t);return ME(e,r),e},FE=Ht&&Ht.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ht,"__esModule",{value:!0});Ht.Manager=void 0;var Dc=mo(),BE=Nc(),jE=DE(wo()),Rn=Ic(),UE=nd(),qE=wn(),KE=FE(qt()),ht=(0,KE.default)("socket.io-client:manager"),Fc=class extends qE.Emitter{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,(0,Dc.installTimerFunctions)(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((n=t.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new UE.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 i=t.parser||jE;this.encoder=new i.Encoder,this.decoder=new i.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(ht("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;ht("opening %s",this.uri),this.engine=new Dc.Socket(this.uri,this.opts);let t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;let i=(0,Rn.on)(t,"open",function(){n.onopen(),e&&e()}),s=f=>{ht("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",f),e?e(f):this.maybeReconnectOnOpen()},a=(0,Rn.on)(t,"error",s);if(this._timeout!==!1){let f=this._timeout;ht("connect attempt will timeout after %d",f);let c=this.setTimeoutFn(()=>{ht("connect attempt timed out after %d",f),i(),s(new Error("timeout")),t.close()},f);this.opts.autoUnref&&c.unref(),this.subs.push(()=>{this.clearTimeoutFn(c)})}return this.subs.push(i),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){ht("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push((0,Rn.on)(e,"ping",this.onping.bind(this)),(0,Rn.on)(e,"data",this.ondata.bind(this)),(0,Rn.on)(e,"error",this.onerror.bind(this)),(0,Rn.on)(e,"close",this.onclose.bind(this)),(0,Rn.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,Dc.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){ht("error",e),this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new BE.Socket(this,e,t),this.nsps[e]=n),n}_destroy(e){let t=Object.keys(this.nsps);for(let n of t)if(this.nsps[n].active){ht("socket %s is still active, skipping close",n);return}this._close()}_packet(e){ht("writing packet %j",e);let t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){ht("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){ht("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;ht("closed due to %s",e),this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)ht("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();ht("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(ht("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(ht("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):(ht("reconnect success"),e.onreconnect())}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}};Ht.Manager=Fc});var cd=I((Ve,ad)=>{"use strict";var WE=Ve&&Ve.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ve,"__esModule",{value:!0});Ve.WebTransport=Ve.WebSocket=Ve.NodeWebSocket=Ve.XHR=Ve.NodeXHR=Ve.Fetch=Ve.Socket=Ve.Manager=Ve.protocol=void 0;Ve.io=In;Ve.connect=In;Ve.default=In;var HE=Xh(),So=id();Object.defineProperty(Ve,"Manager",{enumerable:!0,get:function(){return So.Manager}});var od=Nc();Object.defineProperty(Ve,"Socket",{enumerable:!0,get:function(){return od.Socket}});var VE=WE(qt()),sd=(0,VE.default)("socket.io-client"),Vi={};function In(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};let t=(0,HE.url)(r,e.path||"/socket.io"),n=t.source,i=t.id,s=t.path,a=Vi[i]&&s in Vi[i].nsps,f=e.forceNew||e["force new connection"]||e.multiplex===!1||a,c;return f?(sd("ignoring socket cache for %s",n),c=new So.Manager(n,e)):(Vi[i]||(sd("new io instance for %s",n),Vi[i]=new So.Manager(n,e)),c=Vi[i]),t.query&&!e.query&&(e.query=t.queryKey),c.socket(t.path,e)}Object.assign(In,{Manager:So.Manager,Socket:od.Socket,io:In,connect:In});var $E=wo();Object.defineProperty(Ve,"protocol",{enumerable:!0,get:function(){return $E.protocol}});var fi=mo();Object.defineProperty(Ve,"Fetch",{enumerable:!0,get:function(){return fi.Fetch}});Object.defineProperty(Ve,"NodeXHR",{enumerable:!0,get:function(){return fi.NodeXHR}});Object.defineProperty(Ve,"XHR",{enumerable:!0,get:function(){return fi.XHR}});Object.defineProperty(Ve,"NodeWebSocket",{enumerable:!0,get:function(){return fi.NodeWebSocket}});Object.defineProperty(Ve,"WebSocket",{enumerable:!0,get:function(){return fi.WebSocket}});Object.defineProperty(Ve,"WebTransport",{enumerable:!0,get:function(){return fi.WebTransport}});ad.exports=In});var jc=I(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});xo.InputStreamReceiver=void 0;var GE=64,zE=30,YE=4,XE=256,ZE=16,Bc=class{streamId;lastAppliedSeq=0;cb;windowSize;ackThrottleMs;ackTimer=null;framesSinceAck=0;lastResendFrom=0;resendSuppressed=0;constructor(e,t,n={}){this.streamId=e,this.cb=t,this.windowSize=Math.max(1,n.windowSize??GE),this.ackThrottleMs=Math.max(0,n.ackThrottleMs??zE)}get appliedSeq(){return this.lastAppliedSeq}receive(e,t,n,i){if(e<=this.lastAppliedSeq){this.flushAck();return}if(e===this.lastAppliedSeq+1){try{this.cb.onApply(t,n,i)}catch{}this.lastAppliedSeq=e,this.scheduleAck();return}this.flushAck();let s=Math.max(this.windowSize*YE,XE);e-this.lastAppliedSeq>s||this.maybeResend(this.lastAppliedSeq+1)}maybeResend(e){if(e===this.lastResendFrom){if(++this.resendSuppressed<ZE)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)}};xo.InputStreamReceiver=Bc});var hd=I(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});To.WebSocketService=void 0;var QE=cd(),fd=Rr(),ud=_s(),ld=gs(),JE=jc(),Uc=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;announcedStreams=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,n,i,s,a,f="vscode",c=[]){this.authService=e,this.cryptoService=t,this.config=n,this.logger=i,this.notification=s,this.deviceId=a,this.platform=f,this.extraCapabilities=c}async connect(){let e=await this.authService.getAccessToken();if(!e)throw new Error("No access token available");this.isManualDisconnect=!1,this.stopReconnect(),this.reconnectAttempts=0,this.agentId=await this.authService.getAgentId();let t=(0,ud.getWsUrl)(this.config);this.logger.info("Connecting to WebSocket",t),this.statusChangeHandler?.("connecting");let n=await this.cryptoService.getPublicKey(),i=this.agentId?await this.cryptoService.getSignedAgentKey(this.agentId):null;return i||this.logger.warn(this.agentId?"No signed agent key available, connecting unsigned (legacy)":"No agentId in storage, connecting unsigned (legacy)"),new Promise((s,a)=>{let f=Array.from(new Set([...fd.DEFAULT_CLIENT_CAPABILITIES,...this.extraCapabilities]));this.socket=(0,QE.io)(`${t}/agent`,{auth:{token:e,protocolVersion:fd.PROTOCOL_VERSION,deviceId:this.deviceId,platform:this.platform,capabilities:f,publicKey:n,identityPublicKey:i?.identityPublicKey,identitySignature:i?.signature,keyVersion:i?.keyVersion},transports:["websocket"],reconnection:!1}),this.socket.on("connect",()=>{if(this.logger.info("WebSocket connected"),this.reconnectAttempts=0,this.statusChangeHandler?.("connected",this.agentId??void 0),this.startHeartbeat(),this.cryptoService.cleanupAllStaleSessions(),this.hasConnectedOnce){this.logger.info("Reconnected - triggering workspace re-registration");for(let c of this.reconnectHandlers)c()}else this.hasConnectedOnce=!0,s()}),this.socket.on("error",c=>{this.logger.error(`Server error [${c.code}]: ${c.message}`),c.code==="E401"&&(this.logger.warn("Auth failure (E401)"),this.authFailureHandler?.())}),this.socket.on("disconnect",c=>{this.logger.warn("WebSocket disconnected",c),this.stopHeartbeat(),this.statusChangeHandler?.("disconnected"),this.isManualDisconnect||(c==="transport close"?(this.logger.info("Transport close - attempting immediate reconnect"),this.attemptReconnect(!0)):this.scheduleReconnect())}),this.socket.on("protocol:info",c=>{this.logger.info("Protocol info received",c.protocolVersion),this.negotiatedCapabilities=c.negotiatedCapabilities,c.agentName&&this.config.getAgentName()!==c.agentName&&(this.isRemoteRename=!0,this.config.setAgentName(c.agentName).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(c.agentName),this.logger.info("Agent name synced from server",c.agentName))}),this.socket.on("pong",()=>{this.lastPongTime=Date.now(),this.clearPongTimeout(),this.logger.debug("Heartbeat pong received")}),this.socket.on("connect_error",c=>{this.logger.error("WebSocket connection error",c),this.statusChangeHandler?.("error"),this.hasConnectedOnce||a(c),this.scheduleReconnect()}),this.socket.on("terminal:input",c=>{this.handleTerminalInput(c)}),this.socket.on("crypto:keyExchange",async(c,l)=>{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 m=await this.cryptoService.getPublicKey(),_=this.agentId?await this.cryptoService.getSignedAgentKey(this.agentId):null,b=this.agentId?await this.cryptoService.signKeyExchangeAck(this.agentId,c.clientPublicKey):null;l?.({success:!0,agentPublicKey:m||void 0,..._&&b?{signedKey:{..._,ackSignature:b},boundClientKey:c.clientPublicKey}:{}}),this.flushOutputBuffer(c.terminalId)}else l?.({success:!1,error:"Key exchange failed"})}catch(p){this.logger.error("Key exchange error",p),l?.({success:!1,error:String(p)})}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 l=await this.cryptoService.handleAgentKeyExchange(c.clientPublicKey,c.sessionId),p={agentId:c.agentId,sessionId:c.sessionId,ok:l,error:l?void 0:"Key exchange failed"};this.socket?.emit("agent:keyExchangeAck",p)}catch(l){this.logger.error("Agent key exchange error",l);let p={agentId:c.agentId,sessionId:c.sessionId,ok:!1,error:String(l)};this.socket?.emit("agent:keyExchangeAck",p)}}),this.socket.on("meta:keyExchange",async(c,l)=>{let{ok:p,isNew:m}=await this.cryptoService.handleMetaKeyExchange(c.clientIdentityPub),_=await this.cryptoService.getPublicKey()||void 0;l?.({ok:p,agentPublicKey:_}),p&&this.metaSessionEstablishedHandler?.(m)}),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,l)=>{if(!this.getBufferHandler){l?.({success:!1,error:"Buffer handler not set"});return}let p=this.getBufferHandler(c.terminalId);if(p===null){l?.({success:!1,error:"Terminal not found"});return}let m=this.cryptoService.encryptOutput(c.terminalId,p);if(!m){this.signalInvalidSession(void 0,c.terminalId),l?.({success:!1,error:"No E2E session"});return}l?.({success:!0,encrypted:m}),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){let t=this.knowsInputStream(e);this.announceInputStream(e);let n=await this.emit("terminal:created",e);return t&&this.sendInputResume(e.terminalId),n}async terminalClosed(e){this.cryptoService.removeSession(e.terminalId),this.announcedStreams.delete(e.terminalId),await this.emit("terminal:closed",e)}terminalNotFound(e){this.socket?.emit("terminal:notFound",{terminalId:e})}sendPtyResized(e,t,n,i){this.socket?.connected&&this.socket.emit("agent:ptyResized",{instanceId:e,terminalId:t,cols:n,rows:i})}sendClaimControl(e,t,n,i){this.socket?.connected&&this.socket.emit("agent:claimControl",{instanceId:e,terminalId:t,cols:n,rows:i})}sendOutput(e,t,n){if(!this.socket?.connected)return;if(this.rekeyingTerminals.has(t)){let a=this.outputBuffer.get(t);a&&a.length<this.OUTPUT_BUFFER_MAX_SIZE&&a.push({instanceId:e,data:n});return}let i=this.cryptoService.encryptOutput(t,n);if(!i){this.attachedClientCount>0&&this.signalInvalidSession(e,t);return}let s={instanceId:e,terminalId:t,encrypted:i};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:n,data:i}of t){let s=this.cryptoService.encryptOutput(e,i);if(!s){this.signalInvalidSession(n,e);continue}let a={instanceId:n,terminalId:e,encrypted:s};this.socket?.emit("terminal:output",a)}}}signalInvalidSession(e,t){let n=Date.now(),i=this.invalidSessionSignalAt.get(t)??0;n-i<this.INVALID_SESSION_SIGNAL_THROTTLE_MS||(this.invalidSessionSignalAt.set(t,n),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,n){let i={instanceId:e,terminalId:t,event:n};this.socket?.emit("terminal:event",i)}hasCapability(e){return this.negotiatedCapabilities.includes(e)}sendFileChangedEvent(e,t,n){let i={instanceId:e,terminalId:t,event:n};this.socket?.emit("file:changed",i)}sendFileListResponse(e,t){let n={instanceId:e,response:t};this.socket?.emit("file:list:response",n)}sendAgentRename(e){this.socket?.emit("agent:rename",{name:e})}isRemoteRenameInProgress(){return this.isRemoteRename}getSocket(){return this.socket}emit(e,t){let n=(0,ld.generateCorrelationId)(),i=t&&typeof t=="object"&&!Array.isArray(t)?{...t,_cid:n}:t;return(0,ld.runWithCorrelation)(n,()=>new Promise((s,a)=>{if(!this.socket?.connected){a(new Error("WebSocket not connected"));return}this.socket.emit(e,i,f=>{f.success?s(f):a(new Error(f.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 n=this.cryptoService.decryptInput(e.terminalId,e.encrypted);if(!n){this.logger.error("Failed to decrypt terminal input",e.terminalId),this.signalInvalidSession(e.instanceId,e.terminalId);return}t=n}else{this.logger.warn("Dropped terminal input without an E2E session",e.terminalId);return}if(e.streamId&&typeof e.seq=="number"){let n=this.getOrCreateInputReceiver(e.terminalId,e.streamId,e.instanceId,e.dbTerminalId);if(!n)return;n.receive(e.seq,t,e.paste,e.answerFor);return}this.inputHandler?.(e.terminalId,t,e.dbTerminalId,void 0,e.answerFor)}getOrCreateInputReceiver(e,t,n,i){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 i&&(s.routeId=i),n&&(s.instanceId=n),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 JE.InputStreamReceiver(t,{onApply:(c,l,p)=>this.inputHandler?.(e,c,this.routeIdFor(e),l,p),onAck:c=>this.sendInputAck(e,t,c),onResend:c=>this.sendInputResend(e,t,c)});this.inputReceivers.set(e,{receiver:a,routeId:i??e,instanceId:n??""});let f=this.announcedStreams.get(e);return f?.streamId===t&&(f.received=!0),a}knowsInputStream({terminalId:e,streamId:t}){return t?this.announcedStreams.get(e)?.streamId===t||this.inputReceivers.get(e)?.receiver.streamId===t:!1}announceInputStream({instanceId:e,terminalId:t,streamId:n}){if(!n){this.announcedStreams.delete(t);return}let i=this.announcedStreams.get(t);if(i?.streamId===n){i.instanceId=e;return}this.announcedStreams.set(t,{streamId:n,instanceId:e,received:this.inputReceivers.get(t)?.receiver.streamId===n})}setTerminalActiveCheck(e){this.terminalActiveCheck=e}routeIdFor(e){return this.inputReceivers.get(e)?.routeId??e}sendInputAck(e,t,n){let i=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:ack",{instanceId:i,terminalId:e,streamId:t,ackSeq:n})}sendInputResend(e,t,n){let i=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:resend",{instanceId:i,terminalId:e,streamId:t,fromSeq:n})}sendInputResume(e){let t=this.inputReceivers.get(e);if(t){let{streamId:i,lastAckSeq:s}=t.receiver.resumeState();this.socket?.emit("input:resume",{instanceId:t.instanceId,terminalId:e,streamId:i,lastAckSeq:s})}let n=this.announcedStreams.get(e);!n||n.received||this.terminalActiveCheck&&!this.terminalActiveCheck(e)||this.socket?.emit("input:resume",{instanceId:n.instanceId,terminalId:e,streamId:n.streamId,lastAckSeq:0})}disposeInputStream(e){this.inputReceivers.get(e)?.receiver.dispose(),this.inputReceivers.delete(e),this.announcedStreams.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(n){this.logger.warn("Reconnect failed",n),this.statusChangeHandler?.("error"),this.scheduleReconnect()}}stopReconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stopNetworkCheck()}async checkNetwork(){let e=Date.now();if(e-this.lastNetworkCheck<1e3)return this.isOnline;this.lastNetworkCheck=e;try{let t=`${(0,ud.getApiUrl)(this.config)}/health`,n=new AbortController,i=setTimeout(()=>n.abort(),5e3),s=await fetch(t,{method:"GET",signal:n.signal});return clearTimeout(i),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)}};To.WebSocketService=Uc});var gd=I(tr=>{"use strict";var eb=tr&&tr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),tb=tr&&tr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Kc=tr&&tr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),i=0;i<n.length;i++)n[i]!=="default"&&eb(t,e,n[i]);return tb(t,e),t}})();Object.defineProperty(tr,"__esModule",{value:!0});tr.FileTransferService=void 0;tr.resolveUploadPath=pd;var Oo=Kc(require("fs")),Ln=Kc(require("path")),dd=Kc(require("crypto")),$e=Rr();function pd(r,e,t){let n=Ln.basename(t),i=(e??"").trim()||".";if(Ln.isAbsolute(i))return Ln.resolve(i,n);let s=Ln.resolve(r,i),a=s===r||s.startsWith(r+Ln.sep)?s:r;return Ln.resolve(a,n)}var qc=class{socket=null;activeTransfers=new Map;instanceId="";logger;fallbackDir;workspaceRoot=null;cryptoService=null;constructor(e,t="/tmp",n=null){this.logger=e,this.fallbackDir=t,this.workspaceRoot=n}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,n,i,s){let a=Oo.readFileSync(t),f=t.split("/").pop()||"file";return this.initAndSendChunks(e,a,f,{mimeType:this.getMimeType(f),requestId:s,onProgress:n,onComplete:i})}async sendBuffer(e,t,n,i,s){return this.initAndSendChunks(e,t,n,{mimeType:i,purpose:s?.purpose,viewMetadata:s?.viewMetadata,requestId:s?.requestId,onProgress:s?.onProgress,onComplete:s?.onComplete})}async initAndSendChunks(e,t,n,i){if(!this.socket)throw new Error("Socket not connected");let s=t.length,a=(0,$e.calculateTotalChunks)(s),f=this.calculateChecksum(t),c=dd.randomUUID(),l={id:c,terminalId:e,filename:n,size:s,totalChunks:a,direction:$e.TransferDirection.DOWNLOAD,status:$e.TransferStatus.PENDING,deliveredChunks:new Set,pendingChunks:new Map,checksum:f,checksumAlgorithm:"sha256",onProgress:i.onProgress?(m,_)=>i.onProgress(c,m,_):void 0,onComplete:i.onComplete?(m,_)=>i.onComplete(c,m,_):void 0,ackTimeouts:new Map};l.chunks=[];for(let m=0;m<a;m++){let _=m*$e.CHUNK_SIZE,b=Math.min(_+$e.CHUNK_SIZE,s);l.chunks.push(t.subarray(_,b))}this.activeTransfers.set(c,l);let p={transferId:c,terminalId:e,filename:n,size:s,totalChunks:a,mimeType:i.mimeType||"application/octet-stream",checksum:f,direction:$e.TransferDirection.DOWNLOAD,instanceId:this.instanceId};return i.requestId&&(p.requestId=i.requestId),i.purpose&&(p.purpose=i.purpose),i.viewMetadata&&(p.viewMetadata=i.viewMetadata),new Promise((m,_)=>{this.socket.emit("file:init",p,b=>{b.accepted?(l.status=$e.TransferStatus.ACTIVE,this.startSendingChunks(c),m(c)):(this.activeTransfers.delete(c),_(new Error(b.error||"Transfer rejected")))})})}async receiveFile(e,t,n,i,s,a,f,c="sha256",l,p){let m={id:e,terminalId:t,filename:n,filePath:f,size:i,totalChunks:s,direction:$e.TransferDirection.UPLOAD,status:$e.TransferStatus.ACTIVE,deliveredChunks:new Set,pendingChunks:new Map,chunks:new Array(s).fill(null),checksum:a,checksumAlgorithm:c,onProgress:l?(_,b)=>l(e,_,b):void 0,onComplete:p?(_,b)=>p(e,_,b):void 0,ackTimeouts:new Map};this.activeTransfers.set(e,m)}cancelTransfer(e,t){let n=this.activeTransfers.get(e);if(n){for(let i of n.ackTimeouts.values())clearTimeout(i);if(n.status=$e.TransferStatus.CANCELLED,n.onComplete?.(!1,t),this.socket){let i={transferId:e,reason:t};this.socket.emit("file:cancel",i)}this.activeTransfers.delete(e)}}async resumeTransfer(e){let t=this.activeTransfers.get(e);!t||!this.socket||this.socket.emit("file:sync",{transferId:e},n=>{if(n.status===$e.TransferStatus.EXPIRED){t.onComplete?.(!1,"Transfer expired"),this.activeTransfers.delete(e);return}if(n.deliveredChunks)for(let i of n.deliveredChunks)t.deliveredChunks.add(i);if(t.direction===$e.TransferDirection.DOWNLOAD&&n.missingChunks){t.status=$e.TransferStatus.ACTIVE;for(let i of n.missingChunks)this.sendChunk(t,i)}})}getTransferStatus(e){return this.activeTransfers.get(e)?.status??null}getTransferProgress(e){let t=this.activeTransfers.get(e);return t?{delivered:t.deliveredChunks.size,total:t.totalChunks}:null}setupEventHandlers(){this.socket&&(this.socket.on("file:chunk",e=>{this.handleIncomingChunk(e)}),this.socket.on("file:chunk:ack",e=>{this.handleChunkAck(e)}),this.socket.on("file:complete",e=>{this.handleComplete(e)}),this.socket.on("file:progress",e=>{this.handleProgress(e)}),this.socket.on("file:init",(e,t)=>{this.handleIncomingFileInit(e,t)}),this.socket.on("file:cancel",e=>{let t=this.activeTransfers.get(e.transferId);if(t){for(let n of t.ackTimeouts.values())clearTimeout(n);t.status=$e.TransferStatus.CANCELLED,t.onComplete?.(!1,e.reason||"Cancelled by remote"),this.activeTransfers.delete(e.transferId)}}))}startSendingChunks(e){let t=this.activeTransfers.get(e);if(!(!t||!t.chunks))for(let n=0;n<Math.min($e.WINDOW_SIZE,t.totalChunks);n++)t.deliveredChunks.has(n)||this.sendChunk(t,n)}sendChunk(e,t){if(!this.socket||!e.chunks)return;let n=e.chunks[t];if(!n)return;let i=e.pendingChunks.get(t),s={seq:t,data:n,retries:i?i.retries:0,sentAt:Date.now()};e.pendingChunks.set(t,s);let a=this.cryptoService?.encryptFileChunk(e.terminalId,new Uint8Array(n.buffer,n.byteOffset,n.byteLength));if(!a){this.cancelTransfer(e.id,"No E2E session for file transfer");return}let f={transferId:e.id,seq:t,encrypted:a};this.socket.emit("file:chunk",f,l=>{l&&!l.success&&this.cancelTransfer(e.id,l.error||"Server rejected chunk")});let c=setTimeout(()=>{this.handleAckTimeout(e.id,t)},$e.ACK_TIMEOUT_MS);e.ackTimeouts.set(t,c)}handleChunkAck(e){let t=this.activeTransfers.get(e.transferId);if(!t||t.status===$e.TransferStatus.COMPLETED)return;let n=t.ackTimeouts.get(e.seq);n&&(clearTimeout(n),t.ackTimeouts.delete(e.seq)),t.deliveredChunks.add(e.seq),t.pendingChunks.delete(e.seq),t.onProgress?.(t.deliveredChunks.size,t.totalChunks);let i=e.seq+$e.WINDOW_SIZE;i<t.totalChunks&&!t.deliveredChunks.has(i)&&this.sendChunk(t,i),t.deliveredChunks.size===t.totalChunks&&this.finishSending(t)}handleAckTimeout(e,t){let n=this.activeTransfers.get(e);if(!n)return;let i=n.pendingChunks.get(t);i&&(i.retries<$e.MAX_RETRIES?(i.retries++,this.sendChunk(n,t)):this.cancelTransfer(e,"Max retries exceeded"))}finishSending(e){if(!this.socket)return;e.status=$e.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 n=e.encrypted?this.cryptoService?.decryptFileChunk(t.terminalId,e.encrypted):null;if(!n){this.cancelTransfer(e.transferId,"Chunk decryption failed (no E2E session?)");return}if(t.chunks[e.seq]=Buffer.from(n),t.deliveredChunks.add(e.seq),this.socket){let i={transferId:e.transferId,seq:e.seq};this.socket.emit("file:chunk:ack",i)}t.onProgress?.(t.deliveredChunks.size,t.totalChunks),t.deliveredChunks.size===t.totalChunks&&this.finishReceiving(t)}finishReceiving(e){if(!e.chunks||!e.filePath)return;let t=Buffer.concat(e.chunks);if(this.calculateChecksum(t,e.checksumAlgorithm)!==e.checksum){e.status=$e.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 i=Ln.dirname(e.filePath);Oo.existsSync(i)||Oo.mkdirSync(i,{recursive:!0}),Oo.writeFileSync(e.filePath,t),e.status=$e.TransferStatus.COMPLETED,e.onComplete?.(!0),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!0})}catch(i){let s=i instanceof Error?i.message:String(i);e.status=$e.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=$e.TransferStatus.COMPLETED,t.onComplete?.(!0)):(t.status=$e.TransferStatus.FAILED,t.onComplete?.(!1,e.error));for(let n of t.ackTimeouts.values())clearTimeout(n);this.activeTransfers.delete(e.transferId)}}handleProgress(e){let t=this.activeTransfers.get(e.transferId);t&&t.onProgress?.(e.deliveredChunks,e.totalChunks)}handleIncomingFileInit(e,t){let n=pd(this.workspaceRoot??this.fallbackDir,e.targetPath,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(i=>t({accepted:!1,error:i.message}))}calculateChecksum(e,t="sha256"){return t==="fnv1a"?this.fnv1aHash(e):dd.createHash("sha256").update(e).digest("hex")}fnv1aHash(e){let t=2166136261;for(let i=0;i<e.length;i++)t^=e[i],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"}};tr.FileTransferService=qc});var Yc=I((GS,ko)=>{function _d(r){return Array.isArray(r)?r:[r]}var rb=void 0,Hc="",md=" ",Wc="\\",nb=/^\s+$/,ib=/(?:[^\\]|^)\\$/,sb=/^\\!/,ob=/^\\#/,ab=/\r?\n/g,cb=/^\.{0,2}\/|^\.{1,2}$/,fb=/\/$/,ui="/",Ed="node-ignore";typeof Symbol<"u"&&(Ed=Symbol.for("node-ignore"));var bd=Ed,li=(r,e,t)=>(Object.defineProperty(r,e,{value:t}),t),ub=/([0-z])-([0-z])/g,wd=()=>!1,lb=r=>r.replace(ub,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:Hc),hb=r=>{let{length:e}=r;return r.slice(0,e-e%2)},db=[[/^\uFEFF/,()=>Hc],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?md:Hc)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+md}],[/[\\$.|*+(){^]/g,r=>`\\${r}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(r,e,t)=>e+6<t.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(r,e,t)=>{let n=t.replace(/\\\*/g,"[^\\/]*");return e+n}],[/\\\\\\(?=[$.|*+(){^])/g,()=>Wc],[/\\\\/g,()=>Wc],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,n,i)=>e===Wc?`\\[${t}${hb(n)}${i}`:i==="]"&&n.length%2===0?`[${lb(t)}${n}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`]],pb=/(^|\\\/)?\\\*$/,$i="regex",Co="checkRegex",yd="_",gb={[$i](r,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[Co](r,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},mb=r=>db.reduce((e,[t,n])=>e.replace(t,n.bind(r)),r),Po=r=>typeof r=="string",yb=r=>r&&Po(r)&&!nb.test(r)&&!ib.test(r)&&r.indexOf("#")!==0,_b=r=>r.split(ab).filter(Boolean),Vc=class{constructor(e,t,n,i,s,a){this.pattern=e,this.mark=t,this.negative=s,li(this,"body",n),li(this,"ignoreCase",i),li(this,"regexPrefix",a)}get regex(){let e=yd+$i;return this[e]?this[e]:this._make($i,e)}get checkRegex(){let e=yd+Co;return this[e]?this[e]:this._make(Co,e)}_make(e,t){let n=this.regexPrefix.replace(pb,gb[e]),i=this.ignoreCase?new RegExp(n,"i"):new RegExp(n);return li(this,t,i)}},Eb=({pattern:r,mark:e},t)=>{let n=!1,i=r;i.indexOf("!")===0&&(n=!0,i=i.substr(1)),i=i.replace(sb,"!").replace(ob,"#");let s=mb(i);return new Vc(r,e,i,t,n,s)},$c=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[bd]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(Po(e)&&(e={pattern:e}),yb(e.pattern)){let t=Eb(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,_d(Po(e)?_b(e):e).forEach(this._add,this),this._added}test(e,t,n){let i=!1,s=!1,a;this._rules.forEach(c=>{let{negative:l}=c;s===l&&i!==s||l&&!i&&!s&&!t||!c[n].test(e)||(i=!l,s=l,a=l?rb:c)});let f={ignored:i,unignored:s};return a&&(f.rule=a),f}},bb=(r,e)=>{throw new e(r)},jr=(r,e,t)=>Po(r)?r?jr.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),vd=r=>cb.test(r);jr.isNotRelative=vd;jr.convert=r=>r;var Gc=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){li(this,bd,!0),this._rules=new $c(t),this._strictPathCheck=!n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(e){return this._rules.add(e)&&this._initCache(),this}addPattern(e){return this.add(e)}_test(e,t,n,i){let s=e&&jr.convert(e);return jr(s,e,this._strictPathCheck?bb:wd),this._t(s,t,n,i)}checkIgnore(e){if(!fb.test(e))return this.test(e);let t=e.split(ui).filter(Boolean);if(t.pop(),t.length){let n=this._t(t.join(ui)+ui,this._testCache,!0,t);if(n.ignored)return n}return this._rules.test(e,!1,Co)}_t(e,t,n,i){if(e in t)return t[e];if(i||(i=e.split(ui).filter(Boolean)),i.pop(),!i.length)return t[e]=this._rules.test(e,n,$i);let s=this._t(i.join(ui)+ui,t,n,i);return t[e]=s.ignored?s:this._rules.test(e,n,$i)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return _d(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},zc=r=>new Gc(r),wb=r=>jr(r&&jr.convert(r),r,wd),Sd=()=>{let r=t=>/^\\\\\?\\/.test(t)||/["<>|\u0000-\u001F]+/u.test(t)?t:t.replace(/\\/g,"/");jr.convert=r;let e=/^[a-z]:\//i;jr.isNotRelative=t=>e.test(t)||vd(t)};typeof process<"u"&&process.platform==="win32"&&Sd();ko.exports=zc;zc.default=zc;ko.exports.isPathValid=wb;li(ko.exports,Symbol.for("setupWindows"),Sd)});var Td=I(Vt=>{"use strict";var vb=Vt&&Vt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Sb=Vt&&Vt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),xd=Vt&&Vt.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),i=0;i<n.length;i++)n[i]!=="default"&&vb(t,e,n[i]);return Sb(t,e),t}})(),xb=Vt&&Vt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Vt,"__esModule",{value:!0});Vt.FileListService=void 0;var hi=xd(require("path")),Xc=xd(require("fs/promises")),Tb=xb(Yc()),Zc=Rr(),Ob=["node_modules",".pnpm","vendor",".git","dist","build","out",".next",".nuxt",".output",".cache",".turbo",".idea",".vscode",".DS_Store","Thumbs.db"],Qc=class{ignoreFilter;workspaceRoot;onResponseCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,Tb.default)(),this.ignoreFilter.add(Ob),this.workspaceRoot&&this.loadGitignore(),this.logger.info("FileListService initialized",t||"null")}async loadGitignore(){if(!this.workspaceRoot)return;let e=hi.join(this.workspaceRoot,".gitignore");try{let t=await Xc.readFile(e,"utf-8");this.ignoreFilter.add(t)}catch{}}onResponse(e){this.onResponseCallback=e}async handleListRequest(e){if(!this.workspaceRoot){this.sendResponse({requestId:e.requestId,path:e.path,entries:[],error:"No workspace root"});return}try{let t=this.resolvePath(e.path),n=await this.listDirectory(t,e.path);this.sendResponse({requestId:e.requestId,path:e.path,entries:n})}catch(t){this.logger.error("Failed to list directory",String(t)),this.sendResponse({requestId:e.requestId,path:e.path,entries:[],error:t instanceof Error?t.message:"Unknown error"})}}async listDirectory(e,t){let n=await Xc.readdir(e,{withFileTypes:!0}),i=[];for(let s of n){let a=t==="."||t===""?s.name:hi.join(t,s.name);if(this.shouldHide(a,s.isDirectory()))continue;let f=hi.join(e,s.name),c={name:s.name,path:a,type:s.isDirectory()?Zc.FileEntryType.DIRECTORY:Zc.FileEntryType.FILE};if(!s.isDirectory())try{let l=await Xc.stat(f);c.size=l.size,c.modified=l.mtime.toISOString()}catch{}i.push(c)}return i.sort((s,a)=>s.type!==a.type?s.type===Zc.FileEntryType.DIRECTORY?-1:1:s.name.localeCompare(a.name))}shouldHide(e,t){let n=e.split(hi.sep).join("/"),i=t?`${n}/`:n;return this.ignoreFilter.ignores(i)}resolvePath(e){if(!this.workspaceRoot)throw new Error("No workspace root");if(e==="."||e==="")return this.workspaceRoot;let t=hi.resolve(this.workspaceRoot,e);if(t!==this.workspaceRoot&&!t.startsWith(this.workspaceRoot+hi.sep))throw new Error("Path outside workspace");return t}sendResponse(e){this.onResponseCallback?.(e)}dispose(){this.onResponseCallback=null}};Vt.FileListService=Qc});var Cd=I(br=>{"use strict";var Cb=br&&br.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Pb=br&&br.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Od=br&&br.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),i=0;i<n.length;i++)n[i]!=="default"&&Cb(t,e,n[i]);return Pb(t,e),t}})();Object.defineProperty(br,"__esModule",{value:!0});br.FileTrackerService=void 0;var Jc=Od(require("path")),Nn=Od(require("fs/promises")),kb=require("child_process"),Ab=require("util"),rr=Rr(),ef=(0,Ab.promisify)(kb.execFile),tf={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},rf=class{trackedFiles=new Map;pendingToolCalls=new Map;outputBuffers=new Map;workspaceRoot;onFileChangedCallback=null;onFileViewTransferCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t}onFileChanged(e){this.onFileChangedCallback=e}onFileViewTransfer(e){this.onFileViewTransferCallback=e}async processOutput(e,t){let n=this.outputBuffers.get(e)||"";n+=t,n.length>10240&&(n=n.slice(-10240)),this.outputBuffers.set(e,n);try{await this.parseToolCalls(e,n)}catch(i){this.logger.error("Error parsing tool calls",i)}}async parseToolCalls(e,t){let n=this.stripAnsi(t),i=n.match(tf.toolStart);if(i){let a=i[1],f=i[2],c=`${a}_${Date.now()}_${f}`;this.pendingToolCalls.has(c)||await this.handleToolStart(e,c,a,{file_path:f})}let s=n.match(tf.toolSuccess);if(s){let a=s[1];for(let[f,c]of this.pendingToolCalls)if(c.filePath===a||a.endsWith(c.filePath)||c.filePath.endsWith(a)){await this.handleToolEnd(e,f,c.toolName,"success");break}}if(tf.toolError.test(n))for(let[a,f]of this.pendingToolCalls)await this.handleToolEnd(e,a,f.toolName,"error")}stripAnsi(e){return e.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g,"").replace(/\x1b\][^\x07]*\x07/g,"").replace(/\x1b[()][AB012]/g,"").replace(/\x1b[=>]/g,"").replace(/\x1b[78DMEHc]/g,"")}async handleToolStart(e,t,n,i){if(!this.isFileModifyingTool(n))return;let s=this.extractFilePath(n,i);if(!s)return;let a=this.resolveFilePath(s),f={toolId:t,toolName:n,filePath:s,timestamp:new Date().toISOString()};this.pendingToolCalls.set(t,f);let c;try{c=await Nn.readFile(a,"utf-8")}catch{c=void 0}let l={path:s,changeType:c===void 0?rr.FileChangeType.CREATE:rr.FileChangeType.MODIFY,toolName:n,toolId:t,timestamp:f.timestamp,previousContent:c},p=this.trackedFiles.get(e)||[];p.push(l),this.trackedFiles.set(e,p)}async handleToolEnd(e,t,n,i){if(!this.isFileModifyingTool(n)||!this.pendingToolCalls.get(t))return;if(this.pendingToolCalls.delete(t),i==="error"){let p=this.trackedFiles.get(e)||[],m=p.findIndex(_=>_.toolId===t);m!==-1&&p.splice(m,1);return}let f=(this.trackedFiles.get(e)||[]).find(p=>p.toolId===t);if(!f)return;let c=this.resolveFilePath(f.path);try{let p=await Nn.stat(c);f.size=p.size}catch{f.changeType=rr.FileChangeType.DELETE,f.size=void 0}let l={path:f.path,changeType:f.changeType,timestamp:new Date().toISOString(),source:"tool-call",toolName:f.toolName,toolId:f.toolId,size:f.size};this.onFileChangedCallback?.(e,l)}async handleViewRequest(e,t){let n=this.resolveFilePath(t.path),i=this.getViewableMimeType(t.path);if(i&&this.onFileViewTransferCallback){try{let a=await Nn.readFile(n),f={requestId:t.requestId,path:t.path,viewType:"content",mimeType:i};this.onFileViewTransferCallback(e,Buffer.from(a),f)}catch(a){let f={requestId:t.requestId,path:t.path,viewType:"content",mimeType:i,error:a instanceof Error?a.message:"Unknown error"};this.onFileViewTransferCallback(e,Buffer.alloc(0),f)}return}let s;try{t.type===rr.FileViewType.CONTENT?s=await this.getFileContent(t,n):s=await this.getFileDiff(e,t,n)}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===rr.FileViewType.CONTENT?"content":"diff",language:s.language,truncated:s.truncated,error:s.error},f=Buffer.from(s.content||"","utf-8");this.onFileViewTransferCallback(e,f,a)}}getViewableMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf"}[t||""]||null}async getFileContent(e,t){let n=e.maxSize||1048576,i=await Nn.stat(t),s=await Nn.readFile(t,"utf-8"),a=!1,f=s;return s.length>n&&(f=s.slice(0,n),a=!0),{requestId:e.requestId,path:e.path,type:rr.FileViewType.CONTENT,content:f,language:(0,rr.getLanguageFromPath)(e.path),size:i.size,truncated:a}}async getFileDiff(e,t,n){let i=t.diffBase||rr.DiffBase.GIT,s;return i===rr.DiffBase.GIT?s=await this.getGitDiff(n):s=await this.getPreviousDiff(e,t.path,n),{requestId:t.requestId,path:t.path,type:rr.FileViewType.DIFF,content:s,language:"diff"}}async getGitDiff(e){if(!this.workspaceRoot)throw new Error("No workspace root");try{let{stdout:t}=await ef("git",["diff","--cached","--",e],{cwd:this.workspaceRoot});if(t.trim())return t;let{stdout:n}=await ef("git",["diff","--",e],{cwd:this.workspaceRoot});if(n.trim())return n;let{stdout:i}=await ef("git",["status","--porcelain","--",e],{cwd:this.workspaceRoot});if(i.startsWith("??")||i.startsWith("A ")){let a=(await Nn.readFile(e,"utf-8")).split(`
|
|
135
|
+
`),f=Jc.relative(this.workspaceRoot,e);return[`diff --git a/${f} b/${f}`,"new file mode 100644","--- /dev/null",`+++ b/${f}`,`@@ -0,0 +1,${a.length} @@`,...a.map(c=>`+${c}`)].join(`
|
|
136
|
+
`)}return"(no changes)"}catch{throw new Error("Git not available")}}async getPreviousDiff(e,t,n){let a=(this.trackedFiles.get(e)||[]).find(l=>l.path===t&&l.previousContent!==void 0)?.previousContent||"",f;try{f=await Nn.readFile(n,"utf-8")}catch{f=""}let c=(0,rr.createSimpleDiff)(a,f,t);return this.diffContentToUnifiedText(c)}diffContentToUnifiedText(e){let t=[];t.push(`--- a/${e.path}`),t.push(`+++ b/${e.path}`);for(let n of e.hunks){t.push(`@@ -${n.oldStart},${n.oldLines} +${n.newStart},${n.newLines} @@`);for(let i of n.lines)switch(i.type){case"add":t.push(`+${i.content}`);break;case"remove":t.push(`-${i.content}`);break;case"context":t.push(` ${i.content}`);break}}return t.join(`
|
|
137
|
+
`)}clearTerminal(e){this.trackedFiles.delete(e),this.outputBuffers.delete(e)}getChangedFiles(e){return(this.trackedFiles.get(e)||[]).map(n=>({path:n.path,changeType:n.changeType,timestamp:n.timestamp,source:"tool-call",toolName:n.toolName,toolId:n.toolId,size:n.size}))}isFileModifyingTool(e){return["Write","Edit","NotebookEdit"].includes(e)}extractFilePath(e,t){return t?e==="Write"||e==="Edit"?t.file_path||null:e==="NotebookEdit"&&t.notebook_path||null:null}resolveFilePath(e){let t=this.workspaceRoot;if(!t)throw new Error("No workspace root configured");let n=Jc.resolve(t,e);if(n!==t&&!n.startsWith(t+Jc.sep))throw new Error("Path escapes workspace root");return n}dispose(){this.trackedFiles.clear(),this.pendingToolCalls.clear(),this.onFileChangedCallback=null,this.onFileViewTransferCallback=null}};br.FileTrackerService=rf});var Pd=I(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.InputStreamReceiver=we.FileTrackerService=we.FileListService=we.FileTransferService=we.WebSocketService=we.SHELL_INTEGRATION_ENV=we.shellIntegrationKind=we.prepareShellLaunch=we.isSessionCrash=we.isInterruptExit=we.agentForProgram=we.AGENT_PROGRAMS=we.AgentExitTracker=we.trackAltScreen=we.isTerminalReplyOnly=we.isAnswerKeystroke=we.StatusDetector=we.AuthService=we.CryptoService=void 0;var Rb=Uu();Object.defineProperty(we,"CryptoService",{enumerable:!0,get:function(){return Rb.CryptoService}});var Ib=qu();Object.defineProperty(we,"AuthService",{enumerable:!0,get:function(){return Ib.AuthService}});var Ao=Vu();Object.defineProperty(we,"StatusDetector",{enumerable:!0,get:function(){return Ao.StatusDetector}});Object.defineProperty(we,"isAnswerKeystroke",{enumerable:!0,get:function(){return Ao.isAnswerKeystroke}});Object.defineProperty(we,"isTerminalReplyOnly",{enumerable:!0,get:function(){return Ao.isTerminalReplyOnly}});Object.defineProperty(we,"trackAltScreen",{enumerable:!0,get:function(){return Ao.trackAltScreen}});var Gi=Zu();Object.defineProperty(we,"AgentExitTracker",{enumerable:!0,get:function(){return Gi.AgentExitTracker}});Object.defineProperty(we,"AGENT_PROGRAMS",{enumerable:!0,get:function(){return Gi.AGENT_PROGRAMS}});Object.defineProperty(we,"agentForProgram",{enumerable:!0,get:function(){return Gi.agentForProgram}});Object.defineProperty(we,"isInterruptExit",{enumerable:!0,get:function(){return Gi.isInterruptExit}});Object.defineProperty(we,"isSessionCrash",{enumerable:!0,get:function(){return Gi.isSessionCrash}});var nf=el();Object.defineProperty(we,"prepareShellLaunch",{enumerable:!0,get:function(){return nf.prepareShellLaunch}});Object.defineProperty(we,"shellIntegrationKind",{enumerable:!0,get:function(){return nf.shellIntegrationKind}});Object.defineProperty(we,"SHELL_INTEGRATION_ENV",{enumerable:!0,get:function(){return nf.SHELL_INTEGRATION_ENV}});var Lb=hd();Object.defineProperty(we,"WebSocketService",{enumerable:!0,get:function(){return Lb.WebSocketService}});var Nb=gd();Object.defineProperty(we,"FileTransferService",{enumerable:!0,get:function(){return Nb.FileTransferService}});var Mb=Td();Object.defineProperty(we,"FileListService",{enumerable:!0,get:function(){return Mb.FileListService}});var Db=Cd();Object.defineProperty(we,"FileTrackerService",{enumerable:!0,get:function(){return Db.FileTrackerService}});var Fb=jc();Object.defineProperty(we,"InputStreamReceiver",{enumerable:!0,get:function(){return Fb.InputStreamReceiver}})});var pi=I(U=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.FP_LABEL=U.KX_ACK_LABEL=U.KX_SIGN_LABEL=U.concatBytes=U.fingerprintShortHex=U.fingerprintIdentityKey=U.buildKxAckCanonical=U.buildKxCanonical=U.verifySessionKey=U.signSessionKey=U.identityPublicFromSecret=U.generateIdentityKeyPair=U.InputStreamReceiver=U.FileTrackerService=U.FileListService=U.FileTransferService=U.WebSocketService=U.SHELL_INTEGRATION_ENV=U.shellIntegrationKind=U.prepareShellLaunch=U.isSessionCrash=U.isInterruptExit=U.agentForProgram=U.AGENT_PROGRAMS=U.AgentExitTracker=U.trackAltScreen=U.isTerminalReplyOnly=U.isAnswerKeystroke=U.StatusDetector=U.AuthService=U.CryptoService=U.getCurrentCorrelationId=U.runWithCorrelation=U.generateCorrelationId=U.getWsUrl=U.getApiUrl=U.CircularBuffer=U.formatLogLine=U.shouldLog=U.LOG_LEVELS=void 0;var sf=tu();Object.defineProperty(U,"LOG_LEVELS",{enumerable:!0,get:function(){return sf.LOG_LEVELS}});Object.defineProperty(U,"shouldLog",{enumerable:!0,get:function(){return sf.shouldLog}});Object.defineProperty(U,"formatLogLine",{enumerable:!0,get:function(){return sf.formatLogLine}});var di=iu();Object.defineProperty(U,"CircularBuffer",{enumerable:!0,get:function(){return di.CircularBuffer}});Object.defineProperty(U,"getApiUrl",{enumerable:!0,get:function(){return di.getApiUrl}});Object.defineProperty(U,"getWsUrl",{enumerable:!0,get:function(){return di.getWsUrl}});Object.defineProperty(U,"generateCorrelationId",{enumerable:!0,get:function(){return di.generateCorrelationId}});Object.defineProperty(U,"runWithCorrelation",{enumerable:!0,get:function(){return di.runWithCorrelation}});Object.defineProperty(U,"getCurrentCorrelationId",{enumerable:!0,get:function(){return di.getCurrentCorrelationId}});var ct=Pd();Object.defineProperty(U,"CryptoService",{enumerable:!0,get:function(){return ct.CryptoService}});Object.defineProperty(U,"AuthService",{enumerable:!0,get:function(){return ct.AuthService}});Object.defineProperty(U,"StatusDetector",{enumerable:!0,get:function(){return ct.StatusDetector}});Object.defineProperty(U,"isAnswerKeystroke",{enumerable:!0,get:function(){return ct.isAnswerKeystroke}});Object.defineProperty(U,"isTerminalReplyOnly",{enumerable:!0,get:function(){return ct.isTerminalReplyOnly}});Object.defineProperty(U,"trackAltScreen",{enumerable:!0,get:function(){return ct.trackAltScreen}});Object.defineProperty(U,"AgentExitTracker",{enumerable:!0,get:function(){return ct.AgentExitTracker}});Object.defineProperty(U,"AGENT_PROGRAMS",{enumerable:!0,get:function(){return ct.AGENT_PROGRAMS}});Object.defineProperty(U,"agentForProgram",{enumerable:!0,get:function(){return ct.agentForProgram}});Object.defineProperty(U,"isInterruptExit",{enumerable:!0,get:function(){return ct.isInterruptExit}});Object.defineProperty(U,"isSessionCrash",{enumerable:!0,get:function(){return ct.isSessionCrash}});Object.defineProperty(U,"prepareShellLaunch",{enumerable:!0,get:function(){return ct.prepareShellLaunch}});Object.defineProperty(U,"shellIntegrationKind",{enumerable:!0,get:function(){return ct.shellIntegrationKind}});Object.defineProperty(U,"SHELL_INTEGRATION_ENV",{enumerable:!0,get:function(){return ct.SHELL_INTEGRATION_ENV}});Object.defineProperty(U,"WebSocketService",{enumerable:!0,get:function(){return ct.WebSocketService}});Object.defineProperty(U,"FileTransferService",{enumerable:!0,get:function(){return ct.FileTransferService}});Object.defineProperty(U,"FileListService",{enumerable:!0,get:function(){return ct.FileListService}});Object.defineProperty(U,"FileTrackerService",{enumerable:!0,get:function(){return ct.FileTrackerService}});Object.defineProperty(U,"InputStreamReceiver",{enumerable:!0,get:function(){return ct.InputStreamReceiver}});var $t=da();Object.defineProperty(U,"generateIdentityKeyPair",{enumerable:!0,get:function(){return $t.generateIdentityKeyPair}});Object.defineProperty(U,"identityPublicFromSecret",{enumerable:!0,get:function(){return $t.identityPublicFromSecret}});Object.defineProperty(U,"signSessionKey",{enumerable:!0,get:function(){return $t.signSessionKey}});Object.defineProperty(U,"verifySessionKey",{enumerable:!0,get:function(){return $t.verifySessionKey}});Object.defineProperty(U,"buildKxCanonical",{enumerable:!0,get:function(){return $t.buildKxCanonical}});Object.defineProperty(U,"buildKxAckCanonical",{enumerable:!0,get:function(){return $t.buildKxAckCanonical}});Object.defineProperty(U,"fingerprintIdentityKey",{enumerable:!0,get:function(){return $t.fingerprintIdentityKey}});Object.defineProperty(U,"fingerprintShortHex",{enumerable:!0,get:function(){return $t.fingerprintShortHex}});Object.defineProperty(U,"concatBytes",{enumerable:!0,get:function(){return $t.concatBytes}});Object.defineProperty(U,"KX_SIGN_LABEL",{enumerable:!0,get:function(){return $t.KX_SIGN_LABEL}});Object.defineProperty(U,"KX_ACK_LABEL",{enumerable:!0,get:function(){return $t.KX_ACK_LABEL}});Object.defineProperty(U,"FP_LABEL",{enumerable:!0,get:function(){return $t.FP_LABEL}})});var ff=I((Yi,cf)=>{(function(r,e){typeof Yi=="object"&&typeof cf=="object"?cf.exports=e(require("child_process"),require("crypto")):typeof define=="function"&&define.amd?define(["child_process","crypto"],e):typeof Yi=="object"?Yi["electron-machine-id"]=e(require("child_process"),require("crypto")):r["electron-machine-id"]=e(r.child_process,r.crypto)})(Yi,function(r,e){return(function(t){function n(s){if(i[s])return i[s].exports;var a=i[s]={exports:{},id:s,loaded:!1};return t[s].call(a.exports,a,a.exports,n),a.loaded=!0,a.exports}var i={};return n.m=t,n.c=i,n.p="",n(0)})([function(t,n,i){t.exports=i(34)},function(t,n,i){var s=i(29)("wks"),a=i(33),f=i(2).Symbol,c=typeof f=="function",l=t.exports=function(p){return s[p]||(s[p]=c&&f[p]||(c?f:a)("Symbol."+p))};l.store=s},function(t,n){var i=t.exports=typeof window<"u"&&window.Math==Math?window:typeof self<"u"&&self.Math==Math?self:Function("return this")();typeof __g=="number"&&(__g=i)},function(t,n,i){var s=i(9);t.exports=function(a){if(!s(a))throw TypeError(a+" is not an object!");return a}},function(t,n,i){t.exports=!i(24)(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7})},function(t,n,i){var s=i(12),a=i(17);t.exports=i(4)?function(f,c,l){return s.f(f,c,a(1,l))}:function(f,c,l){return f[c]=l,f}},function(t,n){var i=t.exports={version:"2.4.0"};typeof __e=="number"&&(__e=i)},function(t,n,i){var s=i(14);t.exports=function(a,f,c){if(s(a),f===void 0)return a;switch(c){case 1:return function(l){return a.call(f,l)};case 2:return function(l,p){return a.call(f,l,p)};case 3:return function(l,p,m){return a.call(f,l,p,m)}}return function(){return a.apply(f,arguments)}}},function(t,n){var i={}.hasOwnProperty;t.exports=function(s,a){return i.call(s,a)}},function(t,n){t.exports=function(i){return typeof i=="object"?i!==null:typeof i=="function"}},function(t,n){t.exports={}},function(t,n){var i={}.toString;t.exports=function(s){return i.call(s).slice(8,-1)}},function(t,n,i){var s=i(3),a=i(26),f=i(32),c=Object.defineProperty;n.f=i(4)?Object.defineProperty:function(l,p,m){if(s(l),p=f(p,!0),s(m),a)try{return c(l,p,m)}catch{}if("get"in m||"set"in m)throw TypeError("Accessors not supported!");return"value"in m&&(l[p]=m.value),l}},function(t,n,i){var s=i(42),a=i(15);t.exports=function(f){return s(a(f))}},function(t,n){t.exports=function(i){if(typeof i!="function")throw TypeError(i+" is not a function!");return i}},function(t,n){t.exports=function(i){if(i==null)throw TypeError("Can't call method on "+i);return i}},function(t,n,i){var s=i(9),a=i(2).document,f=s(a)&&s(a.createElement);t.exports=function(c){return f?a.createElement(c):{}}},function(t,n){t.exports=function(i,s){return{enumerable:!(1&i),configurable:!(2&i),writable:!(4&i),value:s}}},function(t,n,i){var s=i(12).f,a=i(8),f=i(1)("toStringTag");t.exports=function(c,l,p){c&&!a(c=p?c:c.prototype,f)&&s(c,f,{configurable:!0,value:l})}},function(t,n,i){var s=i(29)("keys"),a=i(33);t.exports=function(f){return s[f]||(s[f]=a(f))}},function(t,n){var i=Math.ceil,s=Math.floor;t.exports=function(a){return isNaN(a=+a)?0:(a>0?s:i)(a)}},function(t,n,i){var s=i(11),a=i(1)("toStringTag"),f=s((function(){return arguments})())=="Arguments",c=function(l,p){try{return l[p]}catch{}};t.exports=function(l){var p,m,_;return l===void 0?"Undefined":l===null?"Null":typeof(m=c(p=Object(l),a))=="string"?m:f?s(p):(_=s(p))=="Object"&&typeof p.callee=="function"?"Arguments":_}},function(t,n){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,n,i){var s=i(2),a=i(6),f=i(7),c=i(5),l="prototype",p=function(m,_,b){var x,O,V,ie=m&p.F,z=m&p.G,T=m&p.S,D=m&p.P,te=m&p.B,q=m&p.W,ee=z?a:a[_]||(a[_]={}),pe=ee[l],K=z?s:T?s[_]:(s[_]||{})[l];z&&(b=_);for(x in b)O=!ie&&K&&K[x]!==void 0,O&&x in ee||(V=O?K[x]:b[x],ee[x]=z&&typeof K[x]!="function"?b[x]:te&&O?f(V,s):q&&K[x]==V?(function(Me){var tt=function(Te,De,ve){if(this instanceof Me){switch(arguments.length){case 0:return new Me;case 1:return new Me(Te);case 2:return new Me(Te,De)}return new Me(Te,De,ve)}return Me.apply(this,arguments)};return tt[l]=Me[l],tt})(V):D&&typeof V=="function"?f(Function.call,V):V,D&&((ee.virtual||(ee.virtual={}))[x]=V,m&p.R&&pe&&!pe[x]&&c(pe,x,V)))};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,n){t.exports=function(i){try{return!!i()}catch{return!0}}},function(t,n,i){t.exports=i(2).document&&document.documentElement},function(t,n,i){t.exports=!i(4)&&!i(24)(function(){return Object.defineProperty(i(16)("div"),"a",{get:function(){return 7}}).a!=7})},function(t,n,i){"use strict";var s=i(28),a=i(23),f=i(57),c=i(5),l=i(8),p=i(10),m=i(45),_=i(18),b=i(52),x=i(1)("iterator"),O=!([].keys&&"next"in[].keys()),V="@@iterator",ie="keys",z="values",T=function(){return this};t.exports=function(D,te,q,ee,pe,K,Me){m(q,te,ee);var tt,Te,De,ve=function(j){if(!O&&j in Fe)return Fe[j];switch(j){case ie:return function(){return new q(this,j)};case z:return function(){return new q(this,j)}}return function(){return new q(this,j)}},We=te+" Iterator",_e=pe==z,rt=!1,Fe=D.prototype,Et=Fe[x]||Fe[V]||pe&&Fe[pe],He=Et||ve(pe),pt=pe?_e?ve("entries"):He:void 0,N=te=="Array"&&Fe.entries||Et;if(N&&(De=b(N.call(new D)),De!==Object.prototype&&(_(De,We,!0),s||l(De,x)||c(De,x,T))),_e&&Et&&Et.name!==z&&(rt=!0,He=function(){return Et.call(this)}),s&&!Me||!O&&!rt&&Fe[x]||c(Fe,x,He),p[te]=He,p[We]=T,pe)if(tt={values:_e?He:ve(z),keys:K?He:ve(ie),entries:pt},Me)for(Te in tt)Te in Fe||f(Fe,Te,tt[Te]);else a(a.P+a.F*(O||rt),te,tt);return tt}},function(t,n){t.exports=!0},function(t,n,i){var s=i(2),a="__core-js_shared__",f=s[a]||(s[a]={});t.exports=function(c){return f[c]||(f[c]={})}},function(t,n,i){var s,a,f,c=i(7),l=i(41),p=i(25),m=i(16),_=i(2),b=_.process,x=_.setImmediate,O=_.clearImmediate,V=_.MessageChannel,ie=0,z={},T="onreadystatechange",D=function(){var q=+this;if(z.hasOwnProperty(q)){var ee=z[q];delete z[q],ee()}},te=function(q){D.call(q.data)};x&&O||(x=function(q){for(var ee=[],pe=1;arguments.length>pe;)ee.push(arguments[pe++]);return z[++ie]=function(){l(typeof q=="function"?q:Function(q),ee)},s(ie),ie},O=function(q){delete z[q]},i(11)(b)=="process"?s=function(q){b.nextTick(c(D,q,1))}:V?(a=new V,f=a.port2,a.port1.onmessage=te,s=c(f.postMessage,f,1)):_.addEventListener&&typeof postMessage=="function"&&!_.importScripts?(s=function(q){_.postMessage(q+"","*")},_.addEventListener("message",te,!1)):s=T in m("script")?function(q){p.appendChild(m("script"))[T]=function(){p.removeChild(this),D.call(q)}}:function(q){setTimeout(c(D,q,1),0)}),t.exports={set:x,clear:O}},function(t,n,i){var s=i(20),a=Math.min;t.exports=function(f){return f>0?a(s(f),9007199254740991):0}},function(t,n,i){var s=i(9);t.exports=function(a,f){if(!s(a))return a;var c,l;if(f&&typeof(c=a.toString)=="function"&&!s(l=c.call(a))||typeof(c=a.valueOf)=="function"&&!s(l=c.call(a))||!f&&typeof(c=a.toString)=="function"&&!s(l=c.call(a)))return l;throw TypeError("Can't convert object to primitive value")}},function(t,n){var i=0,s=Math.random();t.exports=function(a){return"Symbol(".concat(a===void 0?"":a,")_",(++i+s).toString(36))}},function(t,n,i){"use strict";function s(T){return T&&T.__esModule?T:{default:T}}function a(){return process.platform!=="win32"?"":process.arch==="ia32"&&process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432")?"mixed":"native"}function f(T){return(0,x.createHash)("sha256").update(T).digest("hex")}function c(T){switch(V){case"darwin":return T.split("IOPlatformUUID")[1].split(`
|
|
138
|
+
`)[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return T.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return T.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"freebsd":return T.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error("Unsupported platform: "+process.platform)}}function l(T){var D=c((0,b.execSync)(z[V]).toString());return T?D:f(D)}function p(T){return new _.default(function(D,te){return(0,b.exec)(z[V],{},function(q,ee,pe){if(q)return te(new Error("Error while obtaining machine id: "+q.stack));var K=c(ee.toString());return D(T?K:f(K))})})}Object.defineProperty(n,"__esModule",{value:!0});var m=i(35),_=s(m);n.machineIdSync=l,n.machineId=p;var b=i(70),x=i(71),O=process,V=O.platform,ie={native:"%windir%\\System32",mixed:"%windir%\\sysnative\\cmd.exe /c %windir%\\System32"},z={darwin:"ioreg -rd1 -c IOPlatformExpertDevice",win32:ie[a()]+"\\REG.exe QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",linux:"( cat /var/lib/dbus/machine-id /etc/machine-id 2> /dev/null || hostname ) | head -n 1 || :",freebsd:"kenv -q smbios.system.uuid || sysctl -n kern.hostuuid"}},function(t,n,i){t.exports={default:i(36),__esModule:!0}},function(t,n,i){i(66),i(68),i(69),i(67),t.exports=i(6).Promise},function(t,n){t.exports=function(){}},function(t,n){t.exports=function(i,s,a,f){if(!(i instanceof s)||f!==void 0&&f in i)throw TypeError(a+": incorrect invocation!");return i}},function(t,n,i){var s=i(13),a=i(31),f=i(62);t.exports=function(c){return function(l,p,m){var _,b=s(l),x=a(b.length),O=f(m,x);if(c&&p!=p){for(;x>O;)if(_=b[O++],_!=_)return!0}else for(;x>O;O++)if((c||O in b)&&b[O]===p)return c||O||0;return!c&&-1}}},function(t,b,i){var s=i(7),a=i(44),f=i(43),c=i(3),l=i(31),p=i(64),m={},_={},b=t.exports=function(x,O,V,ie,z){var T,D,te,q,ee=z?function(){return x}:p(x),pe=s(V,ie,O?2:1),K=0;if(typeof ee!="function")throw TypeError(x+" is not iterable!");if(f(ee)){for(T=l(x.length);T>K;K++)if(q=O?pe(c(D=x[K])[0],D[1]):pe(x[K]),q===m||q===_)return q}else for(te=ee.call(x);!(D=te.next()).done;)if(q=a(te,pe,D.value,O),q===m||q===_)return q};b.BREAK=m,b.RETURN=_},function(t,n){t.exports=function(i,s,a){var f=a===void 0;switch(s.length){case 0:return f?i():i.call(a);case 1:return f?i(s[0]):i.call(a,s[0]);case 2:return f?i(s[0],s[1]):i.call(a,s[0],s[1]);case 3:return f?i(s[0],s[1],s[2]):i.call(a,s[0],s[1],s[2]);case 4:return f?i(s[0],s[1],s[2],s[3]):i.call(a,s[0],s[1],s[2],s[3])}return i.apply(a,s)}},function(t,n,i){var s=i(11);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(a){return s(a)=="String"?a.split(""):Object(a)}},function(t,n,i){var s=i(10),a=i(1)("iterator"),f=Array.prototype;t.exports=function(c){return c!==void 0&&(s.Array===c||f[a]===c)}},function(t,n,i){var s=i(3);t.exports=function(a,f,c,l){try{return l?f(s(c)[0],c[1]):f(c)}catch(m){var p=a.return;throw p!==void 0&&s(p.call(a)),m}}},function(t,n,i){"use strict";var s=i(49),a=i(17),f=i(18),c={};i(5)(c,i(1)("iterator"),function(){return this}),t.exports=function(l,p,m){l.prototype=s(c,{next:a(1,m)}),f(l,p+" Iterator")}},function(t,n,i){var s=i(1)("iterator"),a=!1;try{var f=[7][s]();f.return=function(){a=!0},Array.from(f,function(){throw 2})}catch{}t.exports=function(c,l){if(!l&&!a)return!1;var p=!1;try{var m=[7],_=m[s]();_.next=function(){return{done:p=!0}},m[s]=function(){return _},c(m)}catch{}return p}},function(t,n){t.exports=function(i,s){return{value:s,done:!!i}}},function(t,n,i){var s=i(2),a=i(30).set,f=s.MutationObserver||s.WebKitMutationObserver,c=s.process,l=s.Promise,p=i(11)(c)=="process";t.exports=function(){var m,_,b,x=function(){var z,T;for(p&&(z=c.domain)&&z.exit();m;){T=m.fn,m=m.next;try{T()}catch(D){throw m?b():_=void 0,D}}_=void 0,z&&z.enter()};if(p)b=function(){c.nextTick(x)};else if(f){var O=!0,V=document.createTextNode("");new f(x).observe(V,{characterData:!0}),b=function(){V.data=O=!O}}else if(l&&l.resolve){var ie=l.resolve();b=function(){ie.then(x)}}else b=function(){a.call(s,x)};return function(z){var T={fn:z,next:void 0};_&&(_.next=T),m||(m=T,b()),_=T}}},function(t,n,i){var s=i(3),a=i(50),f=i(22),c=i(19)("IE_PROTO"),l=function(){},p="prototype",m=function(){var _,b=i(16)("iframe"),x=f.length,O=">";for(b.style.display="none",i(25).appendChild(b),b.src="javascript:",_=b.contentWindow.document,_.open(),_.write("<script>document.F=Object</script"+O),_.close(),m=_.F;x--;)delete m[p][f[x]];return m()};t.exports=Object.create||function(_,b){var x;return _!==null?(l[p]=s(_),x=new l,l[p]=null,x[c]=_):x=m(),b===void 0?x:a(x,b)}},function(t,n,i){var s=i(12),a=i(3),f=i(54);t.exports=i(4)?Object.defineProperties:function(c,l){a(c);for(var p,m=f(l),_=m.length,b=0;_>b;)s.f(c,p=m[b++],l[p]);return c}},function(t,n,i){var s=i(55),a=i(17),f=i(13),c=i(32),l=i(8),p=i(26),m=Object.getOwnPropertyDescriptor;n.f=i(4)?m:function(_,b){if(_=f(_),b=c(b,!0),p)try{return m(_,b)}catch{}if(l(_,b))return a(!s.f.call(_,b),_[b])}},function(t,n,i){var s=i(8),a=i(63),f=i(19)("IE_PROTO"),c=Object.prototype;t.exports=Object.getPrototypeOf||function(l){return l=a(l),s(l,f)?l[f]:typeof l.constructor=="function"&&l instanceof l.constructor?l.constructor.prototype:l instanceof Object?c:null}},function(t,n,i){var s=i(8),a=i(13),f=i(39)(!1),c=i(19)("IE_PROTO");t.exports=function(l,p){var m,_=a(l),b=0,x=[];for(m in _)m!=c&&s(_,m)&&x.push(m);for(;p.length>b;)s(_,m=p[b++])&&(~f(x,m)||x.push(m));return x}},function(t,n,i){var s=i(53),a=i(22);t.exports=Object.keys||function(f){return s(f,a)}},function(t,n){n.f={}.propertyIsEnumerable},function(t,n,i){var s=i(5);t.exports=function(a,f,c){for(var l in f)c&&a[l]?a[l]=f[l]:s(a,l,f[l]);return a}},function(t,n,i){t.exports=i(5)},function(t,n,i){var s=i(9),a=i(3),f=function(c,l){if(a(c),!s(l)&&l!==null)throw TypeError(l+": can't set as prototype!")};t.exports={set:Object.setPrototypeOf||("__proto__"in{}?(function(c,l,p){try{p=i(7)(Function.call,i(51).f(Object.prototype,"__proto__").set,2),p(c,[]),l=!(c instanceof Array)}catch{l=!0}return function(m,_){return f(m,_),l?m.__proto__=_:p(m,_),m}})({},!1):void 0),check:f}},function(t,n,i){"use strict";var s=i(2),a=i(6),f=i(12),c=i(4),l=i(1)("species");t.exports=function(p){var m=typeof a[p]=="function"?a[p]:s[p];c&&m&&!m[l]&&f.f(m,l,{configurable:!0,get:function(){return this}})}},function(t,n,i){var s=i(3),a=i(14),f=i(1)("species");t.exports=function(c,l){var p,m=s(c).constructor;return m===void 0||(p=s(m)[f])==null?l:a(p)}},function(t,n,i){var s=i(20),a=i(15);t.exports=function(f){return function(c,l){var p,m,_=String(a(c)),b=s(l),x=_.length;return b<0||b>=x?f?"":void 0:(p=_.charCodeAt(b),p<55296||p>56319||b+1===x||(m=_.charCodeAt(b+1))<56320||m>57343?f?_.charAt(b):p:f?_.slice(b,b+2):(p-55296<<10)+(m-56320)+65536)}}},function(t,n,i){var s=i(20),a=Math.max,f=Math.min;t.exports=function(c,l){return c=s(c),c<0?a(c+l,0):f(c,l)}},function(t,n,i){var s=i(15);t.exports=function(a){return Object(s(a))}},function(t,n,i){var s=i(21),a=i(1)("iterator"),f=i(10);t.exports=i(6).getIteratorMethod=function(c){if(c!=null)return c[a]||c["@@iterator"]||f[s(c)]}},function(t,n,i){"use strict";var s=i(37),a=i(47),f=i(10),c=i(13);t.exports=i(27)(Array,"Array",function(l,p){this._t=c(l),this._i=0,this._k=p},function(){var l=this._t,p=this._k,m=this._i++;return!l||m>=l.length?(this._t=void 0,a(1)):p=="keys"?a(0,m):p=="values"?a(0,l[m]):a(0,[m,l[m]])},"values"),f.Arguments=f.Array,s("keys"),s("values"),s("entries")},function(t,n){},function(t,n,i){"use strict";var s,a,f,c=i(28),l=i(2),p=i(7),m=i(21),_=i(23),b=i(9),x=(i(3),i(14)),O=i(38),V=i(40),ie=(i(58).set,i(60)),z=i(30).set,T=i(48)(),D="Promise",te=l.TypeError,ee=l.process,q=l[D],ee=l.process,pe=m(ee)=="process",K=function(){},Me=!!(function(){try{var N=q.resolve(1),j=(N.constructor={})[i(1)("species")]=function(L){L(K,K)};return(pe||typeof PromiseRejectionEvent=="function")&&N.then(K)instanceof j}catch{}})(),tt=function(N,j){return N===j||N===q&&j===f},Te=function(N){var j;return!(!b(N)||typeof(j=N.then)!="function")&&j},De=function(N){return tt(q,N)?new ve(N):new a(N)},ve=a=function(N){var j,L;this.promise=new N(function(se,Ae){if(j!==void 0||L!==void 0)throw te("Bad Promise constructor");j=se,L=Ae}),this.resolve=x(j),this.reject=x(L)},We=function(N){try{N()}catch(j){return{error:j}}},_e=function(N,j){if(!N._n){N._n=!0;var L=N._c;T(function(){for(var se=N._v,Ae=N._s==1,B=0,oe=function(Ue){var nt,bt,zt=Ae?Ue.ok:Ue.fail,ln=Ue.resolve,Kr=Ue.reject,Fn=Ue.domain;try{zt?(Ae||(N._h==2&&Et(N),N._h=1),zt===!0?nt=se:(Fn&&Fn.enter(),nt=zt(se),Fn&&Fn.exit()),nt===Ue.promise?Kr(te("Promise-chain cycle")):(bt=Te(nt))?bt.call(nt,ln,Kr):ln(nt)):Kr(se)}catch(ss){Kr(ss)}};L.length>B;)oe(L[B++]);N._c=[],N._n=!1,j&&!N._h&&rt(N)})}},rt=function(N){z.call(l,function(){var j,L,se,Ae=N._v;if(Fe(N)&&(j=We(function(){pe?ee.emit("unhandledRejection",Ae,N):(L=l.onunhandledrejection)?L({promise:N,reason:Ae}):(se=l.console)&&se.error&&se.error("Unhandled promise rejection",Ae)}),N._h=pe||Fe(N)?2:1),N._a=void 0,j)throw j.error})},Fe=function(N){if(N._h==1)return!1;for(var j,L=N._a||N._c,se=0;L.length>se;)if(j=L[se++],j.fail||!Fe(j.promise))return!1;return!0},Et=function(N){z.call(l,function(){var j;pe?ee.emit("rejectionHandled",N):(j=l.onrejectionhandled)&&j({promise:N,reason:N._v})})},He=function(N){var j=this;j._d||(j._d=!0,j=j._w||j,j._v=N,j._s=2,j._a||(j._a=j._c.slice()),_e(j,!0))},pt=function(N){var j,L=this;if(!L._d){L._d=!0,L=L._w||L;try{if(L===N)throw te("Promise can't be resolved itself");(j=Te(N))?T(function(){var se={_w:L,_d:!1};try{j.call(N,p(pt,se,1),p(He,se,1))}catch(Ae){He.call(se,Ae)}}):(L._v=N,L._s=1,_e(L,!1))}catch(se){He.call({_w:L,_d:!1},se)}}};Me||(q=function(N){O(this,q,D,"_h"),x(N),s.call(this);try{N(p(pt,this,1),p(He,this,1))}catch(j){He.call(this,j)}},s=function(N){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},s.prototype=i(56)(q.prototype,{then:function(N,j){var L=De(ie(this,q));return L.ok=typeof N!="function"||N,L.fail=typeof j=="function"&&j,L.domain=pe?ee.domain:void 0,this._c.push(L),this._a&&this._a.push(L),this._s&&_e(this,!1),L.promise},catch:function(N){return this.then(void 0,N)}}),ve=function(){var N=new s;this.promise=N,this.resolve=p(pt,N,1),this.reject=p(He,N,1)}),_(_.G+_.W+_.F*!Me,{Promise:q}),i(18)(q,D),i(59)(D),f=i(6)[D],_(_.S+_.F*!Me,D,{reject:function(N){var j=De(this),L=j.reject;return L(N),j.promise}}),_(_.S+_.F*(c||!Me),D,{resolve:function(N){if(N instanceof q&&tt(N.constructor,this))return N;var j=De(this),L=j.resolve;return L(N),j.promise}}),_(_.S+_.F*!(Me&&i(46)(function(N){q.all(N).catch(K)})),D,{all:function(N){var j=this,L=De(j),se=L.resolve,Ae=L.reject,B=We(function(){var oe=[],Ue=0,nt=1;V(N,!1,function(bt){var zt=Ue++,ln=!1;oe.push(void 0),nt++,j.resolve(bt).then(function(Kr){ln||(ln=!0,oe[zt]=Kr,--nt||se(oe))},Ae)}),--nt||se(oe)});return B&&Ae(B.error),L.promise},race:function(N){var j=this,L=De(j),se=L.reject,Ae=We(function(){V(N,!1,function(B){j.resolve(B).then(L.resolve,se)})});return Ae&&se(Ae.error),L.promise}})},function(t,n,i){"use strict";var s=i(61)(!0);i(27)(String,"String",function(a){this._t=String(a),this._i=0},function(){var a,f=this._t,c=this._i;return c>=f.length?{value:void 0,done:!0}:(a=s(f,c),this._i+=a.length,{value:a,done:!1})})},function(t,n,i){i(65);for(var s=i(2),a=i(5),f=i(10),c=i(1)("toStringTag"),l=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],p=0;p<5;p++){var m=l[p],_=s[m],b=_&&_.prototype;b&&!b[c]&&a(b,c,m),f[m]=f.Array}},function(t,n){t.exports=require("child_process")},function(t,n){t.exports=require("crypto")}])})});function Kb(){try{return lf.default.statSync("/.dockerenv"),!0}catch{return!1}}function Wb(){try{return lf.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function hf(){return uf===void 0&&(uf=Kb()||Wb()),uf}var lf,uf,Ld=Yt(()=>{lf=he(require("node:fs"),1)});function gi(){return df===void 0&&(df=Hb()||hf()),df}var Nd,df,Hb,pf=Yt(()=>{Nd=he(require("node:fs"),1);Ld();Hb=()=>{try{return Nd.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var gf,Dd,Fd,Md,sn,mf=Yt(()=>{gf=he(require("node:process"),1),Dd=he(require("node:os"),1),Fd=he(require("node:fs"),1);pf();Md=()=>{if(gf.default.platform!=="linux")return!1;if(Dd.default.release().toLowerCase().includes("microsoft"))return!gi();try{return Fd.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!gi():!1}catch{return!1}},sn=gf.default.env.__IS_WSL_TEST__?Md:Md()});var yf,Qi,Vb,$b,_f,Bd=Yt(()=>{yf=he(require("node:process"),1),Qi=he(require("node:fs/promises"),1);mf();mf();Vb=(()=>{let r="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",n=!1;try{await Qi.default.access(t,Qi.constants.F_OK),n=!0}catch{}if(!n)return r;let i=await Qi.default.readFile(t,{encoding:"utf8"}),s=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(i);return s?(e=s.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):r}})(),$b=async()=>`${await Vb()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,_f=async()=>sn?$b():`${yf.default.env.SYSTEMROOT||yf.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function on(r,e,t){let n=i=>Object.defineProperty(r,e,{value:i,enumerable:!0,writable:!0});return Object.defineProperty(r,e,{configurable:!0,enumerable:!0,get(){let i=t();return n(i),i},set(i){n(i)}}),r}var jd=Yt(()=>{});async function Ef(){if(qd.default.platform!=="darwin")throw new Error("macOS only");let{stdout:r}=await Gb("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 Ud,qd,Kd,Gb,Wd=Yt(()=>{Ud=require("node:util"),qd=he(require("node:process"),1),Kd=require("node:child_process"),Gb=(0,Ud.promisify)(Kd.execFile)});async function $d(r,{humanReadableOutput:e=!0,signal:t}={}){if(Hd.default.platform!=="darwin")throw new Error("macOS only");let n=e?[]:["-ss"],i={};t&&(i.signal=t);let{stdout:s}=await zb("osascript",["-e",r,n],i);return s.trim()}var Hd,Vd,bf,zb,Gd=Yt(()=>{Hd=he(require("node:process"),1),Vd=require("node:util"),bf=require("node:child_process"),zb=(0,Vd.promisify)(bf.execFile)});async function wf(r){return $d(`tell application "Finder" to set app_path to application file id "${r}" as string
|
|
139
|
+
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var zd=Yt(()=>{Gd()});async function Sf(r=Yb){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 vf(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:n}=t.groups,i=n.lastIndexOf("."),s=n.lastIndexOf("-"),a=i===-1?void 0:n.slice(0,i),f=s===-1?void 0:n.slice(0,s);return Io[n]??Io[a]??Io[f]??{name:n,id:n}}var Yd,Xd,Yb,Io,px,vf,Zd=Yt(()=>{Yd=require("node:util"),Xd=require("node:child_process"),Yb=(0,Yd.promisify)(Xd.execFile),Io={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"}},px=new Map(Object.entries(Io)),vf=class extends Error{}});async function xf(){if(Lo.default.platform==="darwin"){let r=await Ef();return{name:await wf(r),id:r}}if(Lo.default.platform==="linux"){let{stdout:r}=await Xb("xdg-mime",["query","default","x-scheme-handler/http"]),e=r.trim();return{name:Zb(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(Lo.default.platform==="win32")return Sf();throw new Error("Only macOS, Linux, and Windows are supported")}var Qd,Lo,Jd,Xb,Zb,ep=Yt(()=>{Qd=require("node:util"),Lo=he(require("node:process"),1),Jd=require("node:child_process");Wd();zd();Zd();Xb=(0,Qd.promisify)(Jd.execFile),Zb=r=>r.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var ap={};fg(ap,{apps:()=>an,default:()=>rw,openApp:()=>tw});async function Jb(){let r=await _f(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=Cf.Buffer.from(e,"utf16le").toString("base64"),{stdout:n}=await Qb(r,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),i=n.trim(),s={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return s[i]?{id:s[i]}:{}}function ip(r){if(typeof r=="string"||Array.isArray(r))return r;let{[rp]:e}=r;if(!e)throw new Error(`${rp} is not supported`);return e}function Mo({[mi]:r},{wsl:e}){if(e&&sn)return ip(e);if(!r)throw new Error(`${mi} is not supported`);return ip(r)}var Of,Cf,Pf,sp,op,kf,No,nw,Qb,Tf,tp,mi,rp,np,Ji,ew,tw,an,rw,cp=Yt(()=>{Of=he(require("node:process"),1),Cf=require("node:buffer"),Pf=he(require("node:path"),1),sp=require("node:url"),op=require("node:util"),kf=he(require("node:child_process"),1),No=he(require("node:fs/promises"),1);Bd();jd();ep();pf();nw={},Qb=(0,op.promisify)(kf.default.execFile),Tf=Pf.default.dirname((0,sp.fileURLToPath)(nw.url)),tp=Pf.default.join(Tf,"xdg-open"),{platform:mi,arch:rp}=Of.default;np=async(r,e)=>{let t;for(let n of r)try{return await e(n)}catch(i){t=i}throw t},Ji=async r=>{if(r={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...r},Array.isArray(r.app))return np(r.app,f=>Ji({...r,app:f}));let{name:e,arguments:t=[]}=r.app??{};if(t=[...t],Array.isArray(e))return np(e,f=>Ji({...r,app:{name:f,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let f={"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"},c={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},l=sn?await Jb():await xf();if(l.id in f){let p=f[l.id];return e==="browserPrivate"&&t.push(c[p]),Ji({...r,app:{name:an[p],arguments:t}})}throw new Error(`${l.name} is not supported as a default browser`)}let n,i=[],s={};if(mi==="darwin")n="open",r.wait&&i.push("--wait-apps"),r.background&&i.push("--background"),r.newInstance&&i.push("--new"),e&&i.push("-a",e);else if(mi==="win32"||sn&&!gi()&&!e){n=await _f(),i.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),sn||(s.windowsVerbatimArguments=!0);let f=["Start"];r.wait&&f.push("-Wait"),e?(f.push(`"\`"${e}\`""`),r.target&&t.push(r.target)):r.target&&f.push(`"${r.target}"`),t.length>0&&(t=t.map(c=>`"\`"${c}\`""`),f.push("-ArgumentList",t.join(","))),r.target=Cf.Buffer.from(f.join(" "),"utf16le").toString("base64")}else{if(e)n=e;else{let f=!Tf||Tf==="/",c=!1;try{await No.default.access(tp,No.constants.X_OK),c=!0}catch{}n=Of.default.versions.electron??(mi==="android"||f||!c)?"xdg-open":tp}t.length>0&&i.push(...t),r.wait||(s.stdio="ignore",s.detached=!0)}mi==="darwin"&&t.length>0&&i.push("--args",...t),r.target&&i.push(r.target);let a=kf.default.spawn(n,i,s);return r.wait?new Promise((f,c)=>{a.once("error",c),a.once("close",l=>{if(!r.allowNonzeroExitCode&&l>0){c(new Error(`Exited with code ${l}`));return}f(a)})}):(a.unref(),a)},ew=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a `target`");return Ji({...e,target:r})},tw=(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 Ji({...e,app:{name:r,arguments:t}})};an={};on(an,"chrome",()=>Mo({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"]}}));on(an,"brave",()=>Mo({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"]}}));on(an,"firefox",()=>Mo({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));on(an,"edge",()=>Mo({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));on(an,"browser",()=>"browser");on(an,"browserPrivate",()=>"browserPrivate");rw=ew});var xr=he(require("fs")),ds=he(require("path"));var Xf=he(require("os")),Zf=he(require("path")),ls=he(require("fs"));function hs(){let r=Zf.join(Xf.homedir(),".termiq");return ls.existsSync(r)||ls.mkdirSync(r,{recursive:!0,mode:448}),r}var Si=class{filePath;data={};constructor(){this.filePath=ds.join(hs(),"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(xr.existsSync(this.filePath)){let e=xr.readFileSync(this.filePath,"utf-8");this.data=JSON.parse(e)}}catch{this.data={}}}save(){let e=ds.dirname(this.filePath);xr.existsSync(e)||xr.mkdirSync(e,{recursive:!0,mode:448}),xr.writeFileSync(this.filePath,JSON.stringify(this.data,null,2),{mode:384})}};var Tr=he(require("fs")),ps=he(require("path"));var lg={serverUrl:"https://termiq.io",agentName:"",multiViewer:!1,signalWaiting:!0},xi=class{config;filePath;constructor(e){this.filePath=ps.join(hs(),"config.json"),this.config={...lg,...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()}getSignalWaiting(){return this.config.signalWaiting}async setSignalWaiting(e){this.config.signalWaiting=e,this.saveToFile()}async setAgentName(e){this.config.agentName=e,this.saveToFile()}loadFromFile(){try{if(Tr.existsSync(this.filePath)){let e=Tr.readFileSync(this.filePath,"utf-8");return JSON.parse(e)}}catch{}return{}}saveToFile(){let e=ps.dirname(this.filePath);Tr.existsSync(e)||Tr.mkdirSync(e,{recursive:!0,mode:448}),Tr.writeFileSync(this.filePath,JSON.stringify(this.config,null,2))}};var St=he(require("fs")),af=he(require("path")),Ad=he(require("os")),Ro=he(pi()),Bb="cli",of=af.join(Ad.homedir(),".termiq","logs"),nn=af.join(of,"cli.log"),jb=5*1024*1024,kd=3;function Ub(){try{if(!St.existsSync(nn)||St.statSync(nn).size<jb)return;for(let e=kd-1;e>=1;e--){let t=`${nn}.${e}`,n=`${nn}.${e+1}`;St.existsSync(t)&&(e+1>kd?St.unlinkSync(t):St.renameSync(t,n))}St.renameSync(nn,`${nn}.1`)}catch{}}function qb(r){try{St.existsSync(of)||St.mkdirSync(of,{recursive:!0}),Ub(),St.appendFileSync(nn,r+`
|
|
140
|
+
`,{encoding:"utf8"})}catch{}}var zi=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 nn}write(e,t,n){if(!(0,Ro.shouldLog)(e,this.level))return;let i=(0,Ro.formatLogLine)(e,Bb,t,n);this.toFile?qb(i):process.stderr.write(i+`
|
|
141
|
+
`)}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 Rd=he(require("os")),Id=he(ff()),Xi=class{cachedId=null;name;constructor(e){this.name=e||Rd.hostname()||"CLI"}async getMachineId(){if(this.cachedId)return this.cachedId;try{this.cachedId=(0,Id.machineIdSync)()}catch{this.cachedId=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}return this.cachedId}getMachineName(){return this.name}};var Zi=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 es=class{async openUrl(e){let{default:t}=await Promise.resolve().then(()=>(cp(),ap));await t(e)}};var fp=he(require("fs")),Af=he(require("path"));function Do(r){let e=r?[r]:[Af.join(__dirname,"..","package.json"),Af.join(__dirname,"..","..","package.json")];for(let t of e)try{let n=JSON.parse(fp.readFileSync(t,"utf8"));if(typeof n.version=="string"&&n.version.length>0)return n.version}catch{}return"unknown"}function up(r,e){for(let t=0;t<r.length;t++){let n=r[t];if(n.startsWith("-")){e.has(n)&&t++;continue}return n}}var Rf=new Set(["--cid","--token","--server","--log-level"]),lp=new Set(["--help","-h","--version","-V","--verbose","-v","--watch","-w","--log-to-file","--statusline","--multi-viewer","--push-prompt-text","--no-signal-waiting","--force"]);function hp(r,e,t){for(let n=0;n<r.length;n++){let i=r[n];if(!i.startsWith("-"))continue;let s=i.includes("=")?i.slice(0,i.indexOf("=")):i;if(e.has(s)||t.has(s)){e.has(s)&&!i.includes("=")&&n++;continue}return i}}var Wp=he(require("path")),dt=he(pi()),Hp=he(Rr());var dp=he(require("os")),pp=require("crypto"),gp=he(require("node-pty")),nr=he(pi()),Fo=class r{ptyProcess=null;outputBuffer=new nr.CircularBuffer(100);altScreenActive=!1;streamId=null;logger;onOutput=null;onExit=null;shellLaunch=null;agentExits=new nr.AgentExitTracker;onAgentEnd=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 n=process.env.SHELL||(dp.platform()==="win32"?"powershell.exe":"/bin/bash"),i=process.stdout.columns||80,s=process.stdout.rows||24,a=Math.max(1,s-t);this.reservedBottomRows=t,this.shellLaunch?.dispose(),this.shellLaunch=(0,nr.prepareShellLaunch)(n,{...process.env,TERMIQ_SESSION_ACTIVE:"1"}),this.agentExits=new nr.AgentExitTracker({nonce:this.shellLaunch.nonce}),this.ptyProcess=gp.spawn(n,this.shellLaunch.args,{name:"xterm-256color",cols:i,rows:a,cwd:e,env:this.shellLaunch.env}),this.onResize?.(i,a),this.streamId=(0,pp.randomUUID)();let f=`cli_${this.ptyProcess.pid}`;return this.ptyProcess.onData(c=>{this.altScreenActive=(0,nr.trackAltScreen)(c,this.altScreenActive),this.preWriteHook?.(c),process.stdout.write(c),this.outputBuffer.append(c),this.onOutput?.(c);for(let l of this.agentExits.processOutput(c))this.onAgentEnd?.(l)}),this.ptyProcess.onExit(({exitCode:c,signal:l})=>{this.logger.info("Shell exited",String(c),{signal:l}),this.shellLaunch?.dispose(),this.onExit?.({exitCode:c,signal:l})}),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",c=>{let l=c.toString();this.multiViewerMode&&!(0,nr.isTerminalReplyOnly)(l)&&this.maybeClaimLocalControl(),this.onLocalInput?.(l),this.ptyProcess?.write(l)}),this.sigwinchListener=()=>{let c=process.stdout.columns||80,l=Math.max(1,(process.stdout.rows||24)-this.reservedBottomRows);if(this.multiViewerMode){this.logger.info("Local resize claims control",{cols:c,rows:l}),this.resize(c,l),this.onLocalClaim?.(c,l);return}if(this.desiredCols!==null&&this.desiredRows!==null){this.logger.info("Local resize ignored (PWA desired-size set)",{host:{cols:c,rows:l},desired:{cols:this.desiredCols,rows:this.desiredRows}});return}if(!this.sigwinchEnabled){this.logger.info("Local resize ignored (PWA viewers attached)",{cols:c,rows:l});return}this.logger.info("Local resize applied",{cols:c,rows:l}),this.ptyProcess?.resize(c,l),this.onResize?.(c,l)},process.platform==="win32"?process.stdout.on("resize",this.sigwinchListener):process.on("SIGWINCH",this.sigwinchListener),this.logger.info("Shell spawned",n,f,{shellIntegration:this.shellLaunch.kind??"none"}),f}write(e,t=!1){if(this.ptyProcess){if(!t&&!this.draining){this.ptyProcess.write(e);return}for(let n of e)this.writeQueue.push(n);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){if(this.desiredCols=e,this.desiredRows=t,this.ptyProcess&&this.ptyProcess.cols===e&&this.ptyProcess.rows===t){this.cancelRebroadcast();return}this.ptyProcess?.resize(e,t),this.onResize?.(e,t),this.cancelRebroadcast();for(let n of r.REBROADCAST_DELAYS_MS)this.rebroadcastTimers.push(setTimeout(()=>{this.ptyProcess&&(this.desiredCols!==e||this.desiredRows!==t||this.ptyProcess.cols===e&&this.ptyProcess.rows===t||this.ptyProcess.resize(e,t))},n))}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(){let e=this.outputBuffer.getContent();return this.altScreenActive?`\x1B[?1049h${e}`:e}isAltScreen(){return this.altScreenActive}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}setOnAgentEnd(e){this.onAgentEnd=e}isAlive(){return this.ptyProcess!==null}kill(){this.ptyProcess?.kill(),this.ptyProcess=null}dispose(){this.kill(),this.shellLaunch?.dispose(),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 cn=he(require("path")),_i=he(require("fs"));var Rp=require("node:events"),Ip=require("node:fs"),Vo=require("node:fs/promises"),xe=he(require("node:path"),1);var Ur=require("node:fs/promises"),qr=require("node:path"),Ep=require("node:stream"),Mt={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},If={root:".",fileFilter:r=>!0,directoryFilter:r=>!0,type:Mt.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(If);var bp="READDIRP_RECURSIVE_ERROR",iw=new Set(["ENOENT","EPERM","EACCES","ELOOP",bp]),mp=[Mt.DIR_TYPE,Mt.EVERYTHING_TYPE,Mt.FILE_DIR_TYPE,Mt.FILE_TYPE],sw=new Set([Mt.DIR_TYPE,Mt.EVERYTHING_TYPE,Mt.FILE_DIR_TYPE]),ow=new Set([Mt.EVERYTHING_TYPE,Mt.FILE_DIR_TYPE,Mt.FILE_TYPE]),aw=r=>iw.has(r.code),cw=process.platform==="win32",yp=r=>!0,_p=r=>{if(r===void 0)return yp;if(typeof r=="function")return r;if(typeof r=="string"){let e=r.trim();return t=>t.basename===e}if(Array.isArray(r)){let e=r.map(t=>t.trim());return t=>e.some(n=>t.basename===n)}return yp},Lf=class extends Ep.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={...If,...e},{root:n,type:i}=t;this._fileFilter=_p(t.fileFilter),this._directoryFilter=_p(t.directoryFilter);let s=t.lstat?Ur.lstat:Ur.stat;cw?this._stat=a=>s(a,{bigint:!0}):this._stat=s,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:If.depth,this._wantsDir=i?sw.has(i):!1,this._wantsFile=i?ow.has(i):!1,this._wantsEverything=i===Mt.EVERYTHING_TYPE,this._root=(0,qr.resolve)(n),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:i,depth:s}=t,a=n.splice(0,e).map(c=>this._formatEntry(c,i)),f=await Promise.all(a);for(let c of f){if(!c)continue;if(this.destroyed)return;let l=await this._getEntryType(c);l==="directory"&&this._directoryFilter(c)?(s<=this._maxDepth&&this.parents.push(this._exploreDir(c.fullPath,s+1)),this._wantsDir&&(this.push(c),e--)):(l==="file"||this._includeAsFile(c))&&this._fileFilter(c)&&this._wantsFile&&(this.push(c),e--)}}else{let i=this.parents.pop();if(!i){this.push(null);break}if(this.parent=await i,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await(0,Ur.readdir)(e,this._rdOptions)}catch(i){this._onError(i)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n,i=this._isDirent?e.name:e;try{let s=(0,qr.resolve)((0,qr.join)(t,i));n={path:(0,qr.relative)(this._root,s),fullPath:s,basename:i},n[this._statsProp]=this._isDirent?e:await this._stat(s)}catch(s){this._onError(s);return}return n}_onError(e){aw(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return"";let t=e[this._statsProp];if(t.isFile())return"file";if(t.isDirectory())return"directory";if(t&&t.isSymbolicLink()){let n=e.fullPath;try{let i=await(0,Ur.realpath)(n),s=await(0,Ur.lstat)(i);if(s.isFile())return"file";if(s.isDirectory()){let a=i.length;if(n.startsWith(i)&&n.substr(a,1)===qr.sep){let f=new Error(`Circular symlink detected: "${n}" points to "${i}"`);return f.code=bp,this._onError(f)}return"directory"}}catch(i){return this._onError(i),""}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function wp(r,e={}){let t=e.entryType||e.type;if(t==="both"&&(t=Mt.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&&!mp.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${mp.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=r,new Lf(e)}var Dn=require("node:fs"),sr=require("node:fs/promises"),Sp=require("node:os"),Ye=he(require("node:path"),1),fw="data",Df="end",xp="close",Ko=()=>{};var Wo=process.platform,Ff=Wo==="win32",uw=Wo==="darwin",lw=Wo==="linux",hw=Wo==="freebsd",Tp=(0,Sp.type)()==="OS400",Ze={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},ir=Ze,dw="watch",pw={lstat:sr.lstat,stat:sr.stat},Mn="listeners",Bo="errHandlers",yi="rawEmitters",gw=[Mn,Bo,yi],mw=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"]),yw=r=>mw.has(Ye.extname(r).slice(1).toLowerCase()),Mf=(r,e)=>{r instanceof Set?r.forEach(e):e(r)},ts=(r,e,t)=>{let n=r[e];n instanceof Set||(r[e]=n=new Set([n])),n.add(t)},_w=r=>e=>{let t=r[e];t instanceof Set?t.clear():delete r[e]},rs=(r,e,t)=>{let n=r[e];n instanceof Set?n.delete(t):n===t&&delete r[e]},Op=r=>r instanceof Set?r.size===0:!r,jo=new Map;function vp(r,e,t,n,i){let s=(a,f)=>{t(r),i(a,f,{watchedPath:r}),f&&r!==f&&Uo(Ye.resolve(r,f),Mn,Ye.join(r,f))};try{return(0,Dn.watch)(r,{persistent:e.persistent},s)}catch(a){n(a);return}}var Uo=(r,e,t,n,i)=>{let s=jo.get(r);s&&Mf(s[e],a=>{a(t,n,i)})},Ew=(r,e,t,n)=>{let{listener:i,errHandler:s,rawEmitter:a}=n,f=jo.get(e),c;if(!t.persistent)return c=vp(r,t,i,s,a),c?c.close.bind(c):void 0;if(f)ts(f,Mn,i),ts(f,Bo,s),ts(f,yi,a);else{if(c=vp(r,t,Uo.bind(null,e,Mn),s,Uo.bind(null,e,yi)),!c)return;c.on(ir.ERROR,async l=>{let p=Uo.bind(null,e,Bo);if(f&&(f.watcherUnusable=!0),Ff&&l.code==="EPERM")try{await(await(0,sr.open)(r,"r")).close(),p(l)}catch{}else p(l)}),f={listeners:i,errHandlers:s,rawEmitters:a,watcher:c},jo.set(e,f)}return()=>{rs(f,Mn,i),rs(f,Bo,s),rs(f,yi,a),Op(f.listeners)&&(f.watcher.close(),jo.delete(e),gw.forEach(_w(f)),f.watcher=void 0,Object.freeze(f))}},Nf=new Map,bw=(r,e,t,n)=>{let{listener:i,rawEmitter:s}=n,a=Nf.get(e),f=a&&a.options;return f&&(f.persistent<t.persistent||f.interval>t.interval)&&((0,Dn.unwatchFile)(e),a=void 0),a?(ts(a,Mn,i),ts(a,yi,s)):(a={listeners:i,rawEmitters:s,options:t,watcher:(0,Dn.watchFile)(e,t,(c,l)=>{Mf(a.rawEmitters,m=>{m(ir.CHANGE,e,{curr:c,prev:l})});let p=c.mtimeMs;(c.size!==l.size||p>l.mtimeMs||p===0)&&Mf(a.listeners,m=>m(r,c))})},Nf.set(e,a)),()=>{rs(a,Mn,i),rs(a,yi,s),Op(a.listeners)&&(Nf.delete(e),(0,Dn.unwatchFile)(e),a.options=a.watcher=void 0,Object.freeze(a))}},qo=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,i=Ye.dirname(e),s=Ye.basename(e);this.fsw._getWatchedDir(i).add(s);let f=Ye.resolve(e),c={persistent:n.persistent};t||(t=Ko);let l;if(n.usePolling){let p=n.interval!==n.binaryInterval;c.interval=p&&yw(s)?n.binaryInterval:n.interval,l=bw(e,f,c,{listener:t,rawEmitter:this.fsw._emitRaw})}else l=Ew(e,f,c,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return l}_handleFile(e,t,n){if(this.fsw.closed)return;let i=Ye.dirname(e),s=Ye.basename(e),a=this.fsw._getWatchedDir(i),f=t;if(a.has(s))return;let c=async(p,m)=>{if(this.fsw._throttle(dw,e,5)){if(!m||m.mtimeMs===0)try{let _=await(0,sr.stat)(e);if(this.fsw.closed)return;let b=_.atimeMs,x=_.mtimeMs;if((!b||b<=x||x!==f.mtimeMs)&&this.fsw._emit(ir.CHANGE,e,_),(uw||lw||hw)&&f.ino!==_.ino){this.fsw._closeFile(p),f=_;let O=this._watchWithNodeFs(e,c);O&&this.fsw._addPathCloser(p,O)}else f=_}catch{this.fsw._remove(i,s)}else if(a.has(s)){let _=m.atimeMs,b=m.mtimeMs;(!_||_<=b||b!==f.mtimeMs)&&this.fsw._emit(ir.CHANGE,e,m),f=m}}},l=this._watchWithNodeFs(e,c);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(ir.ADD,e,0))return;this.fsw._emit(ir.ADD,e,t)}return l}async _handleSymlink(e,t,n,i){if(this.fsw.closed)return;let s=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let f;try{f=await(0,sr.realpath)(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(i)?this.fsw._symlinkPaths.get(s)!==f&&(this.fsw._symlinkPaths.set(s,f),this.fsw._emit(ir.CHANGE,n,e.stats)):(a.add(i),this.fsw._symlinkPaths.set(s,f),this.fsw._emit(ir.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(s))return!0;this.fsw._symlinkPaths.set(s,!0)}_handleRead(e,t,n,i,s,a,f){e=Ye.join(e,"");let c=i?`${e}:${i}`:e;if(f=this.fsw._throttle("readdir",c,1e3),!f)return;let l=this.fsw._getWatchedDir(n.path),p=new Set,m=this.fsw._readdirp(e,{fileFilter:_=>n.filterPath(_),directoryFilter:_=>n.filterDir(_)});if(m)return m.on(fw,async _=>{if(this.fsw.closed){m=void 0;return}let b=_.path,x=Ye.join(e,b);if(p.add(b),!(_.stats.isSymbolicLink()&&await this._handleSymlink(_,e,x,b))){if(this.fsw.closed){m=void 0;return}(b===i||!i&&!l.has(b))&&(this.fsw._incrReadyCount(),x=Ye.join(s,Ye.relative(s,x)),this._addToNodeFs(x,t,n,a+1))}}).on(ir.ERROR,this._boundHandleError),new Promise((_,b)=>{if(!m)return b();m.once(Df,()=>{if(this.fsw.closed){m=void 0;return}let x=f?f.clear():!1;_(void 0),l.getChildren().filter(O=>O!==e&&!p.has(O)).forEach(O=>{this.fsw._remove(e,O)}),m=void 0,x&&this._handleRead(e,!1,n,i,s,a,f)})})}async _handleDir(e,t,n,i,s,a,f){let c=this.fsw._getWatchedDir(Ye.dirname(e)),l=c.has(Ye.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!s&&!l&&this.fsw._emit(ir.ADD_DIR,e,t),c.add(Ye.basename(e)),this.fsw._getWatchedDir(e);let p,m,_=this.fsw.options.depth;if((_==null||i<=_)&&!this.fsw._symlinkPaths.has(f)){if(!s&&(await this._handleRead(e,n,a,s,e,i,p),this.fsw.closed))return;m=this._watchWithNodeFs(e,(b,x)=>{x&&x.mtimeMs===0||this._handleRead(b,!1,a,s,e,i,p)})}return m}async _addToNodeFs(e,t,n,i,s){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let f=this.fsw._getWatchHelpers(e);n&&(f.filterPath=c=>n.filterPath(c),f.filterDir=c=>n.filterDir(c));try{let c=await pw[f.statMethod](f.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(f.watchPath,c))return a(),!1;let l=this.fsw.options.followSymlinks,p;if(c.isDirectory()){let m=Ye.resolve(e),_=l?await(0,sr.realpath)(e):e;if(this.fsw.closed||(p=await this._handleDir(f.watchPath,c,t,i,s,f,_),this.fsw.closed))return;m!==_&&_!==void 0&&this.fsw._symlinkPaths.set(m,_)}else if(c.isSymbolicLink()){let m=l?await(0,sr.realpath)(e):e;if(this.fsw.closed)return;let _=Ye.dirname(f.watchPath);if(this.fsw._getWatchedDir(_).add(f.watchPath),this.fsw._emit(ir.ADD,f.watchPath,c),p=await this._handleDir(_,c,t,i,e,f,m),this.fsw.closed)return;m!==void 0&&this.fsw._symlinkPaths.set(Ye.resolve(e),m)}else p=this._handleFile(f.watchPath,c,t);return a(),p&&this.fsw._addPathCloser(e,p),!1}catch(c){if(this.fsw._handleError(c))return a(),e}}};var Bf="/",ww="//",Lp=".",vw="..",Sw="string",xw=/\\/g,Np=/\/\//g,Tw=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Ow=/^\.[/\\]/;function Ho(r){return Array.isArray(r)?r:[r]}var jf=r=>typeof r=="object"&&r!==null&&!(r instanceof RegExp);function Cw(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=xe.relative(r.path,e);return t?!t.startsWith("..")&&!xe.isAbsolute(t):!1}return!1}:()=>!1}function Pw(r){if(typeof r!="string")throw new Error("string expected");r=xe.normalize(r),r=r.replace(/\\/g,"/");let e=!1;return r.startsWith("//")&&(e=!0),r=r.replace(Np,"/"),e&&(r="/"+r),r}function Cp(r,e,t){let n=Pw(e);for(let i=0;i<r.length;i++){let s=r[i];if(s(n,t))return!0}return!1}function kw(r,e){if(r==null)throw new TypeError("anymatch: specify first argument");let n=Ho(r).map(i=>Cw(i));return e==null?(i,s)=>Cp(n,i,s):Cp(n,e)}var Pp=r=>{let e=Ho(r).flat();if(!e.every(t=>typeof t===Sw))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Mp)},kp=r=>{let e=r.replace(xw,Bf),t=!1;return e.startsWith(ww)&&(t=!0),e=e.replace(Np,Bf),t&&(e=Bf+e),e},Mp=r=>kp(xe.normalize(kp(r))),Ap=(r="")=>e=>typeof e=="string"?Mp(xe.isAbsolute(e)?e:xe.join(r,e)):e,Aw=(r,e)=>xe.isAbsolute(r)?r:xe.join(e,r),Rw=Object.freeze(new Set),Uf=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!==Lp&&e!==vw&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await(0,Vo.readdir)(n)}catch{this._removeWatcher&&this._removeWatcher(xe.dirname(n),xe.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=Ko,this.items=Rw,Object.freeze(this)}},Iw="stat",Lw="lstat",qf=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,t,n){this.fsw=n;let i=e;this.path=e=e.replace(Ow,""),this.watchPath=i,this.fullWatchPath=xe.resolve(i),this.dirParts=[],this.dirParts.forEach(s=>{s.length>1&&s.pop()}),this.followSymlinks=t,this.statMethod=t?Iw:Lw}entryPath(e){return xe.join(this.watchPath,xe.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Kf=class extends Rp.EventEmitter{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},i={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?Ho(e.ignored):Ho([]),awaitWriteFinish:t===!0?n:typeof t=="object"?{...n,...t}:!1};Tp&&(i.usePolling=!0),i.atomic===void 0&&(i.atomic=!i.usePolling);let s=process.env.CHOKIDAR_USEPOLLING;if(s!==void 0){let c=s.toLowerCase();c==="false"||c==="0"?i.usePolling=!1:c==="true"||c==="1"?i.usePolling=!0:i.usePolling=!!c}let a=process.env.CHOKIDAR_INTERVAL;a&&(i.interval=Number.parseInt(a,10));let f=0;this._emitReady=()=>{f++,f>=this._readyCount&&(this._emitReady=Ko,this._readyEmitted=!0,process.nextTick(()=>this.emit(Ze.READY)))},this._emitRaw=(...c)=>this.emit(Ze.RAW,...c),this._boundRemove=this._remove.bind(this),this.options=i,this._nodeFsHandler=new qo(this),Object.freeze(i)}_addIgnoredPath(e){if(jf(e)){for(let t of this._ignoredPaths)if(jf(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)jf(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:i}=this.options;this.closed=!1,this._closePromise=void 0;let s=Pp(e);return i&&(s=s.map(a=>Aw(a,i))),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 f=await this._nodeFsHandler._addToNodeFs(a,!n,void 0,0,t);return f&&this._emitReady(),f})).then(a=>{this.closed||a.forEach(f=>{f&&this.add(xe.dirname(f),xe.basename(t||f))})}),this}unwatch(e){if(this.closed)return this;let t=Pp(e),{cwd:n}=this.options;return t.forEach(i=>{!xe.isAbsolute(i)&&!this._closers.has(i)&&(n&&(i=xe.join(n,i)),i=xe.resolve(i)),this._closePath(i),this._addIgnoredPath(i),this._watched.has(i)&&this._addIgnoredPath({path:i,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(n=>{let i=n();i instanceof Promise&&e.push(i)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let s=(this.options.cwd?xe.relative(this.options.cwd,n):n)||Lp;e[s]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==Ze.ERROR&&this.emit(Ze.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let i=this.options;Ff&&(t=xe.normalize(t)),i.cwd&&(t=xe.relative(i.cwd,t));let s=[t];n!=null&&s.push(n);let a=i.awaitWriteFinish,f;if(a&&(f=this._pendingWrites.get(t)))return f.lastChange=new Date,this;if(i.atomic){if(e===Ze.UNLINK)return this._pendingUnlinks.set(t,[e,...s]),setTimeout(()=>{this._pendingUnlinks.forEach((c,l)=>{this.emit(...c),this.emit(Ze.ALL,...c),this._pendingUnlinks.delete(l)})},typeof i.atomic=="number"?i.atomic:100),this;e===Ze.ADD&&this._pendingUnlinks.has(t)&&(e=Ze.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===Ze.ADD||e===Ze.CHANGE)&&this._readyEmitted){let c=(l,p)=>{l?(e=Ze.ERROR,s[0]=l,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,c),this}if(e===Ze.CHANGE&&!this._throttle(Ze.CHANGE,t,50))return this;if(i.alwaysStat&&n===void 0&&(e===Ze.ADD||e===Ze.ADD_DIR||e===Ze.CHANGE)){let c=i.cwd?xe.join(i.cwd,t):t,l;try{l=await(0,Vo.stat)(c)}catch{}if(!l||this.closed)return;s.push(l)}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(Ze.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let i=this._throttled.get(e);if(!i)throw new Error("invalid throttle");let s=i.get(t);if(s)return s.count++,!1;let a,f=()=>{let l=i.get(t),p=l?l.count:0;return i.delete(t),clearTimeout(a),l&&clearTimeout(l.timeoutObject),p};a=setTimeout(f,n);let c={timeoutObject:a,clear:f,count:0};return i.set(t,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,i){let s=this.options.awaitWriteFinish;if(typeof s!="object")return;let a=s.pollInterval,f,c=e;this.options.cwd&&!xe.isAbsolute(e)&&(c=xe.join(this.options.cwd,e));let l=new Date,p=this._pendingWrites;function m(_){(0,Ip.stat)(c,(b,x)=>{if(b||!p.has(e)){b&&b.code!=="ENOENT"&&i(b);return}let O=Number(new Date);_&&x.size!==_.size&&(p.get(e).lastChange=O);let V=p.get(e);O-V.lastChange>=t?(p.delete(e),i(void 0,x)):f=setTimeout(m,a,x)})}p.has(e)||(p.set(e,{lastChange:l,cancelWait:()=>(p.delete(e),clearTimeout(f),n)}),f=setTimeout(m,a))}_isIgnored(e,t){if(this.options.atomic&&Tw.test(e))return!0;if(!this._userIgnored){let{cwd:n}=this.options,s=(this.options.ignored||[]).map(Ap(n)),f=[...[...this._ignoredPaths].map(Ap(n)),...s];this._userIgnored=kw(f,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new qf(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=xe.resolve(e);return this._watched.has(t)||this._watched.set(t,new Uf(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let i=xe.join(e,t),s=xe.resolve(i);if(n=n??(this._watched.has(i)||this._watched.has(s)),!this._throttle("remove",i,100))return;!n&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(i).getChildren().forEach(_=>this._remove(i,_));let c=this._getWatchedDir(e),l=c.has(t);c.remove(t),this._symlinkPaths.has(s)&&this._symlinkPaths.delete(s);let p=i;if(this.options.cwd&&(p=xe.relative(this.options.cwd,i)),this.options.awaitWriteFinish&&this._pendingWrites.has(p)&&this._pendingWrites.get(p).cancelWait()===Ze.ADD)return;this._watched.delete(i),this._watched.delete(s);let m=n?Ze.UNLINK_DIR:Ze.UNLINK;l&&!this._isIgnored(i)&&this._emit(m,i),this._closePath(i)}_closePath(e){this._closeFile(e);let t=xe.dirname(e);this._getWatchedDir(t).remove(xe.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(n=>n()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n={type:Ze.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},i=wp(e,n);return this._streams.add(i),i.once(xp,()=>{i=void 0}),i.once(Df,()=>{i&&(this._streams.delete(i),i=void 0)}),i}};function Dp(r,e={}){let t=new Kf(e);return t.add(r),t}var Fp=he(Yc()),wr=he(Rr()),Nw=["**/node_modules/**","**/.git/**","**/dist/**","**/.next/**","**/.turbo/**","**/.cache/**","**/coverage/**","**/*.log"],Mw=300,$o=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,Fp.default)(),this.initializeIgnoreFilter()}initializeIgnoreFilter(){this.ignoreFilter.add(Nw);let e=cn.join(this.workspaceRoot,".gitignore");try{if(_i.existsSync(e)){let t=_i.readFileSync(e,"utf-8");this.ignoreFilter.add(t)}}catch{}}onFileChanged(e){this.onFileChangedCallback=e}start(){this.watcher||(this.watcher=Dp(this.workspaceRoot,{ignored:e=>{let t=cn.relative(this.workspaceRoot,e);if(!t||t===".")return!1;let n=t.split(cn.sep).join("/");return this.ignoreFilter.ignores(n)},persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:200,pollInterval:50}}),this.watcher.on("add",e=>this.handleEvent(e,wr.FileChangeType.CREATE)),this.watcher.on("change",e=>this.handleEvent(e,wr.FileChangeType.MODIFY)),this.watcher.on("unlink",e=>this.handleEvent(e,wr.FileChangeType.DELETE)),this.watcher.on("error",e=>this.logger.error("File watcher error",e)),this.logger.info("File watcher started"))}stop(){this.watcher?.close(),this.watcher=null;for(let e of this.pendingEvents.values())clearTimeout(e);this.pendingEvents.clear(),this.pendingTypes.clear()}handleEvent(e,t){let n=cn.relative(this.workspaceRoot,e);if(!n)return;let i=this.pendingEvents.get(n);i&&clearTimeout(i);let s=this.pendingTypes.get(n);this.pendingTypes.set(n,this.mergeTypes(s,t));let a=setTimeout(()=>{this.emit(n,this.pendingTypes.get(n)||t),this.pendingEvents.delete(n),this.pendingTypes.delete(n)},Mw);this.pendingEvents.set(n,a)}mergeTypes(e,t){return e?t===wr.FileChangeType.DELETE||e===wr.FileChangeType.DELETE?wr.FileChangeType.DELETE:e===wr.FileChangeType.CREATE?wr.FileChangeType.CREATE:t:t}emit(e,t){let n={path:e,changeType:t,timestamp:new Date().toISOString(),source:"watcher"};if(t!==wr.FileChangeType.DELETE)try{let i=cn.join(this.workspaceRoot,e),s=_i.statSync(i);n.size=s.size}catch{}this.onFileChangedCallback?.(n)}dispose(){this.stop(),this.onFileChangedCallback=null}};var Dw={online:!1,viewerCount:0},Go=class r{enabled=!1;state={...Dw};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(),n=`\x1B[1;${e-1}r\x1B7\x1B[${e};1H\x1B[2K${t}\x1B8`;process.stdout.write(n)}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 ")+" "}};var Bp=he(pi()),Fw=3e3;async function jp(r,e,t=Fw){if(!(0,Bp.isSessionCrash)(r))return!1;let n,i=new Promise(s=>{n=setTimeout(s,t)});return await Promise.race([e().catch(()=>{}),i]),clearTimeout(n),!0}async function zo(r,e,t,n){if(n)return process.stderr.write(`Logging in with API key...
|
|
38
142
|
`),await r.loginWithApiKey(n)?(process.stderr.write(`Login successful.
|
|
39
143
|
`),!0):(process.stderr.write(`Login failed. Check your API key.
|
|
40
144
|
`),!1);try{let i=await r.startDeviceCodeFlow();process.stderr.write(`
|
|
@@ -47,22 +151,23 @@ tell application "System Events" to get value of property list item "CFBundleNam
|
|
|
47
151
|
`),!0):(process.stderr.write(` Login failed or expired.
|
|
48
152
|
|
|
49
153
|
`),!1)}catch(i){return t.error("Login error",i),process.stderr.write(`Login error: ${i instanceof Error?i.message:String(i)}
|
|
50
|
-
`),!1}}var
|
|
51
|
-
`);let T=new
|
|
52
|
-
`),await
|
|
53
|
-
`),
|
|
54
|
-
`),
|
|
55
|
-
`),process.exit(1)}let tt=
|
|
56
|
-
|
|
57
|
-
`),
|
|
58
|
-
`),
|
|
59
|
-
`)}async function
|
|
154
|
+
`),!1}}var ns=he(Rr());function Bw(r){switch(r){case"numbered-choice":return"select";case"free-input":return"input";default:return"confirmation"}}function Up(r,e,t,n){let i=new Date().toISOString();switch(r){case"working":return e==="idle"?{type:ns.TerminalEventType.SESSION_START,timestamp:i}:null;case"waiting":return{type:ns.TerminalEventType.WAITING_INPUT,timestamp:i,promptType:Bw(t?.type),...n&&{source:n}};case"completed":return{type:ns.TerminalEventType.SESSION_END,timestamp:i,status:"success"};case"error":return{type:ns.TerminalEventType.SESSION_END,timestamp:i,status:"error"};default:return null}}var qp=require("crypto");function Kp(){return`cli_${(0,qp.randomUUID)()}`}async function Vp(r){let{storage:e,config:t,logger:n,machineId:i,notification:s,browser:a,cwd:f,watch:c,statusLine:l,multiViewer:p,signalWaiting:m=!0,apiKey:_}=r,b=new Go(n);l&&b.enable();let x=t.getServerUrl(),O=new URL(x).host,V=await i.getMachineId(),ie=new dt.CryptoService(e,n,O,V);await ie.initialize();let z=await ie.getShortFingerprint();process.stderr.write(`Agent fingerprint: ${z} (verify in the web app; run 'termiq fingerprint' for the full safety number)
|
|
155
|
+
`);let T=new dt.AuthService(e,ie,i,t,n,s,a,O,V),D=await T.hasValidToken();D||await T.refreshAccessToken()||(process.stderr.write(`Not logged in. Starting login flow...
|
|
156
|
+
`),await zo(T,a,n,_)||process.exit(1),D=!0);let te;try{let{machineIdSync:B}=await Promise.resolve().then(()=>he(ff()));te=B()}catch{te=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}let q,ee=new dt.StatusDetector((B,oe,Ue)=>{if(!K.getStatus().connected)return;let nt=q;q=oe,K.updateStatus({instanceId:Te,terminalId:B,status:oe,encryptedPrompt:Ue&&ie.encryptPromptInfo(Ue)||void 0}).catch(()=>{});let bt=Up(oe,nt,Ue,ee.getWaitingSource(B)??void 0);bt&&K.sendTerminalEvent(Te,B,bt)},B=>{n.warn("Detector drift: agent announced waiting, parser did not see it",{terminalId:B})},{signalWaiting:m}),pe=p?[Hp.Capability.MULTI_VIEWER_RENDER]:[],K=new dt.WebSocketService(T,ie,t,n,s,te,"cli",pe);p&&n.info("Multi-viewer rendering capability advertised");let Me=!1;K.onStatusChange(B=>{if(B==="connected"){if(Me)n.info("Reconnected to termiq.io");else{let oe=p?" (multi-viewer mode)":"";process.stderr.write(`Connected to termiq.io${oe}
|
|
157
|
+
`),Me=!0}b.update({online:!0})}else B==="disconnected"?(n.info("Disconnected from termiq.io (will retry)"),b.update({online:!1})):B==="error"&&(n.warn("Connection degraded (no server response) \u2014 reconnecting"),b.update({online:!1}))}),K.onAuthFailure(()=>{process.stderr.write(`Session expired. Please run "termiq login" again.
|
|
158
|
+
`),Ae(),process.exit(1)});try{await K.connect()}catch(B){process.stderr.write(`Connection failed: ${B instanceof Error?B.message:String(B)}
|
|
159
|
+
`),process.exit(1)}let tt=Wp.basename(f),Te=Kp(),De=ie.encryptWorkspaceInfo({name:tt,path:f});await K.registerWorkspace({instanceId:Te,encryptedInfo:De||void 0});let ve=new Fo(n);p&&ve.setMultiViewerMode(!0),ve.setPreWriteHook(B=>b.inspectPtyOutput(B));let We=null;ve.setOnResize((B,oe)=>{b.update({ptyCols:B,ptyRows:oe}),p&&We&&K.sendPtyResized(Te,We,B,oe)}),ve.setOnLocalClaim((B,oe)=>{p&&We&&K.sendClaimControl(Te,We,B,oe)});let _e=ve.spawn(f,b.reservedRows()),rt=`CLI: ${tt}`,Fe=process.env.SHELL||"/bin/bash",Et=ie.encryptTerminalInfo({name:rt,command:Fe,cwd:f});await K.terminalCreated({instanceId:Te,terminalId:_e,encryptedInfo:Et||void 0,streamId:ve.getStreamId()??void 0}),We=_e,p&&K.sendPtyResized(Te,_e,ve.getPtyCols(),ve.getPtyRows());let He=new dt.FileTransferService(n,"/tmp",f);He.setCrypto(ie);let pt=new dt.FileTrackerService(n,f),N=new dt.FileListService(n,f),j=c?new $o(n,f):null,L=K.getSocket();L&&He.attach(L,Te),pt.onFileChanged((B,oe)=>{K.sendFileChangedEvent(Te,B,oe)}),pt.onFileViewTransfer(async(B,oe,Ue)=>{try{await He.sendBuffer(B,oe,Ue.path.split("/").pop()||"view",Ue.mimeType||"text/plain",{purpose:"view",viewMetadata:Ue})}catch(nt){n.error("File view transfer failed",nt)}}),K.onFileViewRequest((B,oe)=>{pt.handleViewRequest(B,oe)}),K.onFileListRequest((B,oe)=>{N.handleListRequest(oe)}),N.onResponse(B=>{K.sendFileListResponse(Te,B)}),K.onFileDownloadRequest(async(B,oe,Ue)=>{try{await He.sendFile(B,oe,void 0,void 0,Ue)}catch(nt){n.error("File download failed",nt)}}),j&&(j.onFileChanged(B=>{K.sendFileChangedEvent(Te,_e,B)}),j.start()),ee.startTracking(_e),ve.setOnOutput(B=>{K.sendOutput(Te,_e,B),ee.processOutput(_e,B),pt.processOutput(_e,B)}),ve.setOnAgentEnd(B=>{n.info("Agent command ended",B),ee.agentEnded(_e,B.failed)}),ve.setOnLocalInput(B=>{(0,dt.isAnswerKeystroke)(B)&&ee.resolvePrompt(_e)}),K.onInput((B,oe,Ue,nt,bt)=>{if(B===_e){if(bt){let zt=ee.getEmittedPromptKey(_e);if(zt&&zt!==bt){n.warn("Stale answer rejected \u2014 prompt changed",{terminalId:_e}),ee.reEmitPrompt(_e);return}}(0,dt.isAnswerKeystroke)(oe)&&ee.resolvePrompt(_e),ve.write(oe,nt)}}),K.setTerminalActiveCheck(B=>B===_e&&ve.isAlive()),K.onResizeRequest((B,oe,Ue)=>{B===_e&&(n.info("Remote resize received",{terminalId:B,cols:oe,rows:Ue}),ve.resize(oe,Ue))}),K.onClientAttached(({clientCount:B})=>{ve.setSigwinchEnabled(!1),b.update({viewerCount:B}),K.sendInputResume(_e)}),K.onClientDetached(({clientCount:B})=>{B===0&&ve.setSigwinchEnabled(!0),b.update({viewerCount:B})}),K.onGetBufferRequest(B=>B===_e?ve.getBuffer():null),K.onRedrawRequest(B=>{B===_e&&ve.redrawNoResize()});async function se(){let B=ie.encryptWorkspaceInfo({name:tt,path:f});await K.registerWorkspace({instanceId:Te,encryptedInfo:B||void 0});let oe=ie.encryptTerminalInfo({name:rt,command:Fe,cwd:f});await K.terminalCreated({instanceId:Te,terminalId:_e,encryptedInfo:oe||void 0,streamId:ve.getStreamId()??void 0})}K.onMetaSessionEstablished(B=>{B&&se().catch(oe=>{n.error("Failed to re-register metadata after meta session",oe)}),ee.resendWaitingPrompts()}),K.onReconnect(async()=>{try{await se();let B=K.getSocket();B&&He.attach(B,Te)}catch(B){n.error("Failed to re-register on reconnect",B)}});function Ae(){j?.dispose(),He.detach(),pt.dispose(),N.dispose(),ee.stopTracking(_e),ee.dispose(),K.disposeInputStream(_e),K.terminalClosed({instanceId:Te,terminalId:_e}).catch(()=>{}),K.unregisterWorkspace(Te).catch(()=>{}),K.disconnect(),ve.dispose()}ve.setOnExit(async B=>{b.disable();let oe=await jp(B,()=>K.updateStatus({instanceId:Te,terminalId:_e,status:"error"}));process.stderr.write(oe?`Session ended: the shell was killed (signal ${B.signal}).
|
|
160
|
+
`:`Session ended.
|
|
161
|
+
`),Ae(),process.exit(0)}),process.on("SIGINT",()=>{b.disable(),process.stderr.write(`Session ended.
|
|
162
|
+
`),Ae(),process.exit(0)}),process.on("SIGTERM",()=>{b.disable(),process.stderr.write(`Session ended.
|
|
163
|
+
`),Ae(),process.exit(0)})}async function $p(r){await r.logout(),process.stderr.write(`Logged out.
|
|
164
|
+
`)}async function Gp(r,e){let t=await r.hasValidToken(),n=await r.getAgentId();if(t?(process.stderr.write(`Status: logged in
|
|
60
165
|
`),n&&process.stderr.write(`Agent ID: ${n}
|
|
61
166
|
`)):(process.stderr.write(`Status: not logged in
|
|
62
167
|
`),process.stderr.write(`Run 'termiq login' to authenticate.
|
|
63
168
|
`)),e){let i=await e.getShortFingerprint();process.stderr.write(`Fingerprint: ${i}
|
|
64
169
|
`),process.stderr.write(`Run 'termiq fingerprint' for the full safety number.
|
|
65
|
-
`)}}async function
|
|
170
|
+
`)}}async function zp(r){let e=await r.getSafetyNumber(),t=await r.getShortFingerprint();process.stdout.write(`
|
|
66
171
|
TermIQ agent safety number
|
|
67
172
|
${e}
|
|
68
173
|
|
|
@@ -71,8 +176,8 @@ Short fingerprint: ${t}
|
|
|
71
176
|
Compare these with the value shown in the TermIQ web app to verify
|
|
72
177
|
you are connected to THIS agent (no server-in-the-middle).
|
|
73
178
|
|
|
74
|
-
`)}var
|
|
75
|
-
termiq v${
|
|
179
|
+
`)}var Dt=he(pi()),Ne=process.argv.slice(2);(Ne.includes("--help")||Ne.includes("-h"))&&(process.stderr.write(`
|
|
180
|
+
termiq v${Do()} \u2014 Access terminals from anywhere
|
|
76
181
|
|
|
77
182
|
Usage:
|
|
78
183
|
termiq Start a shell with cloud access (default)
|
|
@@ -97,12 +202,10 @@ you are connected to THIS agent (no server-in-the-middle).
|
|
|
97
202
|
follows whoever typed or resized last; other viewers
|
|
98
203
|
mirror it. Default \u2014 LCD policy (min size over viewers).
|
|
99
204
|
--push-prompt-text
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
only that a terminal is waiting
|
|
103
|
-
|
|
104
|
-
the clear, so the server can show them in the shade.
|
|
105
|
-
The prompt itself always reaches your devices encrypted.
|
|
205
|
+
No effect; still accepted so existing scripts keep
|
|
206
|
+
working. Notifications never carry the prompt's text:
|
|
207
|
+
they say only that a terminal is waiting. The prompt
|
|
208
|
+
itself reaches your devices encrypted.
|
|
106
209
|
--no-signal-waiting
|
|
107
210
|
Ignore the agent's own "waiting" signal (codex and gemini
|
|
108
211
|
put it in the window title). On by default: when our
|
|
@@ -112,17 +215,22 @@ you are connected to THIS agent (no server-in-the-middle).
|
|
|
112
215
|
|
|
113
216
|
Environment:
|
|
114
217
|
TERMIQ_TOKEN API key (equivalent to --token)
|
|
218
|
+
TERMIQ_SHELL_INTEGRATION=0
|
|
219
|
+
Start bash and zsh without the hook that reports how
|
|
220
|
+
each command ended (it tells TermIQ that an agent such
|
|
221
|
+
as claude failed, for the error notification).
|
|
115
222
|
|
|
116
|
-
`),process.exit(0));(
|
|
117
|
-
`),process.exit(0));var
|
|
223
|
+
`),process.exit(0));(Ne.includes("--version")||Ne.includes("-V"))&&(process.stdout.write(`${Do()}
|
|
224
|
+
`),process.exit(0));var Yp=hp(Ne,Rf,lp);Yp&&(process.stderr.write(`Unknown flag: ${Yp}
|
|
118
225
|
Run 'termiq --help' for usage.
|
|
119
|
-
`),process.exit(1));var
|
|
120
|
-
|
|
121
|
-
`),process.exit(1)),
|
|
226
|
+
`),process.exit(1));var Xp=up(Ne,Rf)??"start",jw=Ne.includes("--verbose")||Ne.includes("-v"),Uw=Ne.includes("--watch")||Ne.includes("-w"),qw=Ne.includes("--log-to-file"),Kw=Ne.includes("--statusline"),Ww=Ne.includes("--multi-viewer"),Hw=Ne.includes("--push-prompt-text"),Vw=Ne.includes("--no-signal-waiting"),$w=Ne.includes("--force"),Zp=Ne.find(r=>r.startsWith("--token="))?.split("=")[1]||(Ne.includes("--token")?Ne[Ne.indexOf("--token")+1]:void 0),Qp=Ne.find(r=>r.startsWith("--server="))?.split("=")[1]||(Ne.includes("--server")?Ne[Ne.indexOf("--server")+1]:void 0),Wf=Ne.find(r=>r.startsWith("--log-level="))?.split("=")[1]||(Ne.includes("--log-level")?Ne[Ne.indexOf("--log-level")+1]:void 0),Gw=["silent","error","warn","info","debug"],zw=Wf&&Gw.includes(Wf)?Wf:jw?"info":"silent",Yw=Ne.find(r=>r.startsWith("--cid="))?.split("=")[1]||(Ne.includes("--cid")?Ne[Ne.indexOf("--cid")+1]:void 0),Xw=Yw||(0,Dt.generateCorrelationId)(),Jp=process.env.TERMIQ_TOKEN,vr=new zi(zw,qw),fn=new Si,Gt=new xi(Qp?{serverUrl:Qp}:void 0),un=new Xi,Yo=new Zi(vr),is=new es;async function Zw(){switch(Xp){case"start":case void 0:{process.env.TERMIQ_SESSION_ACTIVE==="1"&&!$w&&(process.stderr.write(`termiq is already running in this terminal (you are inside a termiq session).
|
|
227
|
+
Use the current session, or pass --force to start a nested one.
|
|
228
|
+
`),process.exit(1)),Ww&&await Gt.setMultiViewer(!0);let r=Gt.getMultiViewer();Hw&&process.stderr.write(`termiq: --push-prompt-text has no effect: notifications never carry the prompt text.
|
|
229
|
+
`),Vw&&await Gt.setSignalWaiting(!1);let e=Gt.getSignalWaiting();await Vp({storage:fn,config:Gt,logger:vr,machineId:un,notification:Yo,browser:is,cwd:process.cwd(),watch:Uw,statusLine:Kw,multiViewer:r,signalWaiting:e,apiKey:Zp||Jp});break}case"login":{let r=new URL(Gt.getServerUrl()).host,e=await un.getMachineId(),t=new Dt.CryptoService(fn,vr,r,e);await t.initialize();let n=new Dt.AuthService(fn,t,un,Gt,vr,Yo,is,r,e),i=await zo(n,is,vr,Zp||Jp);process.exit(i?0:1);break}case"logout":{let r=new URL(Gt.getServerUrl()).host,e=await un.getMachineId(),t=new Dt.CryptoService(fn,vr,r,e);await t.initialize();let n=new Dt.AuthService(fn,t,un,Gt,vr,Yo,is,r,e);await $p(n),process.exit(0);break}case"status":{let r=new URL(Gt.getServerUrl()).host,e=await un.getMachineId(),t=new Dt.CryptoService(fn,vr,r,e);await t.initialize();let n=new Dt.AuthService(fn,t,un,Gt,vr,Yo,is,r,e);await Gp(n,t),process.exit(0);break}case"fingerprint":{let r=new URL(Gt.getServerUrl()).host,e=await un.getMachineId(),t=new Dt.CryptoService(fn,vr,r,e);await t.initialize(),await zp(t),process.exit(0);break}case"version":{process.stdout.write(`${Do()}
|
|
122
230
|
`),process.exit(0);break}case"help":{process.stderr.write(`Run 'termiq --help' for full usage.
|
|
123
|
-
`),process.exit(0);break}default:process.stderr.write(`Unknown command: ${
|
|
231
|
+
`),process.exit(0);break}default:process.stderr.write(`Unknown command: ${Xp}
|
|
124
232
|
Run 'termiq --help' for usage.
|
|
125
|
-
`),process.exit(1)}}(0,
|
|
233
|
+
`),process.exit(1)}}(0,Dt.runWithCorrelation)(Xw,()=>Zw().catch(r=>{process.stderr.write(`Fatal error: ${r instanceof Error?r.message:String(r)}
|
|
126
234
|
`),process.exit(1)}));
|
|
127
235
|
/*! Bundled license information:
|
|
128
236
|
|